code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
# This file collects a few examples on how the modules of # the package can be tested. This file can also be used by # the github continuous integration (CI) to the test the code # everytime there is a push. # # The <test coverage> can then be assessed using pytest-cov. # This basically tests how many percents of the modules are # being tested. # # Documentation: # https://docs.pytest.org/en/stable/contents.html import pytest import numpy as np from pathlib import Path from numpy.testing import assert_almost_equal # -- Addition --------------------------------------------------------- @pytest.mark.parametrize("inputs, expected", [("1+2", 3), ("3*4", 12)]) def test_computation(inputs, expected): """Test a function that takes 2 arguments and compute the results according to a given operations. Parameters ---------- inputs: operations Operation to be computed expected: int Expected results """ assert eval(inputs) == expected # -- Mean ------------------------------------------------------------- # Compare function that computes the mean of an array with numpy.mean DIM_X = 10 DIM_Y = 20 DIM_Z = 40 def _mean(arr): """Compute mean in the standard way.""" result = np.zeros((DIM_Y, DIM_Z)) for fl in range(DIM_Y): for x in range(DIM_Z): repl = 0 for rep in range(DIM_X): repl += arr[rep][fl][x] result[fl][x] = repl return result / DIM_X def test_mean(): """ Compare standard mean and the numpy implementation""" arr = np.random.uniform(0, 1, size=[DIM_X, DIM_Y, DIM_Z]) st_mean = _mean(arr) np_mean = np.mean(arr, axis=0) assert_almost_equal(np_mean, st_mean, decimal=10) # -- Test a class ----------------------------------------------------- class CheckDir: curr_path = Path().absolute() def return_dir(self): return self.curr_path def checkatttribute(cl, attr): """This function checks if an attribute `attr` is present in the class `cl`. Parameters ---------- cl: class A given class attr: Name of the attribute """ __tracebackhide__ = True if not hasattr(cl, attr): pytest.fail("{cl} has no attribute {attr}") def test_checkatttribute(): """This is the test function that is going to be called by pytest in order to test the `checkatttribute` method. """ checkatttribute(CheckDir, "return_dir")
[ "numpy.mean", "pathlib.Path", "pytest.fail", "numpy.testing.assert_almost_equal", "pytest.mark.parametrize", "numpy.zeros", "numpy.random.uniform" ]
[((596, 666), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""inputs, expected"""', "[('1+2', 3), ('3*4', 12)]"], {}), "('inputs, expected', [('1+2', 3), ('3*4', 12)])\n", (619, 666), False, 'import pytest\n'), ((1256, 1280), 'numpy.zeros', 'np.zeros', (['(DIM_Y, DIM_Z)'], {}), '((DIM_Y, DIM_Z))\n', (1264, 1280), True, 'import numpy as np\n'), ((1588, 1639), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': '[DIM_X, DIM_Y, DIM_Z]'}), '(0, 1, size=[DIM_X, DIM_Y, DIM_Z])\n', (1605, 1639), True, 'import numpy as np\n'), ((1679, 1699), 'numpy.mean', 'np.mean', (['arr'], {'axis': '(0)'}), '(arr, axis=0)\n', (1686, 1699), True, 'import numpy as np\n'), ((1704, 1753), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['np_mean', 'st_mean'], {'decimal': '(10)'}), '(np_mean, st_mean, decimal=10)\n', (1723, 1753), False, 'from numpy.testing import assert_almost_equal\n'), ((2252, 2295), 'pytest.fail', 'pytest.fail', (['"""{cl} has no attribute {attr}"""'], {}), "('{cl} has no attribute {attr}')\n", (2263, 2295), False, 'import pytest\n'), ((1861, 1867), 'pathlib.Path', 'Path', ([], {}), '()\n', (1865, 1867), False, 'from pathlib import Path\n')]
# -*- coding: utf-8 -*- """ Created on Sat Feb 18 16:21:13 2017 @author: <NAME> This code is modified based on https://github.com/KGPML/Hyperspectral """ import tensorflow as tf import numpy as np import scipy.io as io from pygco import cut_simple, cut_simple_vh from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import spectral as spy import cv2 from skimage.util import pad from collections import Counter patch_size = 9 # can be tuned class DataSet(object): def __init__(self, images, labels, dtype=tf.float32): """Construct a DataSet. FIXME: fake_data options one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. """ images = np.transpose(images,(0,2,3,1)) labels = np.transpose(labels) dtype = tf.as_dtype(dtype).base_dtype if dtype not in (tf.uint8, tf.float32): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype) assert images.shape[0] == labels.shape[0], ( 'images.shape: %s labels.shape: %s' % (images.shape, labels.shape)) self._num_examples = images.shape[0] images = images.reshape(images.shape[0],images.shape[1] * images.shape[2] * images.shape[3]) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size): """Return the next `batch_size` examples from this data set.""" start = self._index_in_epoch self._index_in_epoch += batch_size if self._index_in_epoch > self._num_examples: # Finished epoch self._epochs_completed += 1 # Shuffle the data perm = np.arange(self._num_examples) np.random.shuffle(perm) self._images = self._images[perm] self._labels = self._labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size assert batch_size <= self._num_examples end = self._index_in_epoch return self._images[start:end], np.reshape(self._labels[start:end],len(self._labels[start:end])) def read_data_sets(directory,value, dtype=tf.float32): images = io.loadmat(directory)[value+'_patch'] labels = io.loadmat(directory)[value+'_labels'] data_sets = DataSet(images, labels, dtype=dtype) return data_sets def convertToOneHot(vector, num_classes=None): """ Converts an input 1-D vector of integers into an output 2-D array of one-hot vectors, where an i'th input value of j will set a '1' in the i'th row, j'th column of the output array. Example: v = np.array((1, 0, 4)) one_hot_v = convertToOneHot(v) print one_hot_v [[0 1 0 0 0] [1 0 0 0 0] [0 0 0 0 1]] """ assert isinstance(vector, np.ndarray) assert len(vector) > 0 if num_classes is None: num_classes = np.max(vector)+1 else: assert num_classes > 0 assert num_classes >= np.max(vector) result = np.zeros(shape=(len(vector), num_classes)) result[np.arange(len(vector)), vector] = 1 return result.astype(int) def draw(GT_Label,ES_Label): fig = plt.figure(figsize=(12,6)) p = plt.subplot(1,2,1) v = spy.imshow(classes=GT_Label,fignum=fig.number) p.set_title('Ground Truth') p.set_xticklabels([]) p.set_yticklabels([]) p = plt.subplot(1,2,2) v = spy.imshow(classes=ES_Label * (GT_Label!=0),fignum=fig.number) p.set_title('CLassification Map') p.set_xticklabels([]) p.set_yticklabels([]) def unaries_reshape(unaries,height,width,num_classes): una = [] for i in range(num_classes): temp = unaries[:,i].reshape(height,width).transpose(1,0) una.append(temp) return np.dstack(una).copy("C") def Post_Processing(prob_map,height,width,num_classes,y_test,test_indexes): # unaries = (prob_map+1e-7).astype(np.int32) unaries = (-5 * np.log(prob_map+1e-7)).astype(np.int32) una = unaries_reshape(unaries,width,height,num_classes) one_d_topology = (np.ones(num_classes)-np.eye(num_classes)).astype(np.int32).copy("C") Seg_Label = cut_simple(una, 2 * one_d_topology) Seg_Label = Seg_Label + 1 seg_Label = Seg_Label.transpose().flatten() seg_accuracy = accuracy_score(y_test,seg_Label[test_indexes]) return Seg_Label, seg_Label, seg_accuracy def Median_filter(prob_map,height,width,y_test,test_indexes): Cla_Label = np.argmax(prob_map,1) + 1 Cla_Label = Cla_Label.reshape(height,width).transpose(1,0) Cla_Label = Cla_Label.astype(np.uint8) Median_Label = cv2.medianBlur(Cla_Label,3) median_Label = Median_Label.transpose().flatten() median_accuracy = accuracy_score(y_test,median_Label[test_indexes].flatten()) return Median_Label, median_Label, median_accuracy def Patch(Label_Padding,height_index,width_index,ksize): """ function to extract patches from the orignal data """ height_slice = slice(height_index, height_index + ksize) width_slice = slice(width_index, width_index + ksize) patch = Label_Padding[height_slice, width_slice] return np.array(patch) def mv_calculate(patch): patch_vec = list(patch.flatten()) patch_vec = [i for i in patch_vec if i>0] mv_value = Counter(patch_vec).most_common(1)[0][0] return mv_value def Majority_voting(Label,ksize): ## padding the data beforehand Height, Width= Label.shape[0], Label.shape[1] Label_Padding = pad(Label,int((ksize-1)/2),'constant') MV_Label = np.zeros((Height,Width)) for j in range(0,Width): for i in range(0,Height): curr_patch = Patch(Label_Padding,i,j,ksize) MV_Label[i,j] = mv_calculate(curr_patch) return MV_Label
[ "scipy.io.loadmat", "numpy.log", "numpy.array", "spectral.imshow", "numpy.arange", "cv2.medianBlur", "numpy.max", "numpy.eye", "numpy.ones", "numpy.argmax", "numpy.transpose", "sklearn.metrics.accuracy_score", "numpy.dstack", "collections.Counter", "matplotlib.pyplot.figure", "numpy.ze...
[((3721, 3748), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (3731, 3748), True, 'import matplotlib.pyplot as plt\n'), ((3761, 3781), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (3772, 3781), True, 'import matplotlib.pyplot as plt\n'), ((3788, 3835), 'spectral.imshow', 'spy.imshow', ([], {'classes': 'GT_Label', 'fignum': 'fig.number'}), '(classes=GT_Label, fignum=fig.number)\n', (3798, 3835), True, 'import spectral as spy\n'), ((3928, 3948), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (3939, 3948), True, 'import matplotlib.pyplot as plt\n'), ((3955, 4020), 'spectral.imshow', 'spy.imshow', ([], {'classes': '(ES_Label * (GT_Label != 0))', 'fignum': 'fig.number'}), '(classes=ES_Label * (GT_Label != 0), fignum=fig.number)\n', (3965, 4020), True, 'import spectral as spy\n'), ((4693, 4728), 'pygco.cut_simple', 'cut_simple', (['una', '(2 * one_d_topology)'], {}), '(una, 2 * one_d_topology)\n', (4703, 4728), False, 'from pygco import cut_simple, cut_simple_vh\n'), ((4826, 4873), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'seg_Label[test_indexes]'], {}), '(y_test, seg_Label[test_indexes])\n', (4840, 4873), False, 'from sklearn.metrics import accuracy_score\n'), ((5150, 5178), 'cv2.medianBlur', 'cv2.medianBlur', (['Cla_Label', '(3)'], {}), '(Cla_Label, 3)\n', (5164, 5178), False, 'import cv2\n'), ((5673, 5688), 'numpy.array', 'np.array', (['patch'], {}), '(patch)\n', (5681, 5688), True, 'import numpy as np\n'), ((6073, 6098), 'numpy.zeros', 'np.zeros', (['(Height, Width)'], {}), '((Height, Width))\n', (6081, 6098), True, 'import numpy as np\n'), ((823, 857), 'numpy.transpose', 'np.transpose', (['images', '(0, 2, 3, 1)'], {}), '(images, (0, 2, 3, 1))\n', (835, 857), True, 'import numpy as np\n'), ((871, 891), 'numpy.transpose', 'np.transpose', (['labels'], {}), '(labels)\n', (883, 891), True, 'import numpy as np\n'), ((2720, 2741), 'scipy.io.loadmat', 'io.loadmat', (['directory'], {}), '(directory)\n', (2730, 2741), True, 'import scipy.io as io\n'), ((2771, 2792), 'scipy.io.loadmat', 'io.loadmat', (['directory'], {}), '(directory)\n', (2781, 2792), True, 'import scipy.io as io\n'), ((4999, 5021), 'numpy.argmax', 'np.argmax', (['prob_map', '(1)'], {}), '(prob_map, 1)\n', (5008, 5021), True, 'import numpy as np\n'), ((926, 944), 'tensorflow.as_dtype', 'tf.as_dtype', (['dtype'], {}), '(dtype)\n', (937, 944), True, 'import tensorflow as tf\n'), ((2199, 2228), 'numpy.arange', 'np.arange', (['self._num_examples'], {}), '(self._num_examples)\n', (2208, 2228), True, 'import numpy as np\n'), ((2241, 2264), 'numpy.random.shuffle', 'np.random.shuffle', (['perm'], {}), '(perm)\n', (2258, 2264), True, 'import numpy as np\n'), ((3444, 3458), 'numpy.max', 'np.max', (['vector'], {}), '(vector)\n', (3450, 3458), True, 'import numpy as np\n'), ((3532, 3546), 'numpy.max', 'np.max', (['vector'], {}), '(vector)\n', (3538, 3546), True, 'import numpy as np\n'), ((4315, 4329), 'numpy.dstack', 'np.dstack', (['una'], {}), '(una)\n', (4324, 4329), True, 'import numpy as np\n'), ((4486, 4510), 'numpy.log', 'np.log', (['(prob_map + 1e-07)'], {}), '(prob_map + 1e-07)\n', (4492, 4510), True, 'import numpy as np\n'), ((5815, 5833), 'collections.Counter', 'Counter', (['patch_vec'], {}), '(patch_vec)\n', (5822, 5833), False, 'from collections import Counter\n'), ((4608, 4628), 'numpy.ones', 'np.ones', (['num_classes'], {}), '(num_classes)\n', (4615, 4628), True, 'import numpy as np\n'), ((4629, 4648), 'numpy.eye', 'np.eye', (['num_classes'], {}), '(num_classes)\n', (4635, 4648), True, 'import numpy as np\n')]
import numpy as np class Fagin: def __init__(self, cran_title, cran_text): self.cran_title = cran_title self.cran_text = cran_text def fagin(self, data, K=200): k = 0 res = {} N = len(data["title"]["order"]) sections = list(data) n = 0 for n in range(N): for section in sections: element = data[section]["order"][n] res[element] = res.get(element, []) + [section] if len(res[element]) == len(sections): k += 1 if k >= K: break if k >= K: break final_result = {k: 0 for k in res} for section in sections: for x in res: element = data[section]["score"] final_result[x] += element.get(x, 0) top_k = sorted([(f, final_result[f]) for f in final_result], key=lambda u: u[1], reverse=True) return top_k def writeData(self, result_DataFrame, top_k, query): new = [] rank = 1 for t_k in top_k: new.append([str(query), str(t_k[0]), str(rank), str(t_k[1])]) rank += 1 new = pd.DataFrame(np.array(new), columns=result_DataFrame.columns) result_DataFrame = pd.concat([result_DataFrame, new], axis=0) return result_DataFrame def main(self): result_DataFrame = pd.DataFrame(columns=["Query_ID", "Doc_ID", "Rank", "Score"]) for query in self.cran_title.keys(): try: title = self.cran_title[query] text = self.cran_text[query] title_rank = [title[t][0] for t in title] text_rank = [text[t][0] for t in text] data = { "title": {"score": {title[t][0]: title[t][1] * 2 for t in title}, "order": title_rank}, "text": {"score": {text[t][0]: text[t][1] for t in text}, "order": text_rank}, } top_k = self.fagin(data) top_k = top_k[:200] result_DataFrame = self.writeData(result_DataFrame, top_k, query) except: continue return result_DataFrame
[ "numpy.array" ]
[((1244, 1257), 'numpy.array', 'np.array', (['new'], {}), '(new)\n', (1252, 1257), True, 'import numpy as np\n')]
import warnings import time import numpy as np # Scipy try: import scipy.linalg as spa except: warnings.warn("You don't have scipy package installed. You may get error while using some feautures.") #pycdd try: from cdd import Polyhedron,Matrix,RepType except: warnings.warn("You don't have CDD package installed. Unable to run cone ray generation.") # Internal Imports try: import pypolycontain as pp except: warnings.warn("You don't have pypolycontain not properly installed.") #try: # from pypolycontain.conversions import to_AH_polytope #except: # pass # warnings.warn("You don't have pypolycontain not properly installed.") try: import pydrake.solvers.mathematicalprogram as MP import pydrake.solvers.gurobi as Gurobi_drake import pydrake.solvers.osqp as OSQP_drake # use Gurobi solver global gurobi_solver,OSQP_solver, license gurobi_solver=Gurobi_drake.GurobiSolver() license = gurobi_solver.AcquireLicense() except: warnings.warn("You don't have pydrake installed properly. Methods that rely on optimization may fail.") """ *********** Description *********** The necessary and sufficient conditions for encoding was provided here. """ def theta_k(circumbody,k=0,i=0): """ This is from the Section 4 of the paper [Sadraddini and Tedrake, 2020]. Inputs: * AH-polytope: ``circumbody`` * int ``N``: the number of columns added to the subspace of ``U``. For more information, look at the paper. *Default* is 0. Outputs: * 2D numpy array ``Theta``, which is defined in the paper """ circumbody_AH=pp.to_AH_polytope(circumbody) H_y=circumbody_AH.P.H q_y=H_y.shape[0] if k<0: return np.eye(q_y) Y=circumbody_AH.T # First identify K=[H_y'^Y'+ ker(H_y')] S_1=np.dot(np.linalg.pinv(H_y.T),Y.T) S_2=spa.null_space(H_y.T) if S_2.shape[1]>0: S=np.hstack((S_1,S_2)) else: S=S_1 # phiw>=0. Now with the augmentation S_complement=spa.null_space(S.T) circumbody.dim_complement=S_complement.shape[1] number_of_columns=min(k,S_complement.shape[1]) psi=np.hstack((S,S_complement[:,i:number_of_columns+i])) p_mat=Matrix(np.hstack((np.zeros((psi.shape[0],1)),psi))) p_mat.rep_type = RepType.INEQUALITY poly=Polyhedron(p_mat) R=np.array(poly.get_generators()) r=R[:,1:].T Theta=np.dot(psi,r) return Theta def be_in_set(program,point,zonotope): """ It forces a point to be a member of a zonotope """ dimension = zonotope.G.shape[1] b=program.NewContinuousVariables( dimension,'b') program.AddBoundingBoxConstraint(-1,1,b) program.AddLinearConstraint( np.equal(point, zonotope.x+np.dot(zonotope.G , b) ,dtype='object').flatten() ) return b def member_in_set(program,x,P): """ Inputs: @ program: mathematical program # x: point # P: my polytope Adds the constraint ..math::`x in P` to the mathematical program """ P=pp.to_AH_polytope(P) x.reshape(len(x),1) zeta=program.NewContinuousVariables( P.P.n,1, 'zeta') program.AddLinearConstraint(A=P.P.H,lb=-np.inf*np.ones((P.P.h.shape[0],1)),ub=P.P.h,vars=zeta) _f=np.equal(np.dot(P.T,zeta),x-P.t,dtype='object') program.AddLinearConstraint(_f.flatten()) def subset(program,inbody,circumbody,k=-1,Theta=None,i=0,alpha=None,verbose=False): """ Adds containment property Q1 subset Q2 Inputs: * program: a `pydrake` mathematical program * inbody: a polytopic object * circumbody: a polytopic object * N: * **Default**: :math:`-1``. Sufficient as in [Sadraddini and Tedrake, 2020] * pick `0` for necessary and sufficient encoding (may be too slow) (2019b) * pick any positive number. As the number is smaller, the condition becomes closer to necessity. However, this may be too slow. Output: * No direct output, adds :\math:`inbody \subseteq circumbody` to the model """ if type(inbody).__name__=="zonotope" and type(circumbody).__name__=="zonotope": """ For the case when both inbody and circumbody sets are zonotope: """ from itertools import product #Defining Variables Gamma=program.NewContinuousVariables( circumbody.G.shape[1], inbody.G.shape[1], 'Gamma') Lambda=program.NewContinuousVariables( circumbody.G.shape[1],'Lambda') #Defining Constraints program.AddLinearConstraint(np.equal(inbody.G,np.dot(circumbody.G,Gamma),dtype='object').flatten()) #inbody_G = circumbody_G * Gamma program.AddLinearConstraint(np.equal(circumbody.x - inbody.x ,np.dot(circumbody.G,Lambda),dtype='object').flatten()) #circumbody_x - inbody_x = circumbody_G * Lambda Gamma_Lambda = np.concatenate((Gamma,Lambda.reshape(circumbody.G.shape[1],1)),axis=1) comb = np.array( list(product([-1, 1], repeat= Gamma_Lambda.shape[1])) ).reshape(-1, Gamma_Lambda.shape[1]) if alpha=='scalar' or alpha== 'vector': comb= np.concatenate( (comb,-1*np.ones((comb.shape[0],1))) , axis=1) # Managing alpha if alpha==None: variable = Gamma_Lambda elif alpha=='scalar': alfa = program.NewContinuousVariables(1,'alpha') elif alpha=='vector': alfa=program.NewContinuousVariables( circumbody.G.shape[1],'alpha') variable = np.concatenate((Gamma_Lambda, alfa.reshape(-1,1)),axis=1) else: raise ValueError('alpha needs to be \'None\', \'scalaer\', or \'vector\'') # infinity norm of matrxi [Gamma,Lambda] <= alfa for j in range(Gamma_Lambda.shape[0]): program.AddLinearConstraint( A= comb, lb= -np.inf * np.ones(comb.shape[0]), ub= np.ones(comb.shape[0]) if alpha==None else np.zeros(comb.shape[0]), vars= variable[j,:] if alpha!='scalar' else np.concatenate((Gamma_Lambda[j,:], alfa )) ) #from pydrake.symbolic import abs as exp_abs # Gamma_abs = np.array([exp_abs(Gamma[i,j]) for i in range(circumbody.G.shape[1]) for j in range(inbody.G.shape[1])]).reshape(*Gamma.shape) # Lambda_abs = np.array([exp_abs(Lambda[i]) for i in range(circumbody.G.shape[1])]).reshape(circumbody.G.shape[1],1) # Gamma_lambda_abs = np.concatenate((Gamma_abs,Lambda_abs),axis=1) # infnorm_Gamma_lambda_abs = np.sum(Gamma_lambda_abs,axis=1) #[program.AddConstraint( infnorm_Gamma_lambda_abs[i] <= 1) for i in range(circumbody.G.shape[1])] #program.AddBoundingBoxConstraint(-np.inf * np.ones(circumbody.G.shape[1]) , np.ones(circumbody.G.shape[1]), infnorm_Gamma_lambda_abs) # program.AddLinearConstraint( # A=np.eye(circumbody.G.shape[1]), # lb= -np.inf * np.ones(circumbody.G.shape[1]), # ub=np.ones(circumbody.G.shape[1]), # vars=infnorm_Gamma_lambda_abs # ) if alpha==None: return Lambda, Gamma else: return Lambda, Gamma , alfa Q1=pp.to_AH_polytope(inbody) Q2=pp.to_AH_polytope(circumbody) Hx,Hy,hx,hy,X,Y,xbar,ybar=Q1.P.H,Q2.P.H,Q1.P.h,Q2.P.h,Q1.T,Q2.T,Q1.t,Q2.t qx,qy,nx,ny=Hx.shape[0],Hy.shape[0],X.shape[1],Y.shape[1] if type(Theta)!=type(None): if verbose: print("theta already computed") pass elif k<0: Theta=np.eye(qy) if verbose: print("Using Positive Orthant") else: if verbose: print("Computing theta with k=%d"%k) Theta=theta_k(circumbody,k,i) Lambda=program.NewContinuousVariables(Theta.shape[1],qx,'Lambda') Gamma=program.NewContinuousVariables(ny,nx,'Gamma') gamma=program.NewContinuousVariables(ny,1,'gamma') # Constraints program.AddBoundingBoxConstraint(0,np.inf,Lambda) # Lambda Non-Negative program.AddLinearConstraint(np.equal(X,np.dot(Y,Gamma),dtype='object').flatten()) #X=YGamma program.AddLinearConstraint(np.equal(ybar-xbar,np.dot(Y,gamma),dtype='object').flatten()) program.AddLinearConstraint(np.equal(np.dot(Lambda,Hx),np.dot(Theta.T,np.dot(Hy,Gamma)),dtype='object').flatten()) program.AddLinearConstraint(np.less_equal(np.dot(Lambda,hx),\ np.dot(Theta.T,hy)+np.dot(Theta.T,np.dot(Hy,gamma)),dtype='object').flatten()) return Theta,Lambda,Gamma,gamma def necessity_gap(X,Y,Theta): """ The necessity gap for the encoding using cone defined by Theta .. warning: To be added later """ alpha_0=alpha(X,Y,theta_k(Y,k=0)) my_alpha= alpha(X,Y,Theta) return 1-my_alpha/alpha_0 def necessity_gap_k(X,Y,plot=True): print("\n\n","="*75,"\n","="*75,"\n\t\tComputing Necessity Gaps ") print("="*75,"\n","="*75) print("k\tTheta.shape \t delta(X,Y,C) \t alpha \t Computation Time") print("-"*75) alpha_0=alpha(X,Y,theta_k(Y,k=0)) Table={} Z=pp.to_AH_polytope(Y) kappa=int(Z.T.shape[1]-Z.T.shape[0]) for k in range(kappa+1): t_0=time.time() Theta=theta_k(Y,k) # print(k,"theta shape",Theta.shape,Theta) a=alpha(X,Y,Theta) delta=1-a/alpha_0 cpu_time=time.time()-t_0 print(k, "\t",Theta.shape,"\t %0.03f"%delta,"\t\t %0.03f"%a,"\t\t %0.003f"%cpu_time) Table[k]=np.array([Theta.shape[1],delta,a,cpu_time]) if plot: import matplotlib.pyplot as plt plt.figure() fig, ax1 = plt.subplots() color = (0.7,0,0) ax1.set_xlabel(r'$k$') ax1.set_ylabel(r'#Rows in $\Theta_k$', color=color,FontSize=20) ax1.plot(range(kappa+1),[Table[k][0] for k in range(kappa+1)],'-',color=color) ax1.plot(range(kappa+1),[Table[k][0] for k in range(kappa+1)],'o',color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis color = (0,0,0.7) ax2.set_xlabel(r'$k$') ax2.set_ylabel(r'$\delta(\mathbb{X},\mathbb{Y},\mathbb{C}_k)$', color=color,FontSize=20) ax2.plot(range(kappa+1),[Table[k][1] for k in range(kappa+1)],'-',color=color) ax2.plot(range(kappa+1),[Table[k][1] for k in range(kappa+1)],'o',color=color) ax2.tick_params(axis='y', labelcolor=color) ax2.set_title(r'$k^*=%d, n=%d$'%(kappa,Z.n),FontSize=20) ax1.grid() fig.tight_layout() # otherwise the right y-label is slightly clipped return Table def alpha(X,Y,Theta): X2=pp.to_AH_polytope(X) Y2=pp.to_AH_polytope(Y) prog=MP.MathematicalProgram() alpha=prog.NewContinuousVariables(1,"alpha") t=prog.NewContinuousVariables(X2.n,1,"t") Y2.P.h=Y2.P.h*alpha X2.t=X2.t+t subset(prog,X2,Y2,Theta=Theta) prog.AddLinearCost(np.eye(1),np.zeros((1)),alpha) result=gurobi_solver.Solve(prog,None,None) if result.is_success(): # print("alpha test successful") # print(result.GetSolution(alpha),result.GetSolution(t)) return 1/result.GetSolution(alpha)[0] else: print("not a subset")
[ "numpy.eye", "pydrake.solvers.gurobi.GurobiSolver", "numpy.linalg.pinv", "numpy.ones", "numpy.hstack", "scipy.linalg.null_space", "itertools.product", "numpy.array", "numpy.dot", "matplotlib.pyplot.figure", "numpy.zeros", "pypolycontain.to_AH_polytope", "numpy.concatenate", "time.time", ...
[((916, 943), 'pydrake.solvers.gurobi.GurobiSolver', 'Gurobi_drake.GurobiSolver', ([], {}), '()\n', (941, 943), True, 'import pydrake.solvers.gurobi as Gurobi_drake\n'), ((1676, 1705), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['circumbody'], {}), '(circumbody)\n', (1693, 1705), True, 'import pypolycontain as pp\n'), ((1909, 1930), 'scipy.linalg.null_space', 'spa.null_space', (['H_y.T'], {}), '(H_y.T)\n', (1923, 1930), True, 'import scipy.linalg as spa\n'), ((2068, 2087), 'scipy.linalg.null_space', 'spa.null_space', (['S.T'], {}), '(S.T)\n', (2082, 2087), True, 'import scipy.linalg as spa\n'), ((2202, 2258), 'numpy.hstack', 'np.hstack', (['(S, S_complement[:, i:number_of_columns + i])'], {}), '((S, S_complement[:, i:number_of_columns + i]))\n', (2211, 2258), True, 'import numpy as np\n'), ((2366, 2383), 'cdd.Polyhedron', 'Polyhedron', (['p_mat'], {}), '(p_mat)\n', (2376, 2383), False, 'from cdd import Polyhedron, Matrix, RepType\n'), ((2448, 2462), 'numpy.dot', 'np.dot', (['psi', 'r'], {}), '(psi, r)\n', (2454, 2462), True, 'import numpy as np\n'), ((3066, 3086), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['P'], {}), '(P)\n', (3083, 3086), True, 'import pypolycontain as pp\n'), ((7251, 7276), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['inbody'], {}), '(inbody)\n', (7268, 7276), True, 'import pypolycontain as pp\n'), ((7284, 7313), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['circumbody'], {}), '(circumbody)\n', (7301, 7313), True, 'import pypolycontain as pp\n'), ((9114, 9134), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['Y'], {}), '(Y)\n', (9131, 9134), True, 'import pypolycontain as pp\n'), ((10718, 10738), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['X'], {}), '(X)\n', (10735, 10738), True, 'import pypolycontain as pp\n'), ((10746, 10766), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['Y'], {}), '(Y)\n', (10763, 10766), True, 'import pypolycontain as pp\n'), ((10776, 10800), 'pydrake.solvers.mathematicalprogram.MathematicalProgram', 'MP.MathematicalProgram', ([], {}), '()\n', (10798, 10800), True, 'import pydrake.solvers.mathematicalprogram as MP\n'), ((104, 216), 'warnings.warn', 'warnings.warn', (['"""You don\'t have scipy package installed. You may get error while using some feautures."""'], {}), '(\n "You don\'t have scipy package installed. You may get error while using some feautures."\n )\n', (117, 216), False, 'import warnings\n'), ((287, 381), 'warnings.warn', 'warnings.warn', (['"""You don\'t have CDD package installed. Unable to run cone ray generation."""'], {}), '(\n "You don\'t have CDD package installed. Unable to run cone ray generation.")\n', (300, 381), False, 'import warnings\n'), ((445, 514), 'warnings.warn', 'warnings.warn', (['"""You don\'t have pypolycontain not properly installed."""'], {}), '("You don\'t have pypolycontain not properly installed.")\n', (458, 514), False, 'import warnings\n'), ((1001, 1114), 'warnings.warn', 'warnings.warn', (['"""You don\'t have pydrake installed properly. Methods that rely on optimization may fail."""'], {}), '(\n "You don\'t have pydrake installed properly. Methods that rely on optimization may fail."\n )\n', (1014, 1114), False, 'import warnings\n'), ((1780, 1791), 'numpy.eye', 'np.eye', (['q_y'], {}), '(q_y)\n', (1786, 1791), True, 'import numpy as np\n'), ((1874, 1895), 'numpy.linalg.pinv', 'np.linalg.pinv', (['H_y.T'], {}), '(H_y.T)\n', (1888, 1895), True, 'import numpy as np\n'), ((1964, 1985), 'numpy.hstack', 'np.hstack', (['(S_1, S_2)'], {}), '((S_1, S_2))\n', (1973, 1985), True, 'import numpy as np\n'), ((3284, 3301), 'numpy.dot', 'np.dot', (['P.T', 'zeta'], {}), '(P.T, zeta)\n', (3290, 3301), True, 'import numpy as np\n'), ((9217, 9228), 'time.time', 'time.time', ([], {}), '()\n', (9226, 9228), False, 'import time\n'), ((9502, 9548), 'numpy.array', 'np.array', (['[Theta.shape[1], delta, a, cpu_time]'], {}), '([Theta.shape[1], delta, a, cpu_time])\n', (9510, 9548), True, 'import numpy as np\n'), ((9607, 9619), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9617, 9619), True, 'import matplotlib.pyplot as plt\n'), ((9639, 9653), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9651, 9653), True, 'import matplotlib.pyplot as plt\n'), ((10994, 11003), 'numpy.eye', 'np.eye', (['(1)'], {}), '(1)\n', (11000, 11003), True, 'import numpy as np\n'), ((11004, 11015), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (11012, 11015), True, 'import numpy as np\n'), ((7591, 7601), 'numpy.eye', 'np.eye', (['qy'], {}), '(qy)\n', (7597, 7601), True, 'import numpy as np\n'), ((9376, 9387), 'time.time', 'time.time', ([], {}), '()\n', (9385, 9387), False, 'import time\n'), ((2283, 2310), 'numpy.zeros', 'np.zeros', (['(psi.shape[0], 1)'], {}), '((psi.shape[0], 1))\n', (2291, 2310), True, 'import numpy as np\n'), ((3220, 3248), 'numpy.ones', 'np.ones', (['(P.P.h.shape[0], 1)'], {}), '((P.P.h.shape[0], 1))\n', (3227, 3248), True, 'import numpy as np\n'), ((8101, 8117), 'numpy.dot', 'np.dot', (['Y', 'Gamma'], {}), '(Y, Gamma)\n', (8107, 8117), True, 'import numpy as np\n'), ((8205, 8221), 'numpy.dot', 'np.dot', (['Y', 'gamma'], {}), '(Y, gamma)\n', (8211, 8221), True, 'import numpy as np\n'), ((8290, 8308), 'numpy.dot', 'np.dot', (['Lambda', 'Hx'], {}), '(Lambda, Hx)\n', (8296, 8308), True, 'import numpy as np\n'), ((8415, 8433), 'numpy.dot', 'np.dot', (['Lambda', 'hx'], {}), '(Lambda, hx)\n', (8421, 8433), True, 'import numpy as np\n'), ((2781, 2802), 'numpy.dot', 'np.dot', (['zonotope.G', 'b'], {}), '(zonotope.G, b)\n', (2787, 2802), True, 'import numpy as np\n'), ((4623, 4650), 'numpy.dot', 'np.dot', (['circumbody.G', 'Gamma'], {}), '(circumbody.G, Gamma)\n', (4629, 4650), True, 'import numpy as np\n'), ((4792, 4820), 'numpy.dot', 'np.dot', (['circumbody.G', 'Lambda'], {}), '(circumbody.G, Lambda)\n', (4798, 4820), True, 'import numpy as np\n'), ((5024, 5070), 'itertools.product', 'product', (['[-1, 1]'], {'repeat': 'Gamma_Lambda.shape[1]'}), '([-1, 1], repeat=Gamma_Lambda.shape[1])\n', (5031, 5070), False, 'from itertools import product\n'), ((5201, 5228), 'numpy.ones', 'np.ones', (['(comb.shape[0], 1)'], {}), '((comb.shape[0], 1))\n', (5208, 5228), True, 'import numpy as np\n'), ((5917, 5939), 'numpy.ones', 'np.ones', (['comb.shape[0]'], {}), '(comb.shape[0])\n', (5924, 5939), True, 'import numpy as np\n'), ((5961, 5983), 'numpy.ones', 'np.ones', (['comb.shape[0]'], {}), '(comb.shape[0])\n', (5968, 5983), True, 'import numpy as np\n'), ((6004, 6027), 'numpy.zeros', 'np.zeros', (['comb.shape[0]'], {}), '(comb.shape[0])\n', (6012, 6027), True, 'import numpy as np\n'), ((6089, 6131), 'numpy.concatenate', 'np.concatenate', (['(Gamma_Lambda[j, :], alfa)'], {}), '((Gamma_Lambda[j, :], alfa))\n', (6103, 6131), True, 'import numpy as np\n'), ((8323, 8340), 'numpy.dot', 'np.dot', (['Hy', 'Gamma'], {}), '(Hy, Gamma)\n', (8329, 8340), True, 'import numpy as np\n'), ((8445, 8464), 'numpy.dot', 'np.dot', (['Theta.T', 'hy'], {}), '(Theta.T, hy)\n', (8451, 8464), True, 'import numpy as np\n'), ((8479, 8496), 'numpy.dot', 'np.dot', (['Hy', 'gamma'], {}), '(Hy, gamma)\n', (8485, 8496), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. """This is a class for MaskTransform.""" import numpy as np import mmcv from vega.core.common.class_factory import ClassFactory, ClassType @ClassFactory.register(ClassType.TRANSFORM) class MaskTransform(object): """Mask tramsform method, which contains. 1. resize masks to expected size and stack to a single array 2. flip the masks (if needed) 3. pad the masks (if needed) """ def __call__(self, masks, pad_shape, scale_factor, flip=False): """Call function of MaskTransform. :param masks: mask image :type masks: ndarray :param pad_shape: (height, width) :type pad_shape: tuple :param scale_factor: the scale factor according to the image tramsform :type scale_factor: float :param flip: whether to flop or not, defaults to False :type flip: bool :return: the mask image after transform :rtype: ndarray """ masks = [ mmcv.imrescale(mask, scale_factor, interpolation='nearest') for mask in masks ] if flip: masks = [mask[:, ::-1] for mask in masks] padded_masks = [ mmcv.impad(mask, pad_shape[:2], pad_val=0) for mask in masks ] padded_masks = np.stack(padded_masks, axis=0) return padded_masks
[ "numpy.stack", "mmcv.imrescale", "mmcv.impad", "vega.core.common.class_factory.ClassFactory.register" ]
[((579, 621), 'vega.core.common.class_factory.ClassFactory.register', 'ClassFactory.register', (['ClassType.TRANSFORM'], {}), '(ClassType.TRANSFORM)\n', (600, 621), False, 'from vega.core.common.class_factory import ClassFactory, ClassType\n'), ((1703, 1733), 'numpy.stack', 'np.stack', (['padded_masks'], {'axis': '(0)'}), '(padded_masks, axis=0)\n', (1711, 1733), True, 'import numpy as np\n'), ((1401, 1460), 'mmcv.imrescale', 'mmcv.imrescale', (['mask', 'scale_factor'], {'interpolation': '"""nearest"""'}), "(mask, scale_factor, interpolation='nearest')\n", (1415, 1460), False, 'import mmcv\n'), ((1609, 1651), 'mmcv.impad', 'mmcv.impad', (['mask', 'pad_shape[:2]'], {'pad_val': '(0)'}), '(mask, pad_shape[:2], pad_val=0)\n', (1619, 1651), False, 'import mmcv\n')]
import csv import os import numpy as np import sentencepiece as spm import torch class DataLoader: def __init__(self, directory, parts, cols, spm_filename): """Dataset loader. Args: directory (str): dataset directory. parts (list[str]): dataset parts. [parts].tsv files must exists in dataset directory. spm_filename (str): file name of the dump sentencepiece model. """ self.pad_idx, self.unk_idx, self.sos_idx, self.eos_idx = range(4) self.cols = cols self.directory = directory self.parts = parts self.spm_filename = spm_filename # Load sentecepiece model: self.sp = spm.SentencePieceProcessor() self.sp.load(self.spm_filename) # Load dataset parts: self.data_parts = {part: list(self.from_tsv(part)) for part in parts} self.part_lens = {part: len(self.data_parts[part]) for part in parts} self.max_lens = {part: self.get_max_len(part) for part in parts} self.max_len = max([self.max_lens[part] for part in parts]) def next_batch(self, batch_size, part, device): """Get next batch. Args: batch_size (int): batch size. part (str): dataset part. device (torch.device): torch device. Returns: Batch: batch wrapper. """ indexes = np.random.randint(0, self.part_lens[part], batch_size) raw_batches = [[self.data_parts[part][i][col] for i in indexes] for col, name in enumerate(self.cols)] return Batch(self, raw_batches, device) def sequential(self, part, device): """Get all examples from dataset sequential. Args: part (str): part of the dataset. device: (torch.Device): torch device. Returns: Batch: batch wrapper with size 1. """ for example in self.data_parts[part]: raw_batches = [example] yield Batch(self, raw_batches, device) def pad(self, data): """Add <sos>, <eos> tags and pad sequences from batch Args: data (list[list[int]]): token indexes Returns: list[list[int]]: padded list of sizes (batch, max_seq_len + 2) """ data = list(map(lambda x: [self.sos_idx] + x + [self.eos_idx], data)) lens = [len(s) for s in data] max_len = max(lens) for i, length in enumerate(lens): to_add = max_len - length data[i] += [self.pad_idx] * to_add return data, lens def from_tsv(self, part): """Read and tokenize data from TSV file. Args: part (str): the name of the part. Yields: (list[int], list[int]): pairs for each example in dataset. """ filename = os.path.join(self.directory, part + '.tsv') with open(filename) as file: reader = csv.reader(file, delimiter='\t') for row in reader: yield tuple(self.sp.EncodeAsIds(row[i]) for i, col in enumerate(self.cols)) def decode(self, data): """Decode encoded sentence tensor. Args: data (torch.Tensor): sentence tensor. Returns: list[str]: decoded sentences. """ return [self.sp.DecodeIds([token.item() for token in sentence]) for sentence in data] def decode_raw(self, data): """Decode encoded sentence tensor without removing auxiliary symbols. Args: data (torch.Tensor): sentence tensor. Returns: list[str]: decoded sentences. """ return [''.join([self.sp.IdToPiece(token.item()) for token in sentence]) for sentence in data] def get_max_len(self, part): lens = [] for example in self.data_parts[part]: for col in example: lens.append(len(col)) return max(lens) + 2 class Batch: def __init__(self, data_loader, raw_batches, device): """Simple batch wrapper. Args: data_loader (DataLoader): data loader object. raw_batches (list[data]): raw data batches. device (torch.device): torch device. Variables: - **cols_name_length** (list[int]): lengths of `cols_name` sequences. - **cols_name** (torch.Tensor): long tensor of `cols_name` sequences. """ for i, col in enumerate(data_loader.cols): tensor, length = data_loader.pad(raw_batches[i]) self.__setattr__(col, torch.tensor(tensor, dtype=torch.long, device=device)) self.__setattr__(col + '_length', length)
[ "sentencepiece.SentencePieceProcessor", "os.path.join", "torch.tensor", "numpy.random.randint", "csv.reader" ]
[((697, 725), 'sentencepiece.SentencePieceProcessor', 'spm.SentencePieceProcessor', ([], {}), '()\n', (723, 725), True, 'import sentencepiece as spm\n'), ((1401, 1455), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.part_lens[part]', 'batch_size'], {}), '(0, self.part_lens[part], batch_size)\n', (1418, 1455), True, 'import numpy as np\n'), ((2860, 2903), 'os.path.join', 'os.path.join', (['self.directory', "(part + '.tsv')"], {}), "(self.directory, part + '.tsv')\n", (2872, 2903), False, 'import os\n'), ((2962, 2994), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '"""\t"""'}), "(file, delimiter='\\t')\n", (2972, 2994), False, 'import csv\n'), ((4638, 4691), 'torch.tensor', 'torch.tensor', (['tensor'], {'dtype': 'torch.long', 'device': 'device'}), '(tensor, dtype=torch.long, device=device)\n', (4650, 4691), False, 'import torch\n')]
import concurrent.futures import time import pandas as pd import numpy as np from tfce_toolbox.tfce_computation import tfce_from_distribution, tfces_from_distributions_st, \ tfces_from_distributions_mt import tfce_toolbox.quicker_raw_value def analyze(data_file, dv, seed): print("go " + data_file) time_overall = time.time() rng = np.random.default_rng(seed) data_frame = pd.read_csv('data/' + data_file, sep="\t") # analyzer = tfce_toolbox.two_by_two_f.TwoByTwoFMultiProcess(dv=dv, within1="condition_tdcs", # within2="condition_time", # subject="subject", n_workers=8) analyzer = tfce_toolbox.quicker_raw_value.QuickerRawValueSingleProcess(dv=dv, datapoint_name="datapoint") print("Computing actual list of values") t = time.time() values = analyzer.compute_values(data_frame) print("Done in {} seconds.".format(time.time() - t)) datapoints_list = data_frame.loc[:, "datapoint"].unique().tolist() output_data = {"datapoint": datapoints_list, "value": values} print("Computing actual TFCE values") t = time.time() actual_tfce = tfce_from_distribution(values) print("Done in {} seconds.".format(time.time() - t)) output_data["tfce"] = actual_tfce print("Generating {} resamplings for {} datapoints".format(n_resamplings, len(datapoints_list))) t = time.time() rs_values = analyzer.resample_and_compute_values(values, n_resamplings) print("Done in {} seconds.".format(time.time() - t)) print("Computing max tfce values for resamplings") resampled_tfce_tdcs = tfces_from_distributions_mt(rs_values, n_workers=7) t = time.time() max_tfce = [] min_tfce = [] for tfce in resampled_tfce_tdcs: max_tfce.append(max(tfce)) min_tfce.append(min(tfce)) print("Done in {} seconds.".format(time.time() - t)) # now, check for significance upper_tfce = np.percentile(max_tfce, 100 * (1 - (alpha / 2.0))) lower_tfce = np.percentile(min_tfce, 100 * (alpha / 2.0)) significance = [] for i in range(len(datapoints_list)): if lower_tfce <= actual_tfce[i] <= upper_tfce: significance.append(0) else: significance.append(1) output_data["sig"] = significance output_data = pd.DataFrame(output_data) output_data.to_csv("outputs/tfce_" + data_file.split('.')[0] + ".tsv", header=True, index=False, sep="\t") print("done {} in {} seconds.".format(data_file, time.time() - time_overall)) if __name__ == "__main__": n_resamplings = 600 n_workers = 8 # each worker will process n_resamplings // n_workers tasks alpha = 0.05 seed = 42 inputFiles = [] subjects = range(1, 11) # analyses = ["3_f"] dv = "local_o" # this logic only creates the data files to be analyzed. It can be changed at will. for subject in subjects: fileName = "subject_" + str(subject) + ".tsv" inputFiles.append(fileName) counter = 0 for data_file in inputFiles: analyze(data_file, dv, seed + counter) counter += 1
[ "tfce_toolbox.tfce_computation.tfce_from_distribution", "numpy.random.default_rng", "pandas.read_csv", "tfce_toolbox.tfce_computation.tfces_from_distributions_mt", "pandas.DataFrame", "numpy.percentile", "time.time" ]
[((330, 341), 'time.time', 'time.time', ([], {}), '()\n', (339, 341), False, 'import time\n'), ((352, 379), 'numpy.random.default_rng', 'np.random.default_rng', (['seed'], {}), '(seed)\n', (373, 379), True, 'import numpy as np\n'), ((397, 439), 'pandas.read_csv', 'pd.read_csv', (["('data/' + data_file)"], {'sep': '"""\t"""'}), "('data/' + data_file, sep='\\t')\n", (408, 439), True, 'import pandas as pd\n'), ((887, 898), 'time.time', 'time.time', ([], {}), '()\n', (896, 898), False, 'import time\n'), ((1193, 1204), 'time.time', 'time.time', ([], {}), '()\n', (1202, 1204), False, 'import time\n'), ((1223, 1253), 'tfce_toolbox.tfce_computation.tfce_from_distribution', 'tfce_from_distribution', (['values'], {}), '(values)\n', (1245, 1253), False, 'from tfce_toolbox.tfce_computation import tfce_from_distribution, tfces_from_distributions_st, tfces_from_distributions_mt\n'), ((1459, 1470), 'time.time', 'time.time', ([], {}), '()\n', (1468, 1470), False, 'import time\n'), ((1686, 1737), 'tfce_toolbox.tfce_computation.tfces_from_distributions_mt', 'tfces_from_distributions_mt', (['rs_values'], {'n_workers': '(7)'}), '(rs_values, n_workers=7)\n', (1713, 1737), False, 'from tfce_toolbox.tfce_computation import tfce_from_distribution, tfces_from_distributions_st, tfces_from_distributions_mt\n'), ((1746, 1757), 'time.time', 'time.time', ([], {}), '()\n', (1755, 1757), False, 'import time\n'), ((2010, 2058), 'numpy.percentile', 'np.percentile', (['max_tfce', '(100 * (1 - alpha / 2.0))'], {}), '(max_tfce, 100 * (1 - alpha / 2.0))\n', (2023, 2058), True, 'import numpy as np\n'), ((2078, 2122), 'numpy.percentile', 'np.percentile', (['min_tfce', '(100 * (alpha / 2.0))'], {}), '(min_tfce, 100 * (alpha / 2.0))\n', (2091, 2122), True, 'import numpy as np\n'), ((2384, 2409), 'pandas.DataFrame', 'pd.DataFrame', (['output_data'], {}), '(output_data)\n', (2396, 2409), True, 'import pandas as pd\n'), ((987, 998), 'time.time', 'time.time', ([], {}), '()\n', (996, 998), False, 'import time\n'), ((1293, 1304), 'time.time', 'time.time', ([], {}), '()\n', (1302, 1304), False, 'import time\n'), ((1586, 1597), 'time.time', 'time.time', ([], {}), '()\n', (1595, 1597), False, 'import time\n'), ((1940, 1951), 'time.time', 'time.time', ([], {}), '()\n', (1949, 1951), False, 'import time\n'), ((2574, 2585), 'time.time', 'time.time', ([], {}), '()\n', (2583, 2585), False, 'import time\n')]
#!/bin/env python3 import cv2 as cv import numpy as np import argparse import tuner.tuner as tuner def scale(img): img = np.absolute(img) return np.uint8(255 * (img / np.max(img))) def ths(img, ths_min, ths_max): ret = np.zeros_like(img) ret[(img >= ths_min) & (img <= ths_max)] = 255 return ret def gradient_component(img, t, ths_min, ths_max, k_size): k_size = k_size + (k_size + 1) % 2 if t == 'x': return ths(scale(cv.Sobel( src = img, ddepth = cv.CV_64F, dx = 1, dy = 0, ksize = k_size )), ths_min, ths_max) return ths(scale(cv.Sobel( src = img, ddepth = cv.CV_64F, dx = 0, dy = 1, ksize = k_size )), ths_min, ths_max) def process(image, args): adj_k = lambda ksize : ksize + (ksize + 1) % 2 gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) gradient_x = gradient_component(gray, 'x', args.ths_min, args.ths_max, adj_k(args.kernel_size)) gradient_y = gradient_component(gray, 'y', args.ths_min, args.ths_max, adj_k(args.kernel_size)) return ((1, 2), [gradient_x, gradient_y]) CFG = [ ['kernel_size', 3, 30], ['ths_min', 20, 255], ['ths_max', 100, 255], ] if __name__ == '__main__': tuner.Tuner_App( process, CFG, 'Gradient XY', 'Tune gradient X and Y components parameters', )
[ "tuner.tuner.Tuner_App", "numpy.absolute", "numpy.max", "cv2.cvtColor", "numpy.zeros_like", "cv2.Sobel" ]
[((128, 144), 'numpy.absolute', 'np.absolute', (['img'], {}), '(img)\n', (139, 144), True, 'import numpy as np\n'), ((236, 254), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (249, 254), True, 'import numpy as np\n'), ((875, 912), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'cv.COLOR_BGR2GRAY'], {}), '(image, cv.COLOR_BGR2GRAY)\n', (886, 912), True, 'import cv2 as cv\n'), ((1285, 1380), 'tuner.tuner.Tuner_App', 'tuner.Tuner_App', (['process', 'CFG', '"""Gradient XY"""', '"""Tune gradient X and Y components parameters"""'], {}), "(process, CFG, 'Gradient XY',\n 'Tune gradient X and Y components parameters')\n", (1300, 1380), True, 'import tuner.tuner as tuner\n'), ((647, 708), 'cv2.Sobel', 'cv.Sobel', ([], {'src': 'img', 'ddepth': 'cv.CV_64F', 'dx': '(0)', 'dy': '(1)', 'ksize': 'k_size'}), '(src=img, ddepth=cv.CV_64F, dx=0, dy=1, ksize=k_size)\n', (655, 708), True, 'import cv2 as cv\n'), ((178, 189), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (184, 189), True, 'import numpy as np\n'), ((463, 524), 'cv2.Sobel', 'cv.Sobel', ([], {'src': 'img', 'ddepth': 'cv.CV_64F', 'dx': '(1)', 'dy': '(0)', 'ksize': 'k_size'}), '(src=img, ddepth=cv.CV_64F, dx=1, dy=0, ksize=k_size)\n', (471, 524), True, 'import cv2 as cv\n')]
# -*- coding: utf-8 -*- import os from PIL import Image, ImageFont, ImageDraw import tensorflow as tf import numpy as np import pickle def getJp(): count = 0 char_vocab = [] shape_vocab = [] char_shape = {} for line in open("joyo2010.txt").readlines(): if line[0] == "#": continue text = line[0] im = Image.new("1", (28,28), 0) dr = ImageDraw.Draw(im) font = ImageFont.truetype("/usr/share/fonts/truetype/takao-mincho/TakaoPMincho.ttf", 28) dr.text((0, 0), text, font=font, fill=1) im.save("1.jpg") img = np.array(im, dtype="int32") char_vocab.append(text) shape_vocab.append(img) char_shape[text] = img count += 0 shape_vocab_data = { "chars": char_vocab, "shapes": shape_vocab, "char_shape": char_shape } with open("jp_shape_vocab.pickle", "wb") as f: pickle._dump(shape_vocab_data, f) def getCh(): count = 0 char_vocab = [] shape_vocab = [] char_shape = {} def getShapes(filename, char_vocab, shape_vocab, char_shape, count): for line in open(filename).readlines(): line = line.split() if len(line)<2: continue text = line[1][0] im = Image.new("1", (28,28), 0) dr = ImageDraw.Draw(im) font = ImageFont.truetype("/usr/share/fonts/opentype/noto/NotoSansCJK-Light.ttc", 28) dr.text((0, -7), text, font=font, fill=1) im.save("ch_shape_jpg/"+text+".jpg") img = np.array(im, dtype="int32") char_vocab.append(text) shape_vocab.append(img) char_shape[text] = img count += 0 getShapes("../cjkvi-tables/zibiao2009-1.txt", char_vocab, shape_vocab, char_shape, count) getShapes("../cjkvi-tables/zibiao2009-2.txt", char_vocab, shape_vocab, char_shape, count) print("Read {number} character shapes.".format(number=len(char_vocab))) shape_vocab_data = { "chars": char_vocab, "shapes": shape_vocab, "char_shape": char_shape } with open("ch_shape_vocab.pickle", "wb") as f: pickle._dump(shape_vocab_data, f) if __name__ == "__main__": getCh()
[ "PIL.Image.new", "PIL.ImageFont.truetype", "numpy.array", "PIL.ImageDraw.Draw", "pickle._dump" ]
[((359, 386), 'PIL.Image.new', 'Image.new', (['"""1"""', '(28, 28)', '(0)'], {}), "('1', (28, 28), 0)\n", (368, 386), False, 'from PIL import Image, ImageFont, ImageDraw\n'), ((399, 417), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['im'], {}), '(im)\n', (413, 417), False, 'from PIL import Image, ImageFont, ImageDraw\n'), ((433, 518), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""/usr/share/fonts/truetype/takao-mincho/TakaoPMincho.ttf"""', '(28)'], {}), "('/usr/share/fonts/truetype/takao-mincho/TakaoPMincho.ttf',\n 28)\n", (451, 518), False, 'from PIL import Image, ImageFont, ImageDraw\n'), ((603, 630), 'numpy.array', 'np.array', (['im'], {'dtype': '"""int32"""'}), "(im, dtype='int32')\n", (611, 630), True, 'import numpy as np\n'), ((928, 961), 'pickle._dump', 'pickle._dump', (['shape_vocab_data', 'f'], {}), '(shape_vocab_data, f)\n', (940, 961), False, 'import pickle\n'), ((2192, 2225), 'pickle._dump', 'pickle._dump', (['shape_vocab_data', 'f'], {}), '(shape_vocab_data, f)\n', (2204, 2225), False, 'import pickle\n'), ((1305, 1332), 'PIL.Image.new', 'Image.new', (['"""1"""', '(28, 28)', '(0)'], {}), "('1', (28, 28), 0)\n", (1314, 1332), False, 'from PIL import Image, ImageFont, ImageDraw\n'), ((1349, 1367), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['im'], {}), '(im)\n', (1363, 1367), False, 'from PIL import Image, ImageFont, ImageDraw\n'), ((1387, 1465), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""/usr/share/fonts/opentype/noto/NotoSansCJK-Light.ttc"""', '(28)'], {}), "('/usr/share/fonts/opentype/noto/NotoSansCJK-Light.ttc', 28)\n", (1405, 1465), False, 'from PIL import Image, ImageFont, ImageDraw\n'), ((1587, 1614), 'numpy.array', 'np.array', (['im'], {'dtype': '"""int32"""'}), "(im, dtype='int32')\n", (1595, 1614), True, 'import numpy as np\n')]
#!/usr/bin/env python ''' Calculate the RNA-seq reads coverage over gene body. This module uses bigwig file as input. ''' #import built-in modules import os,sys if sys.version_info[0] != 2 or sys.version_info[1] != 7: print >>sys.stderr, "\nYou are using python" + str(sys.version_info[0]) + '.' + str(sys.version_info[1]) + " RSeQC needs python2.7!\n" sys.exit() import re import string from optparse import OptionParser import warnings import string import collections import math import sets from time import strftime import subprocess #import third-party modules import numpy as np from bx.bitset import * from bx.bitset_builders import * from bx.intervals import * from bx.bbi.bigwig_file import BigWigFile #import my own modules from qcmodule import SAM from qcmodule import mystat #changes to the paths __author__ = "<NAME>" __copyright__ = "Copyleft" __credits__ = [] __license__ = "GPL" __version__="2.6.4" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" def coverageGeneBody_bigwig(bigFile,refbed,outfile,gtype="png"): '''Calculate reads coverage over gene body, from 5'to 3'. each gene will be equally divided into 100 regsions. bigFile is bigwig format file''' if refbed is None: print >>sys.stderr,"You must specify a bed file representing gene model\n" exit(0) OUT1 = open(outfile + ".geneBodyCoverage_plot.r",'w') OUT2 = open(outfile + ".geneBodyCoverage.txt",'w') bw = BigWigFile( file = open(bigFile) ) print >>sys.stderr, "calculating coverage over gene body ..." coverage=collections.defaultdict(int) flag=0 gene_count = 0 for line in open(refbed,'r'): try: if line.startswith(('#','track','browser')):continue gene_count += 1 # Parse fields from gene tabls fields = line.split() chrom = fields[0] tx_start = int( fields[1] ) tx_end = int( fields[2] ) geneName = fields[3] strand = fields[5] exon_starts = map( int, fields[11].rstrip( ',\n' ).split( ',' ) ) exon_starts = map((lambda x: x + tx_start ), exon_starts) exon_ends = map( int, fields[10].rstrip( ',\n' ).split( ',' ) ) exon_ends = map((lambda x, y: x + y ), exon_starts, exon_ends); except: print >>sys.stderr,"[NOTE:input bed must be 12-column] skipped this line: " + line, continue gene_all_base=[] percentile_base=[] mRNA_len =0 flag=0 for st,end in zip(exon_starts,exon_ends): gene_all_base.extend(range(st+1,end+1)) #0-based coordinates on genome mRNA_len = len(gene_all_base) if mRNA_len <100: flag=1 break if flag==1: continue if strand == '-': gene_all_base.sort(reverse=True) #deal with gene on minus stand else: gene_all_base.sort(reverse=False) percentile_base = mystat.percentile_list (gene_all_base) #get 101 points from each gene's coordinates for i in range(0,len(percentile_base)): #try: sig = bw.get_as_array(chrom,percentile_base[i]-1,percentile_base[i]) if sig is None:continue coverage[i] += np.nan_to_num(sig[0]) #except: # continue print >>sys.stderr, " %d genes finished\r" % gene_count, x_coord=[] y_coord=[] print >>OUT2, "percentile\tcount" for i in coverage: x_coord.append(str(i)) y_coord.append(str(coverage[i])) print >>OUT2, str(i) + '\t' + str(coverage[i]) print >>OUT1, "%s(\'%s\')" % (gtype, outfile + ".geneBodyCoverage." + gtype) print >>OUT1, "x=1:100" print >>OUT1, "y=c(" + ','.join(y_coord) + ')' print >>OUT1, "plot(x,y/%s,xlab=\"percentile of gene body (5'->3')\",ylab='average wigsum',type='s')" % gene_count print >>OUT1, "dev.off()" def main(): usage="%prog [options]" + '\n' + __doc__ + "\n" parser = OptionParser(usage,version="%prog " + __version__) parser.add_option("-i","--input-file",action="store",type="string",dest="input_file",help="Coverage signal file in bigwig format") parser.add_option("-r","--refgene",action="store",type="string",dest="ref_gene_model",help="Reference gene model in bed format. [required]") parser.add_option("-o","--out-prefix",action="store",type="string",dest="output_prefix",help="Prefix of output files(s). [required]") parser.add_option("-t","--graph-type",action="store",type="string",dest="graph_type",default="pdf",help="Graphic file type in \"pdf\", \"jpeg\", \"bmp\", \"bmp\", \"tiff\" or \"png\".default=%default [optional]") (options,args)=parser.parse_args() gt = options.graph_type.lower() if gt not in ("pdf","png",'bmp','jpeg','tiff'): print >>sys.stderr, "graphic file type must be 'pdf' or 'png'" parser.print_help() sys.exit(0) if not (options.output_prefix and options.input_file and options.ref_gene_model): parser.print_help() sys.exit(0) if not os.path.exists(options.ref_gene_model): print >>sys.stderr, '\n\n' + options.ref_gene_model + " does NOT exists" + '\n' #parser.print_help() sys.exit(0) if os.path.exists(options.input_file): coverageGeneBody_bigwig(options.input_file,options.ref_gene_model,options.output_prefix,gtype=options.graph_type) try: subprocess.call("Rscript " + options.output_prefix + '.geneBodyCoverage_plot.r',shell=True) except: print >>sys.stderr, "Cannot generate plot from " + options.output_prefix + '.geneBodyCoverage_plot.r' pass else: print >>sys.stderr, '\n\n' + options.input_file + " does NOT exists" + '\n' #parser.print_help() sys.exit(0) if __name__ == '__main__': main()
[ "os.path.exists", "optparse.OptionParser", "collections.defaultdict", "qcmodule.mystat.percentile_list", "subprocess.call", "sys.exit", "numpy.nan_to_num" ]
[((356, 366), 'sys.exit', 'sys.exit', ([], {}), '()\n', (364, 366), False, 'import os, sys\n'), ((1539, 1567), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (1562, 1567), False, 'import collections\n'), ((3656, 3707), 'optparse.OptionParser', 'OptionParser', (['usage'], {'version': "('%prog ' + __version__)"}), "(usage, version='%prog ' + __version__)\n", (3668, 3707), False, 'from optparse import OptionParser\n'), ((4841, 4875), 'os.path.exists', 'os.path.exists', (['options.input_file'], {}), '(options.input_file)\n', (4855, 4875), False, 'import os, sys\n'), ((2733, 2770), 'qcmodule.mystat.percentile_list', 'mystat.percentile_list', (['gene_all_base'], {}), '(gene_all_base)\n', (2755, 2770), False, 'from qcmodule import mystat\n'), ((4538, 4549), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (4546, 4549), False, 'import os, sys\n'), ((4657, 4668), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (4665, 4668), False, 'import os, sys\n'), ((4678, 4716), 'os.path.exists', 'os.path.exists', (['options.ref_gene_model'], {}), '(options.ref_gene_model)\n', (4692, 4716), False, 'import os, sys\n'), ((4825, 4836), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (4833, 4836), False, 'import os, sys\n'), ((5328, 5339), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (5336, 5339), False, 'import os, sys\n'), ((2989, 3010), 'numpy.nan_to_num', 'np.nan_to_num', (['sig[0]'], {}), '(sig[0])\n', (3002, 3010), True, 'import numpy as np\n'), ((5003, 5099), 'subprocess.call', 'subprocess.call', (["('Rscript ' + options.output_prefix + '.geneBodyCoverage_plot.r')"], {'shell': '(True)'}), "('Rscript ' + options.output_prefix +\n '.geneBodyCoverage_plot.r', shell=True)\n", (5018, 5099), False, 'import subprocess\n')]
import numpy as np import csv def read_ages_contact_matrix(country, n_ages): """Create a country-specific contact matrix from stored data. Read a stored contact matrix based on age intervals. Return a matrix of expected number of contacts for each pair of raw ages. Extrapolate to age ranges that are not covered. Args: country (str): country name. Returns: float n_ages x n_ages matrix: expected number of contacts between of a person of age i and age j is Poisson(matrix[i][j]). """ contact_matrix_age_groups_dict = { 'infected_1': '0-4', 'contact_1': '0-4', 'infected_2': '5-9', 'contact_2': '5-9', 'infected_3': '10-14', 'contact_3': '10-14', 'infected_4': '15-19', 'contact_4': '15-19', 'infected_5': '20-24', 'contact_5': '20-24', 'infected_6': '25-29', 'contact_6': '25-29', 'infected_7': '30-34', 'contact_7': '30-34', 'infected_8': '35-39', 'contact_8': '35-39', 'infected_9': '40-44', 'contact_9': '40-44', 'infected_10': '45-49', 'contact_10': '45-49', 'infected_11': '50-54', 'contact_11': '50-54', 'infected_12': '55-59', 'contact_12': '55-59', 'infected_13': '60-64', 'contact_13': '60-64', 'infected_14': '65-69', 'contact_14': '65-69', 'infected_15': '70-74', 'contact_15': '70-74', 'infected_16': '75-79', 'contact_16': '75-79'} matrix = np.zeros((n_ages, n_ages)) with open('Contact_Matrices/{}/All_{}.csv'.format(country, country), 'r') as f: csvraw = list(csv.reader(f)) col_headers = csvraw[0][1:-1] row_headers = [row[0] for row in csvraw[1:]] data = np.array([row[1:-1] for row in csvraw[1:]]) for i in range(len(row_headers)): for j in range(len(col_headers)): interval_infected = contact_matrix_age_groups_dict[row_headers[i]] interval_infected = [int(x) for x in interval_infected.split('-')] interval_contact = contact_matrix_age_groups_dict[col_headers[j]] interval_contact = [int(x) for x in interval_contact.split('-')] for age_infected in range(interval_infected[0], interval_infected[1]+1): for age_contact in range(interval_contact[0], interval_contact[1]+1): matrix[age_infected, age_contact] = float(data[i][j])/(interval_contact[1] - interval_contact[0] + 1) # extrapolate from 79yo out to 100yo # start by fixing the age of the infected person and then assuming linear decrease # in their number of contacts of a given age, following the slope of the largest # pair of age brackets that doesn't contain a diagonal term (since those are anomalously high) for i in range(interval_infected[1]+1): if i < 65: # 0-65 slope = (matrix[i, 70] - matrix[i, 75])/5 elif i < 70: # 65-70 slope = (matrix[i, 55] - matrix[i, 60])/5 elif i < 75: # 70-75 slope = (matrix[i, 60] - matrix[i, 65])/5 else: # 75-80 slope = (matrix[i, 65] - matrix[i, 70])/5 start_age = 79 if i >= 75: start_age = 70 for j in range(interval_contact[1]+1, n_ages): matrix[i, j] = matrix[i, start_age] - slope*(j - start_age) if matrix[i, j] < 0: matrix[i, j] = 0 # fix diagonal terms for i in range(interval_infected[1]+1, n_ages): matrix[i] = matrix[interval_infected[1]] for i in range(int((100-80)/5)): age = 80 + i*5 matrix[age:age+5, age:age+5] = matrix[79, 79] matrix[age:age+5, 75:80] = matrix[75, 70] matrix[100, 95:] = matrix[79, 79] matrix[95:, 100] = matrix[79, 79] return matrix
[ "numpy.array", "numpy.zeros", "csv.reader" ]
[((1377, 1403), 'numpy.zeros', 'np.zeros', (['(n_ages, n_ages)'], {}), '((n_ages, n_ages))\n', (1385, 1403), True, 'import numpy as np\n'), ((1619, 1662), 'numpy.array', 'np.array', (['[row[1:-1] for row in csvraw[1:]]'], {}), '([row[1:-1] for row in csvraw[1:]])\n', (1627, 1662), True, 'import numpy as np\n'), ((1510, 1523), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1520, 1523), False, 'import csv\n')]
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler ## Here we have consider last N days as training data for today's predict values ## X=[[1,......,100],[2,.....,101]] ## Y=[ 101st day, 102 ] def previous_data(data,prev_days): """ Return: numpy array of train and test set ---------------------- Parameters: data: numpy array of train data prev_days: number of previos days to consier for prediction """ X,Y=[],[] for i in range(len(data)-prev_days-1): previous=data[i:i+prev_days,0] X.append(previous) Y.append(data[i+prev_days,0]) return np.array(X),np.array(Y) def read_data(filename): """ Return: pandas dataframe --------------------- Parameters: filename: csv file to read """ df = pd.read_csv(filename) return df def transform_data(filename1, filename2): """ Return: train and test set in format required by LSTM model -------------------- Parameters: filename1: train_data filename filename2: test_data filename """ df_train = read_data(filename1) df_test = read_data(filename2) # Normalizing the dataset in range 0,1 scaler = MinMaxScaler(feature_range=(0,1)) df_train_close = df_train['close'] df_train_close = scaler.fit_transform(np.array(df_train_close).reshape(-1,1)) df_test_close = df_test['close'] df_test_close = scaler.fit_transform(np.array(df_test_close).reshape(-1,1)) X_train,Y_train = previous_data(df_train_close,300) X_test,Y_test = previous_data(df_test_close,300) ## Reshaping data for LSTM X_train = X_train.reshape(X_train.shape[0],X_train.shape[1],1) X_test = X_test.reshape(X_test.shape[0],X_test.shape[1],1) return (X_train, X_test, Y_train, Y_test)
[ "numpy.array", "sklearn.preprocessing.MinMaxScaler", "pandas.read_csv" ]
[((852, 873), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (863, 873), True, 'import pandas as pd\n'), ((1251, 1285), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (1263, 1285), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((675, 686), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (683, 686), True, 'import numpy as np\n'), ((687, 698), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (695, 698), True, 'import numpy as np\n'), ((1366, 1390), 'numpy.array', 'np.array', (['df_train_close'], {}), '(df_train_close)\n', (1374, 1390), True, 'import numpy as np\n'), ((1485, 1508), 'numpy.array', 'np.array', (['df_test_close'], {}), '(df_test_close)\n', (1493, 1508), True, 'import numpy as np\n')]
"""Performs naive Bayes on the data from a given subreddit. """ import math import datetime import pandas as pd from sklearn.naive_bayes import MultinomialNB import numpy as np import bag_of_words as bow import sentimentAnalyzer as sa MODEL = MultinomialNB() def extract_features(data_frame: pd.DataFrame) -> pd.DataFrame: """Obtains training features from the data frame containing subreddit data. Params: - data_frame (pd.DataFrame): data frame containing subreddit data Returns: - features (pd.DataFrame): the training features returned by the data frame """ title_bow = bow.bag_of_words(data_frame, 'title') selftext_bow = bow.bag_of_words(data_frame, 'selftext') title_sentiments = sa.analyzeSentiments(data_frame, 'title') selftext_sentiments = sa.analyzeSentiments(data_frame, 'selftext') post_time = timeofday(data_frame, 'created_utc') features = pd.concat([ title_bow, selftext_bow, title_sentiments, selftext_sentiments, post_time ], axis=1) print(features.head()) return features # End of extract_features() def get_quartiles(scores: []) -> []: """Gets the quartile boundaries for the given array of scores. Params: - scores ([int]): array of integer scores of the posts Returns: - quartiles ([int]): an array of the 3 quartile boundaries (for q1|q2|q3|q4) """ s = np.array(scores).astype(np.float) q1 = math.floor(np.percentile(s, 25)) q2 = math.floor(np.percentile(s, 50)) q3 = math.floor(np.percentile(s, 75)) print("Q1 | Q2 | Q3 | Q4") print(" " + str(q1) + " " + str(q2) + " " + str(q3)) return [q1,q2,q3] # End of get_quartiles() def extract_targets(scores: [], quartiles: []) -> []: """Gets the quartile targets for the given array of scores. Params: - scores ([int]): array of integer scores of the posts - quartiles ([int]): an array of the 3 quartile boundaries (for q1|q2|q3|q4) Returns: - targets ([int]): array of which quartile each post belongs in """ targets = [None] * len(scores) q1 = quartiles[0] q2 = quartiles[1] q3 = quartiles[2] for i in range(0, len(scores)): score = int(scores[i]) if score < q1: targets[i] = 1 elif score < q2: targets[i] = 2 elif score < q3: targets[i] = 3 else: targets[i] = 4 # end for loop return targets # End of extract_targets() def classify(data_frame: pd.DataFrame): """Performs naive Bayes classification on the data in a data frame. Params: - data_frame (pd.DataFrame): data frame containing subreddit data Categories: - 1: 1st Quartile - 2: 2nd Quartile - 3: 3rd Quartile - 4: 4th Quartile """ data_frame = data_frame.sample(frac=1).reset_index(drop=True) features = extract_features(data_frame) num_rows = len(features.index) separator = math.floor(0.8 * num_rows) train_X = features.loc[:separator].values test_X = features.loc[separator:].values quartiles = get_quartiles(data_frame.loc[:separator, 'score'].values) train_Y = extract_targets(data_frame.loc[:separator, 'score'].values, quartiles) test_Y = extract_targets(data_frame.loc[separator:, 'score'].values, quartiles) model = MODEL.fit(train_X, train_Y) predicted = list(model.predict(test_X)) chart = [[0 for x in range(4)] for y in range(4)] # Chart with x = actual, y = predicted for x in range(0, len(test_Y)): chart[test_Y[x] - 1][predicted[x] - 1] += 1 # End for loop print("------------------------------------") print(" <25 <50 <75 <100") print("------------------------------------") for x in range(0, 4): line = "<" + str((x+1)*25) + " | " for y in range(0, 4): line += str(chart[x][y]) + " " # End y print(line) # End x score = model.score(test_X, test_Y) print("Accuracy = (%% accuracy against test data by model) = {}".format(score)) # End of regress() def timeofday(data_frame: pd.DataFrame, column: str) -> pd.DataFrame: """Creates a sentiments data frame out of the text in the given column of the data frame. Params: - data_frame (pd.DataFrame): The data frame containing text data - column (str): The name of the column for which to analyze the sentiment Returns: - sentiments_data_frame (pd.DataFrame): The data frame containing the sentiment for each item in the given column. Note that sentiments are from 0 to 2, with 1 being neutral, 0 being negative, and 2 being positive. """ data_frame_copy = data_frame.copy() column_data = data_frame_copy[column] column_data = column_data.apply(lambda a: datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S").hour) print(column_data) entries = column_data.values.tolist() res_data_frame = pd.DataFrame(entries, columns=["sentiment"]) return res_data_frame # End of analyzeSentiments() if __name__ == "__main__": args = bow.parse_arguments() data_frame = bow.csv_to_data_frame(args.subreddit) classify(data_frame)
[ "math.floor", "bag_of_words.bag_of_words", "datetime.datetime.strptime", "bag_of_words.csv_to_data_frame", "numpy.array", "sklearn.naive_bayes.MultinomialNB", "sentimentAnalyzer.analyzeSentiments", "bag_of_words.parse_arguments", "pandas.DataFrame", "numpy.percentile", "pandas.concat" ]
[((246, 261), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {}), '()\n', (259, 261), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((608, 645), 'bag_of_words.bag_of_words', 'bow.bag_of_words', (['data_frame', '"""title"""'], {}), "(data_frame, 'title')\n", (624, 645), True, 'import bag_of_words as bow\n'), ((665, 705), 'bag_of_words.bag_of_words', 'bow.bag_of_words', (['data_frame', '"""selftext"""'], {}), "(data_frame, 'selftext')\n", (681, 705), True, 'import bag_of_words as bow\n'), ((729, 770), 'sentimentAnalyzer.analyzeSentiments', 'sa.analyzeSentiments', (['data_frame', '"""title"""'], {}), "(data_frame, 'title')\n", (749, 770), True, 'import sentimentAnalyzer as sa\n'), ((797, 841), 'sentimentAnalyzer.analyzeSentiments', 'sa.analyzeSentiments', (['data_frame', '"""selftext"""'], {}), "(data_frame, 'selftext')\n", (817, 841), True, 'import sentimentAnalyzer as sa\n'), ((910, 1008), 'pandas.concat', 'pd.concat', (['[title_bow, selftext_bow, title_sentiments, selftext_sentiments, post_time]'], {'axis': '(1)'}), '([title_bow, selftext_bow, title_sentiments, selftext_sentiments,\n post_time], axis=1)\n', (919, 1008), True, 'import pandas as pd\n'), ((2876, 2902), 'math.floor', 'math.floor', (['(0.8 * num_rows)'], {}), '(0.8 * num_rows)\n', (2886, 2902), False, 'import math\n'), ((4832, 4876), 'pandas.DataFrame', 'pd.DataFrame', (['entries'], {'columns': "['sentiment']"}), "(entries, columns=['sentiment'])\n", (4844, 4876), True, 'import pandas as pd\n'), ((4972, 4993), 'bag_of_words.parse_arguments', 'bow.parse_arguments', ([], {}), '()\n', (4991, 4993), True, 'import bag_of_words as bow\n'), ((5011, 5048), 'bag_of_words.csv_to_data_frame', 'bow.csv_to_data_frame', (['args.subreddit'], {}), '(args.subreddit)\n', (5032, 5048), True, 'import bag_of_words as bow\n'), ((1442, 1462), 'numpy.percentile', 'np.percentile', (['s', '(25)'], {}), '(s, 25)\n', (1455, 1462), True, 'import numpy as np\n'), ((1482, 1502), 'numpy.percentile', 'np.percentile', (['s', '(50)'], {}), '(s, 50)\n', (1495, 1502), True, 'import numpy as np\n'), ((1522, 1542), 'numpy.percentile', 'np.percentile', (['s', '(75)'], {}), '(s, 75)\n', (1535, 1542), True, 'import numpy as np\n'), ((1390, 1406), 'numpy.array', 'np.array', (['scores'], {}), '(scores)\n', (1398, 1406), True, 'import numpy as np\n'), ((4682, 4732), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['a', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(a, '%Y-%m-%d %H:%M:%S')\n", (4708, 4732), False, 'import datetime\n')]
import shutil import numpy as np import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) BUCKET = None # set from task.py PATTERN = "of" CSV_COLUMNS = [ "weight_pounds", "is_male", "mother_age", "plurality", "gestation_weeks", ] LABEL_COLUMN = "weight_pounds" DEFAULTS = [[0.0], ["null"], [0.0], ["null"], [0.0]] TRAIN_STEPS = 10000 EVAL_STEPS = None BATCH_SIZE = 512 NEMBEDS = 3 NNSIZE = [64, 16, 4] def read_dataset(filename_pattern, mode, batch_size): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv( records=value_column, record_defaults=DEFAULTS ) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label file_path = "gs://{}/babyweight/preproc/{}*{}*".format( BUCKET, filename_pattern, PATTERN) file_list = tf.gfile.Glob(filename=file_path) dataset = ( tf.data.TextLineDataset(filenames=file_list).map( map_func=decode_csv) ) if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 dataset = dataset.repeat(count=num_epochs).batch(batch_size=batch_size) return dataset return _input_fn def get_wide_deep(): fc_is_male = tf.feature_column.categorical_column_with_vocabulary_list( key="is_male", vocabulary_list=["True", "False", "Unknown"] ) fc_plurality = tf.feature_column.categorical_column_with_vocabulary_list( key="plurality", vocabulary_list=[ "Single(1)", "Twins(2)", "Triplets(3)", "Quadruplets(4)", "Quintuplets(5)", "Multiple(2+)" ] ) fc_mother_age = tf.feature_column.numeric_column("mother_age") fc_gestation_weeks = tf.feature_column.numeric_column("gestation_weeks") fc_age_buckets = tf.feature_column.bucketized_column( source_column=fc_mother_age, boundaries=np.arange(start=15, stop=45, step=1).tolist() ) fc_gestation_buckets = tf.feature_column.bucketized_column( source_column=fc_gestation_weeks, boundaries=np.arange(start=17, stop=47, step=1).tolist()) wide = [ fc_is_male, fc_plurality, fc_age_buckets, fc_gestation_buckets ] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column( keys=wide, hash_bucket_size=20000 ) fc_embed = tf.feature_column.embedding_column( categorical_column=crossed, dimension=3 ) # Continuous columns are deep, have a complex relationship with the output deep = [ fc_mother_age, fc_gestation_weeks, fc_embed ] return wide, deep def serving_input_fn(): feature_placeholders = { "is_male": tf.placeholder(dtype=tf.string, shape=[None]), "mother_age": tf.placeholder(dtype=tf.float32, shape=[None]), "plurality": tf.placeholder(dtype=tf.string, shape=[None]), "gestation_weeks": tf.placeholder(dtype=tf.float32, shape=[None]) } features = { key: tf.expand_dims(input=tensor, axis=-1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver( features=features, receiver_tensors=feature_placeholders ) def my_rmse(labels, predictions): pred_values = predictions["predictions"] return { "rmse": tf.metrics.root_mean_squared_error( labels=labels, predictions=pred_values ) } def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 # seconds run_config = tf.estimator.RunConfig( save_checkpoints_secs=EVAL_INTERVAL, keep_checkpoint_max=3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir=output_dir, linear_feature_columns=wide, dnn_feature_columns=deep, dnn_hidden_units=NNSIZE, config=run_config) estimator = tf.contrib.estimator.add_metrics(estimator, my_rmse) train_spec = tf.estimator.TrainSpec( input_fn=read_dataset( "train", tf.estimator.ModeKeys.TRAIN, BATCH_SIZE), max_steps=TRAIN_STEPS) exporter = tf.estimator.LatestExporter( name="exporter", serving_input_receiver_fn=serving_input_fn, exports_to_keep=None) eval_spec = tf.estimator.EvalSpec( input_fn=read_dataset( "eval", tf.estimator.ModeKeys.EVAL, 2**15), steps=EVAL_STEPS, start_delay_secs=60, # start evaluating after N seconds throttle_secs=EVAL_INTERVAL, # evaluate every N seconds exporters=exporter) tf.estimator.train_and_evaluate( estimator=estimator, train_spec=train_spec, eval_spec=eval_spec )
[ "tensorflow.feature_column.crossed_column", "tensorflow.estimator.RunConfig", "tensorflow.estimator.train_and_evaluate", "tensorflow.estimator.LatestExporter", "tensorflow.placeholder", "tensorflow.logging.set_verbosity", "tensorflow.gfile.Glob", "tensorflow.data.TextLineDataset", "tensorflow.featur...
[((64, 105), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), '(tf.logging.INFO)\n', (88, 105), True, 'import tensorflow as tf\n'), ((1548, 1670), 'tensorflow.feature_column.categorical_column_with_vocabulary_list', 'tf.feature_column.categorical_column_with_vocabulary_list', ([], {'key': '"""is_male"""', 'vocabulary_list': "['True', 'False', 'Unknown']"}), "(key='is_male',\n vocabulary_list=['True', 'False', 'Unknown'])\n", (1605, 1670), True, 'import tensorflow as tf\n'), ((1714, 1906), 'tensorflow.feature_column.categorical_column_with_vocabulary_list', 'tf.feature_column.categorical_column_with_vocabulary_list', ([], {'key': '"""plurality"""', 'vocabulary_list': "['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)',\n 'Multiple(2+)']"}), "(key='plurality',\n vocabulary_list=['Single(1)', 'Twins(2)', 'Triplets(3)',\n 'Quadruplets(4)', 'Quintuplets(5)', 'Multiple(2+)'])\n", (1771, 1906), True, 'import tensorflow as tf\n'), ((2036, 2082), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""mother_age"""'], {}), "('mother_age')\n", (2068, 2082), True, 'import tensorflow as tf\n'), ((2111, 2162), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""gestation_weeks"""'], {}), "('gestation_weeks')\n", (2143, 2162), True, 'import tensorflow as tf\n'), ((2729, 2796), 'tensorflow.feature_column.crossed_column', 'tf.feature_column.crossed_column', ([], {'keys': 'wide', 'hash_bucket_size': '(20000)'}), '(keys=wide, hash_bucket_size=20000)\n', (2761, 2796), True, 'import tensorflow as tf\n'), ((2829, 2904), 'tensorflow.feature_column.embedding_column', 'tf.feature_column.embedding_column', ([], {'categorical_column': 'crossed', 'dimension': '(3)'}), '(categorical_column=crossed, dimension=3)\n', (2863, 2904), True, 'import tensorflow as tf\n'), ((3627, 3729), 'tensorflow.estimator.export.ServingInputReceiver', 'tf.estimator.export.ServingInputReceiver', ([], {'features': 'features', 'receiver_tensors': 'feature_placeholders'}), '(features=features,\n receiver_tensors=feature_placeholders)\n', (3667, 3729), True, 'import tensorflow as tf\n'), ((4118, 4204), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', ([], {'save_checkpoints_secs': 'EVAL_INTERVAL', 'keep_checkpoint_max': '(3)'}), '(save_checkpoints_secs=EVAL_INTERVAL,\n keep_checkpoint_max=3)\n', (4140, 4204), True, 'import tensorflow as tf\n'), ((4239, 4408), 'tensorflow.estimator.DNNLinearCombinedRegressor', 'tf.estimator.DNNLinearCombinedRegressor', ([], {'model_dir': 'output_dir', 'linear_feature_columns': 'wide', 'dnn_feature_columns': 'deep', 'dnn_hidden_units': 'NNSIZE', 'config': 'run_config'}), '(model_dir=output_dir,\n linear_feature_columns=wide, dnn_feature_columns=deep, dnn_hidden_units\n =NNSIZE, config=run_config)\n', (4278, 4408), True, 'import tensorflow as tf\n'), ((4465, 4517), 'tensorflow.contrib.estimator.add_metrics', 'tf.contrib.estimator.add_metrics', (['estimator', 'my_rmse'], {}), '(estimator, my_rmse)\n', (4497, 4517), True, 'import tensorflow as tf\n'), ((4708, 4823), 'tensorflow.estimator.LatestExporter', 'tf.estimator.LatestExporter', ([], {'name': '"""exporter"""', 'serving_input_receiver_fn': 'serving_input_fn', 'exports_to_keep': 'None'}), "(name='exporter', serving_input_receiver_fn=\n serving_input_fn, exports_to_keep=None)\n", (4735, 4823), True, 'import tensorflow as tf\n'), ((5173, 5273), 'tensorflow.estimator.train_and_evaluate', 'tf.estimator.train_and_evaluate', ([], {'estimator': 'estimator', 'train_spec': 'train_spec', 'eval_spec': 'eval_spec'}), '(estimator=estimator, train_spec=train_spec,\n eval_spec=eval_spec)\n', (5204, 5273), True, 'import tensorflow as tf\n'), ((995, 1028), 'tensorflow.gfile.Glob', 'tf.gfile.Glob', ([], {'filename': 'file_path'}), '(filename=file_path)\n', (1008, 1028), True, 'import tensorflow as tf\n'), ((3208, 3253), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.string', 'shape': '[None]'}), '(dtype=tf.string, shape=[None])\n', (3222, 3253), True, 'import tensorflow as tf\n'), ((3278, 3324), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None]'}), '(dtype=tf.float32, shape=[None])\n', (3292, 3324), True, 'import tensorflow as tf\n'), ((3348, 3393), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.string', 'shape': '[None]'}), '(dtype=tf.string, shape=[None])\n', (3362, 3393), True, 'import tensorflow as tf\n'), ((3423, 3469), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None]'}), '(dtype=tf.float32, shape=[None])\n', (3437, 3469), True, 'import tensorflow as tf\n'), ((3511, 3548), 'tensorflow.expand_dims', 'tf.expand_dims', ([], {'input': 'tensor', 'axis': '(-1)'}), '(input=tensor, axis=-1)\n', (3525, 3548), True, 'import tensorflow as tf\n'), ((3868, 3942), 'tensorflow.metrics.root_mean_squared_error', 'tf.metrics.root_mean_squared_error', ([], {'labels': 'labels', 'predictions': 'pred_values'}), '(labels=labels, predictions=pred_values)\n', (3902, 3942), True, 'import tensorflow as tf\n'), ((608, 669), 'tensorflow.decode_csv', 'tf.decode_csv', ([], {'records': 'value_column', 'record_defaults': 'DEFAULTS'}), '(records=value_column, record_defaults=DEFAULTS)\n', (621, 669), True, 'import tensorflow as tf\n'), ((1065, 1109), 'tensorflow.data.TextLineDataset', 'tf.data.TextLineDataset', ([], {'filenames': 'file_list'}), '(filenames=file_list)\n', (1088, 1109), True, 'import tensorflow as tf\n'), ((2285, 2321), 'numpy.arange', 'np.arange', ([], {'start': '(15)', 'stop': '(45)', 'step': '(1)'}), '(start=15, stop=45, step=1)\n', (2294, 2321), True, 'import numpy as np\n'), ((2468, 2504), 'numpy.arange', 'np.arange', ([], {'start': '(17)', 'stop': '(47)', 'step': '(1)'}), '(start=17, stop=47, step=1)\n', (2477, 2504), True, 'import numpy as np\n')]
import numpy as np # reverse = True: descending order (TOPSIS, CODAS), False: ascending order (VIKOR, SPOTIS) def rank_preferences(pref, reverse = True): """ Rank alternatives according to MCDM preference function values. Parameters ---------- pref : ndarray vector with MCDM preference function values for alternatives reverse : bool Boolean variable which is True for MCDM methods which rank alternatives in descending order and False for MCDM methods which rank alternatives in ascending order Returns ------- ndarray vector with alternatives ranking. Alternative with 1 value is the best. """ rank = np.zeros(len(pref)) sorted_pref = sorted(pref, reverse = reverse) pos = 1 for i in range(len(sorted_pref) - 1): ind = np.where(sorted_pref[i] == pref)[0] rank[ind] = pos if sorted_pref[i] != sorted_pref[i + 1]: pos += 1 ind = np.where(sorted_pref[i + 1] == pref)[0] rank[ind] = pos return rank.astype(int)
[ "numpy.where" ]
[((1001, 1037), 'numpy.where', 'np.where', (['(sorted_pref[i + 1] == pref)'], {}), '(sorted_pref[i + 1] == pref)\n', (1009, 1037), True, 'import numpy as np\n'), ((861, 893), 'numpy.where', 'np.where', (['(sorted_pref[i] == pref)'], {}), '(sorted_pref[i] == pref)\n', (869, 893), True, 'import numpy as np\n')]
import argparse import os import sys import logging import numpy import numpy as np import torch import torch.utils.data import torchvision from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from tqdm import tqdm from learning3d.ops import se3 # Only if the files are in example folder. BASE_DIR = os.path.dirname(os.path.abspath(__file__)) if BASE_DIR[-8:] == 'examples': sys.path.append(os.path.join(BASE_DIR, os.pardir)) os.chdir(os.path.join(BASE_DIR, os.pardir)) from learning3d.models import MaskNet from learning3d.data_utils import RegistrationData, ModelNet40Data, AnyData def _init_(args): if not os.path.exists('checkpoints'): os.makedirs('checkpoints') if not os.path.exists('checkpoints/' + args.exp_name): os.makedirs('checkpoints/' + args.exp_name) if not os.path.exists('checkpoints/' + args.exp_name + '/' + 'models'): os.makedirs('checkpoints/' + args.exp_name + '/' + 'models') os.system('cp train.py checkpoints' + '/' + args.exp_name + '/' + 'train.py.backup') os.system('cp learning3d/models/masknet.py checkpoints' + '/' + args.exp_name + '/' + 'masknet.py.backup') os.system('cp learning3d/data_utils/dataloaders.py checkpoints' + '/' + args.exp_name + '/' + 'dataloaders.py.backup') class IOStream: def __init__(self, path): self.f = open(path, 'a') def cprint(self, text): print(text) self.f.write(text + '\n') self.f.flush() def close(self): self.f.close() def eval_one_epoch(args, model, test_loader): model.eval() test_loss = 0.0 test_loss_y = 0.0 test_loss_x = 0.0 percent_x_mean = 0.0 percent_y_mean = 0.0 pred = 0.0 count = 0 predict_num_x= 0 target_num_x= 0 acc_num_x = 0 predict_num_y= 0 target_num_y= 0 acc_num_y = 0 for i, data in enumerate(tqdm(test_loader)): template, source, igt, gt_mask_y, gt_mask_x = data template = template.to(args.device) source = source.to(args.device) gt_mask_y = gt_mask_y.to(args.device) gt_mask_x = gt_mask_x.to(args.device) masked_template,masked_source, predicted_mask_y, predicted_mask_x= model(template, source) if args.loss_fn == 'mse': loss_mask_y = torch.nn.functional.mse_loss(predicted_mask_y, gt_mask_y) loss_mask_x = torch.nn.functional.mse_loss(predicted_mask_x, gt_mask_x) elif args.loss_fn == 'bce': loss_mask_y = torch.nn.BCELoss()(predicted_mask_y, gt_mask_y) loss_mask_x = torch.nn.BCELoss()(predicted_mask_x, gt_mask_x) loss_mask = loss_mask_y +loss_mask_x# mask_x_binary = torch.where(predicted_mask_x > 0.5, torch.ones(predicted_mask_x.size()).cuda(), torch.zeros(predicted_mask_x.size()).cuda()) mask_y_binary = torch.where(predicted_mask_y > 0.5, torch.ones(predicted_mask_y.size()).cuda(), torch.zeros(predicted_mask_y.size()).cuda()) percent_x = torch.mean((mask_x_binary.size()[1] - torch.sum(torch.abs(mask_x_binary - gt_mask_x), dim =1))/mask_x_binary.size()[1]) percent_y = torch.mean((mask_y_binary.size()[1] - torch.sum(torch.abs(mask_y_binary - gt_mask_y), dim =1))/mask_y_binary.size()[1]) percent_x_mean += percent_x percent_y_mean += percent_y test_loss += loss_mask.item() test_loss_y += loss_mask_y.item() test_loss_x += loss_mask_x.item() count += 1 percent_x_mean = float(percent_x_mean)/count percent_y_mean = float(percent_y_mean)/count test_loss = float(test_loss)/count test_loss_y = float(test_loss_y)/count test_loss_x = float(test_loss_x)/count return test_loss, test_loss_y, test_loss_x, percent_y_mean, percent_x_mean def test_one_epoch(args, model, test_loader): model.eval() test_loss = 0.0 test_loss_y = 0.0 test_loss_x = 0.0 percent_x_mean = 0.0 percent_y_mean = 0.0 pred = 0.0 count = 0 predict_num_x= 0 target_num_x= 0 acc_num_x = 0 predict_num_y= 0 target_num_y= 0 acc_num_y = 0 for i, data in enumerate(tqdm(test_loader)): template, source, igt, gt_mask_y, gt_mask_x = data template = template.to(args.device) source = source.to(args.device) igt = igt.to(args.device) # [source] = [igt]*[template] gt_mask_y = gt_mask_y.to(args.device) gt_mask_x = gt_mask_x.to(args.device) masked_template,masked_source, predicted_mask_y, predicted_mask_x= model(template, source) mask_x_binary = torch.where(predicted_mask_x > 0.5, torch.ones(predicted_mask_x.size()).cuda(), torch.zeros(predicted_mask_x.size()).cuda()) mask_y_binary = torch.where(predicted_mask_y > 0.5, torch.ones(predicted_mask_y.size()).cuda(), torch.zeros(predicted_mask_y.size()).cuda()) if args.loss_fn == 'mse': loss_mask_y = torch.nn.functional.mse_loss(predicted_mask_y, gt_mask_y) loss_mask_x = torch.nn.functional.mse_loss(predicted_mask_x, gt_mask_x) elif args.loss_fn == 'bce': loss_mask_y = torch.nn.BCELoss()(predicted_mask_y, gt_mask_y) loss_mask_x = torch.nn.BCELoss()(predicted_mask_x, gt_mask_x) loss_mask = loss_mask_y +loss_mask_x # predict_num_x += mask_x_binary.sum(1) target_num_x += gt_mask_x.sum(1) acc_mask_x = mask_x_binary*gt_mask_x acc_num_x += acc_mask_x.sum(1) predict_num_y += mask_y_binary.sum(1) target_num_y += gt_mask_y.sum(1) acc_mask_y = mask_y_binary*gt_mask_y acc_num_y += acc_mask_y.sum(1) test_loss += loss_mask.item() test_loss_y += loss_mask_y.item() test_loss_x += loss_mask_x.item() count += 1 mask_x_binary = mask_x_binary.unsqueeze(2).repeat(1, 1, 3) #B,N1, 3 mask_y_binary = mask_y_binary.unsqueeze(2).repeat(1, 1, 3) #B, N2, 3 transformed_source = se3.transform(igt, source.permute(0,2,1))#B, 3, N1 non_masked_template = template.clone().detach() non_masked_source = transformed_source.permute(0,2,1).clone().detach() non_masked_template[torch.tensor(gt_mask_y, dtype = torch.bool)] = 0.0 non_masked_source[torch.tensor(gt_mask_x, dtype = torch.bool)] =0.0 np.savetxt(str(i)+'_template.txt', np.column_stack((non_masked_template.cpu().numpy()[0,:, 0],non_masked_template.cpu().numpy()[0,:, 1],non_masked_template.cpu().numpy()[0,:, 2])),fmt='%f %f %f',newline='\n' ) #保存为整数 np.savetxt(str(i)+'_source.txt', np.column_stack((non_masked_source.cpu().numpy()[0,:, 0],non_masked_source.cpu().numpy()[0,:, 1],non_masked_source.cpu().numpy()[0,:, 2])),fmt='%f %f %f',newline='\n' ) #保存为整数 masked_template = template.clone().detach() masked_source = transformed_source.permute(0,2,1).clone().detach() masked_template[~torch.tensor(mask_y_binary, dtype = torch.bool)] = 0.0 masked_source[~torch.tensor(mask_x_binary, dtype = torch.bool)] =0.0 gt_masked_template = template.clone().detach() gt_masked_source = transformed_source.permute(0,2,1).clone().detach() gt_masked_template[~torch.tensor(gt_mask_y, dtype = torch.bool)] = 0.0 gt_masked_source[~torch.tensor(gt_mask_x, dtype = torch.bool)] =0.0 np.savetxt(str(i)+'_masked_template.txt', np.column_stack((masked_template.cpu().numpy()[0,:, 0],masked_template.cpu().numpy()[0,:, 1],masked_template.cpu().numpy()[0,:, 2])),fmt='%f %f %f',newline='\n' ) #保存为整数 np.savetxt(str(i)+'_masked_source.txt',np.column_stack((masked_source.cpu().numpy()[0,:, 0],masked_source.cpu().numpy()[0,:,1],masked_source.cpu().numpy()[0,:, 2])),fmt='%f %f %f',newline='\n') #保存为整数 np.savetxt(str(i)+'_gt_masked_template.txt', np.column_stack((gt_masked_template.cpu().numpy()[0,:, 0],gt_masked_template.cpu().numpy()[0,:, 1],gt_masked_template.cpu().numpy()[0,:, 2])),fmt='%f %f %f',newline='\n' ) #保存为整数 np.savetxt(str(i)+'_gt_masked_source.txt',np.column_stack((gt_masked_source.cpu().numpy()[0,:, 0],gt_masked_source.cpu().numpy()[0,:,1],gt_masked_source.cpu().numpy()[0,:, 2])),fmt='%f %f %f',newline='\n') #保存为整数 recall_x = acc_num_x/target_num_x precision_x = acc_num_x/predict_num_x F1_x = 2*recall_x*precision_x/(recall_x+precision_x) print('recall_x: %f,precision_x: %f, F1_x:%f'%(recall_x,precision_x, F1_x) ) recall_y = acc_num_y/target_num_y precision_y = acc_num_y/predict_num_y F1_y = 2*recall_y*precision_y/(recall_y+precision_y) print('recall_y: %f,precision_y: %f, F1_y:%f'%(recall_y,precision_y, F1_y) ) test_loss = float(test_loss)/count test_loss_y = float(test_loss_y)/count test_loss_x = float(test_loss_x)/count return test_loss, test_loss_y, test_loss_x, precision_y, precision_x def test(args, model, test_loader, textio): test_loss, test_loss_y, test_loss_x, percent_y_mean, percent_x_mean = test_one_epoch(args, model, test_loader) textio.cprint('Test Loss: %f, Test Loss y: %f, Test Loss x: %f,Test y: %f,Test x: %f'%(test_loss, test_loss_y, test_loss_x, percent_y_mean, percent_x_mean)) def train_one_epoch(args, model, train_loader, optimizer): model.train() train_loss = 0.0 train_loss_y = 0.0 train_loss_x = 0.0 percent_x_mean = 0.0 percent_y_mean = 0.0 pred = 0.0 count = 0 for i, data in enumerate(tqdm(train_loader)): template, source, igt, gt_mask_y, gt_mask_x = data template = template.to(args.device) source = source.to(args.device) gt_mask_y = gt_mask_y.to(args.device) gt_mask_x = gt_mask_x.to(args.device) masked_template, masked_source, predicted_mask_y, predicted_mask_x= model(template, source) if args.loss_fn == 'mse': loss_mask_y = torch.nn.functional.mse_loss(predicted_mask_y, gt_mask_y) loss_mask_x = torch.nn.functional.mse_loss(predicted_mask_x, gt_mask_x) elif args.loss_fn == 'bce': loss_mask_y = torch.nn.BCELoss()(predicted_mask_y, gt_mask_y) loss_mask_x = torch.nn.BCELoss()(predicted_mask_x, gt_mask_x) mask_x_binary = torch.where(predicted_mask_x > 0.5, torch.ones(predicted_mask_x.size()).cuda(), torch.zeros(predicted_mask_x.size()).cuda()) mask_y_binary = torch.where(predicted_mask_y > 0.5, torch.ones(predicted_mask_y.size()).cuda(), torch.zeros(predicted_mask_y.size()).cuda()) percent_x = torch.mean((mask_x_binary.size()[1] - torch.sum(torch.abs(mask_x_binary - gt_mask_x), dim =1))/mask_x_binary.size()[1]) percent_y = torch.mean((mask_y_binary.size()[1] - torch.sum(torch.abs(mask_y_binary - gt_mask_y), dim =1))/mask_y_binary.size()[1]) loss_mask =loss_mask_y +loss_mask_x # # forward + backward + optimize optimizer.zero_grad() loss_mask.backward() optimizer.step() percent_x_mean += percent_x percent_y_mean += percent_y train_loss += loss_mask.item() train_loss_y += loss_mask_y.item() train_loss_x += loss_mask_x.item() count += 1 percent_x_mean = float(percent_x_mean)/count percent_y_mean = float(percent_y_mean)/count train_loss = float(train_loss)/count train_loss_y = float(train_loss_y)/count train_loss_x = float(train_loss_x)/count return train_loss, train_loss_y, train_loss_x, percent_y_mean, percent_x_mean def train(args, model, train_loader, test_loader, boardio, textio, checkpoint): learnable_params = filter(lambda p: p.requires_grad, model.parameters()) if args.optimizer == 'Adam': optimizer = torch.optim.Adam(learnable_params, lr=0.001)#0.001 else: optimizer = torch.optim.SGD(learnable_params, lr=0.1) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50, eta_min=0.000001) if checkpoint is not None: min_loss = checkpoint['min_loss'] optimizer.load_state_dict(checkpoint['optimizer']) best_test_loss = np.inf for epoch in range(args.start_epoch, args.epochs): train_loss, train_loss_y, train_loss_x, train_percent_y, train_percent_x = train_one_epoch(args, model, train_loader, optimizer) test_loss, test_loss_y, test_loss_x, test_percent_y, test_percent_x = eval_one_epoch(args, model, test_loader) scheduler.step() if test_loss<best_test_loss: best_test_loss = test_loss snap = {'epoch': epoch + 1, 'model': model.state_dict(), 'min_loss': best_test_loss, 'optimizer' : optimizer.state_dict(),} torch.save(snap, 'checkpoints/%s/models/best_model_snap.t7' % (args.exp_name)) torch.save(model.state_dict(), 'checkpoints/%s/models/best_model.t7' % (args.exp_name)) snap = {'epoch': epoch + 1, 'model': model.state_dict(), 'min_loss': best_test_loss, 'optimizer' : optimizer.state_dict(),} torch.save(snap, 'checkpoints/%s/models/model_snap.t7' % (args.exp_name)) torch.save(model.state_dict(), 'checkpoints/%s/models/model.t7' % (args.exp_name)) boardio.add_scalar('Train_Loss', train_loss, epoch+1) boardio.add_scalar('Test_Loss', test_loss, epoch+1) boardio.add_scalar('Best_Test_Loss', best_test_loss, epoch+1) textio.cprint('EPOCH:: %d, Train Loss: %f, Train Loss y: %f,Train Loss x: %f,Train y: %f,Train x: %f'%(epoch+1, train_loss, train_loss_y, train_loss_x, train_percent_y, train_percent_x)) textio.cprint('Test Loss: %f, Test Loss y: %f, Test Loss x: %f,Test y: %f,Test x: %f, Best Loss: %f'%(test_loss, test_loss_y, test_loss_x, test_percent_y, test_percent_x, best_test_loss)) def options(): parser = argparse.ArgumentParser(description='MaskNet: A Fully-Convolutional Network For Inlier Estimation (Training)') parser.add_argument('--exp_name', type=str, default='exp_masknet', metavar='N', help='Name of the experiment') parser.add_argument('--eval', type=bool, default=False, help='Train or Evaluate the network.') # settings for input data parser.add_argument('--num_points', default=1024, type=int, metavar='N', help='points in point-cloud (default: 1024)') parser.add_argument('--partial', default= 1, type= int, help='Add partial to template point cloud.') parser.add_argument('--noise', default=0, type=int, help='Add noise in source point clouds.') parser.add_argument('--outliers', default=0 , type=int, help='Add outliers to template point cloud.') # settings for on training parser.add_argument('--seed', type=int, default=1234) parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', help='number of data loading workers (default: 4)') parser.add_argument('-b', '--batch_size', default=32, type=int, metavar='N', help='mini-batch size (default: 32)') parser.add_argument('--test_batch_size', default=8, type=int, metavar='N', help='test-mini-batch size (default: 8)') parser.add_argument('--unseen', default=False, type=bool, help='Use first 20 categories for training and last 20 for testing') parser.add_argument('--epochs', default=500, type=int, metavar='N', help='number of total epochs to run') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('--optimizer', default='Adam', choices=['Adam', 'SGD'], metavar='METHOD', help='name of an optimizer (default: Adam)') parser.add_argument('--resume', default='', type=str, metavar='PATH', help='path to latest checkpoint (default: null (no-use))') parser.add_argument('--pretrained', default='', type=str, metavar='PATH', help='path to pretrained model file (default: null (no-use))') parser.add_argument('--device', default='cuda:0', type=str, metavar='DEVICE', help='use CUDA if available') parser.add_argument('--loss_fn', default='mse', type=str, choices=['mse', 'bce']) parser.add_argument('--user_data', type=bool, default=False, help='Train or Evaluate the network with User Input Data.') parser.add_argument('--any_data', type=bool, default=False, help='Evaluate the network with Any Point Cloud.') parser.add_argument('--dataset_path_train', default='learning3d/match/train', type=str, help='Provide the path to .ply file in 3DMatch dataset.') parser.add_argument('--dataset_path_test', default='learning3d/match/test', type=str, help='Provide the path to .ply file in 3DMatch dataset.') args = parser.parse_args() return args import os import pandas as pd from plyfile import PlyData, PlyElement def readplyfile(filename): file_dir = filename #文件的路径 plydata = PlyData.read(file_dir) # 读取文件 data = plydata.elements[0].data # 读取数据 data_pd = pd.DataFrame(data) # 转换成DataFrame, 因为DataFrame可以解析结构化的数据 data_np = np.zeros(data_pd.shape, dtype=np.double) # 初始化储存数据的array property_names = data[0].dtype.names # 读取property的名字 for i, name in enumerate(property_names): # 按property读取数据,这样可以保证读出的数据是同样的数据类型。 data_np[:, i] = data_pd[name] return data_np[:,0:3] def normalize_pc(point_cloud): centroid = np.mean(point_cloud, axis=0) point_cloud -= centroid furthest_distance = np.max(np.sqrt(np.sum(abs(point_cloud)**2,axis=-1))) point_cloud /= furthest_distance return point_cloud def read_mesh(path, sample_pc=True, num_points=10000): all_data = [] files= os.listdir(path) for file in files: # if not os.path.isdir(file): # pc = readplyfile(path+"/"+file) points = normalize_pc(np.array(pc)) if sample_pc: # points_idx = farthest_point_sample(points, 10000) points_idx = np.arange(points.shape[0]) np.random.shuffle(points_idx) points = points[points_idx[:num_points], :]#int(points.shape[0]/num_points) * all_data.append(points) all_data = np.concatenate(all_data, axis=0) all_data = all_data.reshape( -1 ,num_points, 3 ) return all_data def main(): args = options() torch.backends.cudnn.deterministic = True torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) np.random.seed(args.seed) boardio = SummaryWriter(log_dir='checkpoints/' + args.exp_name) _init_(args) textio = IOStream('checkpoints/' + args.exp_name + '/run.log') textio.cprint(str(args)) if args.eval == False: if args.any_data: points_train = read_mesh(path=args.dataset_path_train, sample_pc=True, num_points=args.num_points) trainset = AnyData(pc=points_train, mask=True) train_loader = DataLoader(trainset, batch_size=args.batch_size, shuffle=False, drop_last=False, num_workers=args.workers) points_test = read_mesh(path=args.dataset_path_test, sample_pc=True, num_points=args.num_points) testset = AnyData(pc=points_test, mask=True) test_loader = DataLoader(testset, batch_size=args.test_batch_size, shuffle=False, drop_last=False, num_workers=args.workers) else: trainset = RegistrationData(ModelNet40Data(train=True, num_points=args.num_points, unseen=args.unseen), partial=args.partial, noise=args.noise, outliers=args.outliers) testset = RegistrationData(ModelNet40Data(train=False, num_points=args.num_points, unseen=args.unseen), partial =args.partial, noise=args.noise, outliers=args.outliers) train_loader = DataLoader(trainset, batch_size=args.batch_size, shuffle=True, drop_last=True, num_workers=args.workers) test_loader = DataLoader(testset, batch_size=args.test_batch_size, shuffle=False, drop_last=False, num_workers=args.workers) elif args.eval == True: if args.any_data: points_test = read_mesh(path=args.dataset_path_test, sample_pc=True, num_points=args.num_points) testset = AnyData(pc=points_test, mask=True) test_loader = DataLoader(testset, batch_size=args.test_batch_size, shuffle=False, drop_last=False, num_workers=args.workers) else: testset = RegistrationData(ModelNet40Data(train=False, num_points=args.num_points, unseen=args.unseen), partial=args.partial, noise=args.noise, outliers=args.outliers) test_loader = DataLoader(testset, batch_size= 1, shuffle=False, drop_last=False, num_workers=args.workers) if not torch.cuda.is_available(): args.device = 'cpu' args.device = torch.device(args.device) model = MaskNet() model = model.to(args.device) checkpoint = None if args.resume: assert os.path.isfile(args.resume) checkpoint = torch.load(args.resume) args.start_epoch = checkpoint['epoch'] model.load_state_dict(checkpoint['model']) if args.pretrained: assert os.path.isfile(args.pretrained) model.load_state_dict(torch.load(args.pretrained, map_location='cpu')) model.to(args.device) if args.eval: test(args, model, test_loader, textio) else: train(args, model, train_loader, test_loader, boardio, textio, checkpoint) if __name__ == '__main__': main()
[ "learning3d.data_utils.AnyData", "learning3d.models.MaskNet", "numpy.array", "torch.cuda.is_available", "numpy.arange", "numpy.mean", "os.path.exists", "os.listdir", "tensorboardX.SummaryWriter", "argparse.ArgumentParser", "os.path.isdir", "numpy.random.seed", "numpy.concatenate", "pandas....
[((343, 368), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (358, 368), False, 'import os\n'), ((941, 1029), 'os.system', 'os.system', (["('cp train.py checkpoints' + '/' + args.exp_name + '/' + 'train.py.backup')"], {}), "('cp train.py checkpoints' + '/' + args.exp_name + '/' +\n 'train.py.backup')\n", (950, 1029), False, 'import os\n'), ((1027, 1138), 'os.system', 'os.system', (["('cp learning3d/models/masknet.py checkpoints' + '/' + args.exp_name + '/' +\n 'masknet.py.backup')"], {}), "('cp learning3d/models/masknet.py checkpoints' + '/' + args.\n exp_name + '/' + 'masknet.py.backup')\n", (1036, 1138), False, 'import os\n'), ((1135, 1257), 'os.system', 'os.system', (["('cp learning3d/data_utils/dataloaders.py checkpoints' + '/' + args.\n exp_name + '/' + 'dataloaders.py.backup')"], {}), "('cp learning3d/data_utils/dataloaders.py checkpoints' + '/' +\n args.exp_name + '/' + 'dataloaders.py.backup')\n", (1144, 1257), False, 'import os\n'), ((10915, 10993), 'torch.optim.lr_scheduler.CosineAnnealingLR', 'torch.optim.lr_scheduler.CosineAnnealingLR', (['optimizer'], {'T_max': '(50)', 'eta_min': '(1e-06)'}), '(optimizer, T_max=50, eta_min=1e-06)\n', (10957, 10993), False, 'import torch\n'), ((12723, 12838), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MaskNet: A Fully-Convolutional Network For Inlier Estimation (Training)"""'}), "(description=\n 'MaskNet: A Fully-Convolutional Network For Inlier Estimation (Training)')\n", (12746, 12838), False, 'import argparse\n'), ((15714, 15736), 'plyfile.PlyData.read', 'PlyData.read', (['file_dir'], {}), '(file_dir)\n', (15726, 15736), False, 'from plyfile import PlyData, PlyElement\n'), ((15803, 15821), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (15815, 15821), True, 'import pandas as pd\n'), ((15875, 15915), 'numpy.zeros', 'np.zeros', (['data_pd.shape'], {'dtype': 'np.double'}), '(data_pd.shape, dtype=np.double)\n', (15883, 15915), True, 'import numpy as np\n'), ((16184, 16212), 'numpy.mean', 'np.mean', (['point_cloud'], {'axis': '(0)'}), '(point_cloud, axis=0)\n', (16191, 16212), True, 'import numpy as np\n'), ((16445, 16461), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (16455, 16461), False, 'import os\n'), ((16869, 16901), 'numpy.concatenate', 'np.concatenate', (['all_data'], {'axis': '(0)'}), '(all_data, axis=0)\n', (16883, 16901), True, 'import numpy as np\n'), ((17045, 17073), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (17062, 17073), False, 'import torch\n'), ((17075, 17112), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (17101, 17112), False, 'import torch\n'), ((17114, 17139), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (17128, 17139), True, 'import numpy as np\n'), ((17152, 17205), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {'log_dir': "('checkpoints/' + args.exp_name)"}), "(log_dir='checkpoints/' + args.exp_name)\n", (17165, 17205), False, 'from tensorboardX import SummaryWriter\n'), ((19222, 19247), 'torch.device', 'torch.device', (['args.device'], {}), '(args.device)\n', (19234, 19247), False, 'import torch\n'), ((19258, 19267), 'learning3d.models.MaskNet', 'MaskNet', ([], {}), '()\n', (19265, 19267), False, 'from learning3d.models import MaskNet\n'), ((419, 452), 'os.path.join', 'os.path.join', (['BASE_DIR', 'os.pardir'], {}), '(BASE_DIR, os.pardir)\n', (431, 452), False, 'import os\n'), ((464, 497), 'os.path.join', 'os.path.join', (['BASE_DIR', 'os.pardir'], {}), '(BASE_DIR, os.pardir)\n', (476, 497), False, 'import os\n'), ((642, 671), 'os.path.exists', 'os.path.exists', (['"""checkpoints"""'], {}), "('checkpoints')\n", (656, 671), False, 'import os\n'), ((675, 701), 'os.makedirs', 'os.makedirs', (['"""checkpoints"""'], {}), "('checkpoints')\n", (686, 701), False, 'import os\n'), ((710, 756), 'os.path.exists', 'os.path.exists', (["('checkpoints/' + args.exp_name)"], {}), "('checkpoints/' + args.exp_name)\n", (724, 756), False, 'import os\n'), ((760, 803), 'os.makedirs', 'os.makedirs', (["('checkpoints/' + args.exp_name)"], {}), "('checkpoints/' + args.exp_name)\n", (771, 803), False, 'import os\n'), ((812, 875), 'os.path.exists', 'os.path.exists', (["('checkpoints/' + args.exp_name + '/' + 'models')"], {}), "('checkpoints/' + args.exp_name + '/' + 'models')\n", (826, 875), False, 'import os\n'), ((879, 939), 'os.makedirs', 'os.makedirs', (["('checkpoints/' + args.exp_name + '/' + 'models')"], {}), "('checkpoints/' + args.exp_name + '/' + 'models')\n", (890, 939), False, 'import os\n'), ((1759, 1776), 'tqdm.tqdm', 'tqdm', (['test_loader'], {}), '(test_loader)\n', (1763, 1776), False, 'from tqdm import tqdm\n'), ((3813, 3830), 'tqdm.tqdm', 'tqdm', (['test_loader'], {}), '(test_loader)\n', (3817, 3830), False, 'from tqdm import tqdm\n'), ((8742, 8760), 'tqdm.tqdm', 'tqdm', (['train_loader'], {}), '(train_loader)\n', (8746, 8760), False, 'from tqdm import tqdm\n'), ((10786, 10830), 'torch.optim.Adam', 'torch.optim.Adam', (['learnable_params'], {'lr': '(0.001)'}), '(learnable_params, lr=0.001)\n', (10802, 10830), False, 'import torch\n'), ((10858, 10899), 'torch.optim.SGD', 'torch.optim.SGD', (['learnable_params'], {'lr': '(0.1)'}), '(learnable_params, lr=0.1)\n', (10873, 10899), False, 'import torch\n'), ((11981, 12052), 'torch.save', 'torch.save', (['snap', "('checkpoints/%s/models/model_snap.t7' % args.exp_name)"], {}), "(snap, 'checkpoints/%s/models/model_snap.t7' % args.exp_name)\n", (11991, 12052), False, 'import torch\n'), ((19158, 19183), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (19181, 19183), False, 'import torch\n'), ((19345, 19372), 'os.path.isfile', 'os.path.isfile', (['args.resume'], {}), '(args.resume)\n', (19359, 19372), False, 'import os\n'), ((19388, 19411), 'torch.load', 'torch.load', (['args.resume'], {}), '(args.resume)\n', (19398, 19411), False, 'import torch\n'), ((19529, 19560), 'os.path.isfile', 'os.path.isfile', (['args.pretrained'], {}), '(args.pretrained)\n', (19543, 19560), False, 'import os\n'), ((2125, 2182), 'torch.nn.functional.mse_loss', 'torch.nn.functional.mse_loss', (['predicted_mask_y', 'gt_mask_y'], {}), '(predicted_mask_y, gt_mask_y)\n', (2153, 2182), False, 'import torch\n'), ((2200, 2257), 'torch.nn.functional.mse_loss', 'torch.nn.functional.mse_loss', (['predicted_mask_x', 'gt_mask_x'], {}), '(predicted_mask_x, gt_mask_x)\n', (2228, 2257), False, 'import torch\n'), ((4533, 4590), 'torch.nn.functional.mse_loss', 'torch.nn.functional.mse_loss', (['predicted_mask_y', 'gt_mask_y'], {}), '(predicted_mask_y, gt_mask_y)\n', (4561, 4590), False, 'import torch\n'), ((4608, 4665), 'torch.nn.functional.mse_loss', 'torch.nn.functional.mse_loss', (['predicted_mask_x', 'gt_mask_x'], {}), '(predicted_mask_x, gt_mask_x)\n', (4636, 4665), False, 'import torch\n'), ((5654, 5695), 'torch.tensor', 'torch.tensor', (['gt_mask_y'], {'dtype': 'torch.bool'}), '(gt_mask_y, dtype=torch.bool)\n', (5666, 5695), False, 'import torch\n'), ((5725, 5766), 'torch.tensor', 'torch.tensor', (['gt_mask_x'], {'dtype': 'torch.bool'}), '(gt_mask_x, dtype=torch.bool)\n', (5737, 5766), False, 'import torch\n'), ((9110, 9167), 'torch.nn.functional.mse_loss', 'torch.nn.functional.mse_loss', (['predicted_mask_y', 'gt_mask_y'], {}), '(predicted_mask_y, gt_mask_y)\n', (9138, 9167), False, 'import torch\n'), ((9185, 9242), 'torch.nn.functional.mse_loss', 'torch.nn.functional.mse_loss', (['predicted_mask_x', 'gt_mask_x'], {}), '(predicted_mask_x, gt_mask_x)\n', (9213, 9242), False, 'import torch\n'), ((11670, 11746), 'torch.save', 'torch.save', (['snap', "('checkpoints/%s/models/best_model_snap.t7' % args.exp_name)"], {}), "(snap, 'checkpoints/%s/models/best_model_snap.t7' % args.exp_name)\n", (11680, 11746), False, 'import torch\n'), ((16495, 16514), 'os.path.isdir', 'os.path.isdir', (['file'], {}), '(file)\n', (16508, 16514), False, 'import os\n'), ((17471, 17506), 'learning3d.data_utils.AnyData', 'AnyData', ([], {'pc': 'points_train', 'mask': '(True)'}), '(pc=points_train, mask=True)\n', (17478, 17506), False, 'from learning3d.data_utils import RegistrationData, ModelNet40Data, AnyData\n'), ((17525, 17636), 'torch.utils.data.DataLoader', 'DataLoader', (['trainset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'drop_last': '(False)', 'num_workers': 'args.workers'}), '(trainset, batch_size=args.batch_size, shuffle=False, drop_last=\n False, num_workers=args.workers)\n', (17535, 17636), False, 'from torch.utils.data import DataLoader\n'), ((17746, 17780), 'learning3d.data_utils.AnyData', 'AnyData', ([], {'pc': 'points_test', 'mask': '(True)'}), '(pc=points_test, mask=True)\n', (17753, 17780), False, 'from learning3d.data_utils import RegistrationData, ModelNet40Data, AnyData\n'), ((17798, 17912), 'torch.utils.data.DataLoader', 'DataLoader', (['testset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(False)', 'drop_last': '(False)', 'num_workers': 'args.workers'}), '(testset, batch_size=args.test_batch_size, shuffle=False,\n drop_last=False, num_workers=args.workers)\n', (17808, 17912), False, 'from torch.utils.data import DataLoader\n'), ((18295, 18404), 'torch.utils.data.DataLoader', 'DataLoader', (['trainset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'drop_last': '(True)', 'num_workers': 'args.workers'}), '(trainset, batch_size=args.batch_size, shuffle=True, drop_last=\n True, num_workers=args.workers)\n', (18305, 18404), False, 'from torch.utils.data import DataLoader\n'), ((18417, 18531), 'torch.utils.data.DataLoader', 'DataLoader', (['testset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(False)', 'drop_last': '(False)', 'num_workers': 'args.workers'}), '(testset, batch_size=args.test_batch_size, shuffle=False,\n drop_last=False, num_workers=args.workers)\n', (18427, 18531), False, 'from torch.utils.data import DataLoader\n'), ((19585, 19632), 'torch.load', 'torch.load', (['args.pretrained'], {'map_location': '"""cpu"""'}), "(args.pretrained, map_location='cpu')\n", (19595, 19632), False, 'import torch\n'), ((6343, 6388), 'torch.tensor', 'torch.tensor', (['mask_y_binary'], {'dtype': 'torch.bool'}), '(mask_y_binary, dtype=torch.bool)\n', (6355, 6388), False, 'import torch\n'), ((6415, 6460), 'torch.tensor', 'torch.tensor', (['mask_x_binary'], {'dtype': 'torch.bool'}), '(mask_x_binary, dtype=torch.bool)\n', (6427, 6460), False, 'import torch\n'), ((6613, 6654), 'torch.tensor', 'torch.tensor', (['gt_mask_y'], {'dtype': 'torch.bool'}), '(gt_mask_y, dtype=torch.bool)\n', (6625, 6654), False, 'import torch\n'), ((6684, 6725), 'torch.tensor', 'torch.tensor', (['gt_mask_x'], {'dtype': 'torch.bool'}), '(gt_mask_x, dtype=torch.bool)\n', (6696, 6725), False, 'import torch\n'), ((16578, 16590), 'numpy.array', 'np.array', (['pc'], {}), '(pc)\n', (16586, 16590), True, 'import numpy as np\n'), ((16683, 16709), 'numpy.arange', 'np.arange', (['points.shape[0]'], {}), '(points.shape[0])\n', (16692, 16709), True, 'import numpy as np\n'), ((16714, 16743), 'numpy.random.shuffle', 'np.random.shuffle', (['points_idx'], {}), '(points_idx)\n', (16731, 16743), True, 'import numpy as np\n'), ((17949, 18023), 'learning3d.data_utils.ModelNet40Data', 'ModelNet40Data', ([], {'train': '(True)', 'num_points': 'args.num_points', 'unseen': 'args.unseen'}), '(train=True, num_points=args.num_points, unseen=args.unseen)\n', (17963, 18023), False, 'from learning3d.data_utils import RegistrationData, ModelNet40Data, AnyData\n'), ((18127, 18202), 'learning3d.data_utils.ModelNet40Data', 'ModelNet40Data', ([], {'train': '(False)', 'num_points': 'args.num_points', 'unseen': 'args.unseen'}), '(train=False, num_points=args.num_points, unseen=args.unseen)\n', (18141, 18202), False, 'from learning3d.data_utils import RegistrationData, ModelNet40Data, AnyData\n'), ((18687, 18721), 'learning3d.data_utils.AnyData', 'AnyData', ([], {'pc': 'points_test', 'mask': '(True)'}), '(pc=points_test, mask=True)\n', (18694, 18721), False, 'from learning3d.data_utils import RegistrationData, ModelNet40Data, AnyData\n'), ((18739, 18853), 'torch.utils.data.DataLoader', 'DataLoader', (['testset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(False)', 'drop_last': '(False)', 'num_workers': 'args.workers'}), '(testset, batch_size=args.test_batch_size, shuffle=False,\n drop_last=False, num_workers=args.workers)\n', (18749, 18853), False, 'from torch.utils.data import DataLoader\n'), ((19055, 19150), 'torch.utils.data.DataLoader', 'DataLoader', (['testset'], {'batch_size': '(1)', 'shuffle': '(False)', 'drop_last': '(False)', 'num_workers': 'args.workers'}), '(testset, batch_size=1, shuffle=False, drop_last=False,\n num_workers=args.workers)\n', (19065, 19150), False, 'from torch.utils.data import DataLoader\n'), ((2309, 2327), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (2325, 2327), False, 'import torch\n'), ((2374, 2392), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (2390, 2392), False, 'import torch\n'), ((4713, 4731), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (4729, 4731), False, 'import torch\n'), ((4778, 4796), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (4794, 4796), False, 'import torch\n'), ((9293, 9311), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (9309, 9311), False, 'import torch\n'), ((9358, 9376), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (9374, 9376), False, 'import torch\n'), ((18889, 18964), 'learning3d.data_utils.ModelNet40Data', 'ModelNet40Data', ([], {'train': '(False)', 'num_points': 'args.num_points', 'unseen': 'args.unseen'}), '(train=False, num_points=args.num_points, unseen=args.unseen)\n', (18903, 18964), False, 'from learning3d.data_utils import RegistrationData, ModelNet40Data, AnyData\n'), ((2828, 2864), 'torch.abs', 'torch.abs', (['(mask_x_binary - gt_mask_x)'], {}), '(mask_x_binary - gt_mask_x)\n', (2837, 2864), False, 'import torch\n'), ((2963, 2999), 'torch.abs', 'torch.abs', (['(mask_y_binary - gt_mask_y)'], {}), '(mask_y_binary - gt_mask_y)\n', (2972, 2999), False, 'import torch\n'), ((9763, 9799), 'torch.abs', 'torch.abs', (['(mask_x_binary - gt_mask_x)'], {}), '(mask_x_binary - gt_mask_x)\n', (9772, 9799), False, 'import torch\n'), ((9898, 9934), 'torch.abs', 'torch.abs', (['(mask_y_binary - gt_mask_y)'], {}), '(mask_y_binary - gt_mask_y)\n', (9907, 9934), False, 'import torch\n')]
import math import time import pickle import argparse from datetime import datetime import tensorflow as tf import numpy as np import dataset_info import model_info # Check num of gpus gpus = tf.config.experimental.list_physical_devices('GPU') num_gpus = len(gpus) for gpu in gpus: print('Name:', gpu.name, ' Type:', gpu.device_type) # Get arguments for job parser = argparse.ArgumentParser() parser.add_argument('--model', default='VGG19', type=str) parser.add_argument('--dataset', default=224, type=int) parser.add_argument('--batch_size', default=128, type=int) parser.add_argument('--optimizer', default='SGD', type=str) parser.add_argument('--prof_or_latency', default='profiling', type=str) parser.add_argument('--use_gpu_num', default=1, type=int) parser.add_argument('--prof_point', default=1.5, type=float) parser.add_argument('--prof_len', default=1, type=int) parser.add_argument('--instance_type', default='EC2', type=str) args = parser.parse_args() # Dataset Info dataset = dataset_info.select_dataset(args.dataset) model_name = args.model num_classes = dataset['num_classes'] img_rows = dataset['img_rows'] img_cols = dataset['img_cols'] img_channels = dataset['img_channels'] num_data = dataset['num_data'] num_test = dataset['num_test'] use_gpu_num = args.use_gpu_num if use_gpu_num > num_gpus: raise Exception(f'Detected gpu num is {num_gpus}, but using {use_gpu_num} gpus') batch_size = args.batch_size * use_gpu_num prof_point = args.prof_point batch_num = math.ceil(num_data/batch_size) epochs = math.ceil(prof_point) prof_start = math.floor(batch_num * prof_point) prof_len = args.prof_len prof_range = '{}, {}'.format(prof_start, prof_start + prof_len) optimizer = 'SGD' ###################### Build Synthetic Dataset ###################### x_train_shape = (num_data, img_rows, img_cols, img_channels) y_train_shape = (num_data, 1) x_test_shape = (num_test, img_rows, img_cols, img_channels) y_test_shape = (num_test, 1) x_train = np.random.rand(*x_train_shape) y_train = np.random.randint(num_classes, size=y_train_shape) x_test = np.random.rand(*x_test_shape) y_test = np.random.randint(num_classes, size=y_test_shape) ############################################################### if tf.keras.backend.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], img_channels, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], img_channels, img_rows, img_cols) input_shape = (img_channels, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, img_channels) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, img_channels) input_shape = (img_rows, img_cols, img_channels) x_train = x_train.astype('float32') x_test = x_test.astype('float32') y_train = tf.keras.utils.to_categorical(y_train, num_classes) y_test = tf.keras.utils.to_categorical(y_test, num_classes) # Select model from model info module device_names = [f'/device:GPU:{x}' for x in range(num_gpus)] use_device_names = device_names[:use_gpu_num] strategy = tf.distribute.MirroredStrategy(devices=use_device_names) print('Number of devices: {}'.format(strategy.num_replicas_in_sync)) if use_gpu_num == 1: model = model_info.select_model(model_name, input_shape, num_classes) model.compile(loss=tf.keras.losses.categorical_crossentropy, optimizer=optimizer, metrics=['accuracy']) else: with strategy.scope(): model = model_info.select_model(model_name, input_shape, num_classes) model.compile(loss=tf.keras.losses.categorical_crossentropy, optimizer=optimizer, metrics=['accuracy']) time_now = datetime.now().strftime("%Y%m%d-%H%M%S.%f") job_name = f'{args.instance_type}-{args.dataset}-{model_name}-{optimizer}-{batch_size}-{use_gpu_num}-{time_now}' logs = f'/home/ubuntu/profet/data_generation/logs/{job_name}' tboard_callback = tf.keras.callbacks.TensorBoard(log_dir = logs, histogram_freq = 1, profile_batch = prof_range) # Setting for latency check callback class BatchTimeCallback(tf.keras.callbacks.Callback): def on_train_begin(self, logs=None): self.all_times = [] def on_train_end(self, logs=None): time_filename = f'/home/ubuntu/profet/data_generation/tensorstats/times-{job_name}.pickle' time_file = open(time_filename, 'ab') pickle.dump(self.all_times, time_file) time_file.close() def on_epoch_begin(self, epoch, logs=None): self.epoch_times = [] self.epoch_time_start = time.time() def on_epoch_end(self, epoch, logs=None): self.epoch_time_end = time.time() self.all_times.append(self.epoch_time_end - self.epoch_time_start) self.all_times.append(self.epoch_times) def on_train_batch_begin(self, batch, logs=None): self.batch_time_start = time.time() def on_train_batch_end(self, batch, logs=None): self.epoch_times.append(time.time() - self.batch_time_start) latency_callback = BatchTimeCallback() prof_model_select = {'profiling': [tboard_callback], 'latency': [latency_callback], 'vanilla': []} model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test), callbacks=prof_model_select[args.prof_or_latency])
[ "dataset_info.select_dataset", "tensorflow.keras.utils.to_categorical", "math.ceil", "numpy.random.rand", "argparse.ArgumentParser", "math.floor", "tensorflow.keras.callbacks.TensorBoard", "model_info.select_model", "pickle.dump", "datetime.datetime.now", "numpy.random.randint", "tensorflow.di...
[((195, 246), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (239, 246), True, 'import tensorflow as tf\n'), ((375, 400), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (398, 400), False, 'import argparse\n'), ((997, 1038), 'dataset_info.select_dataset', 'dataset_info.select_dataset', (['args.dataset'], {}), '(args.dataset)\n', (1024, 1038), False, 'import dataset_info\n'), ((1492, 1524), 'math.ceil', 'math.ceil', (['(num_data / batch_size)'], {}), '(num_data / batch_size)\n', (1501, 1524), False, 'import math\n'), ((1532, 1553), 'math.ceil', 'math.ceil', (['prof_point'], {}), '(prof_point)\n', (1541, 1553), False, 'import math\n'), ((1567, 1601), 'math.floor', 'math.floor', (['(batch_num * prof_point)'], {}), '(batch_num * prof_point)\n', (1577, 1601), False, 'import math\n'), ((1972, 2002), 'numpy.random.rand', 'np.random.rand', (['*x_train_shape'], {}), '(*x_train_shape)\n', (1986, 2002), True, 'import numpy as np\n'), ((2013, 2063), 'numpy.random.randint', 'np.random.randint', (['num_classes'], {'size': 'y_train_shape'}), '(num_classes, size=y_train_shape)\n', (2030, 2063), True, 'import numpy as np\n'), ((2073, 2102), 'numpy.random.rand', 'np.random.rand', (['*x_test_shape'], {}), '(*x_test_shape)\n', (2087, 2102), True, 'import numpy as np\n'), ((2112, 2161), 'numpy.random.randint', 'np.random.randint', (['num_classes'], {'size': 'y_test_shape'}), '(num_classes, size=y_test_shape)\n', (2129, 2161), True, 'import numpy as np\n'), ((2804, 2855), 'tensorflow.keras.utils.to_categorical', 'tf.keras.utils.to_categorical', (['y_train', 'num_classes'], {}), '(y_train, num_classes)\n', (2833, 2855), True, 'import tensorflow as tf\n'), ((2865, 2915), 'tensorflow.keras.utils.to_categorical', 'tf.keras.utils.to_categorical', (['y_test', 'num_classes'], {}), '(y_test, num_classes)\n', (2894, 2915), True, 'import tensorflow as tf\n'), ((3073, 3129), 'tensorflow.distribute.MirroredStrategy', 'tf.distribute.MirroredStrategy', ([], {'devices': 'use_device_names'}), '(devices=use_device_names)\n', (3103, 3129), True, 'import tensorflow as tf\n'), ((3904, 3996), 'tensorflow.keras.callbacks.TensorBoard', 'tf.keras.callbacks.TensorBoard', ([], {'log_dir': 'logs', 'histogram_freq': '(1)', 'profile_batch': 'prof_range'}), '(log_dir=logs, histogram_freq=1,\n profile_batch=prof_range)\n', (3934, 3996), True, 'import tensorflow as tf\n'), ((2230, 2266), 'tensorflow.keras.backend.image_data_format', 'tf.keras.backend.image_data_format', ([], {}), '()\n', (2264, 2266), True, 'import tensorflow as tf\n'), ((3234, 3295), 'model_info.select_model', 'model_info.select_model', (['model_name', 'input_shape', 'num_classes'], {}), '(model_name, input_shape, num_classes)\n', (3257, 3295), False, 'import model_info\n'), ((3461, 3522), 'model_info.select_model', 'model_info.select_model', (['model_name', 'input_shape', 'num_classes'], {}), '(model_name, input_shape, num_classes)\n', (3484, 3522), False, 'import model_info\n'), ((3667, 3681), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3679, 3681), False, 'from datetime import datetime\n'), ((4451, 4489), 'pickle.dump', 'pickle.dump', (['self.all_times', 'time_file'], {}), '(self.all_times, time_file)\n', (4462, 4489), False, 'import pickle\n'), ((4627, 4638), 'time.time', 'time.time', ([], {}), '()\n', (4636, 4638), False, 'import time\n'), ((4716, 4727), 'time.time', 'time.time', ([], {}), '()\n', (4725, 4727), False, 'import time\n'), ((4938, 4949), 'time.time', 'time.time', ([], {}), '()\n', (4947, 4949), False, 'import time\n'), ((5035, 5046), 'time.time', 'time.time', ([], {}), '()\n', (5044, 5046), False, 'import time\n')]
import copy from collections import OrderedDict from typing import List import numpy as np from opticverge.core.chromosome.abstract_chromosome import AbstractChromosome from opticverge.core.chromosome.function_chromosome import FunctionChromosome from opticverge.core.generator.int_distribution_generator import rand_int from opticverge.core.generator.options_generator import rand_options from opticverge.core.generator.real_generator import rand_real class RandArrayChromosome(FunctionChromosome): """ The chromosome for generating fixed or dynamic arrays """ def __init__(self, generator: AbstractChromosome, length: int, fixed: bool = False): """ The constructor for this class Args: generator (AbstractChromosome): An instance of a class derived from an AbstractChromosome length (int): The length of the array fixed (bool): Whether the array length is fixed """ super(RandArrayChromosome, self).__init__(generator, OrderedDict()) """ The generator is responsible for producing each entry within the array """ self.__generator = generator """ The length represents the initial size of the array if fixed is True """ self.__length = length """ Fixed represents whether the array is subject to change during the evolutionary process. """ self.__fixed = fixed def generate(self, **kwargs): # determine the length of the array to generate length: int = self.__length if self.__fixed is True else rand_int(1, self.__length) # generate each of the positions of the array using the generator for i in range(length): self.genotype[i] = self.__generator.generate(**kwargs) # the phenotype of an array represents the values from the genotype, # since we use an OrderedDict as our base representation we are safe to # use list(self.genotype.values()) self.phenotype = list(self.genotype.values()) return self.phenotype def mutate(self, mutation_probability: float, **kwargs): """ The mutation function for the array_chromosome When mutating the ArrayChromosome we use a number of techniques to modify the contents. 1. Iterate through each entry in the array and with some probability change the value based on the generator 2. Then select pairs of positions at random with some probability and swap their values 3. If fixed is set to False then: a) Attempt to add an item to the array with some probability b) Attempt to remove an item from the array with some probability Args: mutation_probability: The likelihood that we will change the array **kwargs: Returns: """ # 1. Attempt to mutate each value for key, val in self.genotype.items(): if rand_real() < mutation_probability: self.genotype[key] = self.__generator.generate(**kwargs) # 2. Attempt to swap positions of the array keys: List[str or int] = list(self.genotype.keys()) if len(keys) > 1: # select the number of items to modify in the list items_to_select: int = rand_int(2, len(keys)) selected: List[str or int] = rand_options(keys, items_to_select) shuffled: List[np.int64] = copy.copy(selected) np.random.shuffle(shuffled) for i, key in enumerate(selected): if rand_real() < mutation_probability: self.genotype[selected[i]], self.genotype[shuffled[i]] = self.genotype[shuffled[i]], self.genotype[ selected[i]] # TODO: Sensibly define how to insert/update an OrderedDict # 3. Attempt to add and remove items to the array # if self.__fixed is False: # # # Add # num_positions = rand_int(1, len(keys)) # # # create a temporary placeholder to update the OrderedDict # temp_phenotype = list(self.genotype.values()) # # for i in range(num_positions): # # if rand_real() < mutation_probability: # position = rand_int(0, len(self.genotype.keys())) # temp_phenotype.insert(position, self.__generator.generate(**kwargs)) # # # Remove self.phenotype = list(self.genotype.values()) return self.phenotype
[ "collections.OrderedDict", "opticverge.core.generator.options_generator.rand_options", "opticverge.core.generator.int_distribution_generator.rand_int", "opticverge.core.generator.real_generator.rand_real", "copy.copy", "numpy.random.shuffle" ]
[((1003, 1016), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1014, 1016), False, 'from collections import OrderedDict\n'), ((1608, 1634), 'opticverge.core.generator.int_distribution_generator.rand_int', 'rand_int', (['(1)', 'self.__length'], {}), '(1, self.__length)\n', (1616, 1634), False, 'from opticverge.core.generator.int_distribution_generator import rand_int\n'), ((3412, 3447), 'opticverge.core.generator.options_generator.rand_options', 'rand_options', (['keys', 'items_to_select'], {}), '(keys, items_to_select)\n', (3424, 3447), False, 'from opticverge.core.generator.options_generator import rand_options\n'), ((3488, 3507), 'copy.copy', 'copy.copy', (['selected'], {}), '(selected)\n', (3497, 3507), False, 'import copy\n'), ((3521, 3548), 'numpy.random.shuffle', 'np.random.shuffle', (['shuffled'], {}), '(shuffled)\n', (3538, 3548), True, 'import numpy as np\n'), ((3000, 3011), 'opticverge.core.generator.real_generator.rand_real', 'rand_real', ([], {}), '()\n', (3009, 3011), False, 'from opticverge.core.generator.real_generator import rand_real\n'), ((3617, 3628), 'opticverge.core.generator.real_generator.rand_real', 'rand_real', ([], {}), '()\n', (3626, 3628), False, 'from opticverge.core.generator.real_generator import rand_real\n')]
#!/usr/bin/env python # # Baseline calculation script for NIfTI data sets. After specifying such # a data set and an optional brain mask, converts each participant to an # autocorrelation-based matrix representation. # # The goal is to summarise each participant as a voxel-by-voxel matrix. # # This script is specifically built for handling parcellated data. Other # data sources are not possible right now, as they would probably exceed # computational resources quickly. import argparse import math import os import warnings import numpy as np import numpy.ma as ma from tqdm import tqdm def basename(filename): """Calculate basename of a file. Removes all extensions from a filename and returns the basename of the file. This function is required to handle filenames with *two* or more extensions. """ filename = os.path.basename(filename) def _split_extension(filename): return os.path.splitext(filename) filename, extension = _split_extension(filename) while extension: filename, extension = _split_extension(filename) return filename if __name__ == '__main__': parser = argparse.ArgumentParser() default_file = \ '../results/parcellated_data/shaefer_masked_subject_data_shifted.npy' parser.add_argument( '-i', '--input', type=str, help='Input file', default=default_file, ) parser.add_argument( '-o', '--output', type=str, help='Output directory. If not set, will default to the current ' 'directory.', default='.' ) args = parser.parse_args() data = np.load(args.input) n_participants = data.shape[0] + 1 # Used to generate nice output files that follow the naming # convention in the remainder of the paper. n_digits = int(math.log10(n_participants) + 1) for index, X in tqdm(enumerate(data), desc='Subject'): filename = f'{index+1:0{n_digits}d}.npz' filename = os.path.join(args.output, filename) # Make sure that we only calculate correlations with valid # voxels. This is only be relevant for the data sets which # actually include a certain brain mask. X = ma.corrcoef(ma.masked_invalid(X.T)) X = np.nan_to_num(X) assert np.isnan(X).sum() == 0 # Nothing should be overwritten. Else, the script might be used # incorrectly, so we refuse to do anything. if os.path.exists(filename): warnings.warn(f'File {filename} already exists. Refusing to ' f'overwrite it and moving on.') continue np.savez(filename, X=X)
[ "os.path.exists", "numpy.savez", "argparse.ArgumentParser", "os.path.join", "os.path.splitext", "warnings.warn", "numpy.isnan", "os.path.basename", "numpy.ma.masked_invalid", "math.log10", "numpy.load", "numpy.nan_to_num" ]
[((847, 873), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (863, 873), False, 'import os\n'), ((1150, 1175), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1173, 1175), False, 'import argparse\n'), ((1649, 1668), 'numpy.load', 'np.load', (['args.input'], {}), '(args.input)\n', (1656, 1668), True, 'import numpy as np\n'), ((926, 952), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (942, 952), False, 'import os\n'), ((2002, 2037), 'os.path.join', 'os.path.join', (['args.output', 'filename'], {}), '(args.output, filename)\n', (2014, 2037), False, 'import os\n'), ((2282, 2298), 'numpy.nan_to_num', 'np.nan_to_num', (['X'], {}), '(X)\n', (2295, 2298), True, 'import numpy as np\n'), ((2474, 2498), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (2488, 2498), False, 'import os\n'), ((2663, 2686), 'numpy.savez', 'np.savez', (['filename'], {'X': 'X'}), '(filename, X=X)\n', (2671, 2686), True, 'import numpy as np\n'), ((1841, 1867), 'math.log10', 'math.log10', (['n_participants'], {}), '(n_participants)\n', (1851, 1867), False, 'import math\n'), ((2246, 2268), 'numpy.ma.masked_invalid', 'ma.masked_invalid', (['X.T'], {}), '(X.T)\n', (2263, 2268), True, 'import numpy.ma as ma\n'), ((2512, 2606), 'warnings.warn', 'warnings.warn', (['f"""File {filename} already exists. Refusing to overwrite it and moving on."""'], {}), "(\n f'File {filename} already exists. Refusing to overwrite it and moving on.')\n", (2525, 2606), False, 'import warnings\n'), ((2315, 2326), 'numpy.isnan', 'np.isnan', (['X'], {}), '(X)\n', (2323, 2326), True, 'import numpy as np\n')]
"""Prediction of Users based on Tweet embeddings.""" import numpy as np from sklearn.linear_model import LogisticRegression from .models import User from .twitter import BASILICA def predict_user( user1_name, user2_name, tweet_text): user1 = User.query.filter( User.name == user1_name).one() user2 = User.query.filter( User.name == user2_name).one() user1_embeddings = np.array( [tweet.embedding for tweet in user1.tweets]) user2_embeddings = np.array( [tweet.embedding for tweet in user2.tweets]) embeddings = np.vstack( [user1_embeddings, user2_embeddings]) labels = np.concatenate( [np.ones( len( user1.tweets)), np.zeros( len( user2.tweets))]) log_reg = LogisticRegression().fit( embeddings, labels) tweet_embedding = BASILICA.embed_sentence( tweet_text, model= 'twitter') return log_reg.predict(np.array( tweet_embedding).reshape( 1, -1))
[ "numpy.array", "numpy.vstack", "sklearn.linear_model.LogisticRegression" ]
[((386, 439), 'numpy.array', 'np.array', (['[tweet.embedding for tweet in user1.tweets]'], {}), '([tweet.embedding for tweet in user1.tweets])\n', (394, 439), True, 'import numpy as np\n'), ((464, 517), 'numpy.array', 'np.array', (['[tweet.embedding for tweet in user2.tweets]'], {}), '([tweet.embedding for tweet in user2.tweets])\n', (472, 517), True, 'import numpy as np\n'), ((536, 583), 'numpy.vstack', 'np.vstack', (['[user1_embeddings, user2_embeddings]'], {}), '([user1_embeddings, user2_embeddings])\n', (545, 583), True, 'import numpy as np\n'), ((720, 740), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (738, 740), False, 'from sklearn.linear_model import LogisticRegression\n'), ((871, 896), 'numpy.array', 'np.array', (['tweet_embedding'], {}), '(tweet_embedding)\n', (879, 896), True, 'import numpy as np\n')]
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), "..")) import time import math import random import numpy as np import scipy as sp from scipy.spatial import distance as scipydistance # from numba import jit, njit, vectorize, float64, int64 from sc2.position import Point2 import pytest from hypothesis import strategies as st, given, settings from typing import List, Dict, Set, Tuple, Any, Optional, Union import platform PYTHON_VERSION = platform.python_version_tuple() USING_PYTHON_3_8: bool = ("3", "8") <= PYTHON_VERSION def distance_to_python_raw(s, p): return ((s[0] - p[0]) ** 2 + (s[1] - p[1]) ** 2) ** 0.5 def distance_to_squared_python_raw(s, p): return (s[0] - p[0]) ** 2 + (s[1] - p[1]) ** 2 if USING_PYTHON_3_8: def distance_to_math_dist(s, p): return math.dist(s, p) def distance_to_math_hypot(s, p): return math.hypot((s[0] - p[0]), (s[1] - p[1])) def distance_scipy_euclidean(p1, p2) -> Union[int, float]: """ Distance calculation using scipy """ dist = scipydistance.euclidean(p1, p2) # dist = distance.cdist(p1.T, p2.T, "euclidean") return dist def distance_numpy_linalg_norm(p1, p2): """ Distance calculation using numpy """ return np.linalg.norm(p1 - p2) def distance_sum_squared_sqrt(p1, p2) -> Union[int, float]: """ Distance calculation using numpy """ return np.sqrt(np.sum((p1 - p2) ** 2)) def distance_sum_squared(p1, p2) -> Union[int, float]: """ Distance calculation using numpy """ return np.sum((p1 - p2) ** 2, axis=0) # @njit # def distance_python_raw_njit(p1: Point2, p2: Point2) -> Union[int, float]: # """ The built in Point2 distance function rewritten differently with njit, same structure as distance02 """ # return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 # @njit # def distance_python_raw_square_njit(p1: Point2, p2: Point2) -> Union[int, float]: # """ The built in Point2 distance function rewritten differently with njit, same structure as distance02 """ # return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 # @njit("float64(float64[:], float64[:])") # def distance_numpy_linalg_norm_njit(p1, p2): # """ Distance calculation using numpy + numba, same structure as distance12 """ # return np.linalg.norm(p1 - p2) # @njit("float64(float64[:], float64[:])") # def distance_numpy_square_sum_sqrt_njit(p1, p2) -> Union[int, float]: # """ Distance calculation using numpy + numba, same structure as distance13 """ # return np.sqrt(np.sum((p1 - p2) ** 2)) # @njit("float64(float64[:], float64[:])") # def distance_numpy_square_sum_njit(p1, p2) -> Union[int, float]: # """ Distance calculation using numpy + numba, same structure as distance13 """ # return np.sum((p1 - p2) ** 2, axis=0) # Points as Point2 object p1 = Point2((random.uniform(0, 300), random.uniform(0, 300))) p2 = Point2((random.uniform(0, 300), random.uniform(0, 300))) # Points as numpy array to get most accuracy if all points do not need to be converted before calculation p1_np = np.asarray(p1) p2_np = np.asarray(p2) # Correct result to ensure that in the functions the correct result is calculated correct_result = distance_to_math_hypot(p1, p2) # print(p1, p1_np) # print(p2, p2_np) # print(np.sum((p1_np - p2_np)**2)) # Do one call to jit to precompile once to get more accurate results # distance_python_raw_njit(p1_np, p2_np) # distance_python_raw_square_njit(p1_np, p2_np) # distance_numpy_linalg_norm_njit(p1_np, p2_np) # distance_numpy_square_sum_sqrt_njit(p1_np, p2_np) # distance_numpy_square_sum_njit(p1_np, p2_np) def check_result(result1, result2, accuracy=1e-5): if abs(result1 - result2) <= accuracy: return True return False if USING_PYTHON_3_8: def test_distance_to_math_dist(benchmark): result = benchmark(distance_to_math_dist, p1, p2) assert check_result(result, correct_result) def test_distance_to_math_hypot(benchmark): result = benchmark(distance_to_math_hypot, p1, p2) assert check_result(result, correct_result) def test_distance_to_python_raw(benchmark): result = benchmark(distance_to_python_raw, p1, p2) assert check_result(result, correct_result) def test_distance_to_squared_python_raw(benchmark): result = benchmark(distance_to_squared_python_raw, p1, p2) assert check_result(result, correct_result ** 2) def test_distance_scipy_euclidean(benchmark): result = benchmark(distance_scipy_euclidean, p1_np, p2_np) assert check_result(result, correct_result) def test_distance_numpy_linalg_norm(benchmark): result = benchmark(distance_numpy_linalg_norm, p1_np, p2_np) assert check_result(result, correct_result) def test_distance_sum_squared_sqrt(benchmark): result = benchmark(distance_sum_squared_sqrt, p1_np, p2_np) assert check_result(result, correct_result) def test_distance_sum_squared(benchmark): result = benchmark(distance_sum_squared, p1_np, p2_np) assert check_result(result, correct_result ** 2) # def test_distance_python_raw_njit(benchmark): # result = benchmark(distance_python_raw_njit, p1_np, p2_np) # assert check_result(result, correct_result) # def test_distance_python_raw_square_njit(benchmark): # result = benchmark(distance_python_raw_square_njit, p1_np, p2_np) # assert check_result(re`sult, correct_result ** 2) # # # def test_distance_numpy_linalg_norm_njit(benchmark): # result = benchmark(distance_numpy_linalg_norm_njit, p1_np, p2_np) # assert check_result(result, correct_result) # # # def test_distance_numpy_square_sum_sqrt_njit(benchmark): # result = benchmark(distance_numpy_square_sum_sqrt_njit, p1_np, p2_np) # assert check_result(result, correct_result) # # # def test_distance_numpy_square_sum_njit(benchmark): # result = benchmark(distance_numpy_square_sum_njit, p1_np, p2_np) # assert check_result(result, correct_result ** 2) # Run this file using # pipenv run pytest test/test_benchmark_distance_two_points.py --benchmark-compare
[ "random.uniform", "math.dist", "platform.python_version_tuple", "numpy.asarray", "numpy.sum", "os.path.dirname", "scipy.spatial.distance.euclidean", "numpy.linalg.norm", "math.hypot" ]
[((469, 500), 'platform.python_version_tuple', 'platform.python_version_tuple', ([], {}), '()\n', (498, 500), False, 'import platform\n'), ((3060, 3074), 'numpy.asarray', 'np.asarray', (['p1'], {}), '(p1)\n', (3070, 3074), True, 'import numpy as np\n'), ((3083, 3097), 'numpy.asarray', 'np.asarray', (['p2'], {}), '(p2)\n', (3093, 3097), True, 'import numpy as np\n'), ((885, 921), 'math.hypot', 'math.hypot', (['(s[0] - p[0])', '(s[1] - p[1])'], {}), '(s[0] - p[0], s[1] - p[1])\n', (895, 921), False, 'import math\n'), ((1043, 1074), 'scipy.spatial.distance.euclidean', 'scipydistance.euclidean', (['p1', 'p2'], {}), '(p1, p2)\n', (1066, 1074), True, 'from scipy.spatial import distance as scipydistance\n'), ((1242, 1265), 'numpy.linalg.norm', 'np.linalg.norm', (['(p1 - p2)'], {}), '(p1 - p2)\n', (1256, 1265), True, 'import numpy as np\n'), ((1529, 1559), 'numpy.sum', 'np.sum', (['((p1 - p2) ** 2)'], {'axis': '(0)'}), '((p1 - p2) ** 2, axis=0)\n', (1535, 1559), True, 'import numpy as np\n'), ((45, 70), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (60, 70), False, 'import sys, os\n'), ((822, 837), 'math.dist', 'math.dist', (['s', 'p'], {}), '(s, p)\n', (831, 837), False, 'import math\n'), ((1392, 1414), 'numpy.sum', 'np.sum', (['((p1 - p2) ** 2)'], {}), '((p1 - p2) ** 2)\n', (1398, 1414), True, 'import numpy as np\n'), ((2835, 2857), 'random.uniform', 'random.uniform', (['(0)', '(300)'], {}), '(0, 300)\n', (2849, 2857), False, 'import random\n'), ((2859, 2881), 'random.uniform', 'random.uniform', (['(0)', '(300)'], {}), '(0, 300)\n', (2873, 2881), False, 'import random\n'), ((2897, 2919), 'random.uniform', 'random.uniform', (['(0)', '(300)'], {}), '(0, 300)\n', (2911, 2919), False, 'import random\n'), ((2921, 2943), 'random.uniform', 'random.uniform', (['(0)', '(300)'], {}), '(0, 300)\n', (2935, 2943), False, 'import random\n')]
""" Baseline functions that can be used without fluffy. """ import numpy as np import scipy.ndimage as ndi import skimage.io import tensorflow as tf def predict_baseline( image: np.ndarray, model: tf.keras.models.Model, bit_depth: int = 16 ) -> np.ndarray: """ Returns a binary or categorical model based prediction of an image. Args: - image: Image to be predicted. - model: Model used to predict the image. - bit_depth: Bit depth to normalize images. Model dependent. Returns: - pred: Predicted image containing a probablilty map. """ if not isinstance(image, np.ndarray): raise TypeError(f"image must be of type np.ndarray but is {type(image)}.") if not isinstance(model, tf.keras.models.Model): raise TypeError(f"model must be of type np.ndarray but is {type(model)}.") if not isinstance(bit_depth, int): raise TypeError( f"bit_depth must be of type np.ndarray but is {type(bit_depth)}." ) if bit_depth == 0: raise ZeroDivisionError(f"bit_depth must not be zero") def __next_power(x: float, k: int = 2): """ Calculates x's next higher power of k. """ y, power = 0, 1 while y < x: y = k ** power power += 1 return y model_output = model.layers[-1].output_shape[-1] if model_output not in [1, 3]: raise ValueError(f"model_output must be 1 or 3 but is {model_output}") pred = image * (1.0 / (2 ** bit_depth - 1)) pad_bottom = __next_power(pred.shape[0]) - pred.shape[0] pad_right = __next_power(pred.shape[1]) - pred.shape[1] pred = np.pad(pred, ((0, pad_bottom), (0, pad_right)), "reflect") pred = model.predict(pred[None, ..., None]).squeeze() pred = pred[: pred.shape[0] - pad_bottom, : pred.shape[1] - pad_right] return pred def add_instances(pred_mask: np.ndarray) -> np.ndarray: """ Adds instances to a categorical prediction with three layers (background, foreground, borders). Args: - pred_mask: Prediction mask to for instances should be added. Returns: - pred: 2D mask containing unique values for every instance. """ if not isinstance(pred_mask, np.ndarray): raise TypeError(f"pred_mask must be np.ndarray but is {type(pred_mask)}") if not pred_mask.ndim == 3: raise ValueError(f"pred_mask must have 3 dimensions but has {pred_mask.ndim}") foreground_eroded = ndi.binary_erosion(pred_mask[..., 1] > 0.5, iterations=2) markers = skimage.measure.label(foreground_eroded) background = 1 - pred_mask[..., 0] > 0.5 foreground = 1 - pred_mask[..., 1] > 0.5 watershed = skimage.morphology.watershed( foreground, markers=markers, mask=background ) mask_new = [] for i in np.unique(watershed): mask_curr = watershed == i mask_curr = ndi.binary_erosion(mask_curr, iterations=2) mask_new.append(mask_curr * i) return np.argmax(mask_new, axis=0)
[ "scipy.ndimage.binary_erosion", "numpy.pad", "numpy.argmax", "numpy.unique" ]
[((1657, 1715), 'numpy.pad', 'np.pad', (['pred', '((0, pad_bottom), (0, pad_right))', '"""reflect"""'], {}), "(pred, ((0, pad_bottom), (0, pad_right)), 'reflect')\n", (1663, 1715), True, 'import numpy as np\n'), ((2475, 2532), 'scipy.ndimage.binary_erosion', 'ndi.binary_erosion', (['(pred_mask[..., 1] > 0.5)'], {'iterations': '(2)'}), '(pred_mask[..., 1] > 0.5, iterations=2)\n', (2493, 2532), True, 'import scipy.ndimage as ndi\n'), ((2815, 2835), 'numpy.unique', 'np.unique', (['watershed'], {}), '(watershed)\n', (2824, 2835), True, 'import numpy as np\n'), ((2986, 3013), 'numpy.argmax', 'np.argmax', (['mask_new'], {'axis': '(0)'}), '(mask_new, axis=0)\n', (2995, 3013), True, 'import numpy as np\n'), ((2892, 2935), 'scipy.ndimage.binary_erosion', 'ndi.binary_erosion', (['mask_curr'], {'iterations': '(2)'}), '(mask_curr, iterations=2)\n', (2910, 2935), True, 'import scipy.ndimage as ndi\n')]
# -*- coding: utf-8 -*- """ Created on Sun Jun 16 07:34:10 2019 @author: Brendan """ import os import numpy as np class TestPreProcess(): def test_works(self): raw_dir = './images/raw/demo' processed_dir = './images/processed/demo' Nfiles = 256 command = ('python preProcessDemo.py --raw_dir {} --processed_dir {} ' '--Nfiles {}').format(raw_dir, processed_dir, Nfiles) os.system(command) assert os.path.exists(os.path.join(processed_dir, 'dataCube.npy')) def test_cube_dim(self): processed_dir = './images/processed/demo' Nfiles = 256 path = os.path.join(processed_dir, 'dataCube.npy') cube_shape = np.load(path).shape assert cube_shape[2] == Nfiles def test_matching_dim(self): processed_dir = './images/processed/demo' Nfiles = 256 ts_size = np.load(os.path.join(processed_dir, 'timestamps.npy')).size exp_size = np.load(os.path.join(processed_dir, 'exposures.npy')).size assert ts_size == exp_size == Nfiles def test_periodic(self): processed_dir = './images/processed/demo' data = np.load(os.path.join(processed_dir, 'dataCube.npy'))[0,0] assert data[0] == data[data.size//2] assert data[data.size//8] == data[data.size//8 + data.size//2] class TestFftAvg(): def test_works(self): processed_dir = './images/processed/demo' box_avg_size = 3 num_segments = 1 command = ('python fftAvg.py --processed_dir {} --box_avg_size {} ' ' --num_segments {}'.format(processed_dir, box_avg_size, num_segments)) os.system(command) assert os.path.exists(os.path.join(processed_dir, 'specCube.npy')) def test_matching_dim(self): processed_dir = './images/processed/demo' cube = np.load(os.path.join(processed_dir, 'dataCube.npy')) spec = np.load(os.path.join(processed_dir, 'specCube.npy')) freqs = np.load(os.path.join(processed_dir, 'frequencies.npy')) print("{} (spec) == {} (freqs) == {}/2 (cube)".format(spec.shape[2], freqs.size, (cube.shape[2]//2))) assert spec.shape[2] == freqs.size == (cube.shape[2]//2) def test_freqs(self): processed_dir = './images/processed/demo' freqs = np.load(os.path.join(processed_dir, 'frequencies.npy')) ts = np.load(os.path.join(processed_dir, 'timestamps.npy')) tDiff = list(np.diff(ts)) timeStep = max(tDiff, key=tDiff.count) assert (1/freqs[-1]) == (2*timeStep) # Nyquist frequency assert (1/freqs[0]) == (ts.size*timeStep) def test_power(self): processed_dir = './images/processed/demo' spec = np.load(os.path.join(processed_dir, 'specCube.npy'))[0,0] assert abs(spec.sum() - 1.) < 0.01 # total power very close to 1
[ "os.system", "numpy.load", "os.path.join", "numpy.diff" ]
[((441, 459), 'os.system', 'os.system', (['command'], {}), '(command)\n', (450, 459), False, 'import os\n'), ((657, 700), 'os.path.join', 'os.path.join', (['processed_dir', '"""dataCube.npy"""'], {}), "(processed_dir, 'dataCube.npy')\n", (669, 700), False, 'import os\n'), ((1712, 1730), 'os.system', 'os.system', (['command'], {}), '(command)\n', (1721, 1730), False, 'import os\n'), ((490, 533), 'os.path.join', 'os.path.join', (['processed_dir', '"""dataCube.npy"""'], {}), "(processed_dir, 'dataCube.npy')\n", (502, 533), False, 'import os\n'), ((722, 735), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (729, 735), True, 'import numpy as np\n'), ((1761, 1804), 'os.path.join', 'os.path.join', (['processed_dir', '"""specCube.npy"""'], {}), "(processed_dir, 'specCube.npy')\n", (1773, 1804), False, 'import os\n'), ((1921, 1964), 'os.path.join', 'os.path.join', (['processed_dir', '"""dataCube.npy"""'], {}), "(processed_dir, 'dataCube.npy')\n", (1933, 1964), False, 'import os\n'), ((1989, 2032), 'os.path.join', 'os.path.join', (['processed_dir', '"""specCube.npy"""'], {}), "(processed_dir, 'specCube.npy')\n", (2001, 2032), False, 'import os\n'), ((2058, 2104), 'os.path.join', 'os.path.join', (['processed_dir', '"""frequencies.npy"""'], {}), "(processed_dir, 'frequencies.npy')\n", (2070, 2104), False, 'import os\n'), ((2390, 2436), 'os.path.join', 'os.path.join', (['processed_dir', '"""frequencies.npy"""'], {}), "(processed_dir, 'frequencies.npy')\n", (2402, 2436), False, 'import os\n'), ((2459, 2504), 'os.path.join', 'os.path.join', (['processed_dir', '"""timestamps.npy"""'], {}), "(processed_dir, 'timestamps.npy')\n", (2471, 2504), False, 'import os\n'), ((2527, 2538), 'numpy.diff', 'np.diff', (['ts'], {}), '(ts)\n', (2534, 2538), True, 'import numpy as np\n'), ((912, 957), 'os.path.join', 'os.path.join', (['processed_dir', '"""timestamps.npy"""'], {}), "(processed_dir, 'timestamps.npy')\n", (924, 957), False, 'import os\n'), ((991, 1035), 'os.path.join', 'os.path.join', (['processed_dir', '"""exposures.npy"""'], {}), "(processed_dir, 'exposures.npy')\n", (1003, 1035), False, 'import os\n'), ((1194, 1237), 'os.path.join', 'os.path.join', (['processed_dir', '"""dataCube.npy"""'], {}), "(processed_dir, 'dataCube.npy')\n", (1206, 1237), False, 'import os\n'), ((2807, 2850), 'os.path.join', 'os.path.join', (['processed_dir', '"""specCube.npy"""'], {}), "(processed_dir, 'specCube.npy')\n", (2819, 2850), False, 'import os\n')]
import zarr from typing import Any, Tuple, List, Union import numpy as np from tqdm import tqdm from .readers import CrReader, H5adReader, NaboH5Reader, LoomReader import os import pandas as pd from .utils import controlled_compute from .logging_utils import logger from scipy.sparse import csr_matrix __all__ = ['create_zarr_dataset', 'create_zarr_obj_array', 'create_zarr_count_assay', 'subset_assay_zarr', 'dask_to_zarr', 'ZarrMerge', 'CrToZarr', 'H5adToZarr', 'MtxToZarr', 'NaboH5ToZarr', 'LoomToZarr', 'SparseToZarr'] def create_zarr_dataset(g: zarr.hierarchy, name: str, chunks: tuple, dtype: Any, shape: Tuple, overwrite: bool = True) -> zarr.hierarchy: from numcodecs import Blosc compressor = Blosc(cname='lz4', clevel=5, shuffle=Blosc.BITSHUFFLE) return g.create_dataset(name, chunks=chunks, dtype=dtype, shape=shape, compressor=compressor, overwrite=overwrite) def create_zarr_obj_array(g: zarr.hierarchy, name: str, data, dtype: Union[str, Any] = None, overwrite: bool = True) -> zarr.hierarchy: data = np.array(data) if dtype is None or dtype == object: dtype = 'U' + str(max([len(str(x)) for x in data])) if np.issubdtype(data.dtype, np.dtype('S')): data = data.astype('U') return g.create_dataset(name, data=data, chunks=(100000,), shape=len(data), dtype=dtype, overwrite=overwrite) def create_zarr_count_assay(z: zarr.hierarchy, assay_name: str, chunk_size: Tuple[int, int], n_cells: int, feat_ids: Union[np.ndarray, List[str]], feat_names: Union[np.ndarray, List[str]], dtype: str = 'uint32') -> zarr.hierarchy: g = z.create_group(assay_name, overwrite=True) g.attrs['is_assay'] = True g.attrs['misc'] = {} create_zarr_obj_array(g, 'featureData/ids', feat_ids) create_zarr_obj_array(g, 'featureData/names', feat_names) create_zarr_obj_array(g, 'featureData/I', [True for _ in range(len(feat_ids))], 'bool') return create_zarr_dataset(g, 'counts', chunk_size, dtype, (n_cells, len(feat_ids)), overwrite=True) class CrToZarr: def __init__(self, cr: CrReader, zarr_fn: str, chunk_size=(1000, 1000), dtype: str = 'uint32'): self.cr = cr self.fn = zarr_fn self.chunkSizes = chunk_size self.z = zarr.open(self.fn, mode='w') self._ini_cell_data() for assay_name in self.cr.assayFeats.columns: create_zarr_count_assay(self.z, assay_name, chunk_size, self.cr.nCells, self.cr.feature_ids(assay_name), self.cr.feature_names(assay_name), dtype) def _ini_cell_data(self): g = self.z.create_group('cellData') create_zarr_obj_array(g, 'ids', self.cr.cell_names()) create_zarr_obj_array(g, 'names', self.cr.cell_names()) create_zarr_obj_array(g, 'I', [True for _ in range(self.cr.nCells)], 'bool') def dump(self, batch_size: int = 1000, lines_in_mem: int = 100000) -> None: stores = [self.z["%s/counts" % x] for x in self.cr.assayFeats.columns] spidx = [0] + list(self.cr.assayFeats.T.nFeatures.cumsum().values) spidx = [(spidx[x - 1], spidx[x]) for x in range(1, len(spidx))] s, e, = 0, 0 n_chunks = self.cr.nCells//batch_size + 1 for a in tqdm(self.cr.consume(batch_size, lines_in_mem), total=n_chunks): e += a.shape[0] a = a.todense() for j in range(len(stores)): stores[j][s:e] = a[:, spidx[j][0]:spidx[j][1]] s = e if e != self.cr.nCells: raise AssertionError("ERROR: This is a bug in CrToZarr. All cells might not have been successfully " "written into the zarr file. Please report this issue") class MtxToZarr: def __init__(self, cr: CrReader, zarr_fn: str, chunk_size=(1000, 1000), dtype: str = 'uint32'): self.cr = cr self.fn = zarr_fn self.chunkSizes = chunk_size self.z = zarr.open(self.fn, mode='w') self._ini_cell_data() for assay_name in set(self.cr.assayFeats.columns): create_zarr_count_assay(self.z, assay_name, chunk_size, self.cr.nCells, self.cr.feature_ids(assay_name), self.cr.feature_names(assay_name), dtype) def _ini_cell_data(self): g = self.z.create_group('cellData') create_zarr_obj_array(g, 'ids', self.cr.cell_names()) create_zarr_obj_array(g, 'names', self.cr.cell_names()) create_zarr_obj_array(g, 'I', [True for _ in range(self.cr.nCells)], 'bool') def _prep_assay_ranges(self): ret_val = {} for assay in set(self.cr.assayFeats.columns): temp = [] if len(self.cr.assayFeats[assay].shape) == 2: for i in self.cr.assayFeats[assay].values[1:3].T: temp.append([i[0], i[1]]) else: idx = self.cr.assayFeats[assay] temp = [[idx.start, idx.end]] ret_val[assay] = temp return ret_val def dump(self, batch_size: int = 1000, lines_in_mem: int = 100000) -> None: stores = {x: self.z["%s/counts" % x] for x in set(self.cr.assayFeats.columns)} assay_ranges = self._prep_assay_ranges() s, e, = 0, 0 n_chunks = self.cr.nCells // batch_size + 1 for a in tqdm(self.cr.consume(batch_size, lines_in_mem), total=n_chunks): e += a.shape[0] a = a.todense() b = {x: [] for x in stores.keys()} for store_name in stores.keys(): ar = assay_ranges[store_name] temp = [] for i in ar: temp.append(a[:, i[0]:i[1]]) if len(temp) > 1: b[store_name] = np.hstack(temp) else: b[store_name] = temp[0] for store_name in stores.keys(): stores[store_name][s:e] = b[store_name] s = e if e != self.cr.nCells: raise AssertionError("ERROR: This is a bug in MtxToZarr. All cells might not have been successfully " "written into the zarr file. Please report this issue") class H5adToZarr: def __init__(self, h5ad: H5adReader, zarr_fn: str, assay_name: str = None, chunk_size=(1000, 1000), dtype: str = 'uint32'): # TODO: support for multiple assay. One of the `var` datasets can be used to group features in separate assays self.h5ad = h5ad self.fn = zarr_fn self.chunkSizes = chunk_size if assay_name is None: logger.info(f"No value provided for assay names. Will use default value: 'RNA'") self.assayName = 'RNA' else: self.assayName = assay_name self.z = zarr.open(self.fn, mode='w') self._ini_cell_data() create_zarr_count_assay(self.z, self.assayName, chunk_size, self.h5ad.nCells, self.h5ad.feat_ids(), self.h5ad.feat_names(), dtype) for i, j in self.h5ad.get_feat_columns(): if i not in self.z[self.assayName]['featureData']: create_zarr_obj_array(self.z[self.assayName]['featureData'], i, j, j.dtype) def _ini_cell_data(self): g = self.z.create_group('cellData') ids = self.h5ad.cell_ids() create_zarr_obj_array(g, 'ids', ids, ids.dtype) create_zarr_obj_array(g, 'names', ids, ids.dtype) create_zarr_obj_array(g, 'I', [True for _ in range(self.h5ad.nCells)], 'bool') for i, j in self.h5ad.get_cell_columns(): create_zarr_obj_array(g, i, j, j.dtype) def dump(self, batch_size: int = 1000) -> None: store = self.z["%s/counts" % self.assayName] s, e, = 0, 0 n_chunks = self.h5ad.nCells//batch_size + 1 for a in tqdm(self.h5ad.consume(batch_size), total=n_chunks): e += a.shape[0] store[s:e] = a s = e if e != self.h5ad.nCells: raise AssertionError("ERROR: This is a bug in H5adToZarr. All cells might not have been successfully " "written into the zarr file. Please report this issue") class NaboH5ToZarr: def __init__(self, h5: NaboH5Reader, zarr_fn: str, assay_name: str = None, chunk_size=(1000, 1000), dtype: str = 'uint32'): self.h5 = h5 self.fn = zarr_fn self.chunkSizes = chunk_size if assay_name is None: logger.info(f"No value provided for assay names. Will use default value: 'RNA'") self.assayName = 'RNA' else: self.assayName = assay_name self.z = zarr.open(self.fn, mode='w') self._ini_cell_data() create_zarr_count_assay(self.z, self.assayName, chunk_size, self.h5.nCells, self.h5.feat_ids(), self.h5.feat_names(), dtype) def _ini_cell_data(self): g = self.z.create_group('cellData') create_zarr_obj_array(g, 'ids', self.h5.cell_ids()) create_zarr_obj_array(g, 'names', self.h5.cell_ids()) create_zarr_obj_array(g, 'I', [True for _ in range(self.h5.nCells)], 'bool') def dump(self, batch_size: int = 500) -> None: store = self.z["%s/counts" % self.assayName] s, e, = 0, 0 n_chunks = self.h5.nCells // batch_size + 1 for a in tqdm(self.h5.consume(batch_size), total=n_chunks): e += a.shape[0] store[s:e] = a s = e if e != self.h5.nCells: raise AssertionError("ERROR: This is a bug in NaboH5ToZarr. All cells might not have been successfully " "written into the zarr file. Please report this issue") class LoomToZarr: def __init__(self, loom: LoomReader, zarr_fn: str, assay_name: str = None, chunk_size=(1000, 1000)): """ Converts Loom file read using scarf.LoomReader into Scarf's Zarr format Args: loom: LoomReader object used to open Loom format file zarr_fn: Output Zarr filename with path assay_name: Name for the output assay. If not provided then automatically set to RNA chunk_size: Chunk size for the count matrix saved in Zarr file. """ # TODO: support for multiple assay. Data from within individual layers can be treated as separate assays self.loom = loom self.fn = zarr_fn self.chunkSizes = chunk_size if assay_name is None: logger.info(f"No value provided for assay names. Will use default value: 'RNA'") self.assayName = 'RNA' else: self.assayName = assay_name self.z = zarr.open(self.fn, mode='w') self._ini_cell_data() create_zarr_count_assay(self.z, self.assayName, chunk_size, self.loom.nCells, self.loom.feature_ids(), self.loom.feature_names(), self.loom.matrixDtype) for i, j in self.loom.get_feature_attrs(): create_zarr_obj_array(self.z[self.assayName]['featureData'], i, j, j.dtype) def _ini_cell_data(self): g = self.z.create_group('cellData') create_zarr_obj_array(g, 'ids', self.loom.cell_ids()) create_zarr_obj_array(g, 'names', self.loom.cell_ids()) create_zarr_obj_array(g, 'I', [True for _ in range(self.loom.nCells)], 'bool') for i, j in self.loom.get_cell_attrs(): create_zarr_obj_array(g, i, j, j.dtype) def dump(self, batch_size: int = 1000) -> None: store = self.z["%s/counts" % self.assayName] s, e, = 0, 0 n_chunks = self.loom.nCells//batch_size + 1 for a in tqdm(self.loom.consume(batch_size), total=n_chunks): e += a.shape[0] store[s:e] = a s = e if e != self.loom.nCells: raise AssertionError("ERROR: This is a bug in LoomToZarr. All cells might not have been successfully " "written into the zarr file. Please report this issue") class SparseToZarr: def __init__(self, csr_mat: csr_matrix, zarr_fn: str, cell_ids: List[str], feature_ids: List[str], assay_name: str = None, chunk_size=(1000, 1000), ): self.mat = csr_mat self.fn = zarr_fn self.chunkSizes = chunk_size if assay_name is None: logger.info(f"No value provided for assay names. Will use default value: 'RNA'") self.assayName = 'RNA' else: self.assayName = assay_name self.nFeatures, self.nCells = self.mat.shape if len(cell_ids) != self.nCells: raise ValueError("ERROR: Number of cell ids are not same as number of cells in the matrix") if len(feature_ids) != self.nFeatures: raise ValueError("ERROR: Number of feature ids are not same as number of features in the matrix") self.z = zarr.open(self.fn, mode='w') self._ini_cell_data(cell_ids) create_zarr_count_assay(self.z, self.assayName, chunk_size, self.nCells, feature_ids, feature_ids, 'int64') def _ini_cell_data(self, cell_ids): g = self.z.create_group('cellData') create_zarr_obj_array(g, 'ids', cell_ids) create_zarr_obj_array(g, 'names', cell_ids) create_zarr_obj_array(g, 'I', [True for _ in range(self.nCells)], 'bool') def dump(self, batch_size: int = 1000) -> None: store = self.z["%s/counts" % self.assayName] s, e, = 0, 0 n_chunks = self.nCells//batch_size + 1 for e in tqdm(range(batch_size, self.nCells+batch_size, batch_size), total=n_chunks): if s == self.nCells: raise ValueError("Unexpected error encountered in writing to Zarr. The last iteration has failed. " "Please report this issue.") if e > self.nCells: e = self.nCells store[s:e] = self.mat[:, s:e].todense().T s = e if e != self.nCells: raise AssertionError("ERROR: This is a bug in SparseToZarr. All cells might not have been successfully " "written into the zarr file. Please report this issue") def subset_assay_zarr(zarr_fn: str, in_grp: str, out_grp: str, cells_idx: np.ndarray, feat_idx: np.ndarray, chunk_size: tuple): z = zarr.open(zarr_fn, 'r+') ig = z[in_grp] og = create_zarr_dataset(z, out_grp, chunk_size, 'uint32', (len(cells_idx), len(feat_idx))) pos_start, pos_end = 0, 0 for i in tqdm(np.array_split(cells_idx, len(cells_idx) // chunk_size[0] + 1)): pos_end += len(i) og[pos_start:pos_end, :] = ig.get_orthogonal_selection((i, feat_idx)) pos_start = pos_end return None def dask_to_zarr(df, z, loc, chunk_size, nthreads: int, msg: str = None): if msg is None: msg = f"Writing data to {loc}" og = create_zarr_dataset(z, loc, chunk_size, 'float64', df.shape) pos_start, pos_end = 0, 0 for i in tqdm(df.blocks, total=df.numblocks[0], desc=msg): pos_end += i.shape[0] og[pos_start:pos_end, :] = controlled_compute(i, nthreads) pos_start = pos_end return None class ZarrMerge: def __init__(self, zarr_path: str, assays: list, names: List[str], merge_assay_name: str, chunk_size=(1000, 1000), dtype: str = 'uint32', overwrite: bool = False): self.assays = assays self.names = names self.mergedCells = self._merge_cell_table() self.nCells = self.mergedCells.shape[0] self.featCollection = self._get_feat_ids(assays) self.mergedFeats = self._merge_order_feats() self.nFeats = self.mergedFeats.shape[0] self.featOrder = self._ref_order_feat_idx() self.z = self._use_existing_zarr(zarr_path, merge_assay_name, overwrite) self._ini_cell_data() self.assayGroup = create_zarr_count_assay( self.z['/'], merge_assay_name, chunk_size, self.nCells, list(self.mergedFeats.index), list(self.mergedFeats.names.values), dtype ) def _merge_cell_table(self): ret_val = [] if len(self.assays) != len(set(self.names)): raise ValueError("ERROR: A unique name should be provided for each of the assay") for assay, name in zip(self.assays, self.names): a = pd.DataFrame({ 'names': assay.cells.fetch_all('names'), 'ids': [f"{name}__{x}" for x in assay.cells.fetch_all('ids')] }) ret_val.append(a) return pd.concat(ret_val).reset_index().drop(columns='index') @staticmethod def _get_feat_ids(assays): ret_val = [] for i in assays: ret_val.append(i.feats.to_pandas_dataframe(['names', 'ids']).set_index('ids')['names'].to_dict()) return ret_val def _merge_order_feats(self): union_set = {} for ids in self.featCollection: for i in ids: if i not in union_set: union_set[i] = ids[i] return pd.DataFrame({'idx': range(len(union_set)), 'names': list(union_set.values()), 'ids': list(union_set.keys())}).set_index('ids') def _ref_order_feat_idx(self): ret_val = [] for ids in self.featCollection: ret_val.append(self.mergedFeats['idx'].reindex(ids).values) return ret_val def _use_existing_zarr(self, zarr_path, merge_assay_name, overwrite): try: z = zarr.open(zarr_path, mode='r') if 'cellData' not in z: raise ValueError( f"ERROR: Zarr file with name {zarr_path} exists but seems corrupted. Either delete the " "existing file or choose another path") if merge_assay_name in z: if overwrite is False: raise ValueError( f"ERROR: Zarr file `{zarr_path}` already contains {merge_assay_name} assay. Choose " "a different zarr path or a different assay name. Otherwise set overwrite to True") try: if not all(z['cellData']['ids'][:] == np.array(self.mergedCells['ids'].values)): raise ValueError(f"ERROR: order of cells does not match the one in existing file: {zarr_path}") except KeyError: raise ValueError(f"ERROR: 'cell data' in Zarr file {zarr_path} seems corrupted. Either delete the " "existing file or choose another path") return zarr.open(zarr_path, mode='r+') except ValueError: # So no zarr file with same name exists. Check if a non zarr folder with the same name exists if os.path.exists(zarr_path): raise ValueError( f"ERROR: Directory/file with name `{zarr_path}`exists. Either delete it or use another name") # creating a new zarr file return zarr.open(zarr_path, mode='w') def _ini_cell_data(self): if 'cellData' not in self.z: g = self.z.create_group('cellData') create_zarr_obj_array(g, 'ids', list(self.mergedCells['ids'].values)) create_zarr_obj_array(g, 'names', list(self.mergedCells['names'])) create_zarr_obj_array(g, 'I', [True for _ in range(self.mergedCells.shape[0])], 'bool') else: logger.info(f"cellData already exists so skipping _ini_cell_data") def write(self, nthreads=2): pos_start, pos_end = 0, 0 for assay, feat_order in zip(self.assays, self.featOrder): for i in tqdm(assay.rawData.blocks, total=assay.rawData.numblocks[0], desc=f"Writing data to merged file"): pos_end += i.shape[0] a = np.ones((i.shape[0], self.nFeats)) a[:, feat_order] = controlled_compute(i, nthreads) self.assayGroup[pos_start:pos_end, :] = a pos_start = pos_end
[ "os.path.exists", "numpy.ones", "numpy.hstack", "tqdm.tqdm", "numpy.array", "zarr.open", "numcodecs.Blosc", "numpy.dtype", "pandas.concat" ]
[((760, 814), 'numcodecs.Blosc', 'Blosc', ([], {'cname': '"""lz4"""', 'clevel': '(5)', 'shuffle': 'Blosc.BITSHUFFLE'}), "(cname='lz4', clevel=5, shuffle=Blosc.BITSHUFFLE)\n", (765, 814), False, 'from numcodecs import Blosc\n'), ((1137, 1151), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1145, 1151), True, 'import numpy as np\n'), ((14660, 14684), 'zarr.open', 'zarr.open', (['zarr_fn', '"""r+"""'], {}), "(zarr_fn, 'r+')\n", (14669, 14684), False, 'import zarr\n'), ((15309, 15357), 'tqdm.tqdm', 'tqdm', (['df.blocks'], {'total': 'df.numblocks[0]', 'desc': 'msg'}), '(df.blocks, total=df.numblocks[0], desc=msg)\n', (15313, 15357), False, 'from tqdm import tqdm\n'), ((1286, 1299), 'numpy.dtype', 'np.dtype', (['"""S"""'], {}), "('S')\n", (1294, 1299), True, 'import numpy as np\n'), ((2465, 2493), 'zarr.open', 'zarr.open', (['self.fn'], {'mode': '"""w"""'}), "(self.fn, mode='w')\n", (2474, 2493), False, 'import zarr\n'), ((4152, 4180), 'zarr.open', 'zarr.open', (['self.fn'], {'mode': '"""w"""'}), "(self.fn, mode='w')\n", (4161, 4180), False, 'import zarr\n'), ((7000, 7028), 'zarr.open', 'zarr.open', (['self.fn'], {'mode': '"""w"""'}), "(self.fn, mode='w')\n", (7009, 7028), False, 'import zarr\n'), ((8889, 8917), 'zarr.open', 'zarr.open', (['self.fn'], {'mode': '"""w"""'}), "(self.fn, mode='w')\n", (8898, 8917), False, 'import zarr\n'), ((10935, 10963), 'zarr.open', 'zarr.open', (['self.fn'], {'mode': '"""w"""'}), "(self.fn, mode='w')\n", (10944, 10963), False, 'import zarr\n'), ((13144, 13172), 'zarr.open', 'zarr.open', (['self.fn'], {'mode': '"""w"""'}), "(self.fn, mode='w')\n", (13153, 13172), False, 'import zarr\n'), ((17867, 17897), 'zarr.open', 'zarr.open', (['zarr_path'], {'mode': '"""r"""'}), "(zarr_path, mode='r')\n", (17876, 17897), False, 'import zarr\n'), ((18936, 18967), 'zarr.open', 'zarr.open', (['zarr_path'], {'mode': '"""r+"""'}), "(zarr_path, mode='r+')\n", (18945, 18967), False, 'import zarr\n'), ((20006, 20108), 'tqdm.tqdm', 'tqdm', (['assay.rawData.blocks'], {'total': 'assay.rawData.numblocks[0]', 'desc': 'f"""Writing data to merged file"""'}), "(assay.rawData.blocks, total=assay.rawData.numblocks[0], desc=\n f'Writing data to merged file')\n", (20010, 20108), False, 'from tqdm import tqdm\n'), ((19116, 19141), 'os.path.exists', 'os.path.exists', (['zarr_path'], {}), '(zarr_path)\n', (19130, 19141), False, 'import os\n'), ((19349, 19379), 'zarr.open', 'zarr.open', (['zarr_path'], {'mode': '"""w"""'}), "(zarr_path, mode='w')\n", (19358, 19379), False, 'import zarr\n'), ((20189, 20223), 'numpy.ones', 'np.ones', (['(i.shape[0], self.nFeats)'], {}), '((i.shape[0], self.nFeats))\n', (20196, 20223), True, 'import numpy as np\n'), ((5962, 5977), 'numpy.hstack', 'np.hstack', (['temp'], {}), '(temp)\n', (5971, 5977), True, 'import numpy as np\n'), ((16881, 16899), 'pandas.concat', 'pd.concat', (['ret_val'], {}), '(ret_val)\n', (16890, 16899), True, 'import pandas as pd\n'), ((18540, 18580), 'numpy.array', 'np.array', (["self.mergedCells['ids'].values"], {}), "(self.mergedCells['ids'].values)\n", (18548, 18580), True, 'import numpy as np\n')]
# Copyright 2017 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import os import re import sys import numpy as np print ('Execturing catwrite.R script... R must be installed...') retcode = os.system("R --no-save < catwrite.R") if retcode != 0: print('catwrite.R failed to execute. Perhaps you need to install R?') sys.exit(retcode) cats = {} for fn in os.listdir(): match = re.match(r'cat(\d?\d)', fn) if match: print("Processing file", fn) grpi = int(match.group(1)) with open(fn) as f: rows = [r.strip().split('"')[-1] for r in list(f)[1:]] arr = np.array([[float(e) for e in row.split()] for row in rows]) assert arr.dtype != 'O' cats[grpi] = arr print('Removing', fn) os.remove(fn) # most of the cats should be the same shape, and begin at 216 (except for Nyan cat) catstack = [] for num, cat in cats.items(): if cat.shape == (72, 288): catstack.append(cat[:, 216:]) assert len(catstack) == len(cats)-1 catstack = np.array(catstack) print('Saving cat stack as cats.npy') np.save('cats', catstack)
[ "os.listdir", "re.match", "numpy.array", "sys.exit", "os.system", "numpy.save", "os.remove" ]
[((759, 796), 'os.system', 'os.system', (['"""R --no-save < catwrite.R"""'], {}), "('R --no-save < catwrite.R')\n", (768, 796), False, 'import os\n'), ((940, 952), 'os.listdir', 'os.listdir', ([], {}), '()\n', (950, 952), False, 'import os\n'), ((1639, 1657), 'numpy.array', 'np.array', (['catstack'], {}), '(catstack)\n', (1647, 1657), True, 'import numpy as np\n'), ((1698, 1723), 'numpy.save', 'np.save', (['"""cats"""', 'catstack'], {}), "('cats', catstack)\n", (1705, 1723), True, 'import numpy as np\n'), ((896, 913), 'sys.exit', 'sys.exit', (['retcode'], {}), '(retcode)\n', (904, 913), False, 'import sys\n'), ((967, 995), 're.match', 're.match', (['"""cat(\\\\d?\\\\d)"""', 'fn'], {}), "('cat(\\\\d?\\\\d)', fn)\n", (975, 995), False, 'import re\n'), ((1370, 1383), 'os.remove', 'os.remove', (['fn'], {}), '(fn)\n', (1379, 1383), False, 'import os\n')]
""" Solves the incompressible Navier Stokes equations using "Stable Fluids" by <NAME> in a closed box with a forcing that creates a bloom. Momentum: ∂u/∂t + (u ⋅ ∇) u = − 1/ρ ∇p + ν ∇²u + f Incompressibility: ∇ ⋅ u = 0 u: Velocity (2d vector) p: Pressure f: Forcing ν: Kinematic Viscosity ρ: Density t: Time ∇: Nabla operator (defining nonlinear convection, gradient and divergence) ∇²: Laplace Operator ---- A closed box u = 0 v = 0 1 +-------------------------------------------------+ | | | * * | | * * * * | 0.8 | | | * | | * * | | * * | 0.6 | * | u = 0 | * * | u = 0 v = 0 | * | v = 0 | * | | * * * | 0.4 | | | | | * * * | | * * | 0.2 | * * | | * | | * * * * * | | * | 0 +-------------------------------------------------+ 0 0.2 0.4 0.6 0.8 1 u = 0 v = 0 * Homogeneous Dirichlet Boundary Condictio ----- Forcing Function 1 +-------------------------------------------------+ | | | * * | | * * * * | 0.8 | | | * | | * * | | * * | 0.6 | * | | * * | | * | | * | | * * * | 0.4 | | | | | * ^ ^ ^ ^ ^ ^ | | * | | | | | | * | 0.2 | | | | | | | * * | | | | | | | | * | | * * * * * | | * | 0 +-------------------------------------------------+ 0 0.2 0.4 0.6 0.8 1 -> Upwards pointing force in the lower center of the domain. ----- Solution Strategy: -> Start with zero velocity everywhere: u = [0, 0] 1. Add forces w₁ = u + Δt f 2. Convect by self-advection (set the value at the current location to be the value at the position backtraced on the streamline.) -> unconditionally stable w₂ = w₁(p(x, −Δt)) 3. Diffuse implicitly (Solve a linear system matrix-free by Conjugate Gradient) -> unconditionally stable (I − ν Δt ∇²)w₃ = w₂ 4.1 Compute a pressure correction (Solve a linear system matrix-free by Conjugate gradient) ∇² p = ∇ ⋅ w₃ 4.2 Correct velocities to be incompressible w₄ = w₃ − ∇p 5. Advance to next time step u = w₄ -> The Boundary Conditions are prescribed indirectly using the discrete differential operators. ----- The solver is unconditionally stable, hence all parameters can be chosen arbitrarily. Still, be careful that too high timesteps can make the advection step highly incorrect. """ import numpy as np import scipy.sparse.linalg as splinalg from scipy import interpolate import matplotlib.pyplot as plt # Optional import cmasher as cmr from tqdm import tqdm DOMAIN_SIZE = 1.0 N_POINTS = 41 N_TIME_STEPS = 100 TIME_STEP_LENGTH = 0.1 KINEMATIC_VISCOSITY = 0.0001 MAX_ITER_CG = None def forcing_function(time, point): time_decay = np.maximum( 2.0 - 0.5 * time, 0.0, ) forced_value = ( time_decay * np.where( ( (point[0] > 0.4) & (point[0] < 0.6) & (point[1] > 0.1) & (point[1] < 0.3) ), np.array([0.0, 1.0]), np.array([0.0, 0.0]), ) ) return forced_value def main(): element_length = DOMAIN_SIZE / (N_POINTS - 1) scalar_shape = (N_POINTS, N_POINTS) scalar_dof = N_POINTS**2 vector_shape = (N_POINTS, N_POINTS, 2) vector_dof = N_POINTS**2 * 2 x = np.linspace(0.0, DOMAIN_SIZE, N_POINTS) y = np.linspace(0.0, DOMAIN_SIZE, N_POINTS) # Using "ij" indexing makes the differential operators more logical. Take # care when plotting. X, Y = np.meshgrid(x, y, indexing="ij") coordinates = np.concatenate( ( X[..., np.newaxis], Y[..., np.newaxis], ), axis=-1, ) forcing_function_vectorized = np.vectorize( pyfunc=forcing_function, signature="(),(d)->(d)", ) def partial_derivative_x(field): diff = np.zeros_like(field) diff[1:-1, 1:-1] = ( ( field[2: , 1:-1] - field[0:-2, 1:-1] ) / ( 2 * element_length ) ) return diff def partial_derivative_y(field): diff = np.zeros_like(field) diff[1:-1, 1:-1] = ( ( field[1:-1, 2: ] - field[1:-1, 0:-2] ) / ( 2 * element_length ) ) return diff def laplace(field): diff = np.zeros_like(field) diff[1:-1, 1:-1] = ( ( field[0:-2, 1:-1] + field[1:-1, 0:-2] - 4 * field[1:-1, 1:-1] + field[2: , 1:-1] + field[1:-1, 2: ] ) / ( element_length**2 ) ) return diff def divergence(vector_field): divergence_applied = ( partial_derivative_x(vector_field[..., 0]) + partial_derivative_y(vector_field[..., 1]) ) return divergence_applied def gradient(field): gradient_applied = np.concatenate( ( partial_derivative_x(field)[..., np.newaxis], partial_derivative_y(field)[..., np.newaxis], ), axis=-1, ) return gradient_applied def curl_2d(vector_field): curl_applied = ( partial_derivative_x(vector_field[..., 1]) - partial_derivative_y(vector_field[..., 0]) ) return curl_applied def advect(field, vector_field): backtraced_positions = np.clip( ( coordinates - TIME_STEP_LENGTH * vector_field ), 0.0, DOMAIN_SIZE, ) advected_field = interpolate.interpn( points=(x, y), values=field, xi=backtraced_positions, ) return advected_field def diffusion_operator(vector_field_flattened): vector_field = vector_field_flattened.reshape(vector_shape) diffusion_applied = ( vector_field - KINEMATIC_VISCOSITY * TIME_STEP_LENGTH * laplace(vector_field) ) return diffusion_applied.flatten() def poisson_operator(field_flattened): field = field_flattened.reshape(scalar_shape) poisson_applied = laplace(field) return poisson_applied.flatten() plt.style.use("dark_background") plt.figure(figsize=(5, 5), dpi=160) velocities_prev = np.zeros(vector_shape) time_current = 0.0 for i in tqdm(range(N_TIME_STEPS)): time_current += TIME_STEP_LENGTH forces = forcing_function_vectorized( time_current, coordinates, ) # (1) Apply Forces velocities_forces_applied = ( velocities_prev + TIME_STEP_LENGTH * forces ) # (2) Nonlinear convection (=self-advection) velocities_advected = advect( field=velocities_forces_applied, vector_field=velocities_forces_applied, ) # (3) Diffuse velocities_diffused = splinalg.cg( A=splinalg.LinearOperator( shape=(vector_dof, vector_dof), matvec=diffusion_operator, ), b=velocities_advected.flatten(), maxiter=MAX_ITER_CG, )[0].reshape(vector_shape) # (4.1) Compute a pressure correction pressure = splinalg.cg( A=splinalg.LinearOperator( shape=(scalar_dof, scalar_dof), matvec=poisson_operator, ), b=divergence(velocities_diffused).flatten(), maxiter=MAX_ITER_CG, )[0].reshape(scalar_shape) # (4.2) Correct the velocities to be incompressible velocities_projected = ( velocities_diffused - gradient(pressure) ) # Advance to next time step velocities_prev = velocities_projected # Plot curl = curl_2d(velocities_projected) plt.contourf( X, Y, curl, cmap=cmr.redshift, levels=100, ) plt.quiver( X, Y, velocities_projected[..., 0], velocities_projected[..., 1], color="dimgray", ) plt.draw() plt.pause(0.0001) plt.clf() plt.show() if __name__ == "__main__": main()
[ "numpy.clip", "scipy.sparse.linalg.LinearOperator", "numpy.array", "matplotlib.pyplot.contourf", "scipy.interpolate.interpn", "matplotlib.pyplot.style.use", "numpy.linspace", "numpy.concatenate", "numpy.meshgrid", "numpy.maximum", "matplotlib.pyplot.quiver", "matplotlib.pyplot.pause", "matpl...
[((5017, 5050), 'numpy.maximum', 'np.maximum', (['(2.0 - 0.5 * time)', '(0.0)'], {}), '(2.0 - 0.5 * time, 0.0)\n', (5027, 5050), True, 'import numpy as np\n'), ((5685, 5724), 'numpy.linspace', 'np.linspace', (['(0.0)', 'DOMAIN_SIZE', 'N_POINTS'], {}), '(0.0, DOMAIN_SIZE, N_POINTS)\n', (5696, 5724), True, 'import numpy as np\n'), ((5733, 5772), 'numpy.linspace', 'np.linspace', (['(0.0)', 'DOMAIN_SIZE', 'N_POINTS'], {}), '(0.0, DOMAIN_SIZE, N_POINTS)\n', (5744, 5772), True, 'import numpy as np\n'), ((5889, 5921), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {'indexing': '"""ij"""'}), "(x, y, indexing='ij')\n", (5900, 5921), True, 'import numpy as np\n'), ((5941, 6006), 'numpy.concatenate', 'np.concatenate', (['(X[..., np.newaxis], Y[..., np.newaxis])'], {'axis': '(-1)'}), '((X[..., np.newaxis], Y[..., np.newaxis]), axis=-1)\n', (5955, 6006), True, 'import numpy as np\n'), ((6100, 6162), 'numpy.vectorize', 'np.vectorize', ([], {'pyfunc': 'forcing_function', 'signature': '"""(),(d)->(d)"""'}), "(pyfunc=forcing_function, signature='(),(d)->(d)')\n", (6112, 6162), True, 'import numpy as np\n'), ((9017, 9049), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""dark_background"""'], {}), "('dark_background')\n", (9030, 9049), True, 'import matplotlib.pyplot as plt\n'), ((9054, 9089), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)', 'dpi': '(160)'}), '(figsize=(5, 5), dpi=160)\n', (9064, 9089), True, 'import matplotlib.pyplot as plt\n'), ((9113, 9135), 'numpy.zeros', 'np.zeros', (['vector_shape'], {}), '(vector_shape)\n', (9121, 9135), True, 'import numpy as np\n'), ((11106, 11116), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11114, 11116), True, 'import matplotlib.pyplot as plt\n'), ((6239, 6259), 'numpy.zeros_like', 'np.zeros_like', (['field'], {}), '(field)\n', (6252, 6259), True, 'import numpy as np\n'), ((6541, 6561), 'numpy.zeros_like', 'np.zeros_like', (['field'], {}), '(field)\n', (6554, 6561), True, 'import numpy as np\n'), ((6830, 6850), 'numpy.zeros_like', 'np.zeros_like', (['field'], {}), '(field)\n', (6843, 6850), True, 'import numpy as np\n'), ((8060, 8132), 'numpy.clip', 'np.clip', (['(coordinates - TIME_STEP_LENGTH * vector_field)', '(0.0)', 'DOMAIN_SIZE'], {}), '(coordinates - TIME_STEP_LENGTH * vector_field, 0.0, DOMAIN_SIZE)\n', (8067, 8132), True, 'import numpy as np\n'), ((8302, 8375), 'scipy.interpolate.interpn', 'interpolate.interpn', ([], {'points': '(x, y)', 'values': 'field', 'xi': 'backtraced_positions'}), '(points=(x, y), values=field, xi=backtraced_positions)\n', (8321, 8375), False, 'from scipy import interpolate\n'), ((10737, 10792), 'matplotlib.pyplot.contourf', 'plt.contourf', (['X', 'Y', 'curl'], {'cmap': 'cmr.redshift', 'levels': '(100)'}), '(X, Y, curl, cmap=cmr.redshift, levels=100)\n', (10749, 10792), True, 'import matplotlib.pyplot as plt\n'), ((10872, 10969), 'matplotlib.pyplot.quiver', 'plt.quiver', (['X', 'Y', 'velocities_projected[..., 0]', 'velocities_projected[..., 1]'], {'color': '"""dimgray"""'}), "(X, Y, velocities_projected[..., 0], velocities_projected[..., 1],\n color='dimgray')\n", (10882, 10969), True, 'import matplotlib.pyplot as plt\n'), ((11046, 11056), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (11054, 11056), True, 'import matplotlib.pyplot as plt\n'), ((11065, 11082), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (11074, 11082), True, 'import matplotlib.pyplot as plt\n'), ((11091, 11100), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (11098, 11100), True, 'import matplotlib.pyplot as plt\n'), ((5370, 5390), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (5378, 5390), True, 'import numpy as np\n'), ((5404, 5424), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (5412, 5424), True, 'import numpy as np\n'), ((9812, 9899), 'scipy.sparse.linalg.LinearOperator', 'splinalg.LinearOperator', ([], {'shape': '(vector_dof, vector_dof)', 'matvec': 'diffusion_operator'}), '(shape=(vector_dof, vector_dof), matvec=\n diffusion_operator)\n', (9835, 9899), True, 'import scipy.sparse.linalg as splinalg\n'), ((10149, 10234), 'scipy.sparse.linalg.LinearOperator', 'splinalg.LinearOperator', ([], {'shape': '(scalar_dof, scalar_dof)', 'matvec': 'poisson_operator'}), '(shape=(scalar_dof, scalar_dof), matvec=poisson_operator\n )\n', (10172, 10234), True, 'import scipy.sparse.linalg as splinalg\n')]
import numpy as np import torch import gym import argparse import os from collections import deque import utils import TD3 import OurDDPG import DDPG import TD3_ad import robosuite as suite from torch.utils.tensorboard import SummaryWriter import time import multiprocessing as mp from functools import partial def createstate(state): all_states = np.array([]) for key in state.keys(): all_states = np.concatenate((all_states, state[key])) return all_states # Runs policy for X episodes and returns average reward # A fixed seed is used for the eval environment def eval_policy(policy, env_name, seed, eval_episodes=2): eval_env = suite.make( args.env, has_renderer=False, # noon-screen renderer has_offscreen_renderer=False, # no off-screen renderer use_object_obs=True, # use object-centric feature use_camera_obs=False, # no camera reward_shaping=True, ) avg_reward = 0. for _ in range(eval_episodes): state, done = eval_env.reset(), False for step in range(200): state = createstate(state) action = policy.select_action(np.array(state)) state, reward, done, _ = eval_env.step(action) reward = reward * 10 avg_reward += reward avg_reward /= eval_episodes print("---------------------------------------") print(f"Evaluation over {eval_episodes} episodes: {avg_reward:.3f}") print("---------------------------------------") return avg_reward def time_format(sec): """ Args: param1 """ hours = sec // 3600 rem = sec - hours * 3600 mins = rem // 60 secs = rem - mins * 60 return hours, mins, secs def main(args, param): file_name = f"{args.policy}_{args.env}_{args.seed}" print("---------------------------------------") print(f"Policy: {args.policy}, Env: {args.env}, Seed: {args.seed}") print("---------------------------------------") scores_window = deque(maxlen=100) if not os.path.exists("./results"): os.makedirs("./results") if args.save_model and not os.path.exists("./models"): os.makedirs("./models") env = suite.make( args.env, has_renderer=False, # noon-screen renderer has_offscreen_renderer=False, # no off-screen renderer use_object_obs=True, # use object-centric feature use_camera_obs=False, # no camera reward_shaping=True, ) max_episode_steps = 200 # Set seeds torch.manual_seed(args.seed) np.random.seed(args.seed) state = env.reset() state = createstate(state) state_dim = state.shape[0] action_dim = env.dof max_action = 1 pathname = str(args.env) + '_batch_size_' + str(args.batch_size) + '_start_learn_' + str(args.start_timesteps) pathname += "_seed_" + str(args.seed) + "_state_dim_" + str(state_dim) pathname += "num_q_target" + str(param) + "updat_freq" + str(args.target_update_freq) print(pathname) tensorboard_name = 'runs/' + pathname writer = SummaryWriter(tensorboard_name) kwargs = { "state_dim": state_dim, "action_dim": action_dim, "max_action": max_action, "discount": args.discount, "tau": args.tau, } # Initialize policy if args.policy == "TD3": # Target policy smoothing is scaled wrt the action scale kwargs["policy_noise"] = args.policy_noise * max_action kwargs["noise_clip"] = args.noise_clip * max_action kwargs["policy_freq"] = args.policy_freq policy = TD3.TD3(**kwargs) elif args.policy == "OurDDPG": policy = OurDDPG.DDPG(**kwargs) elif args.policy == "DDPG": policy = DDPG.DDPG(**kwargs) if args.load_model != "": policy_file = file_name if args.load_model == "default" else args.load_model policy.load(f"./models/{policy_file}") kwargs["num_q_target"] = param policy = TD3_ad.TD3_ad(**kwargs) replay_buffer = utils.ReplayBuffer(state_dim, action_dim) # Evaluate untrained policy evaluations = [eval_policy(policy, args.env, args.seed)] state, done = env.reset(), 0 state = createstate(state) episode_reward = 0 episode_timesteps = 0 episode_num = 0 tb_update_counter = 0 t0 = time.time() for t in range(int(args.max_timesteps)): episode_timesteps += 1 tb_update_counter += 1 # Select action randomly or according to policy if t < args.start_timesteps: action = np.random.randn(env.dof) else: action = ( policy.select_action(np.array(state)) + np.random.normal(0, max_action * args.expl_noise, size=action_dim) ).clip(-max_action, max_action) # Perform action next_state, reward, done, _ = env.step(action) next_state = createstate(next_state) done_bool = float(done) if episode_timesteps < max_episode_steps else 0 if max_episode_steps == episode_timesteps: done= 1 # Store data in replay buffer replay_buffer.add(state, action, next_state, reward, done_bool) state = next_state reward = reward * args.reward_scaling episode_reward += reward # Train agent after collecting sufficient data if t >= args.start_timesteps: policy.train(replay_buffer, args.batch_size) if t % args.target_update_freq == 0: policy.hardupdate() #pass if done: # +1 to account for 0 indexing. +0 on ep_timesteps since it will increment +1 even if done=True duration = time_format(time.time()-t0) print(f"Total T: {t+1} Episode Num: {episode_num+1} Episode T: {episode_timesteps} Reward: {episode_reward:.3f} Time: {duration} ") # Reset environment if tb_update_counter > args.tensorboard_freq: print("tensorboard") tb_update_counter = 0 scores_window.append(episode_reward) average_mean = np.mean(scores_window) writer.add_scalar('Reward', episode_reward, t) writer.add_scalar('Reward mean ', average_mean, t) state, done = env.reset(), False state = createstate(state) episode_reward = 0 episode_timesteps = 0 episode_num += 1 # Evaluate episode if (t + 1) % args.eval_freq == 0: evaluations.append(eval_policy(policy, args.env, args.seed)) np.save(f"./results/{file_name}", evaluations) if args.save_model: policy.save(f"./models/{file_name}-" + str(t)) print("save model") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--policy", default="TD3") # Policy name (TD3, DDPG or OurDDPG) parser.add_argument("--env", default="SawyerLift") # OpenAI gym environment name parser.add_argument("--seed", default=0, type=int) # Sets Gym, PyTorch and Numpy seeds parser.add_argument("--start_timesteps", default=25e3, type=int)# Time steps initial random policy is used parser.add_argument("--eval_freq", default=25e3, type=int) # How often (time steps) we evaluate parser.add_argument("--max_timesteps", default=1e6, type=int) # Max time steps to run environment parser.add_argument("--expl_noise", default=0.1) # Std of Gaussian exploration noise parser.add_argument("--batch_size", default=256, type=int) # Batch size for both actor and critic parser.add_argument("--discount", default=0.99) # Discount factor parser.add_argument("--tau", default=0.005) # Target network update rate parser.add_argument("--policy_noise", default=0.2) # Noise added to target policy during critic update parser.add_argument("--noise_clip", default=0.5) # Range to clip target policy noise parser.add_argument("--policy_freq", default=2, type=int) # Frequency of delayed policy updates parser.add_argument("--tensorboard_freq", default=50, type=int) # Frequency of delayed policy updates parser.add_argument("--target_update_freq", default=500, type=int) # Frequency of hard updates parser.add_argument("--reward_scaling", default=10, type=int) # Frequency of delayed policy updates parser.add_argument("--save_model", action="store_true") # Save model and optimizer parameters parser.add_argument("--load_model", default="") # Model load file name, "" doesn't load, "default" uses file_name args = parser.parse_args() processes = [] pool = mp.Pool() seeds = [4, 8, 12, 16] func = partial(main, args) pool.map(func, seeds) pool.close()
[ "numpy.array", "numpy.save", "robosuite.make", "torch.utils.tensorboard.SummaryWriter", "os.path.exists", "numpy.mean", "collections.deque", "argparse.ArgumentParser", "TD3_ad.TD3_ad", "utils.ReplayBuffer", "numpy.random.seed", "numpy.concatenate", "numpy.random.normal", "OurDDPG.DDPG", ...
[((356, 368), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (364, 368), True, 'import numpy as np\n'), ((663, 801), 'robosuite.make', 'suite.make', (['args.env'], {'has_renderer': '(False)', 'has_offscreen_renderer': '(False)', 'use_object_obs': '(True)', 'use_camera_obs': '(False)', 'reward_shaping': '(True)'}), '(args.env, has_renderer=False, has_offscreen_renderer=False,\n use_object_obs=True, use_camera_obs=False, reward_shaping=True)\n', (673, 801), True, 'import robosuite as suite\n'), ((2067, 2084), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (2072, 2084), False, 'from collections import deque\n'), ((2262, 2400), 'robosuite.make', 'suite.make', (['args.env'], {'has_renderer': '(False)', 'has_offscreen_renderer': '(False)', 'use_object_obs': '(True)', 'use_camera_obs': '(False)', 'reward_shaping': '(True)'}), '(args.env, has_renderer=False, has_offscreen_renderer=False,\n use_object_obs=True, use_camera_obs=False, reward_shaping=True)\n', (2272, 2400), True, 'import robosuite as suite\n'), ((2649, 2677), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (2666, 2677), False, 'import torch\n'), ((2682, 2707), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (2696, 2707), True, 'import numpy as np\n'), ((3195, 3226), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['tensorboard_name'], {}), '(tensorboard_name)\n', (3208, 3226), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((4100, 4123), 'TD3_ad.TD3_ad', 'TD3_ad.TD3_ad', ([], {}), '(**kwargs)\n', (4113, 4123), False, 'import TD3_ad\n'), ((4144, 4185), 'utils.ReplayBuffer', 'utils.ReplayBuffer', (['state_dim', 'action_dim'], {}), '(state_dim, action_dim)\n', (4162, 4185), False, 'import utils\n'), ((4447, 4458), 'time.time', 'time.time', ([], {}), '()\n', (4456, 4458), False, 'import time\n'), ((6960, 6985), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6983, 6985), False, 'import argparse\n'), ((8974, 8983), 'multiprocessing.Pool', 'mp.Pool', ([], {}), '()\n', (8981, 8983), True, 'import multiprocessing as mp\n'), ((9022, 9041), 'functools.partial', 'partial', (['main', 'args'], {}), '(main, args)\n', (9029, 9041), False, 'from functools import partial\n'), ((420, 460), 'numpy.concatenate', 'np.concatenate', (['(all_states, state[key])'], {}), '((all_states, state[key]))\n', (434, 460), True, 'import numpy as np\n'), ((2097, 2124), 'os.path.exists', 'os.path.exists', (['"""./results"""'], {}), "('./results')\n", (2111, 2124), False, 'import os\n'), ((2134, 2158), 'os.makedirs', 'os.makedirs', (['"""./results"""'], {}), "('./results')\n", (2145, 2158), False, 'import os\n'), ((2227, 2250), 'os.makedirs', 'os.makedirs', (['"""./models"""'], {}), "('./models')\n", (2238, 2250), False, 'import os\n'), ((3721, 3738), 'TD3.TD3', 'TD3.TD3', ([], {}), '(**kwargs)\n', (3728, 3738), False, 'import TD3\n'), ((2191, 2217), 'os.path.exists', 'os.path.exists', (['"""./models"""'], {}), "('./models')\n", (2205, 2217), False, 'import os\n'), ((3796, 3818), 'OurDDPG.DDPG', 'OurDDPG.DDPG', ([], {}), '(**kwargs)\n', (3808, 3818), False, 'import OurDDPG\n'), ((4680, 4704), 'numpy.random.randn', 'np.random.randn', (['env.dof'], {}), '(env.dof)\n', (4695, 4704), True, 'import numpy as np\n'), ((6754, 6800), 'numpy.save', 'np.save', (['f"""./results/{file_name}"""', 'evaluations'], {}), "(f'./results/{file_name}', evaluations)\n", (6761, 6800), True, 'import numpy as np\n'), ((1216, 1231), 'numpy.array', 'np.array', (['state'], {}), '(state)\n', (1224, 1231), True, 'import numpy as np\n'), ((3868, 3887), 'DDPG.DDPG', 'DDPG.DDPG', ([], {}), '(**kwargs)\n', (3877, 3887), False, 'import DDPG\n'), ((6258, 6280), 'numpy.mean', 'np.mean', (['scores_window'], {}), '(scores_window)\n', (6265, 6280), True, 'import numpy as np\n'), ((5849, 5860), 'time.time', 'time.time', ([], {}), '()\n', (5858, 5860), False, 'import time\n'), ((4822, 4888), 'numpy.random.normal', 'np.random.normal', (['(0)', '(max_action * args.expl_noise)'], {'size': 'action_dim'}), '(0, max_action * args.expl_noise, size=action_dim)\n', (4838, 4888), True, 'import numpy as np\n'), ((4783, 4798), 'numpy.array', 'np.array', (['state'], {}), '(state)\n', (4791, 4798), True, 'import numpy as np\n')]
"""応答の格納・管理""" import numpy as np from asva.utils.wave import read_case_wave, divide_wave, add_wave_required_zero class Response: """応答の格納・管理""" def __init__(self, analysis): self.analysis = analysis self.n_dof_plus_1 = self.analysis.model.n_dof + 1 self.acc_00_origin = read_case_wave(self.analysis.wave, self.analysis.case_conf) acc_00_origin_res = add_wave_required_zero(self.acc_00_origin, self.analysis.resp_end_step) self.acc_00_res = acc_00_origin_res[self.analysis.resp_start_step:self.analysis.resp_end_step] self.acc_00_ndiv = divide_wave(acc_00_origin_res, self.analysis.n_div) self.acc_00 = self.acc_00_ndiv[self.analysis.start_step:self.analysis.end_step] self.time = np.arange(self.analysis.resp_n_steps) * self.analysis.dt self.a_acc = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.acc = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.vel = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.dis = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.fu = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.rat_fu = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.cum_dis = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.fs = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) self.fd = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof, self.analysis.max_nd)) self.fk = np.zeros((self.analysis.resp_n_steps, len(self.analysis.model.ki))) # Custom response self.cum_dis_vel = np.zeros((self.analysis.resp_n_steps, self.analysis.model.n_dof)) # amp wsize = self.analysis.amplitude_config['N_W'] self.frequency: np.ndarray = np.array([]) self.amp_acc = np.zeros((wsize, self.analysis.model.n_dof)) self.amp_a_acc = np.zeros((wsize, self.analysis.model.n_dof)) @property def storey(self) -> np.ndarray: return np.arange(self.n_dof_plus_1) @property def acc_00_max(self) -> np.ndarray: acc_00_max = np.max(np.abs(self.acc_00_res)) return acc_00_max @property def a_acc_max(self) -> np.ndarray: a_acc_max = np.zeros((self.n_dof_plus_1)) for n in range(self.n_dof_plus_1): a_acc_max[n] = np.max(np.abs(self.a_acc[:, n-1])) if n != 0 else self.acc_00_max return a_acc_max @property def acc_max(self) -> np.ndarray: acc_max = np.zeros((self.n_dof_plus_1)) for n in range(self.n_dof_plus_1): acc_max[n] = np.max(np.abs(self.acc[:, n-1])) if n != 0 else self.acc_00_max return acc_max @property def vel_max(self) -> np.ndarray: vel_max = np.zeros((self.n_dof_plus_1)) for n in range(self.n_dof_plus_1): vel_max[n] = np.max(np.abs(self.vel[:, n-1])) if n != 0 else 0 return vel_max @property def dis_max(self) -> np.ndarray: dis_max = np.zeros((self.n_dof_plus_1)) for n in range(self.n_dof_plus_1): dis_max[n] = np.max(np.abs(self.dis[:, n-1])) if n != 0 else 0 return dis_max @property def fu_max(self) -> np.ndarray: fu_max = np.zeros((self.n_dof_plus_1)) for n in range(self.n_dof_plus_1): fu_max[n] = np.max(np.abs(self.fu[:, n-1])) if n != 0 else 0 return fu_max @property def rat_fu_max(self) -> np.ndarray: rat_fu_max = np.zeros((self.n_dof_plus_1)) for n in range(self.n_dof_plus_1): rat_fu_max[n] = np.max(np.abs(self.rat_fu[:, n-1])) if n != 0 else 0 return rat_fu_max @property def fs_max(self) -> np.ndarray: fs_max = np.zeros((self.n_dof_plus_1)) for n in range(self.n_dof_plus_1): fs_max[n] = np.max(np.abs(self.fs[:, n-1])) if n != 0 else 0 return fs_max @property def fd_max(self) -> np.ndarray: fd_max = np.zeros((self.n_dof_plus_1, self.analysis.max_nd)) for n in range(self.n_dof_plus_1): for nn in range(self.analysis.max_nd): fd_max[n, nn] = np.max( np.abs(self.fd[:, n-1, nn])) if n != 0 else 0 return fd_max
[ "numpy.abs", "asva.utils.wave.divide_wave", "asva.utils.wave.add_wave_required_zero", "asva.utils.wave.read_case_wave", "numpy.array", "numpy.zeros", "numpy.arange" ]
[((307, 366), 'asva.utils.wave.read_case_wave', 'read_case_wave', (['self.analysis.wave', 'self.analysis.case_conf'], {}), '(self.analysis.wave, self.analysis.case_conf)\n', (321, 366), False, 'from asva.utils.wave import read_case_wave, divide_wave, add_wave_required_zero\n'), ((395, 466), 'asva.utils.wave.add_wave_required_zero', 'add_wave_required_zero', (['self.acc_00_origin', 'self.analysis.resp_end_step'], {}), '(self.acc_00_origin, self.analysis.resp_end_step)\n', (417, 466), False, 'from asva.utils.wave import read_case_wave, divide_wave, add_wave_required_zero\n'), ((597, 648), 'asva.utils.wave.divide_wave', 'divide_wave', (['acc_00_origin_res', 'self.analysis.n_div'], {}), '(acc_00_origin_res, self.analysis.n_div)\n', (608, 648), False, 'from asva.utils.wave import read_case_wave, divide_wave, add_wave_required_zero\n'), ((835, 900), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (843, 900), True, 'import numpy as np\n'), ((920, 985), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (928, 985), True, 'import numpy as np\n'), ((1005, 1070), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (1013, 1070), True, 'import numpy as np\n'), ((1090, 1155), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (1098, 1155), True, 'import numpy as np\n'), ((1174, 1239), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (1182, 1239), True, 'import numpy as np\n'), ((1262, 1327), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (1270, 1327), True, 'import numpy as np\n'), ((1351, 1416), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (1359, 1416), True, 'import numpy as np\n'), ((1435, 1500), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (1443, 1500), True, 'import numpy as np\n'), ((1519, 1611), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof, self.analysis.max_nd)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof, self.\n analysis.max_nd))\n', (1527, 1611), True, 'import numpy as np\n'), ((1747, 1812), 'numpy.zeros', 'np.zeros', (['(self.analysis.resp_n_steps, self.analysis.model.n_dof)'], {}), '((self.analysis.resp_n_steps, self.analysis.model.n_dof))\n', (1755, 1812), True, 'import numpy as np\n'), ((1919, 1931), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1927, 1931), True, 'import numpy as np\n'), ((1955, 1999), 'numpy.zeros', 'np.zeros', (['(wsize, self.analysis.model.n_dof)'], {}), '((wsize, self.analysis.model.n_dof))\n', (1963, 1999), True, 'import numpy as np\n'), ((2025, 2069), 'numpy.zeros', 'np.zeros', (['(wsize, self.analysis.model.n_dof)'], {}), '((wsize, self.analysis.model.n_dof))\n', (2033, 2069), True, 'import numpy as np\n'), ((2136, 2164), 'numpy.arange', 'np.arange', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (2145, 2164), True, 'import numpy as np\n'), ((2373, 2400), 'numpy.zeros', 'np.zeros', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (2381, 2400), True, 'import numpy as np\n'), ((2634, 2661), 'numpy.zeros', 'np.zeros', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (2642, 2661), True, 'import numpy as np\n'), ((2889, 2916), 'numpy.zeros', 'np.zeros', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (2897, 2916), True, 'import numpy as np\n'), ((3130, 3157), 'numpy.zeros', 'np.zeros', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (3138, 3157), True, 'import numpy as np\n'), ((3369, 3396), 'numpy.zeros', 'np.zeros', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (3377, 3396), True, 'import numpy as np\n'), ((3613, 3640), 'numpy.zeros', 'np.zeros', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (3621, 3640), True, 'import numpy as np\n'), ((3861, 3888), 'numpy.zeros', 'np.zeros', (['self.n_dof_plus_1'], {}), '(self.n_dof_plus_1)\n', (3869, 3888), True, 'import numpy as np\n'), ((4097, 4148), 'numpy.zeros', 'np.zeros', (['(self.n_dof_plus_1, self.analysis.max_nd)'], {}), '((self.n_dof_plus_1, self.analysis.max_nd))\n', (4105, 4148), True, 'import numpy as np\n'), ((757, 794), 'numpy.arange', 'np.arange', (['self.analysis.resp_n_steps'], {}), '(self.analysis.resp_n_steps)\n', (766, 794), True, 'import numpy as np\n'), ((2248, 2271), 'numpy.abs', 'np.abs', (['self.acc_00_res'], {}), '(self.acc_00_res)\n', (2254, 2271), True, 'import numpy as np\n'), ((2480, 2508), 'numpy.abs', 'np.abs', (['self.a_acc[:, n - 1]'], {}), '(self.a_acc[:, n - 1])\n', (2486, 2508), True, 'import numpy as np\n'), ((2739, 2765), 'numpy.abs', 'np.abs', (['self.acc[:, n - 1]'], {}), '(self.acc[:, n - 1])\n', (2745, 2765), True, 'import numpy as np\n'), ((2994, 3020), 'numpy.abs', 'np.abs', (['self.vel[:, n - 1]'], {}), '(self.vel[:, n - 1])\n', (3000, 3020), True, 'import numpy as np\n'), ((3235, 3261), 'numpy.abs', 'np.abs', (['self.dis[:, n - 1]'], {}), '(self.dis[:, n - 1])\n', (3241, 3261), True, 'import numpy as np\n'), ((3473, 3498), 'numpy.abs', 'np.abs', (['self.fu[:, n - 1]'], {}), '(self.fu[:, n - 1])\n', (3479, 3498), True, 'import numpy as np\n'), ((3721, 3750), 'numpy.abs', 'np.abs', (['self.rat_fu[:, n - 1]'], {}), '(self.rat_fu[:, n - 1])\n', (3727, 3750), True, 'import numpy as np\n'), ((3965, 3990), 'numpy.abs', 'np.abs', (['self.fs[:, n - 1]'], {}), '(self.fs[:, n - 1])\n', (3971, 3990), True, 'import numpy as np\n'), ((4303, 4332), 'numpy.abs', 'np.abs', (['self.fd[:, n - 1, nn]'], {}), '(self.fd[:, n - 1, nn])\n', (4309, 4332), True, 'import numpy as np\n')]
import numpy as np from apps.keyboard.core.mfcc import mfcc def mapminmax(x, ymin=-1, ymax=+1): x = np.asanyarray(x) xmax = x.max(axis=-1) xmin = x.min(axis=-1) if (xmax == xmin).any(): raise ValueError("some rows have no variation") return (ymax - ymin) * (x - xmin) / (xmax - xmin) + ymin # function [Mfcc] = mfcc_transform(OriginalData, fs, Tw, Ts, alpha, M, C, HF, LF) # % Define variables # % Tw = 25; % analysis frame duration (ms) 帧持续时长 # % Ts = 10; % analysis frame shift (ms) 帧移 # % alpha = 0.97; % preemphasis coefficient 预加重 # % M = 20; % number of filterbank channels 滤波器通道数 # % C = 13; % number of cepstral coefficients 倒谱系数 # L = 22; % cepstral sine lifter parameter 倒谱正弦参数 # % LF = 10; % lower frequency limit (Hz) 低频门限 # % HF = 800; % upper frequency limit (Hz) 高频门限 def mfcc_transform(OriginalData, fs, Tw, Ts, alpha, M, C, HF, LF): speech = mapminmax(OriginalData) # cepstral sine lifter parameter 倒谱正弦参数 L = 22 MFCCs, FBEs, frames = mfcc.mfcc(speech, fs, Tw, Ts, alpha, np.hamming, [LF, HF], M, C, L) return MFCCs.T
[ "apps.keyboard.core.mfcc.mfcc.mfcc", "numpy.asanyarray" ]
[((107, 123), 'numpy.asanyarray', 'np.asanyarray', (['x'], {}), '(x)\n', (120, 123), True, 'import numpy as np\n'), ((1118, 1185), 'apps.keyboard.core.mfcc.mfcc.mfcc', 'mfcc.mfcc', (['speech', 'fs', 'Tw', 'Ts', 'alpha', 'np.hamming', '[LF, HF]', 'M', 'C', 'L'], {}), '(speech, fs, Tw, Ts, alpha, np.hamming, [LF, HF], M, C, L)\n', (1127, 1185), False, 'from apps.keyboard.core.mfcc import mfcc\n')]
# Copyright (c) 2021 <NAME>. 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 the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ----------------------------------------------------------------------------- """Reporter classes. Classes implementing presentation, storage and retrieval of major geometric characteristics of the spatial systems. Provides a unified set of class methods imtended to be used in a similar way. Two operational modes are possible: - initial analysis, visualization and export of the results: R.create(tp, s).pipeline(sp) - import and visualization of stored analysis results: R.create(tp, s).restore(p) where: 'R': the report class name, 'tp': type of the spatial system, 's': flag of interactive visualization, 'sp': list of spatial system instances to be analysed, 'p': path to the stored analysis results. """ from __future__ import annotations import json from pathlib import Path from typing import Final, Optional import numpy as np import cytoskeleton_analyser.fitting as fit from ..histograms import Experimental from ..histograms import Histogram from ..histograms import Simulated from ..report import Report from .spatial_systems import FullDepth from .spatial_systems import ListOfSpatialSystems class Features: """Classification of reported features """ #: Features applicable to both full and sliced cell representations. common: Final[list[str]] = [ 'Lengths3d', 'Lengths2d', 'Curvature3d', 'RadialMass', 'RadialEnds', 'AnglesToRad', 'SegmentNumbers', ] #: Features applicable to full cell representation alone. only_full: Final[list[str]] = [ 'AgesByNode', 'AgesByFilament', ] #: Features applicable to sliced cell representation alone. only_slice: Final[list[str]] = [ 'Curvature2dConv', 'Curvature2dMboc17', ] #: Complete set of implemented features. all: Final[list[str]] = common + only_full + only_slice __all__ = all @staticmethod def is_common(f: str) -> bool: """True if ``f`` belongs to set common to both representations. :param f: Feature class name. """ return any(f == g for g in Features.common) @staticmethod def is_full(f: str) -> bool: """True if feature ``f`` is applicable to full representation. :param f: Feature class name. """ return any(f == g for g in Features.only_full) @staticmethod def is_slice(f: str) -> bool: """True if feature ``f`` is applicable to slice representation. :param f: Feature class name. """ return any(f == g for g in Features.only_slice) @staticmethod def is_any(f: str) -> bool: """True if feature ``f`` is applicable to any representation. :param f: Feature class name. """ return any(f == g for g in Features.all) @staticmethod def is_applicable( f: str, tp: type[FullDepth], ) -> bool: """True if feature ``f`` is applicable to representation ``tp``. :param f: Feature class name. :param tp: Feature class name. """ return \ Features.is_common(f) or \ tp.type == 'slice' and Features.is_slice(f) or \ tp.type == 'full' and Features.is_full(f) @staticmethod def reporter(f: str): """Convert feature name ``f`` to corresponding reporter type. :param f: Feature name. """ if not Features.is_any(f): raise ValueError(f"{f} is not a valid position_feature.") return globals()[f] class _Report(Report): """Adaptation of report.Report class for spatial systems. For subclassing specific to reported cytoskeleton attributes. """ tp: type[FullDepth] #: Type of the spatial system. @classmethod def _create( cls, tp: type[FullDepth], name: str, show: bool = True, ) -> None: cls.tp = tp cls.__create( tp.logger, tp.paths.data_out, name + '_' + tp.type, show ) class Lengths3d(_Report): """Reports of microtubule lengths in . """ #: Part of figure and report titles. LABEL: Final = '3d filament length in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[Lengths3d]: super()._create(tp, __class__.__name__, show) cls.units = tp.len_units return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.len_total3d for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) h = Histogram( cls.name, Simulated().initialise(data, cls.fits_sim, dx=0.4, density=True) ) h.to_csv(cls.path_out) cls.plot(h) cls.logger.info('') return h, [avg], [std] @classmethod def plot( cls, h: Histogram ) -> None: h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'length ({cls.units})', xlim=[0., 60.], save_path=cls.path_out, show=cls.show ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: cls.fits_sim = [ # (fit.Gamma.loc0, [2., 0.1, 0.]), # (fit.Weibull.full, [2., 1.]), # (fit.Rayleigh.f, [1.]), ] rep = cls.report(sp) cls.summarize(rep, [0]) class Lengths2d(_Report): """Reports lengths of xy projections of the microtubules. Examines apparent lengths of simulated microtubules and compares them with experimental data obtained using optical microscopy. For this purpose, implements experimental sets from microtubule length measurements with superresolution methods by Zhang et al. (MBoC 2017) """ #: Part of figure and report titles. LABEL: Final = 'length of filament 2d projections in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[Lengths2d]: super()._create(tp, __class__.__name__, show) cls.units = tp.len_units return cls @classmethod def _experimental( cls, cell_type: str, ): import cytoskeleton_analyser.position.empirical_data.mboc17 as mboc17 bc, (contr, ca_ras) = mboc17.length(density=True) if cell_type == 'RW_Protr': h = ca_ras elif cell_type == 'SpreRou': h = contr avg = mboc17.avg(bc, h) cls.logger.info('\nEmpirical length of filament 2d projections in ' + f'{cls.tp.type}: {avg} {cls.units}') return bc, h, avg @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.len_total2d for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) ct = cls.tp.params['cell'].typename if cls.tp.type == 'slice' and \ (ct == 'RW_Protr' or ct == 'SpreRou'): bc, l, l_avg = cls._experimental(ct) e = Experimental().initialise((bc, l), cls.fits_exp) h = Histogram( cls.name, Simulated().initialise( data, cls.fits_sim, dx=0.4, exper_bc=e.bc, density=True), experimental=e ) avg, std = [avg, l_avg], [std, np.nan] else: h = Histogram( cls.name, Simulated().initialise( data, cls.fits_sim, dx=0.4, density=True), ) avg, std = [avg], [std] h.to_csv(cls.path_out) cls.plot(h) cls.logger.info('') return h, avg, std @classmethod def plot( cls, h: Histogram ) -> None: h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'length ({cls.units})', xlim=[0., 60.], save_path=cls.path_out, show=cls.show ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: best = [] if cls.tp.type == 'full': cls.fits_sim = [ # (fit.Gamma.loc0, [1., 1, 0.]), # (fit.Weibull.full, [2., 3.]), ] best = [0] if cls.tp.type == 'slice': # e = fit.Exponential.create() # p = fit.Exponential.Pars # tu = cls.units cls.fits_exp = [ # (e.d_h, p(a=1., tau1=2.), tu), # (fit.Gamma.loc0, [1., 1, 0.]), # (fit.Weibull.full, [2., 3.]), ] cls.fits_sim = [ # (e.d_h, p(a=1., tau1=2.), tu), # (fit.Gamma.loc0, [1., 1, 0.]), # (fit.Weibull.full, [2., 3.]), ] best = [1, 1] rep = cls.report(sp) cls.summarize(rep, best) class RadialMass(_Report): """Reports distribution of microtubule masss. Microtubule mass is analysed as a function of distance to cell center in xy plane. """ #: Part of figure and report titles. LABEL: Final = 'mass vs distance to center ' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[RadialMass]: super()._create(tp, __class__.__name__, show) cls.units = tp.len_units return cls @classmethod def report( cls, sp: ListOfSpatialSystems ) -> tuple[Histogram, list, list]: data = [np.concatenate(s.center_dist_2d) for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) h = Histogram( cls.name, Simulated().initialise( data, fits=cls.fits_sim, dx=0.25, density=True ), ) h.to_csv(cls.path_out) cls.plot(h) cls.logger.info('') return h, [avg], [std] @classmethod def plot( cls, h: Histogram ): h.plot( cls.LABEL + cls.tp.type, xlabel=f'length ({cls.units})', xlim=[0., 30.], save_path=cls.path_out, show=cls.show, ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: cls.report(sp) class RadialEnds(_Report): """Reports positions of of microtubule plus ends. Analyse the distribution of microtubule plus ends as a function of distance to cell center in xy plane. """ #: Part of figure and report titles. LABEL: Final = 'plus-ends vs distance to center ' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[RadialEnds]: super()._create(tp, __class__.__name__, show) cls.units = tp.len_units return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [np.concatenate(s.center_dist_2d_ends) for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) h = Histogram( cls.name, Simulated().initialise( data, fits=cls.fits_sim, dx=0.25, density=True) ) h.to_csv(cls.path_out) cls.plot(h) cls.logger.info('') return h, [avg], [std] @classmethod def plot( cls, h: Histogram ): h.plot( cls.LABEL + cls.tp.type, xlabel=f'length ({cls.units})', xlim=[0., 30.], save_path=cls.path_out, show=cls.show, ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: cls.report(sp) class SegmentNumbers(_Report): """Reports apparent number of microtubules. Measure statistics on apparent number of microtubules in full system and as visible in TIRF microscopy observations. """ @classmethod def create( cls, tp: type[FullDepth], _, ) -> type[SegmentNumbers]: super()._create(tp, __class__.__name__) cls.units = 'segments' return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Optional[Histogram], list, list]: cls.logger.info(f"Number of filaments in {cls.tp.type}:") data = np.array([len(s.len_total3d) for s in sp]) [cls.logger.info(f'\t {n}') for n in data] avg = np.mean(data) std = np.std(data) cls.logger.info(f"overall: {avg} ± {std} slices\n") fname = cls.path_out / f"{cls.name}.json" with open(fname, 'w') as f: json.dump({'num': {'avg': avg, 'std': std}}, f) cls.logger.info('') return None, [avg], [std] @classmethod def restore( cls, path: Path ) -> dict: cls.logger.info('Restoring ' + cls.name + ':') summary = cls.log_stats(path) # fname = f"{cls.path_out}{cls.name}.json" # with open(fname, 'w') as f: # json.dump({'num': {'avg': avg, 'std': std}}, f) cls.logger.info('') return {'summary': summary, 'h_sim_avg': None, } @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: cls.report(sp) class Curvature3d(_Report): """Reports 3d curvature of microtubule fibers. """ #: Part of figure and report titles. LABEL: Final = '3d curvature of filaments in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[Curvature3d]: super()._create(tp, __class__.__name__, show) cls.units = '1/' + tp.len_units return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.curv3d for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) h = Histogram( cls.name, Simulated().initialise(data, cls.fits_sim, dx=0.02, density=True) ) h.to_csv(cls.path_out) cls.plot(h) return h, [avg], [std] @classmethod def plot( cls, h: Histogram ) -> None: h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'curvature ({cls.units})', xlim=[0., 1.5], save_path=cls.path_out, show=cls.show ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: cls.fits_sim = [ (fit.Rayleigh.f, [1.]), ] rep = cls.report(sp) cls.summarize(rep, [0]) class Curvature2dConv(_Report): """Reports of apparent curvature of microtubule projections to xy plane. """ #: Part of figure and report titles. LABEL: Final = '2d curvature of projected filaments in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[Curvature2dConv]: super()._create(tp, __class__.__name__, show) cls.units = '1/' + tp.len_units return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.curv2d for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) h = Histogram( cls.name, Simulated().initialise(data, cls.fits_sim, dx=0.02, density=True) ) h.to_csv(cls.path_out) cls.plot(h) return h, [avg], [std] @classmethod def plot( cls, h: Histogram ) -> None: h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'curvature ({cls.units})', xlim=[0., 1.5], save_path=cls.path_out, show=cls.show ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: cls.fits_sim = [ # (fit.Gamma.loc0, [2., 0.1, 0.]), # (fit.Weibull.full, [2., 1.]), # (fit.Rayleigh.f, [.5]), ] rep = cls.report(sp) cls.summarize(rep, [0]) class Curvature2dMboc17(_Report): """Reports microtubule curvatures using formulas applied in the processing of superresolution images by Zhang et al. MBoC 2017 """ #: Part of figure and report titles. LABEL: Final = 'empirical curvature of filament 2d projections in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[Curvature2dMboc17]: name = __class__.__name__ if tp.type != 'slice': tp.logger.warning( f'WARNING: Analysis of {name} makes only ' f'sence for Tirf slices.' ) ct = tp.params['cell'].typename if ct != 'RW_Protr' and ct != 'SpreRou': tp.logger.warning( f'WARNING: Analysis of {name} makes only ' f'sence for specific cell types.' ) super()._create(tp, name, show) cls.units = '1/' + tp.len_units return cls @classmethod def experimental( cls, cell_type: str ) -> tuple[list, Histogram, float]: import cytoskeleton_analyser.position.empirical_data.mboc17 as zh bc, (contr, ca_ras) = zh.curvature(density=True) if cell_type == 'RW_Protr': h = ca_ras elif cell_type == 'SpreRou': h = contr else: assert False, 'Wrong Cell Type' avg = zh.avg(bc, h) cls.logger.info('\nEmpirical curvature of filament 2d projections in ' + f'{cls.tp.type}: {avg} {cls.units}') return bc, h, avg @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.curv2d_mboc17 for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) ct = cls.tp.params['cell'].typename if cls.tp.type == 'slice' and \ (ct == 'RW_Protr' or ct == 'SpreRou'): bc, c, c_avg = cls.experimental(ct) e = Experimental().initialise((bc, c), cls.fits_exp) h = Histogram( cls.name, Simulated().initialise( data, cls.fits_sim, dx=0.02, exper_bc=e.bc, density=True), e, ) avg, std = [avg, c_avg], [std, np.nan] else: h = Histogram( cls.name, Simulated().initialise( data, cls.fits_sim, dx=0.02, density=True), ) avg, std = [avg], [std] h.to_csv(cls.path_out) cls.plot(h) return h, avg, std @classmethod def plot( cls, h: Histogram ) -> None: h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'curvature ({cls.units})', xlim=[0., 1.5], save_path=cls.path_out, show=cls.show ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: cls.fits_sim = [ # (fit.Gamma.loc0, [2., 0.1, 0.]), # (fit.Weibull.full, [2., 1.]), # (fit.Rayleigh.f, [1.]), ] cls.fits_exp = [ # (fit.Gamma.loc0, [2., 0.1, 0.]), # (fit.Weibull.full, [2., 1.]), # (fit.Rayleigh.f, [1.]), ] rep = cls.report(sp) cls.summarize(rep, [0, 0]) class AnglesToRad(_Report): """Reports distribution of angles between points on the microtubule and local radial direction. """ #: Part of figure and report titles. LABEL: Final = 'angle to radial direction in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[AnglesToRad]: super()._create(tp, __class__.__name__, show) cls.units = 'grad' cls.is_polar = True cls.is_halfpolar = True return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.threshold_radial_dev(cls.tp.params['cell']. regions.lamella.is_inside) for s in sp] data = [np.array([2.*np.pi - d if d >= np.pi else d for d in dd]) for dd in data] avg, std = cls.tp.print_avgstd(cls.LABEL, [d/np.pi*180. for d in data], cls.units) h = Histogram( cls.name, Simulated() .initialise(data, cls.fits_sim, dx=2.*np.pi/180., density=True, polar=cls.is_polar, halfpolar=cls.is_halfpolar), ) h.to_csv(cls.path_out) cls.plot(h) return h, [avg], [std] @classmethod def plot( cls, h: Histogram ): h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'angle ({cls.units})', xlim=[0., 2. * np.pi], save_path=cls.path_out, show=cls.show ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ): cls.fits_sim = [ (fit.VonMisesDouble.full, [0.6, 0.3, 32., 5., np.pi / 3.]) ] rep = cls.report(sp) cls.summarize(rep, [0]) class AgesByNode(_Report): """Report ages (time after the polymerization event) of microtubules by filament nodes: individual node ages. """ #: Part of figure and report titles. LABEL: Final = 'node ages in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[AgesByNode]: super()._create(tp, __class__.__name__, show) cls.units = 'sec' return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.ages_cumulative for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) h = Histogram( cls.name, Simulated().initialise(data, cls.fits_sim, dx=10., density=True), ) h.to_csv(cls.path_out) cls.plot(h) return h, [avg], [std] @classmethod def plot( cls, h: Histogram ) -> None: h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'age ({cls.units})', xlim=[0., 10000], yscale='log', save_path=cls.path_out, show=cls.show ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: e = fit.Exponential.create() p = fit.Exponential.Pars tu = cls.units a = 1. tau1 = 10 tau2 = 1000 cls.fits_sim = [ (e.d_h, p(a=a, tau1=tau1), tu), (e.d_d_h, p(a=a, tau1=tau1, b=0.9, tau2=tau2), tu), ] rep = cls.report(sp) cls.summarize(rep, [1]) class AgesByFilament(_Report): """Report ages of microtubules. Age is defined as time passed after the polymerization event. Here node age averages over all filament nodes are considered. """ #: Part of figure and report titles. LABEL: Final = 'filament ages in' @classmethod def create( cls, tp: type[FullDepth], show: bool = True, ) -> type[AgesByFilament]: super()._create(tp, __class__.__name__, show) cls.units = 'sec' return cls @classmethod def report( cls, sp: ListOfSpatialSystems, ) -> tuple[Histogram, list, list]: data = [s.ages_by_filament for s in sp] avg, std = cls.tp.print_avgstd(cls.LABEL, data, cls.units) h = Histogram( cls.name, Simulated().initialise(data, cls.fits_sim, dx=10., density=True), ) h.to_csv(cls.path_out) cls.plot(h) return h, [avg], [std] @classmethod def plot( cls, h: Histogram ) -> None: h.plot( cls.LABEL + ' ' + cls.tp.type, xlabel=f'age ({cls.units})', xlim=[0., 10000], yscale='log', save_path=cls.path_out, show=cls.show, ) @classmethod def pipeline( cls, sp: ListOfSpatialSystems, ) -> None: e = fit.Exponential.create() p = fit.Exponential.Pars tu = cls.units a = 1. tau1 = 10 tau2 = 1000 cls.fits_sim = [ (e.d_h, p(a=a, tau1=tau1), tu), (e.d_d_h, p(a=a, tau1=tau1, b=0.9, tau2=tau2), tu), ] rep = cls.report(sp) cls.summarize(rep, [1])
[ "numpy.mean", "cytoskeleton_analyser.position.empirical_data.mboc17.avg", "cytoskeleton_analyser.position.empirical_data.mboc17.length", "cytoskeleton_analyser.position.empirical_data.mboc17.curvature", "cytoskeleton_analyser.fitting.Exponential.create", "numpy.array", "numpy.concatenate", "numpy.std"...
[((8058, 8085), 'cytoskeleton_analyser.position.empirical_data.mboc17.length', 'mboc17.length', ([], {'density': '(True)'}), '(density=True)\n', (8071, 8085), True, 'import cytoskeleton_analyser.position.empirical_data.mboc17 as mboc17\n'), ((8218, 8235), 'cytoskeleton_analyser.position.empirical_data.mboc17.avg', 'mboc17.avg', (['bc', 'h'], {}), '(bc, h)\n', (8228, 8235), True, 'import cytoskeleton_analyser.position.empirical_data.mboc17 as mboc17\n'), ((14443, 14456), 'numpy.mean', 'np.mean', (['data'], {}), '(data)\n', (14450, 14456), True, 'import numpy as np\n'), ((14471, 14483), 'numpy.std', 'np.std', (['data'], {}), '(data)\n', (14477, 14483), True, 'import numpy as np\n'), ((19552, 19578), 'cytoskeleton_analyser.position.empirical_data.mboc17.curvature', 'zh.curvature', ([], {'density': '(True)'}), '(density=True)\n', (19564, 19578), True, 'import cytoskeleton_analyser.position.empirical_data.mboc17 as zh\n'), ((19769, 19782), 'cytoskeleton_analyser.position.empirical_data.mboc17.avg', 'zh.avg', (['bc', 'h'], {}), '(bc, h)\n', (19775, 19782), True, 'import cytoskeleton_analyser.position.empirical_data.mboc17 as zh\n'), ((25107, 25131), 'cytoskeleton_analyser.fitting.Exponential.create', 'fit.Exponential.create', ([], {}), '()\n', (25129, 25131), True, 'import cytoskeleton_analyser.fitting as fit\n'), ((26882, 26906), 'cytoskeleton_analyser.fitting.Exponential.create', 'fit.Exponential.create', ([], {}), '()\n', (26904, 26906), True, 'import cytoskeleton_analyser.fitting as fit\n'), ((11376, 11408), 'numpy.concatenate', 'np.concatenate', (['s.center_dist_2d'], {}), '(s.center_dist_2d)\n', (11390, 11408), True, 'import numpy as np\n'), ((12873, 12910), 'numpy.concatenate', 'np.concatenate', (['s.center_dist_2d_ends'], {}), '(s.center_dist_2d_ends)\n', (12887, 12910), True, 'import numpy as np\n'), ((14643, 14690), 'json.dump', 'json.dump', (["{'num': {'avg': avg, 'std': std}}", 'f'], {}), "({'num': {'avg': avg, 'std': std}}, f)\n", (14652, 14690), False, 'import json\n'), ((22649, 22711), 'numpy.array', 'np.array', (['[(2.0 * np.pi - d if d >= np.pi else d) for d in dd]'], {}), '([(2.0 * np.pi - d if d >= np.pi else d) for d in dd])\n', (22657, 22711), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt import scipy.stats as sp import math import random as rm import NumerosGenerados as ng n = 100000 inicio = 0 ancho = 20 K = 3 numerosGamma = sp.gamma.rvs(size=n, a = K) print("Media: ", round(np.mean(numerosGamma),3)) print("Desvio: ", round(np.sqrt(np.var(numerosGamma)),3)) print("Varianza: ", round(np.var(numerosGamma),3)) plt.hist(numerosGamma, bins=50, color='red', histtype="bar",alpha=0.8,ec="black") plt.xlabel("valores") plt.ylabel("Frecuencia Absoluta") plt.show() #----------Naylor---------- randomGCL = ng.generarNumeros(n) def gamma(k, alfa): gammas= [] for i in range (n): tr=1 for j in range (k): r=rm.choice(randomGCL) tr= tr * r x= -math.log(tr)/alfa gammas.append(x) print("Media: ", round(np.mean(gammas),3)) print("Desvio: ", round(np.sqrt(np.var(gammas)),3)) print("Varianza: ", round(np.var(gammas),3)) plt.title("Distribucion Gamma") plt.hist(numerosGamma, bins=50, color='red', histtype="bar",alpha=0.8,ec="black") plt.hist(gammas, bins=50, edgecolor="black", histtype="bar",alpha=0.6) plt.show() gamma(K,1)
[ "numpy.mean", "random.choice", "matplotlib.pyplot.hist", "scipy.stats.gamma.rvs", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "math.log", "matplotlib.pyplot.title", "NumerosGenerados.generarNumeros", "numpy.var", "matplotlib.pyplot.show" ]
[((193, 218), 'scipy.stats.gamma.rvs', 'sp.gamma.rvs', ([], {'size': 'n', 'a': 'K'}), '(size=n, a=K)\n', (205, 218), True, 'import scipy.stats as sp\n'), ((381, 469), 'matplotlib.pyplot.hist', 'plt.hist', (['numerosGamma'], {'bins': '(50)', 'color': '"""red"""', 'histtype': '"""bar"""', 'alpha': '(0.8)', 'ec': '"""black"""'}), "(numerosGamma, bins=50, color='red', histtype='bar', alpha=0.8, ec=\n 'black')\n", (389, 469), True, 'import matplotlib.pyplot as plt\n'), ((463, 484), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""valores"""'], {}), "('valores')\n", (473, 484), True, 'import matplotlib.pyplot as plt\n'), ((485, 518), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frecuencia Absoluta"""'], {}), "('Frecuencia Absoluta')\n", (495, 518), True, 'import matplotlib.pyplot as plt\n'), ((519, 529), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (527, 529), True, 'import matplotlib.pyplot as plt\n'), ((571, 591), 'NumerosGenerados.generarNumeros', 'ng.generarNumeros', (['n'], {}), '(n)\n', (588, 591), True, 'import NumerosGenerados as ng\n'), ((962, 993), 'matplotlib.pyplot.title', 'plt.title', (['"""Distribucion Gamma"""'], {}), "('Distribucion Gamma')\n", (971, 993), True, 'import matplotlib.pyplot as plt\n'), ((998, 1086), 'matplotlib.pyplot.hist', 'plt.hist', (['numerosGamma'], {'bins': '(50)', 'color': '"""red"""', 'histtype': '"""bar"""', 'alpha': '(0.8)', 'ec': '"""black"""'}), "(numerosGamma, bins=50, color='red', histtype='bar', alpha=0.8, ec=\n 'black')\n", (1006, 1086), True, 'import matplotlib.pyplot as plt\n'), ((1084, 1155), 'matplotlib.pyplot.hist', 'plt.hist', (['gammas'], {'bins': '(50)', 'edgecolor': '"""black"""', 'histtype': '"""bar"""', 'alpha': '(0.6)'}), "(gammas, bins=50, edgecolor='black', histtype='bar', alpha=0.6)\n", (1092, 1155), True, 'import matplotlib.pyplot as plt\n'), ((1159, 1169), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1167, 1169), True, 'import matplotlib.pyplot as plt\n'), ((245, 266), 'numpy.mean', 'np.mean', (['numerosGamma'], {}), '(numerosGamma)\n', (252, 266), True, 'import numpy as np\n'), ((355, 375), 'numpy.var', 'np.var', (['numerosGamma'], {}), '(numerosGamma)\n', (361, 375), True, 'import numpy as np\n'), ((303, 323), 'numpy.var', 'np.var', (['numerosGamma'], {}), '(numerosGamma)\n', (309, 323), True, 'import numpy as np\n'), ((707, 727), 'random.choice', 'rm.choice', (['randomGCL'], {}), '(randomGCL)\n', (716, 727), True, 'import random as rm\n'), ((833, 848), 'numpy.mean', 'np.mean', (['gammas'], {}), '(gammas)\n', (840, 848), True, 'import numpy as np\n'), ((939, 953), 'numpy.var', 'np.var', (['gammas'], {}), '(gammas)\n', (945, 953), True, 'import numpy as np\n'), ((763, 775), 'math.log', 'math.log', (['tr'], {}), '(tr)\n', (771, 775), False, 'import math\n'), ((889, 903), 'numpy.var', 'np.var', (['gammas'], {}), '(gammas)\n', (895, 903), True, 'import numpy as np\n')]
import numpy as np from pmesh.pm import ParticleMesh from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower from nbodykit.source.mesh.field import FieldMesh from nbodykit.lab import SimulationBox2PCF, FFTCorr import os import sys sys.path.append('./utils') import tools, dohod # from time import time #Get model as parameter import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', '--size', help='for small or big box', default='small') parser.add_argument('-a', '--amp', help='amplitude for up/down sigma 8', default=None) parser.add_argument('-r', '--res', help='resolution', default='high') args = parser.parse_args() boxsize = args.size amp = args.amp res = args.res #Global, fixed things scratchyf = '/global/cscratch1/sd/yfeng1/m3127/' project = '/project/projectdirs/m3127/H1mass/' myscratch = '/global/cscratch1/sd/chmodi/m3127/H1mass/' cosmodef = {'omegam':0.309167, 'h':0.677, 'omegab':0.048} aafiles = [0.1429, 0.1538, 0.1667, 0.1818, 0.2000, 0.2222, 0.2500, 0.2857, 0.3333] #aafiles = aafiles[4:] zzfiles = [round(tools.atoz(aa), 2) for aa in aafiles] #Paramteres if res == 'high': if boxsize == 'small': bs, nc, ncsim, sim, prefix = 256, 512, 2560, 'highres/%d-9100-fixed'%2560, 'highres' elif boxsize == 'big': bs, nc, ncsim, sim, prefix = 1024, 1024, 10240, 'highres/%d-9100-fixed'%10240, 'highres' else: bs, nc, ncsim, sim, prefix = 256, 256, 256, 'lowres/%d-9100-fixed'%256, 'lowres' if amp is not None: if amp == 'up' or amp == 'dn': sim = sim + '-%s'%amp else: print('Amplitude not understood. Should be "up" or "dn". Given : {}. Fallback to fiducial'.format(amp)) # It's useful to have my rank for printing... pm = ParticleMesh(BoxSize=bs, Nmesh=[nc, nc, nc]) rank = pm.comm.rank comm = pm.comm if rank == 0: print(args) def readincatalog(aa, matter=False): if matter: dmcat = BigFileCatalog(scratchyf + sim + '/fastpm_%0.4f/'%aa, dataset='1') halocat = BigFileCatalog(scratchyf + sim + '/fastpm_%0.4f/'%aa, dataset='LL-0.200') mp = halocat.attrs['MassTable'][1]*1e10 print('Mass of particle is = %0.2e'%mp) halocat['Mass'] = halocat['Length'] * mp print(halocat['Mass'][:5].compute()/1e10) halocat['Position'] = halocat['Position']%bs # Wrapping positions assuming periodic boundary conditions if matter: return dmcat, halocat else: return halocat def savecatalogmesh(bs, nc, aa): dmcat = BigFileCatalog(scratchyf + sim + '/fastpm_%0.4f/'%aa, dataset='1') pm = ParticleMesh(BoxSize = bs, Nmesh = [nc, nc, nc]) pos = dmcat['Position'].compute() layout = pm.decompose(pos) mesh = pm.paint(pos, layout=layout) mesh = FieldMesh(mesh) path = project + sim + '/fastpm_%0.4f/'%aa + '/dmesh_N%04d'%nc mesh.save(path, dataset='1', mode='real') def make_galcat(aa,save=True): '''do HOD with Zheng model using nbodykit''' zz = tools.atoz(aa) print('Redshift = %0.2f'%zz) halocat = readincatalog(aa) #Do hod ofolder = project + '/%s/fastpm_%0.4f/'%(sim, aa) galcat = dohod.make_galcat(halocat, ofolder, z=zz, pm=pm) if save: colsave = [cols for cols in galcat.columns] galcat.save(ofolder+'galcat', colsave) print('Galaxies saved at path\n%s'%ofolder) def assignH1mass(aa, save=True): '''assign H1 masses to halos based on numbers from arxiv...''' zz = tools.atoz(aa) print('Redshift = %0.2f'%zz) halocat = readincatalog(aa) #Do hod ofolder = project + '/%s/fastpm_%0.4f/'%(sim, aa) halocat['H1mass'] = dohod.assignH1mass(halocat, z=zz) if save: colsave = [cols for cols in halocat.columns] colsave = ['ID', 'Position', 'Mass', 'H1mass'] print(colsave) halocat.save(ofolder+'halocat', colsave) print('Halos saved at path\n%s'%ofolder) def measurepk(nc=nc, dpath=scratchyf): '''plot the power spectrum of halos on 'nc' grid''' pm = ParticleMesh(BoxSize = bs, Nmesh = [nc, nc, nc]) for i, aa in enumerate(aafiles): zz = zzfiles[i] if rank == 0: print('redshift = ', zz) if ncsim == 10240: dm = BigFileMesh(scratchyf+sim+'/fastpm_%0.4f/'%aa+\ '/1-mesh/N%04d'%nc,'').paint() else: dm = BigFileMesh(project+sim+'/fastpm_%0.4f/'%aa+\ '/dmesh_N%04d/1/'%nc,'').paint() #dm = BigFileMesh(project + sim + '/fastpm_%0.4f/'%aa + '/dmesh_N%04d'%nc, '1').paint() halos = BigFileCatalog(scratchyf + sim + '/fastpm_%0.4f/'%aa, dataset='LL-0.200') mp = halos.attrs['MassTable'][1]*1e10 if rank == 0: print('Mass of particle is = %0.2e'%mp) hmass = halos["Length"].compute()*mp hpos = halos['Position'].compute() layout = pm.decompose(hpos) if rank == 0: print("paint") hpmesh = pm.paint(hpos, layout=layout) hmesh = pm.paint(hpos, mass=hmass, layout=layout) print(rank, dm.cmean(), hmesh.cmean(), hpmesh.cmean()) pkm = FFTPower(dm/dm.cmean(), mode='1d').power pkh = FFTPower(hmesh/hmesh.cmean(), mode='1d').power pkhp = FFTPower(hpmesh/hpmesh.cmean(), mode='1d').power pkhm = FFTPower(hmesh/hmesh.cmean(), second=dm/dm.cmean(), mode='1d').power pkhpm = FFTPower(hpmesh/hpmesh.cmean(), second=dm/dm.cmean(), mode='1d').power def savebinned(path, binstat, header): if halos.comm.rank == 0: k, p, modes = binstat['k'].real, binstat['power'].real, binstat['modes'].real np.savetxt(path, np.stack((k, p, modes), axis=1), header=header) ofolder = "../data/outputs/halos/{}/".format(sim) if rank == 0: print(ofolder) try: os.makedirs(ofolder) except : pass savebinned(ofolder+'pkhp_%0.4f.txt'%aa, pkhp, header='k, P(k), Nmodes') savebinned(ofolder+'pkhm_%0.4f.txt'%aa, pkh, header='k, P(k), Nmodes') savebinned(ofolder+'pkd_%0.4f.txt'%aa, pkm, header='k, P(k), Nmodes') savebinned(ofolder+'pkhpxd_%0.4f.txt'%aa, pkhpm, header='k, P(k), Nmodes') savebinned(ofolder+'pkhmxd_%0.4f.txt'%aa, pkhm, header='k, P(k), Nmodes') def measurexi(N, edges): '''plot the power spectrum of halos and H1 with subsampling''' for i, aa in enumerate(aafiles): dm = BigFileCatalog(scratch + sim + '/fastpm_%0.4f/'%aa , dataset='1') halos = BigFileCatalog(project + sim + '/fastpm_%0.4f/halocat/'%aa) h1 = BigFileCatalog(project + sim + '/fastpm_%0.4f/halocat/'%aa) for cat in [dm, halos, h1]: # nbodykit bug in SimBox2PCF that asserts boxsize cat.attrs['BoxSize'] = np.broadcast_to(cat.attrs['BoxSize'], 3) rng = np.random.RandomState(halos.comm.rank) rank = dm.comm.rank zz = zzfiles[i] if rank == 0 : print('redshift = ', zz) print('Number of dm particles = ', dm.csize) print('Number of halos particles = ', h1.csize) def subsampler(cat, rng, N, rmax): # subsample such that we have at most N particles to rmax nbar = (cat.csize / cat.attrs['BoxSize'].prod()) ratio = (N / rmax ** 3) / nbar mask = rng.uniform(size=cat.size) < ratio cat1 = cat[mask] if rank == 0: print('truncating catalog from %d to %d' % (cat.csize, cat1.csize)) return cat1 if rank == 0 : print('Create weight array') halos = subsampler(halos, rng, N, edges.max()) h1 = subsampler(h1, rng, N, edges.max()) dm = subsampler(dm, rng, N, edges.max()) halos['Weight'] = halos['Mass'] h1['Weight'] = h1['H1mass'] dm['Weight'] = np.ones(dm.size) if rank == 0 : print("Correlation function for edges :\n", edges) start=time() xim = SimulationBox2PCF('1d', data1=dm, edges=edges) end=time() if rank == 0 : print('Time for matter = ', end-start) start=end xih = SimulationBox2PCF('1d', data1=halos, edges=edges) end=time() if rank == 0 : print('Time for halos = ', end-start) start=end ximxh = SimulationBox2PCF('1d', data1=halos, data2=dm, edges=edges) end=time() if rank == 0 : print('Time for matter x halos = ', end-start) start=end #Others mass weighted xihmass = SimulationBox2PCF('1d', data1=halos, weight='Weight', edges=edges) xih1mass = SimulationBox2PCF('1d', data1=h1, weight='Weight', edges=edges) ximxhmass = SimulationBox2PCF('1d', data1=halos, data2=dm, weight='Weight', edges=edges) ximxh1mass = SimulationBox2PCF('1d', data1=h1, data2=dm, weight='Weight', edges=edges) def savebinned(path, binstat, header): r, xi = binstat.corr['r'].real, binstat.corr['corr'].real if rank == 0: try: os.makedirs(os.path.dirname(path)) except IOError: pass np.savetxt(path, np.stack((r, xi), axis=1), header=header) ofolder = project + '/%s/fastpm_%0.4f/ss-%d/' % (sim, aa, N) savebinned(ofolder+'xihpos.txt', xih, header='r, xi(r)') savebinned(ofolder+'ximatter.txt', xim, header='r, xi(r)') savebinned(ofolder+'xihmass.txt', xihmass, header='r, xi(r)') savebinned(ofolder+'xih1mass.txt', xih1mass, header='r, xi(r)') savebinned(ofolder+'ximxhmass.txt', ximxhmass, header='r, xi(r)') savebinned(ofolder+'ximxh1mass.txt', ximxh1mass, header='r, xi(r)') if __name__=="__main__": #measurepk(nc) for aa in aafiles: if rank == 0: print(aa) #readincatalog(aa=aa) #assignH1mass(aa=aa) savecatalogmesh(bs=bs, nc=nc, aa=aa) #edges = np.logspace(np.log10(0.5), np.log10(20), 10) ## use 1000 particles up to (20 Mpc/h) ** 3 volume; ## looks good enough? #measurexi(N=1000, edges=edges) #make_galcat(aa=0.2000)
[ "pmesh.pm.ParticleMesh", "numpy.broadcast_to", "numpy.ones", "argparse.ArgumentParser", "os.makedirs", "nbodykit.lab.SimulationBox2PCF", "tools.atoz", "nbodykit.lab.BigFileMesh", "dohod.make_galcat", "dohod.assignH1mass", "numpy.stack", "os.path.dirname", "nbodykit.lab.BigFileCatalog", "ti...
[((239, 265), 'sys.path.append', 'sys.path.append', (['"""./utils"""'], {}), "('./utils')\n", (254, 265), False, 'import sys\n'), ((373, 398), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (396, 398), False, 'import argparse\n'), ((1724, 1768), 'pmesh.pm.ParticleMesh', 'ParticleMesh', ([], {'BoxSize': 'bs', 'Nmesh': '[nc, nc, nc]'}), '(BoxSize=bs, Nmesh=[nc, nc, nc])\n', (1736, 1768), False, 'from pmesh.pm import ParticleMesh\n'), ((1974, 2049), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(scratchyf + sim + '/fastpm_%0.4f/' % aa)"], {'dataset': '"""LL-0.200"""'}), "(scratchyf + sim + '/fastpm_%0.4f/' % aa, dataset='LL-0.200')\n", (1988, 2049), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((2452, 2520), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(scratchyf + sim + '/fastpm_%0.4f/' % aa)"], {'dataset': '"""1"""'}), "(scratchyf + sim + '/fastpm_%0.4f/' % aa, dataset='1')\n", (2466, 2520), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((2528, 2572), 'pmesh.pm.ParticleMesh', 'ParticleMesh', ([], {'BoxSize': 'bs', 'Nmesh': '[nc, nc, nc]'}), '(BoxSize=bs, Nmesh=[nc, nc, nc])\n', (2540, 2572), False, 'from pmesh.pm import ParticleMesh\n'), ((2697, 2712), 'nbodykit.source.mesh.field.FieldMesh', 'FieldMesh', (['mesh'], {}), '(mesh)\n', (2706, 2712), False, 'from nbodykit.source.mesh.field import FieldMesh\n'), ((2923, 2937), 'tools.atoz', 'tools.atoz', (['aa'], {}), '(aa)\n', (2933, 2937), False, 'import tools, dohod\n'), ((3082, 3130), 'dohod.make_galcat', 'dohod.make_galcat', (['halocat', 'ofolder'], {'z': 'zz', 'pm': 'pm'}), '(halocat, ofolder, z=zz, pm=pm)\n', (3099, 3130), False, 'import tools, dohod\n'), ((3406, 3420), 'tools.atoz', 'tools.atoz', (['aa'], {}), '(aa)\n', (3416, 3420), False, 'import tools, dohod\n'), ((3577, 3610), 'dohod.assignH1mass', 'dohod.assignH1mass', (['halocat'], {'z': 'zz'}), '(halocat, z=zz)\n', (3595, 3610), False, 'import tools, dohod\n'), ((3962, 4006), 'pmesh.pm.ParticleMesh', 'ParticleMesh', ([], {'BoxSize': 'bs', 'Nmesh': '[nc, nc, nc]'}), '(BoxSize=bs, Nmesh=[nc, nc, nc])\n', (3974, 4006), False, 'from pmesh.pm import ParticleMesh\n'), ((1072, 1086), 'tools.atoz', 'tools.atoz', (['aa'], {}), '(aa)\n', (1082, 1086), False, 'import tools, dohod\n'), ((1893, 1961), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(scratchyf + sim + '/fastpm_%0.4f/' % aa)"], {'dataset': '"""1"""'}), "(scratchyf + sim + '/fastpm_%0.4f/' % aa, dataset='1')\n", (1907, 1961), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((4506, 4581), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(scratchyf + sim + '/fastpm_%0.4f/' % aa)"], {'dataset': '"""LL-0.200"""'}), "(scratchyf + sim + '/fastpm_%0.4f/' % aa, dataset='LL-0.200')\n", (4520, 4581), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((6406, 6472), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(scratch + sim + '/fastpm_%0.4f/' % aa)"], {'dataset': '"""1"""'}), "(scratch + sim + '/fastpm_%0.4f/' % aa, dataset='1')\n", (6420, 6472), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((6489, 6550), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(project + sim + '/fastpm_%0.4f/halocat/' % aa)"], {}), "(project + sim + '/fastpm_%0.4f/halocat/' % aa)\n", (6503, 6550), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((6562, 6623), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(project + sim + '/fastpm_%0.4f/halocat/' % aa)"], {}), "(project + sim + '/fastpm_%0.4f/halocat/' % aa)\n", (6576, 6623), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((6800, 6838), 'numpy.random.RandomState', 'np.random.RandomState', (['halos.comm.rank'], {}), '(halos.comm.rank)\n', (6821, 6838), True, 'import numpy as np\n'), ((7825, 7841), 'numpy.ones', 'np.ones', (['dm.size'], {}), '(dm.size)\n', (7832, 7841), True, 'import numpy as np\n'), ((7931, 7937), 'time.time', 'time', ([], {}), '()\n', (7935, 7937), False, 'from time import time\n'), ((7952, 7998), 'nbodykit.lab.SimulationBox2PCF', 'SimulationBox2PCF', (['"""1d"""'], {'data1': 'dm', 'edges': 'edges'}), "('1d', data1=dm, edges=edges)\n", (7969, 7998), False, 'from nbodykit.lab import SimulationBox2PCF, FFTCorr\n'), ((8012, 8018), 'time.time', 'time', ([], {}), '()\n', (8016, 8018), False, 'from time import time\n'), ((8113, 8162), 'nbodykit.lab.SimulationBox2PCF', 'SimulationBox2PCF', (['"""1d"""'], {'data1': 'halos', 'edges': 'edges'}), "('1d', data1=halos, edges=edges)\n", (8130, 8162), False, 'from nbodykit.lab import SimulationBox2PCF, FFTCorr\n'), ((8176, 8182), 'time.time', 'time', ([], {}), '()\n', (8180, 8182), False, 'from time import time\n'), ((8278, 8337), 'nbodykit.lab.SimulationBox2PCF', 'SimulationBox2PCF', (['"""1d"""'], {'data1': 'halos', 'data2': 'dm', 'edges': 'edges'}), "('1d', data1=halos, data2=dm, edges=edges)\n", (8295, 8337), False, 'from nbodykit.lab import SimulationBox2PCF, FFTCorr\n'), ((8351, 8357), 'time.time', 'time', ([], {}), '()\n', (8355, 8357), False, 'from time import time\n'), ((8495, 8561), 'nbodykit.lab.SimulationBox2PCF', 'SimulationBox2PCF', (['"""1d"""'], {'data1': 'halos', 'weight': '"""Weight"""', 'edges': 'edges'}), "('1d', data1=halos, weight='Weight', edges=edges)\n", (8512, 8561), False, 'from nbodykit.lab import SimulationBox2PCF, FFTCorr\n'), ((8582, 8645), 'nbodykit.lab.SimulationBox2PCF', 'SimulationBox2PCF', (['"""1d"""'], {'data1': 'h1', 'weight': '"""Weight"""', 'edges': 'edges'}), "('1d', data1=h1, weight='Weight', edges=edges)\n", (8599, 8645), False, 'from nbodykit.lab import SimulationBox2PCF, FFTCorr\n'), ((8667, 8743), 'nbodykit.lab.SimulationBox2PCF', 'SimulationBox2PCF', (['"""1d"""'], {'data1': 'halos', 'data2': 'dm', 'weight': '"""Weight"""', 'edges': 'edges'}), "('1d', data1=halos, data2=dm, weight='Weight', edges=edges)\n", (8684, 8743), False, 'from nbodykit.lab import SimulationBox2PCF, FFTCorr\n'), ((8766, 8839), 'nbodykit.lab.SimulationBox2PCF', 'SimulationBox2PCF', (['"""1d"""'], {'data1': 'h1', 'data2': 'dm', 'weight': '"""Weight"""', 'edges': 'edges'}), "('1d', data1=h1, data2=dm, weight='Weight', edges=edges)\n", (8783, 8839), False, 'from nbodykit.lab import SimulationBox2PCF, FFTCorr\n'), ((6744, 6784), 'numpy.broadcast_to', 'np.broadcast_to', (["cat.attrs['BoxSize']", '(3)'], {}), "(cat.attrs['BoxSize'], 3)\n", (6759, 6784), True, 'import numpy as np\n'), ((5787, 5807), 'os.makedirs', 'os.makedirs', (['ofolder'], {}), '(ofolder)\n', (5798, 5807), False, 'import os\n'), ((4164, 4243), 'nbodykit.lab.BigFileMesh', 'BigFileMesh', (["(scratchyf + sim + '/fastpm_%0.4f/' % aa + '/1-mesh/N%04d' % nc)", '""""""'], {}), "(scratchyf + sim + '/fastpm_%0.4f/' % aa + '/1-mesh/N%04d' % nc, '')\n", (4175, 4243), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((4291, 4370), 'nbodykit.lab.BigFileMesh', 'BigFileMesh', (["(project + sim + '/fastpm_%0.4f/' % aa + '/dmesh_N%04d/1/' % nc)", '""""""'], {}), "(project + sim + '/fastpm_%0.4f/' % aa + '/dmesh_N%04d/1/' % nc, '')\n", (4302, 4370), False, 'from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower\n'), ((5584, 5615), 'numpy.stack', 'np.stack', (['(k, p, modes)'], {'axis': '(1)'}), '((k, p, modes), axis=1)\n', (5592, 5615), True, 'import numpy as np\n'), ((9160, 9185), 'numpy.stack', 'np.stack', (['(r, xi)'], {'axis': '(1)'}), '((r, xi), axis=1)\n', (9168, 9185), True, 'import numpy as np\n'), ((9047, 9068), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (9062, 9068), False, 'import os\n')]
import argparse import json import logging import numpy as np import warnings import pandas as pd from sklearn.model_selection import KFold from interprete.src.models.available_models import MODELS from interprete.src.struct_probing.code_augs import available_augs, CodeAugmentation from interprete.src.utils import Setup, get_aug_data from interprete.tasks import DATASETS log = logging.getLogger("save_embeddings") log.setLevel(logging.INFO) def get_dataset(args): return DATASETS[args.task]() def iter_models(args): if args.model == "all": models = MODELS.items() else: models = list(filter(lambda x: x[0] == args.model, MODELS.items())) for name, model in models: yield name, model def get_code_augmentation(args) -> CodeAugmentation: aug = available_augs[args.insert_bug]() if aug.type != args.insert_bug: warnings.warn(f"aug.type != args.insert_bug, {aug.type}, {args.insert_bug}") # aug.type = args.insert_bug return aug def main(args): logging.info(f"start {args.insert_bug}") code_aug = get_code_augmentation(args) if code_aug.required_dataset() is not None: warnings.warn(f"changed task data: {args.task} -> {code_aug.required_dataset()}") args.task = code_aug.required_dataset() dataset = get_dataset(args) for i in dataset: # preview print(i) break save_path = Setup.get_aug_path(dataset.type, args.insert_bug, data_dir=args.data_dir) logging.info(f"Save to: {str(save_path)}") # train, test = train_test_split(list(dataset), train_size=0.7, random_state=42) # print("len(train)", len(train)) # print("len(test)", len(test)) saver = get_aug_data(args, list(dataset), code_aug, save_path, mode="all") # will split later # test_saver = get_aug_data(args, test, code_aug, save_path, mode="test") sent_ids = [] for elem in saver.data: sent_id = elem["sent_id"] sent_ids.append(sent_id) assert len(np.unique(sent_ids)) == len(sent_ids) # random.shuffle(sent_ids) sent_ids = np.array(sent_ids) print(f"got {len(sent_ids)} unique sent_ids") # train test splits train, test = {}, {} for i, (train_ids, test_ids) in enumerate(KFold(args.prep_folds, random_state=42, shuffle=True).split(sent_ids)): train[i] = train_ids.tolist() test[i] = test_ids.tolist() with open(f"{save_path}/train.json", "w") as f: json.dump(train, f) with open(f"{save_path}/test.json", "w") as f: json.dump(test, f) if not args.debug: saver.save_json() else: warnings.warn("Data is not saved in DEBUG mode!") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data_dir", default="CodeAnalysis2", help="data-dir") parser.add_argument("--prep_folds", default=4, help="number of train/test splits") parser.add_argument("--task", default="mlm", help="data-dir") parser.add_argument("--n_samples", type=int, default=1000000) parser.add_argument( '-i', "--insert_bug", type=str, choices=list(available_augs.keys()), default="identity", help="data augmentation for probing tasks (bug detection)", ) # Debug parser.add_argument("--debug", action="store_true") # parser.add_argument("--preview", action="store_true") args = parser.parse_args() main(args)
[ "logging.getLogger", "numpy.unique", "argparse.ArgumentParser", "interprete.src.utils.Setup.get_aug_path", "numpy.array", "interprete.src.struct_probing.code_augs.available_augs.keys", "warnings.warn", "sklearn.model_selection.KFold", "logging.info", "json.dump", "interprete.src.models.available...
[((383, 419), 'logging.getLogger', 'logging.getLogger', (['"""save_embeddings"""'], {}), "('save_embeddings')\n", (400, 419), False, 'import logging\n'), ((1023, 1063), 'logging.info', 'logging.info', (['f"""start {args.insert_bug}"""'], {}), "(f'start {args.insert_bug}')\n", (1035, 1063), False, 'import logging\n'), ((1417, 1490), 'interprete.src.utils.Setup.get_aug_path', 'Setup.get_aug_path', (['dataset.type', 'args.insert_bug'], {'data_dir': 'args.data_dir'}), '(dataset.type, args.insert_bug, data_dir=args.data_dir)\n', (1435, 1490), False, 'from interprete.src.utils import Setup, get_aug_data\n'), ((2102, 2120), 'numpy.array', 'np.array', (['sent_ids'], {}), '(sent_ids)\n', (2110, 2120), True, 'import numpy as np\n'), ((2739, 2764), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2762, 2764), False, 'import argparse\n'), ((575, 589), 'interprete.src.models.available_models.MODELS.items', 'MODELS.items', ([], {}), '()\n', (587, 589), False, 'from interprete.src.models.available_models import MODELS\n'), ((876, 952), 'warnings.warn', 'warnings.warn', (['f"""aug.type != args.insert_bug, {aug.type}, {args.insert_bug}"""'], {}), "(f'aug.type != args.insert_bug, {aug.type}, {args.insert_bug}')\n", (889, 952), False, 'import warnings\n'), ((2477, 2496), 'json.dump', 'json.dump', (['train', 'f'], {}), '(train, f)\n', (2486, 2496), False, 'import json\n'), ((2556, 2574), 'json.dump', 'json.dump', (['test', 'f'], {}), '(test, f)\n', (2565, 2574), False, 'import json\n'), ((2647, 2696), 'warnings.warn', 'warnings.warn', (['"""Data is not saved in DEBUG mode!"""'], {}), "('Data is not saved in DEBUG mode!')\n", (2660, 2696), False, 'import warnings\n'), ((2018, 2037), 'numpy.unique', 'np.unique', (['sent_ids'], {}), '(sent_ids)\n', (2027, 2037), True, 'import numpy as np\n'), ((659, 673), 'interprete.src.models.available_models.MODELS.items', 'MODELS.items', ([], {}), '()\n', (671, 673), False, 'from interprete.src.models.available_models import MODELS\n'), ((2271, 2324), 'sklearn.model_selection.KFold', 'KFold', (['args.prep_folds'], {'random_state': '(42)', 'shuffle': '(True)'}), '(args.prep_folds, random_state=42, shuffle=True)\n', (2276, 2324), False, 'from sklearn.model_selection import KFold\n'), ((3171, 3192), 'interprete.src.struct_probing.code_augs.available_augs.keys', 'available_augs.keys', ([], {}), '()\n', (3190, 3192), False, 'from interprete.src.struct_probing.code_augs import available_augs, CodeAugmentation\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 9 15:47:00 2021 @author: yusheng """ import sys import numpy as np import matplotlib.pyplot as plt FILE = "./train/restarted_agent_00_net_" ftype = np.float32 W = np.fromfile(FILE +"weights.raw", dtype=ftype)
[ "numpy.fromfile" ]
[((239, 285), 'numpy.fromfile', 'np.fromfile', (["(FILE + 'weights.raw')"], {'dtype': 'ftype'}), "(FILE + 'weights.raw', dtype=ftype)\n", (250, 285), True, 'import numpy as np\n')]
import numpy as np class HMM: def __init__(self, A=None, B=None, pi=None): self.A = A self.B = B self.pi = pi def forward(self, O, detailed=False): alpha = self.pi*self.B[:, O[0]] if detailed: print("alpha: {}".format(alpha)) for t in range(1, len(O)): alpha = np.squeeze(np.matmul(self.A.T, alpha[..., None]))*self.B[:, O[t]] return np.sum(alpha) def backward(self, O): beta = np.ones(self.pi.shape) for t in range(len(O)-1, 0, -1): beta = np.squeeze(np.matmul(self.A, (self.B[:, O[t]]*beta)[..., None])) return np.sum(self.pi*self.B[:, O[0]]*beta) def Viterbi(self, O): # initialization delta = self.pi*self.B[:, O[0]] psi = np.zeros((len(O), len(delta))) # t*i for t in range(1, len(O)): delta = np.max(delta[..., None]*self.A, axis=-1)*self.B[:, O[t]] psi[t, :] = np.argmax(delta[..., None]*self.A, axis=-1) I = [] i = np.argmax(delta) I.append(i) for t in range(len(O)-1, 0, -1): i = psi[t, int(i)] I.append(i) I = [int(i) for i in I] return np.max(delta), I[::-1]
[ "numpy.ones", "numpy.argmax", "numpy.max", "numpy.sum", "numpy.matmul" ]
[((423, 436), 'numpy.sum', 'np.sum', (['alpha'], {}), '(alpha)\n', (429, 436), True, 'import numpy as np\n'), ((488, 510), 'numpy.ones', 'np.ones', (['self.pi.shape'], {}), '(self.pi.shape)\n', (495, 510), True, 'import numpy as np\n'), ((651, 691), 'numpy.sum', 'np.sum', (['(self.pi * self.B[:, O[0]] * beta)'], {}), '(self.pi * self.B[:, O[0]] * beta)\n', (657, 691), True, 'import numpy as np\n'), ((1046, 1062), 'numpy.argmax', 'np.argmax', (['delta'], {}), '(delta)\n', (1055, 1062), True, 'import numpy as np\n'), ((975, 1020), 'numpy.argmax', 'np.argmax', (['(delta[..., None] * self.A)'], {'axis': '(-1)'}), '(delta[..., None] * self.A, axis=-1)\n', (984, 1020), True, 'import numpy as np\n'), ((1226, 1239), 'numpy.max', 'np.max', (['delta'], {}), '(delta)\n', (1232, 1239), True, 'import numpy as np\n'), ((582, 636), 'numpy.matmul', 'np.matmul', (['self.A', '(self.B[:, O[t]] * beta)[..., None]'], {}), '(self.A, (self.B[:, O[t]] * beta)[..., None])\n', (591, 636), True, 'import numpy as np\n'), ((894, 936), 'numpy.max', 'np.max', (['(delta[..., None] * self.A)'], {'axis': '(-1)'}), '(delta[..., None] * self.A, axis=-1)\n', (900, 936), True, 'import numpy as np\n'), ((353, 390), 'numpy.matmul', 'np.matmul', (['self.A.T', 'alpha[..., None]'], {}), '(self.A.T, alpha[..., None])\n', (362, 390), True, 'import numpy as np\n')]
import os import unittest import logging import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * from slicer.util import VTKObservationMixin # # SegmentCrossSectionArea # class SegmentCrossSectionArea(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "Segment Cross-Section Area" self.parent.categories = ["Quantification"] self.parent.dependencies = [] self.parent.contributors = ["<NAME> (AMNH)", "<NAME> (PerkLab)"] self.parent.helpText = """This module computes cross-section of segments (created by Segment Editor module) and displays them in a plot. Write to <a href="https://discourse.slicer.org">Slicer forum</a> if you need help using this module """ self.parent.acknowledgementText = """ This file was originally developed by <NAME> and <NAME>. """ # # SegmentCrossSectionAreaWidget # class SegmentCrossSectionAreaWidget(ScriptedLoadableModuleWidget, VTKObservationMixin): """Uses ScriptedLoadableModuleWidget base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent=None): """ Called when the user opens the module the first time and the widget is initialized. """ ScriptedLoadableModuleWidget.__init__(self, parent) VTKObservationMixin.__init__(self) # needed for parameter node observation self.logic = None self._parameterNode = None def setup(self): """ Called when the user opens the module the first time and the widget is initialized. """ ScriptedLoadableModuleWidget.setup(self) # Load widget from .ui file (created by Qt Designer) uiWidget = slicer.util.loadUI(self.resourcePath('UI/SegmentCrossSectionArea.ui')) self.layout.addWidget(uiWidget) self.ui = slicer.util.childWidgetVariables(uiWidget) # Set scene in MRML widgets. Make sure that in Qt designer # "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget'rowCount. # "setMRMLScene(vtkMRMLScene*)" slot. uiWidget.setMRMLScene(slicer.mrmlScene) # Create a new parameterNode # This parameterNode stores all user choices in parameter values, node selections, etc. # so that when the scene is saved and reloaded, these settings are restored. self.logic = SegmentCrossSectionAreaLogic() self.ui.parameterNodeSelector.addAttribute("vtkMRMLScriptedModuleNode", "ModuleName", self.moduleName) self.setParameterNode(self.logic.getParameterNode()) # Connections self.ui.parameterNodeSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.setParameterNode) self.ui.applyButton.connect('clicked(bool)', self.onApplyButton) self.ui.showTablePushButton.connect('clicked(bool)', self.onShowTableButton) self.ui.showChartPushButton.connect('clicked(bool)', self.onShowChartButton) # These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene # (in the selected parameter node). self.ui.segmentationSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.volumeSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.axisSelectorBox.connect("currentIndexChanged(int)", self.updateParameterNodeFromGUI) self.ui.tableSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.chartSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) # Initial GUI update self.updateGUIFromParameterNode() def cleanup(self): """ Called when the application closes and the module widget is destroyed. """ self.removeObservers() def setParameterNode(self, inputParameterNode): """ Adds observers to the selected parameter node. Observation is needed because when the parameter node is changed then the GUI must be updated immediately. """ if inputParameterNode: self.logic.setDefaultParameters(inputParameterNode) # TODO: uncomment this when nodeFromIndex method will be available in Python # # Select first segmentation node by default # if not inputParameterNode.GetNodeReference("Segmentation"): # segmentationNode = self.ui.segmentationSelector.nodeFromIndex(0) # if segmentationNode: # inputParameterNode.SetNodeReferenceID(segmentationNode.GetID()) # Set parameter node in the parameter node selector widget wasBlocked = self.ui.parameterNodeSelector.blockSignals(True) self.ui.parameterNodeSelector.setCurrentNode(inputParameterNode) self.ui.parameterNodeSelector.blockSignals(wasBlocked) if inputParameterNode == self._parameterNode: # No change return # Unobserve previously selected parameter node and add an observer to the newly selected. # Changes of parameter node are observed so that whenever parameters are changed by a script or any other module # those are reflected immediately in the GUI. if self._parameterNode is not None: self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode) if inputParameterNode is not None: self.addObserver(inputParameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode) self._parameterNode = inputParameterNode # Initial GUI update self.updateGUIFromParameterNode() def updateGUIFromParameterNode(self, caller=None, event=None): """ This method is called whenever parameter node is changed. The module GUI is updated to show the current state of the parameter node. """ # Disable all sections if no parameter node is selected self.ui.basicCollapsibleButton.enabled = self._parameterNode is not None if self._parameterNode is None: return # Update each widget from parameter node # Need to temporarily block signals to prevent infinite recursion (MRML node update triggers # GUI update, which triggers MRML node update, which triggers GUI update, ...) wasBlocked = self.ui.segmentationSelector.blockSignals(True) self.ui.segmentationSelector.setCurrentNode(self._parameterNode.GetNodeReference("Segmentation")) self.ui.segmentationSelector.blockSignals(wasBlocked) wasBlocked = self.ui.volumeSelector.blockSignals(True) self.ui.volumeSelector.setCurrentNode(self._parameterNode.GetNodeReference("Volume")) self.ui.volumeSelector.blockSignals(wasBlocked) wasBlocked = self.ui.axisSelectorBox.blockSignals(True) self.ui.axisSelectorBox.currentText = self._parameterNode.GetParameter("Axis") self.ui.axisSelectorBox.blockSignals(wasBlocked) wasBlocked = self.ui.tableSelector.blockSignals(True) self.ui.tableSelector.setCurrentNode(self._parameterNode.GetNodeReference("ResultsTable")) self.ui.tableSelector.blockSignals(wasBlocked) wasBlocked = self.ui.axisSelectorBox.blockSignals(True) self.ui.chartSelector.setCurrentNode(self._parameterNode.GetNodeReference("ResultsChart")) self.ui.axisSelectorBox.blockSignals(wasBlocked) # Update buttons states and tooltips if self._parameterNode.GetNodeReference("Segmentation"): self.ui.applyButton.toolTip = "Compute cross sections" self.ui.applyButton.enabled = True else: self.ui.applyButton.toolTip = "Select input segmentation node" self.ui.applyButton.enabled = False def updateParameterNodeFromGUI(self, caller=None, event=None): """ This method is called when the user makes any change in the GUI. The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded). """ if self._parameterNode is None: return self._parameterNode.SetNodeReferenceID("Segmentation", self.ui.segmentationSelector.currentNodeID) self._parameterNode.SetNodeReferenceID("Volume", self.ui.volumeSelector.currentNodeID) self._parameterNode.SetParameter("Axis", self.ui.axisSelectorBox.currentText) self._parameterNode.SetNodeReferenceID("ResultsTable", self.ui.tableSelector.currentNodeID) self._parameterNode.SetNodeReferenceID("ResultsChart", self.ui.chartSelector.currentNodeID) def onApplyButton(self): """ Run processing when user clicks "Apply" button. """ try: # Create nodes for results tableNode = self.ui.tableSelector.currentNode() if not tableNode: tableNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLTableNode", "Segment cross-section area table") self.ui.tableSelector.setCurrentNode(tableNode) plotChartNode = self.ui.chartSelector.currentNode() if not plotChartNode: plotChartNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLPlotChartNode", "Segment cross-section area plot") self.ui.chartSelector.setCurrentNode(plotChartNode) self.logic.run(self.ui.segmentationSelector.currentNode(), self.ui.volumeSelector.currentNode(), self.ui.axisSelectorBox.currentText, tableNode, plotChartNode) self.logic.showChart(plotChartNode) except Exception as e: slicer.util.errorDisplay("Failed to compute results: "+str(e)) import traceback traceback.print_exc() def onShowTableButton(self): tableNode = self.ui.tableSelector.currentNode() if not tableNode: self.onApplyButton() tableNode = self.ui.tableSelector.currentNode() if tableNode: self.logic.showTable(tableNode) def onShowChartButton(self): plotChartNode = self.ui.chartSelector.currentNode() if not plotChartNode: self.onApplyButton() plotChartNode = self.ui.chartSelector.currentNode() if plotChartNode: self.logic.showChart(plotChartNode) # # SegmentCrossSectionAreaLogic # class SegmentCrossSectionAreaLogic(ScriptedLoadableModuleLogic): """This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget. Uses ScriptedLoadableModuleLogic base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def setDefaultParameters(self, parameterNode): """ Initialize parameter node with default settings. """ if not parameterNode.GetParameter("Axis"): parameterNode.SetParameter("Axis", "slice") def run(self, segmentationNode, volumeNode, axis, tableNode, plotChartNode): """ Run the processing algorithm. Can be used without GUI widget. :param segmentationNode: cross section area will be computed on this :param volumeNode: optional reference volume (to determine slice positions and directions) :param axis: axis index to compute cross section areas along :param tableNode: result table node :param plotChartNode: result chart node """ import numpy as np logging.info('Processing started') if not segmentationNode: raise ValueError("Segmentation node is invalid") # Get visible segment ID list. # Get segment ID list visibleSegmentIds = vtk.vtkStringArray() segmentationNode.GetDisplayNode().GetVisibleSegmentIDs(visibleSegmentIds) if visibleSegmentIds.GetNumberOfValues() == 0: raise ValueError("SliceAreaPlot will not return any results: there are no visible segments") if axis=="row": axisIndex = 0 elif axis=="column": axisIndex = 1 elif axis=="slice": axisIndex = 2 else: raise ValueError("Invalid axis name: "+axis) # # Make a table and set the first column as the slice number. This is used # as the X axis for plots. # tableNode.RemoveAllColumns() table = tableNode.GetTable() # Make a plot chart node. Plot series nodes will be added to this in the # loop below that iterates over each segment. plotChartNode.SetTitle('Segment cross-section area ('+axis+')') plotChartNode.SetXAxisTitle(axis +" index") plotChartNode.SetYAxisTitle('Area in mm^2') # TODO: use length unit # # For each segment, get the area and put it in the table in a new column. # try: # Create temporary volume node tempSegmentLabelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLLabelMapVolumeNode', "SegmentCrossSectionAreaTemp") for segmentIndex in range(visibleSegmentIds.GetNumberOfValues()): segmentID = visibleSegmentIds.GetValue(segmentIndex) segmentList = vtk.vtkStringArray() segmentList.InsertNextValue(segmentID) if not slicer.modules.segmentations.logic().ExportSegmentsToLabelmapNode(segmentationNode, segmentList, tempSegmentLabelmapVolumeNode, volumeNode): continue if segmentIndex == 0: volumeExtents = tempSegmentLabelmapVolumeNode.GetImageData().GetExtent() numSlices = volumeExtents[axisIndex*2+1] - volumeExtents[axisIndex*2] + 1 startPosition_Ijk = [ (volumeExtents[0]+volumeExtents[1])/2.0 if axisIndex!=0 else volumeExtents[0], (volumeExtents[2]+volumeExtents[3])/2.0 if axisIndex!=1 else volumeExtents[2], (volumeExtents[4]+volumeExtents[5])/2.0 if axisIndex!=2 else volumeExtents[4], 1 ] endPosition_Ijk = [ (volumeExtents[0]+volumeExtents[1])/2.0 if axisIndex!=0 else volumeExtents[1], (volumeExtents[2]+volumeExtents[3])/2.0 if axisIndex!=1 else volumeExtents[3], (volumeExtents[4]+volumeExtents[5])/2.0 if axisIndex!=2 else volumeExtents[5], 1 ] # Get physical coordinates from voxel coordinates volumeIjkToRas = vtk.vtkMatrix4x4() tempSegmentLabelmapVolumeNode.GetIJKToRASMatrix(volumeIjkToRas) startPosition_Ras = np.array([0.0,0.0,0.0,1.0]) volumeIjkToRas.MultiplyPoint(startPosition_Ijk, startPosition_Ras) endPosition_Ras = np.array([0.0,0.0,0.0,1.0]) volumeIjkToRas.MultiplyPoint(endPosition_Ijk, endPosition_Ras) volumePositionIncrement_Ras = np.array([0,0,0,1]) if numSlices > 1: volumePositionIncrement_Ras = (endPosition_Ras - startPosition_Ras) / (numSlices - 1.0) # If volume node is transformed, apply that transform to get volume's RAS coordinates transformVolumeRasToRas = vtk.vtkGeneralTransform() slicer.vtkMRMLTransformNode.GetTransformBetweenNodes(tempSegmentLabelmapVolumeNode.GetParentTransformNode(), None, transformVolumeRasToRas) sliceNumberArray = vtk.vtkIntArray() sliceNumberArray.SetName("Index") slicePositionArray = vtk.vtkFloatArray() slicePositionArray.SetNumberOfComponents(3) slicePositionArray.SetComponentName(0, "R") slicePositionArray.SetComponentName(1, "A") slicePositionArray.SetComponentName(2, "S") slicePositionArray.SetName("Position") for i in range(numSlices): sliceNumberArray.InsertNextValue(i) point_VolumeRas = startPosition_Ras + i * volumePositionIncrement_Ras point_Ras = transformVolumeRasToRas.TransformPoint(point_VolumeRas[0:3]) slicePositionArray.InsertNextTuple3(*point_Ras) table.AddColumn(sliceNumberArray) tableNode.SetColumnDescription(sliceNumberArray.GetName(), "Index of " + axis) tableNode.SetColumnUnitLabel(sliceNumberArray.GetName(), "voxel") table.AddColumn(slicePositionArray) tableNode.SetColumnDescription(slicePositionArray.GetName(), "RAS position of slice center") tableNode.SetColumnUnitLabel(slicePositionArray.GetName(), "mm") # TODO: use length unit narray = slicer.util.arrayFromVolume(tempSegmentLabelmapVolumeNode) areaArray = vtk.vtkFloatArray() segmentName = segmentationNode.GetSegmentation().GetSegment(segmentID).GetName() areaArray.SetName(segmentName) # Convert number of voxels to area in mm2 spacing = tempSegmentLabelmapVolumeNode.GetSpacing() areaOfPixelMm2 = spacing[0] * spacing[1] * spacing[2] / spacing[axisIndex] # Count number of >0 voxels for each slice for i in range(numSlices): if axisIndex == 0: areaBySliceInVoxels = np.count_nonzero(narray[:,:,i]) elif axisIndex == 1: areaBySliceInVoxels = np.count_nonzero(narray[:, i, :]) elif axisIndex == 2: areaBySliceInVoxels = np.count_nonzero(narray[i, :, :]) areaBySliceInMm2 = areaBySliceInVoxels * areaOfPixelMm2 areaArray.InsertNextValue(areaBySliceInMm2) tableNode.AddColumn(areaArray) tableNode.SetColumnUnitLabel(areaArray.GetName(), "mm2") # TODO: use length unit tableNode.SetColumnDescription(areaArray.GetName(), "Cross-section area") # Make a plot series node for this column. plotSeriesNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLPlotSeriesNode", segmentName) plotSeriesNode.SetAndObserveTableNodeID(tableNode.GetID()) plotSeriesNode.SetXColumnName("Index") plotSeriesNode.SetYColumnName(segmentName) plotSeriesNode.SetUniqueColor() # Add this series to the plot chart node created above. plotChartNode.AddAndObservePlotSeriesNodeID(plotSeriesNode.GetID()) finally: # Remove temporary volume node colorNode = tempSegmentLabelmapVolumeNode.GetDisplayNode().GetColorNode() if colorNode: slicer.mrmlScene.RemoveNode(colorNode) slicer.mrmlScene.RemoveNode(tempSegmentLabelmapVolumeNode) logging.info('Processing completed') def showChart(self, plotChartNode): # Choose a layout where plots are visible layoutManager = slicer.app.layoutManager() layoutWithPlot = slicer.modules.plots.logic().GetLayoutWithPlot(layoutManager.layout) layoutManager.setLayout(layoutWithPlot) # Select chart in plot view plotWidget = layoutManager.plotWidget(0) plotViewNode = plotWidget.mrmlPlotViewNode() plotViewNode.SetPlotChartNodeID(plotChartNode.GetID()) def showTable(self, tableNode): # Choose a layout where plots are visible layoutManager = slicer.app.layoutManager() layoutWithPlot = slicer.modules.tables.logic().GetLayoutWithTable(layoutManager.layout) layoutManager.setLayout(layoutWithPlot) # Select chart in plot view tableWidget = layoutManager.tableWidget(0) tableWidget.tableView().setMRMLTableNode(tableNode) # # SegmentCrossSectionAreaTest # class SegmentCrossSectionAreaTest(ScriptedLoadableModuleTest): """ This is the test case for your scripted module. Uses ScriptedLoadableModuleTest base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0) def runTest(self): """Run as few or as many tests as needed here. """ self.setUp() self.test_SegmentCrossSectionArea1() def test_SegmentCrossSectionArea1(self): """ Ideally you should have several levels of tests. At the lowest level tests should exercise the functionality of the logic with different inputs (both valid and invalid). At higher levels your tests should emulate the way the user would interact with your code and confirm that it still works the way you intended. One of the most important features of the tests is that it should alert other developers when their changes will have an impact on the behavior of your module. For example, if a developer removes a feature that you depend on, your test should break so they know that the feature is needed. """ self.delayDisplay("Starting the test") # Load master volume import SampleData sampleDataLogic = SampleData.SampleDataLogic() masterVolumeNode = sampleDataLogic.downloadMRBrainTumor1() # Create segmentation segmentationNode = slicer.vtkMRMLSegmentationNode() slicer.mrmlScene.AddNode(segmentationNode) segmentationNode.CreateDefaultDisplayNodes() # only needed for display segmentationNode.SetReferenceImageGeometryParameterFromVolumeNode(masterVolumeNode) # Create a sphere shaped segment radius = 20 tumorSeed = vtk.vtkSphereSource() tumorSeed.SetCenter(-6, 30, 28) tumorSeed.SetRadius(radius) tumorSeed.SetPhiResolution(120) tumorSeed.SetThetaResolution(120) tumorSeed.Update() segmentId = segmentationNode.AddSegmentFromClosedSurfaceRepresentation(tumorSeed.GetOutput(), "Tumor", [1.0, 0.0, 0.0]) tableNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLTableNode", "Segment cross-section area table") plotChartNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLPlotChartNode", "Segment cross-section area plot") logic = SegmentCrossSectionAreaLogic() logic.run(segmentationNode, masterVolumeNode, "slice", tableNode, plotChartNode) logic.showChart(plotChartNode) self.assertEqual(tableNode.GetNumberOfColumns(), 3) self.assertEqual(tableNode.GetNumberOfColumns(), 3) # Compute error crossSectionAreas = slicer.util.arrayFromTableColumn(tableNode, "Tumor") largestCrossSectionArea = crossSectionAreas.max() import math expectedlargestCrossSectionArea = radius*radius*math.pi logging.info("Largest cross-section area: {0:.2f}".format(largestCrossSectionArea)) logging.info("Expected largest cross-section area: {0:.2f}".format(expectedlargestCrossSectionArea)) errorPercent = 100.0 * abs(largestCrossSectionArea - expectedlargestCrossSectionArea) < expectedlargestCrossSectionArea logging.info("Largest cross-section area error: {0:.2f}%".format(errorPercent)) # Error between expected and actual cross section is due to finite resolution of the segmentation. # It should not be more than a few percent. The actual error in this case is around 1%, but use 2% to account for # numerical differences between different platforms. self.assertTrue(errorPercent < 2.0) self.delayDisplay('Test passed')
[ "slicer.util.childWidgetVariables", "numpy.count_nonzero", "numpy.array", "vtk.vtkGeneralTransform", "vtk.vtkFloatArray", "logging.info", "slicer.util.arrayFromTableColumn", "slicer.mrmlScene.AddNewNodeByClass", "slicer.mrmlScene.AddNode", "traceback.print_exc", "SampleData.SampleDataLogic", "...
[((1523, 1557), 'slicer.util.VTKObservationMixin.__init__', 'VTKObservationMixin.__init__', (['self'], {}), '(self)\n', (1551, 1557), False, 'from slicer.util import VTKObservationMixin\n'), ((2015, 2057), 'slicer.util.childWidgetVariables', 'slicer.util.childWidgetVariables', (['uiWidget'], {}), '(uiWidget)\n', (2047, 2057), False, 'import vtk, qt, ctk, slicer\n'), ((11202, 11236), 'logging.info', 'logging.info', (['"""Processing started"""'], {}), "('Processing started')\n", (11214, 11236), False, 'import logging\n'), ((11412, 11432), 'vtk.vtkStringArray', 'vtk.vtkStringArray', ([], {}), '()\n', (11430, 11432), False, 'import vtk, qt, ctk, slicer\n'), ((17937, 17973), 'logging.info', 'logging.info', (['"""Processing completed"""'], {}), "('Processing completed')\n", (17949, 17973), False, 'import logging\n'), ((18079, 18105), 'slicer.app.layoutManager', 'slicer.app.layoutManager', ([], {}), '()\n', (18103, 18105), False, 'import vtk, qt, ctk, slicer\n'), ((18526, 18552), 'slicer.app.layoutManager', 'slicer.app.layoutManager', ([], {}), '()\n', (18550, 18552), False, 'import vtk, qt, ctk, slicer\n'), ((19260, 19285), 'slicer.mrmlScene.Clear', 'slicer.mrmlScene.Clear', (['(0)'], {}), '(0)\n', (19282, 19285), False, 'import vtk, qt, ctk, slicer\n'), ((20238, 20266), 'SampleData.SampleDataLogic', 'SampleData.SampleDataLogic', ([], {}), '()\n', (20264, 20266), False, 'import SampleData\n'), ((20380, 20412), 'slicer.vtkMRMLSegmentationNode', 'slicer.vtkMRMLSegmentationNode', ([], {}), '()\n', (20410, 20412), False, 'import vtk, qt, ctk, slicer\n'), ((20417, 20459), 'slicer.mrmlScene.AddNode', 'slicer.mrmlScene.AddNode', (['segmentationNode'], {}), '(segmentationNode)\n', (20441, 20459), False, 'import vtk, qt, ctk, slicer\n'), ((20694, 20715), 'vtk.vtkSphereSource', 'vtk.vtkSphereSource', ([], {}), '()\n', (20713, 20715), False, 'import vtk, qt, ctk, slicer\n'), ((21097, 21191), 'slicer.mrmlScene.AddNewNodeByClass', 'slicer.mrmlScene.AddNewNodeByClass', (['"""vtkMRMLTableNode"""', '"""Segment cross-section area table"""'], {}), "('vtkMRMLTableNode',\n 'Segment cross-section area table')\n", (21131, 21191), False, 'import vtk, qt, ctk, slicer\n'), ((21208, 21305), 'slicer.mrmlScene.AddNewNodeByClass', 'slicer.mrmlScene.AddNewNodeByClass', (['"""vtkMRMLPlotChartNode"""', '"""Segment cross-section area plot"""'], {}), "('vtkMRMLPlotChartNode',\n 'Segment cross-section area plot')\n", (21242, 21305), False, 'import vtk, qt, ctk, slicer\n'), ((21624, 21676), 'slicer.util.arrayFromTableColumn', 'slicer.util.arrayFromTableColumn', (['tableNode', '"""Tumor"""'], {}), "(tableNode, 'Tumor')\n", (21656, 21676), False, 'import vtk, qt, ctk, slicer\n'), ((12532, 12630), 'slicer.mrmlScene.AddNewNodeByClass', 'slicer.mrmlScene.AddNewNodeByClass', (['"""vtkMRMLLabelMapVolumeNode"""', '"""SegmentCrossSectionAreaTemp"""'], {}), "('vtkMRMLLabelMapVolumeNode',\n 'SegmentCrossSectionAreaTemp')\n", (12566, 12630), False, 'import vtk, qt, ctk, slicer\n'), ((17872, 17930), 'slicer.mrmlScene.RemoveNode', 'slicer.mrmlScene.RemoveNode', (['tempSegmentLabelmapVolumeNode'], {}), '(tempSegmentLabelmapVolumeNode)\n', (17899, 17930), False, 'import vtk, qt, ctk, slicer\n'), ((8678, 8772), 'slicer.mrmlScene.AddNewNodeByClass', 'slicer.mrmlScene.AddNewNodeByClass', (['"""vtkMRMLTableNode"""', '"""Segment cross-section area table"""'], {}), "('vtkMRMLTableNode',\n 'Segment cross-section area table')\n", (8712, 8772), False, 'import vtk, qt, ctk, slicer\n'), ((8935, 9032), 'slicer.mrmlScene.AddNewNodeByClass', 'slicer.mrmlScene.AddNewNodeByClass', (['"""vtkMRMLPlotChartNode"""', '"""Segment cross-section area plot"""'], {}), "('vtkMRMLPlotChartNode',\n 'Segment cross-section area plot')\n", (8969, 9032), False, 'import vtk, qt, ctk, slicer\n'), ((9446, 9467), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (9465, 9467), False, 'import traceback\n'), ((12784, 12804), 'vtk.vtkStringArray', 'vtk.vtkStringArray', ([], {}), '()\n', (12802, 12804), False, 'import vtk, qt, ctk, slicer\n'), ((16037, 16095), 'slicer.util.arrayFromVolume', 'slicer.util.arrayFromVolume', (['tempSegmentLabelmapVolumeNode'], {}), '(tempSegmentLabelmapVolumeNode)\n', (16064, 16095), False, 'import vtk, qt, ctk, slicer\n'), ((16117, 16136), 'vtk.vtkFloatArray', 'vtk.vtkFloatArray', ([], {}), '()\n', (16134, 16136), False, 'import vtk, qt, ctk, slicer\n'), ((17249, 17321), 'slicer.mrmlScene.AddNewNodeByClass', 'slicer.mrmlScene.AddNewNodeByClass', (['"""vtkMRMLPlotSeriesNode"""', 'segmentName'], {}), "('vtkMRMLPlotSeriesNode', segmentName)\n", (17283, 17321), False, 'import vtk, qt, ctk, slicer\n'), ((17827, 17865), 'slicer.mrmlScene.RemoveNode', 'slicer.mrmlScene.RemoveNode', (['colorNode'], {}), '(colorNode)\n', (17854, 17865), False, 'import vtk, qt, ctk, slicer\n'), ((18127, 18155), 'slicer.modules.plots.logic', 'slicer.modules.plots.logic', ([], {}), '()\n', (18153, 18155), False, 'import vtk, qt, ctk, slicer\n'), ((18574, 18603), 'slicer.modules.tables.logic', 'slicer.modules.tables.logic', ([], {}), '()\n', (18601, 18603), False, 'import vtk, qt, ctk, slicer\n'), ((13984, 14002), 'vtk.vtkMatrix4x4', 'vtk.vtkMatrix4x4', ([], {}), '()\n', (14000, 14002), False, 'import vtk, qt, ctk, slicer\n'), ((14107, 14137), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 0.0, 1.0])\n', (14115, 14137), True, 'import numpy as np\n'), ((14240, 14270), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 0.0, 1.0])\n', (14248, 14270), True, 'import numpy as np\n'), ((14381, 14403), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (14389, 14403), True, 'import numpy as np\n'), ((14662, 14687), 'vtk.vtkGeneralTransform', 'vtk.vtkGeneralTransform', ([], {}), '()\n', (14685, 14687), False, 'import vtk, qt, ctk, slicer\n'), ((14868, 14885), 'vtk.vtkIntArray', 'vtk.vtkIntArray', ([], {}), '()\n', (14883, 14885), False, 'import vtk, qt, ctk, slicer\n'), ((14961, 14980), 'vtk.vtkFloatArray', 'vtk.vtkFloatArray', ([], {}), '()\n', (14978, 14980), False, 'import vtk, qt, ctk, slicer\n'), ((16610, 16643), 'numpy.count_nonzero', 'np.count_nonzero', (['narray[:, :, i]'], {}), '(narray[:, :, i])\n', (16626, 16643), True, 'import numpy as np\n'), ((12867, 12903), 'slicer.modules.segmentations.logic', 'slicer.modules.segmentations.logic', ([], {}), '()\n', (12901, 12903), False, 'import vtk, qt, ctk, slicer\n'), ((16707, 16740), 'numpy.count_nonzero', 'np.count_nonzero', (['narray[:, i, :]'], {}), '(narray[:, i, :])\n', (16723, 16740), True, 'import numpy as np\n'), ((16806, 16839), 'numpy.count_nonzero', 'np.count_nonzero', (['narray[i, :, :]'], {}), '(narray[i, :, :])\n', (16822, 16839), True, 'import numpy as np\n')]
__author__ = "<NAME>" __copyright__ = "Copyright 2018, Harvard Medical School" __license__ = "MIT" import numpy as np import tensorflow as tf from ast import literal_eval class switch(object): """Switch statement for Python, based on recipe from Python Cookbook.""" def __init__(self, value): self.value = value self.fall = False def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: # changed for v1.5 self.fall = True return True else: return False def merge_two_dicts(x, y): """ Efficiently merges two dicts, giving precedence to second dict. """ z = x.copy() z.update(y) return z def merge_dicts(*dict_args): """ Efficiently merges arbitrary number of dicts, giving precedence to latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result def ops_to_dict(session, ops): """ Helper function that converts canonical dict of TF ops to an actual dict. Runs ops first. """ dict_ = dict(zip(ops.keys(), session.run(ops.values()))) return dict_ def cum_quantile_positions(weights, quantiles = np.linspace(0.25, 0.99, 4)): """ Computes cumulative quantiles from curriculum weights. """ if len(weights) != 0: return [next(x[0] + 1 for x in enumerate(np.cumsum(weights / sum(weights))) if x[1] > p) for p in quantiles] else: return [] def dict_to_init(dict_, seed=None, dtype=tf.float32): """ Accepts a dict in canonical config form and returns the appropriate initializer. """ # effect defaults init_center = dict_.get('center', 0.0) init_range = dict_.get('range', 0.01) init_dist = dict_.get('dist', 'gaussian') init_scale = dict_.get('scale', 1.0) init_mode = dict_.get('mode', 'fan_in') # also accepts fan_out, fan_avg for case in switch(init_dist): if case('gaussian'): init = tf.initializers.random_normal( init_center, init_range, seed=seed, dtype=dtype) elif case('uniform'): init = tf.initializers.random_uniform( init_center - init_range, init_center + init_range, seed=seed, dtype=dtype) elif case('orthogonal'): init = tf.initializers.orthogonal( init_scale, seed=seed, dtype=dtype) elif case('gaussian_variance_scaling'): init = tf.initializers.variance_scaling(init_scale, init_mode, 'normal', seed=seed, dtype=dtype) elif case('uniform_variance_scaling'): init = tf.initializers.variance_scaling(init_scale, init_mode, 'uniform', seed=seed, dtype=dtype) return init def dict_to_inits(dict_, seed=None, dtype=tf.float32): """ Accepts a dict of dicts, each of which contains a canonical config for an initializer. """ inits = {k: dict_to_init(v, seed, dtype) for k, v in dict_.items()} return inits
[ "tensorflow.initializers.random_normal", "tensorflow.initializers.orthogonal", "numpy.linspace", "tensorflow.initializers.random_uniform", "tensorflow.initializers.variance_scaling" ]
[((1421, 1447), 'numpy.linspace', 'np.linspace', (['(0.25)', '(0.99)', '(4)'], {}), '(0.25, 0.99, 4)\n', (1432, 1447), True, 'import numpy as np\n'), ((2203, 2281), 'tensorflow.initializers.random_normal', 'tf.initializers.random_normal', (['init_center', 'init_range'], {'seed': 'seed', 'dtype': 'dtype'}), '(init_center, init_range, seed=seed, dtype=dtype)\n', (2232, 2281), True, 'import tensorflow as tf\n'), ((2361, 2471), 'tensorflow.initializers.random_uniform', 'tf.initializers.random_uniform', (['(init_center - init_range)', '(init_center + init_range)'], {'seed': 'seed', 'dtype': 'dtype'}), '(init_center - init_range, init_center +\n init_range, seed=seed, dtype=dtype)\n', (2391, 2471), True, 'import tensorflow as tf\n'), ((2522, 2584), 'tensorflow.initializers.orthogonal', 'tf.initializers.orthogonal', (['init_scale'], {'seed': 'seed', 'dtype': 'dtype'}), '(init_scale, seed=seed, dtype=dtype)\n', (2548, 2584), True, 'import tensorflow as tf\n'), ((2698, 2791), 'tensorflow.initializers.variance_scaling', 'tf.initializers.variance_scaling', (['init_scale', 'init_mode', '"""normal"""'], {'seed': 'seed', 'dtype': 'dtype'}), "(init_scale, init_mode, 'normal', seed=seed,\n dtype=dtype)\n", (2730, 2791), True, 'import tensorflow as tf\n'), ((2873, 2968), 'tensorflow.initializers.variance_scaling', 'tf.initializers.variance_scaling', (['init_scale', 'init_mode', '"""uniform"""'], {'seed': 'seed', 'dtype': 'dtype'}), "(init_scale, init_mode, 'uniform', seed=\n seed, dtype=dtype)\n", (2905, 2968), True, 'import tensorflow as tf\n')]
import rospy from std_msgs.msg import String from skeleton_markers.msg import Skeleton import numpy as np class SkeletonAngles(): def __init__(self): self.pub = rospy.Publisher ('skeleton_angles', String, queue_size=10) self.names = ['head', 'neck', 'torso', 'left_shoulder', 'left_elbow', 'left_hand', 'right_shoulder', 'right_elbow', 'right_hand', 'left_hip', 'left_knee', 'left_foot', 'right_hip', 'right_knee', 'right_foot'] self.positions = {} for name in self.names: self.positions[name] = {'x': None, 'y': None, 'z': None} self.skeleton_angles = np.zeros([8]) def start(self): #init a listener to kinect and rospy.init_node('skeleton_angle') rospy.Subscriber("skeleton", Skeleton, self.callback) rospy.spin() def callback(self, data): positions = data.position for name in self.names: self.positions[name]['x'] = positions[self.names.index(name)].x self.positions[name]['y'] = positions[self.names.index(name)].y self.positions[name]['z'] = positions[self.names.index(name)].z #print(self.positions) #x_0 x_0=np.array([self.positions["left_shoulder"]['x']-self.positions["right_shoulder"]['x'], self.positions["left_shoulder"]['y']-self.positions["right_shoulder"]['y'], self.positions["left_shoulder"]['z']-self.positions["right_shoulder"]['z']]) x_0=(x_0/np.linalg.norm(x_0)) #y_0 mid_shoulder=np.array([self.positions["left_shoulder"]['x']+self.positions["right_shoulder"]['x'], self.positions["left_shoulder"]['y']+self.positions["right_shoulder"]['y'], self.positions["left_shoulder"]['z']+self.positions["right_shoulder"]['z']])/2 mid_hip=np.array([self.positions["left_hip"]['x']+self.positions["right_hip"]['x'], self.positions["left_hip"]['y']+self.positions["right_hip"]['y'], self.positions["left_hip"]['z']+self.positions["right_hip"]['z']])/2 torso=np.array([self.positions["torso"]['x'], self.positions["torso"]['y'], self.positions["torso"]['z']]) y_0= mid_shoulder-torso y_0= y_0/np.linalg.norm(y_0) #z_0 z_0=np.cross(x_0,y_0) #z_l2 z_l2=np.array([self.positions["left_elbow"]['x']-self.positions["left_shoulder"]['x'], self.positions["left_elbow"]['y']-self.positions["left_shoulder"]['y'], self.positions["left_elbow"]['z']-self.positions["left_shoulder"]['z']]) z_l2=z_l2/np.linalg.norm(z_l2) #thtrl z_2_z_0_l=np.dot(z_l2,z_0) z_2_y_0_l=np.dot(z_l2,y_0) thtl1=np.arctan2(-z_2_y_0_l,z_2_z_0_l) # psil1 x_l1=x_0 z_l1=np.dot(self.rot_x(thtl1),z_0) z_2_x_1_l=np.dot(z_l2,x_l1) z_2_z_1_l=np.dot(z_l2,z_l1) psil1=np.arctan2(z_2_x_1_l,z_2_z_1_l) #phi_L r_l=np.dot(self.rot_y(psil1),self.rot_x(thtl1)) x_2l=np.dot(r_l,x_0) y_2l=np.dot(r_l,y_0) z_l4=np.array([self.positions["left_hand"]['x']-self.positions["left_elbow"]['x'], self.positions["left_hand"]['y']-self.positions["left_elbow"]['y'], self.positions["left_hand"]['z']-self.positions["left_elbow"]['z']]) z_l4 = z_l4/np.linalg.norm(z_l4) z_4_y_2_l=np.dot(z_l4,y_2l) z_4_x_2_l=np.dot(z_l4,x_2l) phi_l=np.arctan2(-z_4_y_2_l,-z_4_x_2_l) #omega_l # x_3l=np.dot(self.rot_z(phi_l),x_2l) # z_3l=z_l2 # z_4_x_3_l=np.dot(z_l4,x_3l) # z_4_z_3=np.dot(z_l4,z_3l) # omega_l=np.arctan2(z_4_x_3_l,z_4_z_3) omega_l=-np.arccos(np.dot(z_l2,z_l4)) # print 'thtl1',thtl1,'psil1',psil1,'phi_l', phi_l,'omega_l', omega_l # psil1= np.arcsin(np.dot(x_0,z_l2)) # thtl1= np.arcsin(-np.dot(y_0,z_l2)/np.cos(psil1)) #z_r2 z_r2=np.array([self.positions["right_elbow"]['x']-self.positions["right_shoulder"]['x'], self.positions["right_elbow"]['y']-self.positions["right_shoulder"]['y'], self.positions["right_elbow"]['z']-self.positions["right_shoulder"]['z']]) z_r2=z_r2/np.linalg.norm(z_r2) #thtrl z_2_z_0_r=np.dot(z_r2,z_0) z_2_y_0_r=np.dot(z_r2,y_0) thtr1=np.arctan2(-z_2_y_0_r,z_2_z_0_r) # psil1 x_r1=x_0 z_r1=np.dot(self.rot_x(thtr1),z_0) z_2_x_1_r=np.dot(z_r2,x_r1) z_2_z_1_r=np.dot(z_r2,z_r1) psir1=np.arctan2(z_2_x_1_r,z_2_z_1_r) #phi_r r_r=np.dot(self.rot_y(psir1),self.rot_x(thtr1)) x_2r=np.dot(r_r,x_0) y_2r=np.dot(r_r,y_0) z_r4=np.array([self.positions["right_hand"]['x']-self.positions["right_elbow"]['x'], self.positions["right_hand"]['y']-self.positions["right_elbow"]['y'], self.positions["right_hand"]['z']-self.positions["right_elbow"]['z']]) z_r4=z_r4/np.linalg.norm(z_r4) z_4_y_2_r=np.dot(z_r4,y_2r) z_4_x_2_r=np.dot(z_r4,x_2r) phi_r=np.arctan2(z_4_y_2_r,z_4_x_2_r) #omega_l # x_3l=np.dot(self.rot_z(phi_l),x_2l) # z_3l=z_l2 # z_4_x_3_l=np.dot(z_l4,x_3l) # z_4_z_3=np.dot(z_l4,z_3l) # omega_l=np.arctan2(z_4_x_3_l,z_4_z_3) omega_r=np.arccos(np.dot(z_r2,z_r4)) # psir1= np.arcsin(np.dot(x_0,z_r2)) # thtr1= np.arcsin(-np.dot(y_0,z_r2)/np.cos(psir1)) # y_l2= np.dot(np.dot(self.rot_y(psil1) ,self.rot_x(thtl1)),y_0) #x_l2 # x_l2= np.dot(np.dot(self.rot_y(psil1) ,self.rot_x(thtl1)),x_0) #z_l4 # z_l4=np.array([self.positions["left_hand"]['x']-self.positions["left_elbow"]['x'], # self.positions["left_hand"]['y']-self.positions["left_elbow"]['y'], # self.positions["left_hand"]['z']-self.positions["left_elbow"]['z']]) # z_l4 = z_l4/np.linalg.norm(z_l4) # z_l4_2=np.array([np.dot(z_l4,x_l2),np.dot(z_l4,y_l2),np.dot(z_l4,z_l2)]) # eta_l= np.arctan2(z_l4_2[0],z_l4_2[1]) # omega_l=-np.arccos(z_l4_2[2]) # print omega_l # omega_l=-np.arccos(np.dot(z_l2,z_l4)) #LElbowRoll # eta_l=np.arcsin(np.dot(z_l4,y_l2)/np.sin(omega_l)) #LElbowYaw # omega_l=-np.arccos(np.dot(z_l2,z_l4)) #LElbowRoll # print 'omega_l',omega_l,'eta_l',eta_l # print "psir1",psir1*60,"thtr1",thtr1*60 # self.skeleton_angles[0:4] = np.zeros([4]) self.skeleton_angles[0]=thtl1 self.skeleton_angles[1]=psil1 # self.skeleton_angles[2]=phi_l # self.skeleton_angles[3]=omega_l # takes right_shoulder, right_elbow, right_hand --> 4 angles # self.skeleton_angles[4:8] = np.zeros([4]) self.skeleton_angles[4]=thtr1 self.skeleton_angles[5]=psir1 # self.skeleton_angles[6]=phi_r # self.skeleton_angles[7]=omega_r pub_str = '' for s in self.skeleton_angles: pub_str += str(s) + ',' self.pub.publish(pub_str[:-1]) # print('====== skeleton_angles ====== published: ', pub_str[:-1]) def rot_x(self,alpa): R= np.array([[1,0,0],[0,np.cos(alpa),np.sin(alpa)],[0,-np.sin(alpa),np.cos(alpa)]]) return R def rot_y(self,alpa): R= np.array([[np.cos(alpa),0,-np.sin(alpa)],[0,1,0],[np.sin(alpa),0,np.cos(alpa)]]) return R def rot_z(self,alpa): R= np.array([[np.cos(alpa),np.sin(alpa),0],[-np.sin(alpa),np.cos(alpa),0],[0,0,1]]) return R skeleton_angles = SkeletonAngles() skeleton_angles.start()
[ "rospy.Subscriber", "numpy.cross", "rospy.init_node", "numpy.array", "numpy.zeros", "numpy.dot", "numpy.arctan2", "rospy.spin", "numpy.cos", "numpy.linalg.norm", "numpy.sin", "rospy.Publisher" ]
[((175, 232), 'rospy.Publisher', 'rospy.Publisher', (['"""skeleton_angles"""', 'String'], {'queue_size': '(10)'}), "('skeleton_angles', String, queue_size=10)\n", (190, 232), False, 'import rospy\n'), ((656, 669), 'numpy.zeros', 'np.zeros', (['[8]'], {}), '([8])\n', (664, 669), True, 'import numpy as np\n'), ((739, 772), 'rospy.init_node', 'rospy.init_node', (['"""skeleton_angle"""'], {}), "('skeleton_angle')\n", (754, 772), False, 'import rospy\n'), ((781, 834), 'rospy.Subscriber', 'rospy.Subscriber', (['"""skeleton"""', 'Skeleton', 'self.callback'], {}), "('skeleton', Skeleton, self.callback)\n", (797, 834), False, 'import rospy\n'), ((843, 855), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (853, 855), False, 'import rospy\n'), ((1240, 1498), 'numpy.array', 'np.array', (["[self.positions['left_shoulder']['x'] - self.positions['right_shoulder'][\n 'x'], self.positions['left_shoulder']['y'] - self.positions[\n 'right_shoulder']['y'], self.positions['left_shoulder']['z'] - self.\n positions['right_shoulder']['z']]"], {}), "([self.positions['left_shoulder']['x'] - self.positions[\n 'right_shoulder']['x'], self.positions['left_shoulder']['y'] - self.\n positions['right_shoulder']['y'], self.positions['left_shoulder']['z'] -\n self.positions['right_shoulder']['z']])\n", (1248, 1498), True, 'import numpy as np\n'), ((2100, 2205), 'numpy.array', 'np.array', (["[self.positions['torso']['x'], self.positions['torso']['y'], self.positions\n ['torso']['z']]"], {}), "([self.positions['torso']['x'], self.positions['torso']['y'], self.\n positions['torso']['z']])\n", (2108, 2205), True, 'import numpy as np\n'), ((2314, 2332), 'numpy.cross', 'np.cross', (['x_0', 'y_0'], {}), '(x_0, y_0)\n', (2322, 2332), True, 'import numpy as np\n'), ((2360, 2606), 'numpy.array', 'np.array', (["[self.positions['left_elbow']['x'] - self.positions['left_shoulder']['x'], \n self.positions['left_elbow']['y'] - self.positions['left_shoulder']['y'\n ], self.positions['left_elbow']['z'] - self.positions['left_shoulder']['z']\n ]"], {}), "([self.positions['left_elbow']['x'] - self.positions[\n 'left_shoulder']['x'], self.positions['left_elbow']['y'] - self.\n positions['left_shoulder']['y'], self.positions['left_elbow']['z'] -\n self.positions['left_shoulder']['z']])\n", (2368, 2606), True, 'import numpy as np\n'), ((2677, 2694), 'numpy.dot', 'np.dot', (['z_l2', 'z_0'], {}), '(z_l2, z_0)\n', (2683, 2694), True, 'import numpy as np\n'), ((2712, 2729), 'numpy.dot', 'np.dot', (['z_l2', 'y_0'], {}), '(z_l2, y_0)\n', (2718, 2729), True, 'import numpy as np\n'), ((2743, 2776), 'numpy.arctan2', 'np.arctan2', (['(-z_2_y_0_l)', 'z_2_z_0_l'], {}), '(-z_2_y_0_l, z_2_z_0_l)\n', (2753, 2776), True, 'import numpy as np\n'), ((2871, 2889), 'numpy.dot', 'np.dot', (['z_l2', 'x_l1'], {}), '(z_l2, x_l1)\n', (2877, 2889), True, 'import numpy as np\n'), ((2907, 2925), 'numpy.dot', 'np.dot', (['z_l2', 'z_l1'], {}), '(z_l2, z_l1)\n', (2913, 2925), True, 'import numpy as np\n'), ((2939, 2971), 'numpy.arctan2', 'np.arctan2', (['z_2_x_1_l', 'z_2_z_1_l'], {}), '(z_2_x_1_l, z_2_z_1_l)\n', (2949, 2971), True, 'import numpy as np\n'), ((3057, 3073), 'numpy.dot', 'np.dot', (['r_l', 'x_0'], {}), '(r_l, x_0)\n', (3063, 3073), True, 'import numpy as np\n'), ((3086, 3102), 'numpy.dot', 'np.dot', (['r_l', 'y_0'], {}), '(r_l, y_0)\n', (3092, 3102), True, 'import numpy as np\n'), ((3115, 3350), 'numpy.array', 'np.array', (["[self.positions['left_hand']['x'] - self.positions['left_elbow']['x'], self\n .positions['left_hand']['y'] - self.positions['left_elbow']['y'], self.\n positions['left_hand']['z'] - self.positions['left_elbow']['z']]"], {}), "([self.positions['left_hand']['x'] - self.positions['left_elbow'][\n 'x'], self.positions['left_hand']['y'] - self.positions['left_elbow'][\n 'y'], self.positions['left_hand']['z'] - self.positions['left_elbow']['z']]\n )\n", (3123, 3350), True, 'import numpy as np\n'), ((3413, 3431), 'numpy.dot', 'np.dot', (['z_l4', 'y_2l'], {}), '(z_l4, y_2l)\n', (3419, 3431), True, 'import numpy as np\n'), ((3449, 3467), 'numpy.dot', 'np.dot', (['z_l4', 'x_2l'], {}), '(z_l4, x_2l)\n', (3455, 3467), True, 'import numpy as np\n'), ((3481, 3515), 'numpy.arctan2', 'np.arctan2', (['(-z_4_y_2_l)', '(-z_4_x_2_l)'], {}), '(-z_4_y_2_l, -z_4_x_2_l)\n', (3491, 3515), True, 'import numpy as np\n'), ((3981, 4233), 'numpy.array', 'np.array', (["[self.positions['right_elbow']['x'] - self.positions['right_shoulder']['x'],\n self.positions['right_elbow']['y'] - self.positions['right_shoulder'][\n 'y'], self.positions['right_elbow']['z'] - self.positions[\n 'right_shoulder']['z']]"], {}), "([self.positions['right_elbow']['x'] - self.positions[\n 'right_shoulder']['x'], self.positions['right_elbow']['y'] - self.\n positions['right_shoulder']['y'], self.positions['right_elbow']['z'] -\n self.positions['right_shoulder']['z']])\n", (3989, 4233), True, 'import numpy as np\n'), ((4311, 4328), 'numpy.dot', 'np.dot', (['z_r2', 'z_0'], {}), '(z_r2, z_0)\n', (4317, 4328), True, 'import numpy as np\n'), ((4346, 4363), 'numpy.dot', 'np.dot', (['z_r2', 'y_0'], {}), '(z_r2, y_0)\n', (4352, 4363), True, 'import numpy as np\n'), ((4377, 4410), 'numpy.arctan2', 'np.arctan2', (['(-z_2_y_0_r)', 'z_2_z_0_r'], {}), '(-z_2_y_0_r, z_2_z_0_r)\n', (4387, 4410), True, 'import numpy as np\n'), ((4505, 4523), 'numpy.dot', 'np.dot', (['z_r2', 'x_r1'], {}), '(z_r2, x_r1)\n', (4511, 4523), True, 'import numpy as np\n'), ((4541, 4559), 'numpy.dot', 'np.dot', (['z_r2', 'z_r1'], {}), '(z_r2, z_r1)\n', (4547, 4559), True, 'import numpy as np\n'), ((4573, 4605), 'numpy.arctan2', 'np.arctan2', (['z_2_x_1_r', 'z_2_z_1_r'], {}), '(z_2_x_1_r, z_2_z_1_r)\n', (4583, 4605), True, 'import numpy as np\n'), ((4690, 4706), 'numpy.dot', 'np.dot', (['r_r', 'x_0'], {}), '(r_r, x_0)\n', (4696, 4706), True, 'import numpy as np\n'), ((4719, 4735), 'numpy.dot', 'np.dot', (['r_r', 'y_0'], {}), '(r_r, y_0)\n', (4725, 4735), True, 'import numpy as np\n'), ((4748, 4989), 'numpy.array', 'np.array', (["[self.positions['right_hand']['x'] - self.positions['right_elbow']['x'], \n self.positions['right_hand']['y'] - self.positions['right_elbow']['y'],\n self.positions['right_hand']['z'] - self.positions['right_elbow']['z']]"], {}), "([self.positions['right_hand']['x'] - self.positions['right_elbow']\n ['x'], self.positions['right_hand']['y'] - self.positions['right_elbow'\n ]['y'], self.positions['right_hand']['z'] - self.positions[\n 'right_elbow']['z']])\n", (4756, 4989), True, 'import numpy as np\n'), ((5050, 5068), 'numpy.dot', 'np.dot', (['z_r4', 'y_2r'], {}), '(z_r4, y_2r)\n', (5056, 5068), True, 'import numpy as np\n'), ((5086, 5104), 'numpy.dot', 'np.dot', (['z_r4', 'x_2r'], {}), '(z_r4, x_2r)\n', (5092, 5104), True, 'import numpy as np\n'), ((5118, 5150), 'numpy.arctan2', 'np.arctan2', (['z_4_y_2_r', 'z_4_x_2_r'], {}), '(z_4_y_2_r, z_4_x_2_r)\n', (5128, 5150), True, 'import numpy as np\n'), ((1520, 1539), 'numpy.linalg.norm', 'np.linalg.norm', (['x_0'], {}), '(x_0)\n', (1534, 1539), True, 'import numpy as np\n'), ((1576, 1834), 'numpy.array', 'np.array', (["[self.positions['left_shoulder']['x'] + self.positions['right_shoulder'][\n 'x'], self.positions['left_shoulder']['y'] + self.positions[\n 'right_shoulder']['y'], self.positions['left_shoulder']['z'] + self.\n positions['right_shoulder']['z']]"], {}), "([self.positions['left_shoulder']['x'] + self.positions[\n 'right_shoulder']['x'], self.positions['left_shoulder']['y'] + self.\n positions['right_shoulder']['y'], self.positions['left_shoulder']['z'] +\n self.positions['right_shoulder']['z']])\n", (1584, 1834), True, 'import numpy as np\n'), ((1858, 2082), 'numpy.array', 'np.array', (["[self.positions['left_hip']['x'] + self.positions['right_hip']['x'], self.\n positions['left_hip']['y'] + self.positions['right_hip']['y'], self.\n positions['left_hip']['z'] + self.positions['right_hip']['z']]"], {}), "([self.positions['left_hip']['x'] + self.positions['right_hip']['x'\n ], self.positions['left_hip']['y'] + self.positions['right_hip']['y'], \n self.positions['left_hip']['z'] + self.positions['right_hip']['z']])\n", (1866, 2082), True, 'import numpy as np\n'), ((2268, 2287), 'numpy.linalg.norm', 'np.linalg.norm', (['y_0'], {}), '(y_0)\n', (2282, 2287), True, 'import numpy as np\n'), ((2621, 2641), 'numpy.linalg.norm', 'np.linalg.norm', (['z_l2'], {}), '(z_l2)\n', (2635, 2641), True, 'import numpy as np\n'), ((3374, 3394), 'numpy.linalg.norm', 'np.linalg.norm', (['z_l4'], {}), '(z_l4)\n', (3388, 3394), True, 'import numpy as np\n'), ((4256, 4276), 'numpy.linalg.norm', 'np.linalg.norm', (['z_r2'], {}), '(z_r2)\n', (4270, 4276), True, 'import numpy as np\n'), ((5011, 5031), 'numpy.linalg.norm', 'np.linalg.norm', (['z_r4'], {}), '(z_r4)\n', (5025, 5031), True, 'import numpy as np\n'), ((5382, 5400), 'numpy.dot', 'np.dot', (['z_r2', 'z_r4'], {}), '(z_r2, z_r4)\n', (5388, 5400), True, 'import numpy as np\n'), ((3748, 3766), 'numpy.dot', 'np.dot', (['z_l2', 'z_l4'], {}), '(z_l2, z_l4)\n', (3754, 3766), True, 'import numpy as np\n'), ((7242, 7254), 'numpy.cos', 'np.cos', (['alpa'], {}), '(alpa)\n', (7248, 7254), True, 'import numpy as np\n'), ((7255, 7267), 'numpy.sin', 'np.sin', (['alpa'], {}), '(alpa)\n', (7261, 7267), True, 'import numpy as np\n'), ((7286, 7298), 'numpy.cos', 'np.cos', (['alpa'], {}), '(alpa)\n', (7292, 7298), True, 'import numpy as np\n'), ((7368, 7380), 'numpy.cos', 'np.cos', (['alpa'], {}), '(alpa)\n', (7374, 7380), True, 'import numpy as np\n'), ((7407, 7419), 'numpy.sin', 'np.sin', (['alpa'], {}), '(alpa)\n', (7413, 7419), True, 'import numpy as np\n'), ((7422, 7434), 'numpy.cos', 'np.cos', (['alpa'], {}), '(alpa)\n', (7428, 7434), True, 'import numpy as np\n'), ((7504, 7516), 'numpy.cos', 'np.cos', (['alpa'], {}), '(alpa)\n', (7510, 7516), True, 'import numpy as np\n'), ((7517, 7529), 'numpy.sin', 'np.sin', (['alpa'], {}), '(alpa)\n', (7523, 7529), True, 'import numpy as np\n'), ((7548, 7560), 'numpy.cos', 'np.cos', (['alpa'], {}), '(alpa)\n', (7554, 7560), True, 'import numpy as np\n'), ((7273, 7285), 'numpy.sin', 'np.sin', (['alpa'], {}), '(alpa)\n', (7279, 7285), True, 'import numpy as np\n'), ((7384, 7396), 'numpy.sin', 'np.sin', (['alpa'], {}), '(alpa)\n', (7390, 7396), True, 'import numpy as np\n'), ((7535, 7547), 'numpy.sin', 'np.sin', (['alpa'], {}), '(alpa)\n', (7541, 7547), True, 'import numpy as np\n')]
# Copyright 2021 The Private Cardinality Estimation Framework Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generate a stream of impressions from a zeta distr.""" from typing import List import numpy as np from wfa_planning_evaluation_framework.data_generators.impression_generator import ( ImpressionGenerator, ) class HeavyTailedImpressionGenerator(ImpressionGenerator): """Generate impressions with heavy tailed impressions.""" def __init__( self, n: int, zeta_s: float = 2, random_generator: np.random.Generator = None ): """Constructor for the HeavyTailedImpressionGenerator. For each user, the number of impressions assigned to that user is determined by drawing from a zeta distribution which has pmf p(k) = k^{-s} / zeta(s), k = 1, 2, ..., zeta(s) being a normalizing factor. Args: n: The number of users. zeta_s: The parameter of the zeta distribution. random_generator: An instance of numpy.random.Generator that is used for making draws from the Zeta distribution. """ assert zeta_s > 1, "Zeta distribution must have power parameter > 1." self._zeta_s = zeta_s self._n = n if random_generator: self._random_generator = random_generator else: self._random_generator = np.random.default_rng(seed=1) def __call__(self) -> List[int]: """Generate a random sequence of impressions. Returns: A list of randomly generated user id's. An id may occur multiple times in the output list, representing the fact that the user may see multiple ads from the publisher over the course of the campaign. """ impressions = [] for i in range(self._n): impressions.extend([i] * self._random_generator.zipf(self._zeta_s)) self._random_generator.shuffle(impressions) return impressions
[ "numpy.random.default_rng" ]
[((1878, 1907), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': '(1)'}), '(seed=1)\n', (1899, 1907), True, 'import numpy as np\n')]
""" These are borrowed from SciPy and used under their license: Copyright (c) 2001, 2002 Enthought, Inc. All rights reserved. Copyright (c) 2003-2012 SciPy Developers. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: a. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b. 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. c. Neither the name of Enthought nor the names of the SciPy Developers may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # From scipy/sparse/sputils.py v0.18.0 from __future__ import absolute_import, division import numpy as np def isscalarlike(x): """Is x either a scalar, an array scalar, or a 0-dim array?""" return np.isscalar(x) or (isdense(x) and x.ndim == 0) def isintlike(x): """Is x appropriate as an index into a sparse matrix? Returns True if it can be cast safely to a machine int. """ if issequence(x): return False try: return bool(int(x) == x) except (TypeError, ValueError): return False def isshape(x): """Is x a valid 2-tuple of dimensions? """ try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = x except: return False else: if isintlike(M) and isintlike(N): if np.ndim(M) == 0 and np.ndim(N) == 0: return True return False def issequence(t): return ((isinstance(t, (list, tuple)) and (len(t) == 0 or np.isscalar(t[0]))) or (isinstance(t, np.ndarray) and (t.ndim == 1))) def ismatrix(t): return ((isinstance(t, (list, tuple)) and len(t) > 0 and issequence(t[0])) or (isinstance(t, np.ndarray) and t.ndim == 2)) def isdense(x): return isinstance(x, np.ndarray)
[ "numpy.isscalar", "numpy.ndim" ]
[((1858, 1872), 'numpy.isscalar', 'np.isscalar', (['x'], {}), '(x)\n', (1869, 1872), True, 'import numpy as np\n'), ((2629, 2646), 'numpy.isscalar', 'np.isscalar', (['t[0]'], {}), '(t[0])\n', (2640, 2646), True, 'import numpy as np\n'), ((2448, 2458), 'numpy.ndim', 'np.ndim', (['M'], {}), '(M)\n', (2455, 2458), True, 'import numpy as np\n'), ((2468, 2478), 'numpy.ndim', 'np.ndim', (['N'], {}), '(N)\n', (2475, 2478), True, 'import numpy as np\n')]
from itertools import combinations import numpy as np import time def friend_numbers_exhaustive_count(count_till_number): friend_numbers_cnt = 0 for pair in combinations(np.arange(1,count_till_number),2): str_1 = str(pair[0]) str_2 = str(pair[1]) # print(str_1, str_2) if np.any([digit in str_2 for digit in str_1]): friend_numbers_cnt +=1 return friend_numbers_cnt N=1000 start = time.time() result = friend_numbers_exhaustive_count(N) end = time.time() print("Counting friend numbers exhaustively till %s yields %s, took %0.5f seconds" %(N,result, end-start))
[ "numpy.any", "time.time", "numpy.arange" ]
[((439, 450), 'time.time', 'time.time', ([], {}), '()\n', (448, 450), False, 'import time\n'), ((501, 512), 'time.time', 'time.time', ([], {}), '()\n', (510, 512), False, 'import time\n'), ((179, 210), 'numpy.arange', 'np.arange', (['(1)', 'count_till_number'], {}), '(1, count_till_number)\n', (188, 210), True, 'import numpy as np\n'), ((313, 358), 'numpy.any', 'np.any', (['[(digit in str_2) for digit in str_1]'], {}), '([(digit in str_2) for digit in str_1])\n', (319, 358), True, 'import numpy as np\n')]
import numpy as N from traits.api import (HasTraits, Array, Range, Instance, Enum) from traitsui.api import View, Item from chaco.api import (ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink, jet) from chaco.default_colormaps import fix from enable.api import ComponentEditor from AwesomeColorMaps import awesome, isoluminant def bone(rng, **traits): """ Generator function for the 'bone' colormap. (Instead of faulty one in Chaco.) Data from Matplotlib. """ _bone_data = { 'red': ((0., 0., 0.), (0.746032, 0.652778, 0.652778), (1.0, 1.0, 1.0)), 'green': ((0., 0., 0.), (0.365079, 0.319444, 0.319444), (0.746032, 0.777778, 0.777778), (1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.), (0.365079, 0.444444, 0.444444), (1.0, 1.0, 1.0))} return ColorMapper.from_segment_map(_bone_data, range=rng, **traits) class CameraImage(HasTraits): data = Array() data_store = Instance(ArrayPlotData) plot = Instance(Plot) hud_overlay = Instance(PlotLabel) # Number of steps of 90 degrees to rotate the image before # displaying it - must be between 0 and 3 rotate = Range(0, 3) # Colormap to use for display; None means use the image's natural # colors (if RGB data) or grayscale (if monochrome). Setting @cmap # to a value coerces the image to monochrome. cmap = Enum(None, gray, bone, pink, jet, isoluminant, awesome) view = View(Item('plot', show_label=False, editor=ComponentEditor())) def __init__(self, **traits): super(CameraImage, self).__init__(**traits) self._dims = (200, 320) self.data_store = ArrayPlotData(image=self.data) self._hud = dict() self.plot = Plot(self.data_store) # Draw the image renderers = self.plot.img_plot('image', name='camera_image', colormap=fix(gray, (0, 255))) self._image = renderers[0] self.plot.aspect_ratio = float(self._dims[1]) / self._dims[0] self.hud_overlay = PlotLabel(text='', component=self.plot, hjustify='left', overlay_position='inside bottom', color='white') self.plot.overlays.append(self.hud_overlay) def _data_default(self): return N.zeros(self._dims, dtype=N.uint8) def _data_changed(self, value): bw = (len(value.shape) == 2) if not bw and self.cmap is not None: # Selecting a colormap coerces the image to monochrome # Use standard NTSC conversion formula value = N.array( 0.2989 * value[..., 0] + 0.5870 * value[..., 1] + 0.1140 * value[..., 2]) value = N.rot90(value, self.rotate) self.data_store['image'] = self.data = value if self._dims != self.data.shape: # Redraw the axes if the image is a different size self.plot.delplot('camera_image') self._dims = self.data.shape renderers = self.plot.img_plot('image', name='camera_image', colormap=self._get_cmap_function()) # colormap is ignored if image is RGB or RGBA self._image = renderers[0] # Make sure the aspect ratio is correct, even after resize self.plot.aspect_ratio = float(self._dims[1]) / self._dims[0] def _get_cmap_function(self): return fix( gray if self.cmap is None else self.cmap, (0, 65535 if self.data.dtype == N.uint16 else 255)) def _cmap_changed(self, old_value, value): # Must redraw the plot if data was RGB if old_value is None or value is None: self._data_changed(self.data) cmap_func = self._get_cmap_function() self._image.color_mapper = cmap_func(self._image.value_range) def hud(self, key, text): if text is None: self._hud.pop(key, None) else: self._hud[key] = text # Do the heads-up display text = '' for key in sorted(self._hud.keys()): text += self._hud[key] + '\n\n' self.hud_overlay.text = text
[ "traits.api.Instance", "traits.api.Enum", "chaco.api.ArrayPlotData", "traits.api.Array", "chaco.api.Plot", "numpy.array", "numpy.zeros", "traits.api.Range", "chaco.default_colormaps.fix", "enable.api.ComponentEditor", "numpy.rot90", "chaco.api.PlotLabel", "chaco.api.ColorMapper.from_segment_...
[((805, 866), 'chaco.api.ColorMapper.from_segment_map', 'ColorMapper.from_segment_map', (['_bone_data'], {'range': 'rng'}), '(_bone_data, range=rng, **traits)\n', (833, 866), False, 'from chaco.api import ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink, jet\n'), ((911, 918), 'traits.api.Array', 'Array', ([], {}), '()\n', (916, 918), False, 'from traits.api import HasTraits, Array, Range, Instance, Enum\n'), ((936, 959), 'traits.api.Instance', 'Instance', (['ArrayPlotData'], {}), '(ArrayPlotData)\n', (944, 959), False, 'from traits.api import HasTraits, Array, Range, Instance, Enum\n'), ((971, 985), 'traits.api.Instance', 'Instance', (['Plot'], {}), '(Plot)\n', (979, 985), False, 'from traits.api import HasTraits, Array, Range, Instance, Enum\n'), ((1004, 1023), 'traits.api.Instance', 'Instance', (['PlotLabel'], {}), '(PlotLabel)\n', (1012, 1023), False, 'from traits.api import HasTraits, Array, Range, Instance, Enum\n'), ((1147, 1158), 'traits.api.Range', 'Range', (['(0)', '(3)'], {}), '(0, 3)\n', (1152, 1158), False, 'from traits.api import HasTraits, Array, Range, Instance, Enum\n'), ((1362, 1417), 'traits.api.Enum', 'Enum', (['None', 'gray', 'bone', 'pink', 'jet', 'isoluminant', 'awesome'], {}), '(None, gray, bone, pink, jet, isoluminant, awesome)\n', (1366, 1417), False, 'from traits.api import HasTraits, Array, Range, Instance, Enum\n'), ((1638, 1668), 'chaco.api.ArrayPlotData', 'ArrayPlotData', ([], {'image': 'self.data'}), '(image=self.data)\n', (1651, 1668), False, 'from chaco.api import ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink, jet\n'), ((1716, 1737), 'chaco.api.Plot', 'Plot', (['self.data_store'], {}), '(self.data_store)\n', (1720, 1737), False, 'from chaco.api import ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink, jet\n'), ((2007, 2117), 'chaco.api.PlotLabel', 'PlotLabel', ([], {'text': '""""""', 'component': 'self.plot', 'hjustify': '"""left"""', 'overlay_position': '"""inside bottom"""', 'color': '"""white"""'}), "(text='', component=self.plot, hjustify='left', overlay_position=\n 'inside bottom', color='white')\n", (2016, 2117), False, 'from chaco.api import ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink, jet\n'), ((2234, 2268), 'numpy.zeros', 'N.zeros', (['self._dims'], {'dtype': 'N.uint8'}), '(self._dims, dtype=N.uint8)\n', (2241, 2268), True, 'import numpy as N\n'), ((2673, 2700), 'numpy.rot90', 'N.rot90', (['value', 'self.rotate'], {}), '(value, self.rotate)\n', (2680, 2700), True, 'import numpy as N\n'), ((3357, 3458), 'chaco.default_colormaps.fix', 'fix', (['(gray if self.cmap is None else self.cmap)', '(0, 65535 if self.data.dtype == N.uint16 else 255)'], {}), '(gray if self.cmap is None else self.cmap, (0, 65535 if self.data.dtype ==\n N.uint16 else 255))\n', (3360, 3458), False, 'from chaco.default_colormaps import fix\n'), ((2526, 2605), 'numpy.array', 'N.array', (['(0.2989 * value[..., 0] + 0.587 * value[..., 1] + 0.114 * value[..., 2])'], {}), '(0.2989 * value[..., 0] + 0.587 * value[..., 1] + 0.114 * value[..., 2])\n', (2533, 2605), True, 'import numpy as N\n'), ((1473, 1490), 'enable.api.ComponentEditor', 'ComponentEditor', ([], {}), '()\n', (1488, 1490), False, 'from enable.api import ComponentEditor\n'), ((1853, 1872), 'chaco.default_colormaps.fix', 'fix', (['gray', '(0, 255)'], {}), '(gray, (0, 255))\n', (1856, 1872), False, 'from chaco.default_colormaps import fix\n')]
''' Define a simple neural net in Keras that recognizes MNIST handwritten digits ''' from __future__ import print_function import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.optimizers import SGD from keras.utils import np_utils np.random.seed(1671) #network and training NB_EPOCH = 200 BATCH_SIZE = 128 VERBOSE = 1 NB_CLASSES = 10 OPTIMIZER = SGD() N_HIDDEN = 128 VALIDATION_SPLIT = 0.2 (X_train, y_train), (X_test, y_test) = mnist.load_data() RESHAPED = 784 X_train = X_train.reshape(60000, RESHAPED) X_test = X_test.reshape(10000, RESHAPED) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test smaples') Y_train = np_utils.to_categorical(y_train, NB_CLASSES) Y_test = np_utils.to_categorical(y_test, NB_CLASSES) model = Sequential() model.add(Dense(NB_CLASSES, input_shape=(RESHAPED,))) model.add(Activation('softmax')) model.summary model.compile(loss='categorical_crossentropy', optimizer=OPTIMIZER, metrics=['accuracy']) history = model.fit(X_train, Y_train, batch_size = BATCH_SIZE, epochs = NB_EPOCH, verbose = VERBOSE, validation_split = VALIDATION_SPLIT) score = model.evaluate(X_test, Y_test, verbose = VERBOSE) print("TEST SCORE: ", score[0]) print("TEST ACCURACY: ", score[1])
[ "keras.layers.core.Activation", "keras.datasets.mnist.load_data", "keras.models.Sequential", "keras.utils.np_utils.to_categorical", "keras.optimizers.SGD", "numpy.random.seed", "keras.layers.core.Dense" ]
[((325, 345), 'numpy.random.seed', 'np.random.seed', (['(1671)'], {}), '(1671)\n', (339, 345), True, 'import numpy as np\n'), ((441, 446), 'keras.optimizers.SGD', 'SGD', ([], {}), '()\n', (444, 446), False, 'from keras.optimizers import SGD\n'), ((525, 542), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (540, 542), False, 'from keras.datasets import mnist\n'), ((832, 876), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['y_train', 'NB_CLASSES'], {}), '(y_train, NB_CLASSES)\n', (855, 876), False, 'from keras.utils import np_utils\n'), ((886, 929), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['y_test', 'NB_CLASSES'], {}), '(y_test, NB_CLASSES)\n', (909, 929), False, 'from keras.utils import np_utils\n'), ((939, 951), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (949, 951), False, 'from keras.models import Sequential\n'), ((962, 1004), 'keras.layers.core.Dense', 'Dense', (['NB_CLASSES'], {'input_shape': '(RESHAPED,)'}), '(NB_CLASSES, input_shape=(RESHAPED,))\n', (967, 1004), False, 'from keras.layers.core import Dense, Activation\n'), ((1016, 1037), 'keras.layers.core.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (1026, 1037), False, 'from keras.layers.core import Dense, Activation\n')]
#!/usr/bin/env python # coding: utf-8 from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals # Command line : # python -m benchmark.AP1.explore import os import numpy as np import matplotlib.pyplot as plt import seaborn as sns from visual import set_plot_config set_plot_config() from config import SAVING_DIR from problem.apples_and_pears.generator import Generator from visual.likelihood import plot_param_around_min DATA_NAME = 'AP1' BENCHMARK_NAME = DATA_NAME DIRECTORY = os.path.join(SAVING_DIR, BENCHMARK_NAME, "explore") def main(): print('hello') generator = Generator(apple_center=7, pear_center=0, n_apple=100, n_pears=100) TRUE_RESCALE = 1.0 TRUE_MU = 1.0 X, y, w = generator.generate(TRUE_RESCALE, TRUE_MU) compute_nll = lambda rescale, mu : generator.nll(X, rescale, mu) directory = DIRECTORY os.makedirs(directory, exist_ok=True) suffix = f"_rescale={TRUE_RESCALE}_mu={TRUE_MU}" plot_data_distrib(X, y, w, generator, TRUE_RESCALE, TRUE_MU, directory, suffix=suffix) plot_rescale_around_min(compute_nll, TRUE_RESCALE, TRUE_MU, directory, suffix=suffix) def plot_rescale_around_min(compute_nll, true_rescale, true_mu, directory, suffix=''): rescale_array = np.linspace(0.5, 6, 50) nll_array = [compute_nll(rescale, true_mu) for rescale in rescale_array] name = 'rescale' plot_param_around_min(rescale_array, nll_array, true_rescale, name, suffix, directory) def plot_data_distrib(X, y, w, generator, rescale, mu, directory, suffix=''): bkg = X[y==0].reshape(-1) sig = X[y==1].reshape(-1) w_bkg = w[y==0] w_sig = w[y==1] min_x = np.min(X) - 0.05 max_x = np.max(X) x_range = np.linspace(min_x, max_x, 1000) proba = generator.proba_density(x_range, rescale, mu) plt.hist([bkg, sig], weights=[w_bkg, w_sig], bins=20, density=True, stacked=True, label=('b', 's')) plt.plot(x_range, proba, label=f"pdf") plt.title(f'Toy distribution ({suffix})') plt.ylabel('density') plt.xlabel('x') plt.legend() fname = os.path.join(directory, f'x_distrib{suffix}.png') plt.savefig(fname) plt.clf() if __name__ == '__main__': main()
[ "matplotlib.pyplot.hist", "matplotlib.pyplot.savefig", "os.makedirs", "matplotlib.pyplot.ylabel", "visual.set_plot_config", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "os.path.join", "matplotlib.pyplot.clf", "numpy.min", "numpy.max", "numpy.linspace", "visual.likelihood.plot_param...
[((361, 378), 'visual.set_plot_config', 'set_plot_config', ([], {}), '()\n', (376, 378), False, 'from visual import set_plot_config\n'), ((580, 631), 'os.path.join', 'os.path.join', (['SAVING_DIR', 'BENCHMARK_NAME', '"""explore"""'], {}), "(SAVING_DIR, BENCHMARK_NAME, 'explore')\n", (592, 631), False, 'import os\n'), ((681, 747), 'problem.apples_and_pears.generator.Generator', 'Generator', ([], {'apple_center': '(7)', 'pear_center': '(0)', 'n_apple': '(100)', 'n_pears': '(100)'}), '(apple_center=7, pear_center=0, n_apple=100, n_pears=100)\n', (690, 747), False, 'from problem.apples_and_pears.generator import Generator\n'), ((948, 985), 'os.makedirs', 'os.makedirs', (['directory'], {'exist_ok': '(True)'}), '(directory, exist_ok=True)\n', (959, 985), False, 'import os\n'), ((1333, 1356), 'numpy.linspace', 'np.linspace', (['(0.5)', '(6)', '(50)'], {}), '(0.5, 6, 50)\n', (1344, 1356), True, 'import numpy as np\n'), ((1459, 1549), 'visual.likelihood.plot_param_around_min', 'plot_param_around_min', (['rescale_array', 'nll_array', 'true_rescale', 'name', 'suffix', 'directory'], {}), '(rescale_array, nll_array, true_rescale, name, suffix,\n directory)\n', (1480, 1549), False, 'from visual.likelihood import plot_param_around_min\n'), ((1769, 1778), 'numpy.max', 'np.max', (['X'], {}), '(X)\n', (1775, 1778), True, 'import numpy as np\n'), ((1793, 1824), 'numpy.linspace', 'np.linspace', (['min_x', 'max_x', '(1000)'], {}), '(min_x, max_x, 1000)\n', (1804, 1824), True, 'import numpy as np\n'), ((1888, 1992), 'matplotlib.pyplot.hist', 'plt.hist', (['[bkg, sig]'], {'weights': '[w_bkg, w_sig]', 'bins': '(20)', 'density': '(True)', 'stacked': '(True)', 'label': "('b', 's')"}), "([bkg, sig], weights=[w_bkg, w_sig], bins=20, density=True, stacked\n =True, label=('b', 's'))\n", (1896, 1992), True, 'import matplotlib.pyplot as plt\n'), ((1992, 2030), 'matplotlib.pyplot.plot', 'plt.plot', (['x_range', 'proba'], {'label': 'f"""pdf"""'}), "(x_range, proba, label=f'pdf')\n", (2000, 2030), True, 'import matplotlib.pyplot as plt\n'), ((2035, 2076), 'matplotlib.pyplot.title', 'plt.title', (['f"""Toy distribution ({suffix})"""'], {}), "(f'Toy distribution ({suffix})')\n", (2044, 2076), True, 'import matplotlib.pyplot as plt\n'), ((2081, 2102), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""density"""'], {}), "('density')\n", (2091, 2102), True, 'import matplotlib.pyplot as plt\n'), ((2107, 2122), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (2117, 2122), True, 'import matplotlib.pyplot as plt\n'), ((2127, 2139), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2137, 2139), True, 'import matplotlib.pyplot as plt\n'), ((2152, 2201), 'os.path.join', 'os.path.join', (['directory', 'f"""x_distrib{suffix}.png"""'], {}), "(directory, f'x_distrib{suffix}.png')\n", (2164, 2201), False, 'import os\n'), ((2206, 2224), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname'], {}), '(fname)\n', (2217, 2224), True, 'import matplotlib.pyplot as plt\n'), ((2229, 2238), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2236, 2238), True, 'import matplotlib.pyplot as plt\n'), ((1740, 1749), 'numpy.min', 'np.min', (['X'], {}), '(X)\n', (1746, 1749), True, 'import numpy as np\n')]
""" Module containing classes that interfaces neural network policies """ from __future__ import annotations from typing import TYPE_CHECKING import numpy as np import pandas as pd from aizynthfinder.chem import RetroReaction from aizynthfinder.utils.models import load_model from aizynthfinder.context.collection import ContextCollection if TYPE_CHECKING: from aizynthfinder.utils.type_utils import Union, Any, Sequence, List, Tuple from aizynthfinder.context.config import Configuration from aizynthfinder.chem import TreeMolecule class PolicyException(Exception): """An exception raised by the Policy classes""" def _make_fingerprint( obj: Union[TreeMolecule, RetroReaction], model: Any ) -> np.ndarray: fingerprint = obj.fingerprint(radius=2, nbits=len(model)) return fingerprint.reshape([1, len(model)]) class ExpansionPolicy(ContextCollection): """ An abstraction of an expansion policy. This policy provides actions (templates) that can be applied to a molecule :param config: the configuration of the tree search """ _collection_name = "expansion policy" def __init__(self, config: Configuration) -> None: super().__init__() self._config = config self._stock = config.stock def __call__( self, molecules: Sequence[TreeMolecule] ) -> Tuple[Sequence[RetroReaction], Sequence[float]]: return self.get_actions(molecules) # pylint: disable=R0914 def get_actions( self, molecules: Sequence[TreeMolecule] ) -> Tuple[List[RetroReaction], List[float]]: """ Get all the probable actions of a set of molecules, using the selected policies and given cutoffs :param molecules: the molecules to consider :return: the actions and the priors of those actions :raises: PolicyException: if the policy isn't selected """ if not self.selection: raise PolicyException("No expansion policy selected") possible_actions = [] priors = [] for mol in molecules: if mol in self._stock: continue for policy_key in self.selection: model = self[policy_key]["model"] templates = self[policy_key]["templates"] all_transforms_prop = self._predict(mol, model) probable_transforms_idx = self._cutoff_predictions(all_transforms_prop) possible_moves = templates.iloc[probable_transforms_idx] probs = all_transforms_prop[probable_transforms_idx] priors.extend(probs) for idx, (move_index, move) in enumerate(possible_moves.iterrows()): metadata = dict(move) del metadata[self._config.template_column] metadata["policy_probability"] = float(probs[idx].round(4)) metadata["policy_probability_rank"] = idx metadata["policy_name"] = policy_key metadata["template_code"] = move_index possible_actions.append( RetroReaction( mol, move[self._config.template_column], metadata=metadata ) ) return possible_actions, priors def load(self, source: Union[str, Any], templatefile: str, key: str) -> None: # type: ignore """ Load a policy and associated templates under the given key If `source` is a string, it is taken as a path to a filename and the policy is loaded as an `LocalKerasModel` object. If `source` is not a string, it is taken as a custom object that implements the `__len__` and `predict` methods. :param source: the source of the policy model :param templatefile: the path to a HDF5 file with the templates :param key: the key or label :raises PolicyException: if the length of the model output vector is not same as the number of templates """ self._logger.info(f"Loading expansion policy model from {source} to {key}") model = load_model(source, key, self._config.use_remote_models) self._logger.info(f"Loading templates from {templatefile} to {key}") templates: pd.DataFrame = pd.read_hdf(templatefile, "table") if hasattr(model, "output_size") and len(templates) != model.output_size: # type: ignore raise PolicyException( f"The number of templates ({len(templates)}) does not agree with the " # type: ignore f"output dimensions of the model ({model.output_size})" ) self._items[key] = {"model": model, "templates": templates} def load_from_config(self, **config: Any) -> None: """ Load one or more expansion policy from a configuration The format should be key: - path_to_model - path_to_templates :param config: the configuration """ for key, policy_spec in config.items(): modelfile, templatefile = policy_spec self.load(modelfile, templatefile, key) def _cutoff_predictions(self, predictions: np.ndarray) -> np.ndarray: """ Get the top transformations, by selecting those that have: * cumulative probability less than a threshold (cutoff_cumulative) * or at most N (cutoff_number) """ sortidx = np.argsort(predictions)[::-1] cumsum: np.ndarray = np.cumsum(predictions[sortidx]) if any(cumsum >= self._config.cutoff_cumulative): maxidx = np.argmin(cumsum < self._config.cutoff_cumulative) else: maxidx = len(cumsum) maxidx = min(maxidx, self._config.cutoff_number) or 1 return sortidx[:maxidx] @staticmethod def _predict(mol: TreeMolecule, model: Any) -> np.ndarray: fp_arr = _make_fingerprint(mol, model) return np.array(model.predict(fp_arr)).flatten() class FilterPolicy(ContextCollection): """ An abstraction of a filter policy. This policy provides a query on a reaction to determine whether it is feasible :param config: the configuration of the tree search """ _single_selection = True _collection_name = "filter policy" def __init__(self, config: Configuration) -> None: super().__init__() self._config = config def __call__(self, reaction: RetroReaction) -> bool: return self.is_feasible(reaction) def feasibility(self, reaction: RetroReaction) -> Tuple[bool, float]: """ Computes if a given reaction is feasible by given the reaction fingerprint to a network model :param reaction: the reaction to query :return: if the reaction is feasible :raises: PolicyException: if the policy isn't selected """ if not self._selection: raise PolicyException("No filter policy selected!") if not reaction.reactants: return False, 0.0 prob = self._predict(reaction) feasible = prob >= self._config.filter_cutoff return feasible, prob def is_feasible(self, reaction: RetroReaction) -> bool: """ Computes if a given reaction is feasible by given the reaction fingerprint to a network model :param reaction: the reaction to query :return: if the reaction is feasible :raises: PolicyException: if the policy isn't selected """ feasible, _ = self.feasibility(reaction) return feasible def load(self, source: Union[str, Any], key: str) -> None: # type: ignore """ Load a policy under the given key If `source` is a string, it is taken as a path to a filename and the policy is loaded as an `LocalKerasModel` object. If `source` is not a string, it is taken as a custom object that implements the `__len__` and `predict` methods. :param source: the source of the policy model :param key: the key or label """ self._logger.info(f"Loading filter policy model from {source} to {key}") self._items[key] = { "model": load_model(source, key, self._config.use_remote_models) } def load_from_config(self, **config: Any) -> None: """ Load one or more filter policy from a configuration The format should be: key: path_to_model :param config: the configuration """ for key, filename in config.items(): self.load(filename, key) def _predict(self, reaction: RetroReaction) -> float: if not isinstance(self.selection, str): raise PolicyException("No policy selected.") model = self[self.selection]["model"] prod_fp, rxn_fp = self._reaction_to_fingerprint(reaction, model) return model.predict([prod_fp, rxn_fp])[0][0] @staticmethod def _reaction_to_fingerprint( reaction: RetroReaction, model: Any ) -> Tuple[np.ndarray, np.ndarray]: rxn_fp = _make_fingerprint(reaction, model) prod_fp = _make_fingerprint(reaction.mol, model) return prod_fp, rxn_fp
[ "aizynthfinder.utils.models.load_model", "numpy.argsort", "aizynthfinder.chem.RetroReaction", "numpy.argmin", "numpy.cumsum", "pandas.read_hdf" ]
[((4164, 4219), 'aizynthfinder.utils.models.load_model', 'load_model', (['source', 'key', 'self._config.use_remote_models'], {}), '(source, key, self._config.use_remote_models)\n', (4174, 4219), False, 'from aizynthfinder.utils.models import load_model\n'), ((4332, 4366), 'pandas.read_hdf', 'pd.read_hdf', (['templatefile', '"""table"""'], {}), "(templatefile, 'table')\n", (4343, 4366), True, 'import pandas as pd\n'), ((5562, 5593), 'numpy.cumsum', 'np.cumsum', (['predictions[sortidx]'], {}), '(predictions[sortidx])\n', (5571, 5593), True, 'import numpy as np\n'), ((5503, 5526), 'numpy.argsort', 'np.argsort', (['predictions'], {}), '(predictions)\n', (5513, 5526), True, 'import numpy as np\n'), ((5673, 5723), 'numpy.argmin', 'np.argmin', (['(cumsum < self._config.cutoff_cumulative)'], {}), '(cumsum < self._config.cutoff_cumulative)\n', (5682, 5723), True, 'import numpy as np\n'), ((8279, 8334), 'aizynthfinder.utils.models.load_model', 'load_model', (['source', 'key', 'self._config.use_remote_models'], {}), '(source, key, self._config.use_remote_models)\n', (8289, 8334), False, 'from aizynthfinder.utils.models import load_model\n'), ((3142, 3215), 'aizynthfinder.chem.RetroReaction', 'RetroReaction', (['mol', 'move[self._config.template_column]'], {'metadata': 'metadata'}), '(mol, move[self._config.template_column], metadata=metadata)\n', (3155, 3215), False, 'from aizynthfinder.chem import RetroReaction\n')]
import os import matplotlib.pyplot as plt import numpy as np def load_data(fpath=''): if len(fpath) == 0: fpaths = ['data/BF_CTU.csv', 'data/BF_V.csv', 'data/BF_OU.csv'] else: fpaths = fpath honest_data = [] dishonest_data = [] for fpath in fpaths: header = True for line in open(fpath): data = line.strip().split(',') if header: header = False continue is_honest = data[-1] == 'H' answers = np.array(data[:10]) if is_honest: honest_data.append(answers) else: dishonest_data.append(answers) return np.array(honest_data), np.array(dishonest_data) def evaluate_pair(true_lies_mask, detected_lies_mask): if np.sum(detected_lies_mask) > 0: prec = np.sum( np.where((detected_lies_mask == true_lies_mask) & (true_lies_mask == np.ones_like(true_lies_mask)), np.ones_like(detected_lies_mask), 0)) / np.sum(detected_lies_mask) else: prec = 0. if np.sum(true_lies_mask) > 0: rec = np.sum(np.where((detected_lies_mask == true_lies_mask) & (true_lies_mask == np.ones_like(true_lies_mask)), np.ones_like(detected_lies_mask), 0)) / np.sum(true_lies_mask) else: rec = 0. if prec + rec > 0: f1 = 2 * prec * rec / (prec + rec) else: f1 = 0.0 return prec, rec, f1 def compute_precs_recs_f1s(true_lies_mask, detected_lies_mask): curr_precs = [] curr_f1s = [] curr_recs = [] for i in range(detected_lies_mask.shape[0]): prec, rec, f1 = evaluate_pair(true_lies_mask[i], detected_lies_mask[i]) curr_f1s.append(f1) curr_precs.append(prec) curr_recs.append(rec) # return np.mean(curr_precs), np.mean(curr_recs), np.mean(curr_f1s) return curr_precs, curr_recs, curr_f1s def estimate_per_question_thresholds(tfidf_scores, thr=80): return [np.percentile(tfidf_scores[:, j], thr) for j in range(tfidf_scores.shape[1])] def optimize_thr_dist(honest_data, faked_data, true_lies_mask): perfs = [] thrs = [] for percentile in np.arange(50, 100, step=1): thresholds = estimate_per_question_thresholds(honest_data, percentile) detected_lies_mask = np.array( [np.where(faked_data[:, j] >= thresholds[j], np.ones_like(faked_data[:, j]), 0) for j in range(faked_data.shape[1])]).transpose() # p, r, f1 = compute_precs_recs_f1s(true_lies_mask, detected_lies_mask) acc = np.mean(np.where(true_lies_mask == detected_lies_mask, np.ones_like(detected_lies_mask), 0)) perfs.append(acc) thrs.append(percentile) best_thr = thrs[np.argmax(perfs)] print('best thr={}'.format(best_thr)) return best_thr def get_train_test_data(test_set): all_fpaths = ['data/BF_CTU.csv', 'data/BF_V.csv', 'data/BF_OU.csv'] # fnames_mapper = {'data/BF_CTU.csv': 'C', 'data/BF_V.csv': 'S', 'data/BF_OU.csv': 'H'} all_fpaths.remove(test_set) assert len(all_fpaths) == 2 hdata_train, ldata_train = load_data(all_fpaths) hdata_train = np.array(hdata_train, dtype=np.float) ldata_train = np.array(ldata_train, dtype=np.float) hdata_test, ldata_test = load_data([test_set]) hdata_test = np.array(hdata_test, dtype=np.float) ldata_test = np.array(ldata_test, dtype=np.float) return hdata_train, hdata_test, ldata_train, ldata_test def compute_perf_distr_model(test_set): print('Distribution Model') hdata_train, hdata_test, ldata_train, ldata_test = get_train_test_data(test_set) true_lies_mask_train = np.where(hdata_train != ldata_train, np.ones_like(hdata_train), 0) true_lies_mask_test = np.where(hdata_test != ldata_test, np.ones_like(ldata_test), 0) percentile = optimize_thr_dist(hdata_train, ldata_train, true_lies_mask_train) print('percentile: {}'.format(percentile)) thresholds = estimate_per_question_thresholds(hdata_train, percentile) detected_lies_mask_test = np.array( [np.where(hdata_test[:, j] >= thresholds[j], np.ones_like(hdata_test[:, j]), 0) for j in range(hdata_test.shape[1])]).transpose() p, r, f1 = compute_precs_recs_f1s(true_lies_mask_test, detected_lies_mask_test) p = np.mean(p) r = np.mean(r) f1 = np.mean(f1) print('Prec: {}, Recall: {}, F1Score: {}'.format(p, r, f1)) print('{:.4f} & {:.4f} & {:.4f}'.format(p, r, f1)) def get_k_closest_vecs(v, pool, k): dists = [np.sum(np.dot(v, p) / (np.linalg.norm(v, ord=2) * np.linalg.norm(p, ord=2))) for p in pool] return np.array(pool)[np.argsort(dists)[: k]] def compute_detected_lies_mask(v, closest_vecs, thr=1.0): avg_neighbor = np.mean(closest_vecs, axis=0) assert avg_neighbor.shape == closest_vecs[0].shape return np.where(np.abs(avg_neighbor - v) > thr, np.ones_like(v), 0) def compute_perf_knn_model(test_set): print('k-NN Model') fnames_mapper = {'data/BF_CTU.csv': 'C', 'data/BF_V.csv': 'S', 'data/BF_OU.csv': 'H'} hdata_train, hdata_test, ldata_train, ldata_test = get_train_test_data(test_set) true_lies_mask_train = np.where(hdata_train != ldata_train, np.ones_like(hdata_train), 0) true_lies_mask_test = np.where(hdata_test != ldata_test, np.ones_like(ldata_test), 0) perfs = [] thrs = [] ks = [] for thr in np.arange(1, 5, 1): for k in np.arange(1, 50, 5): detected_lies_masks_train = [] for v in ldata_train: closest_vecs = get_k_closest_vecs(v, hdata_train, k) curr_detected_lies = compute_detected_lies_mask(v, closest_vecs, thr=thr) detected_lies_masks_train.append(curr_detected_lies) detected_lies_masks_train = np.array(detected_lies_masks_train) p, r, f1 = compute_precs_recs_f1s(true_lies_mask_train, detected_lies_masks_train) p = np.mean(p) r = np.mean(r) f1 = np.mean(f1) perfs.append(p) ks.append(k) thrs.append(thr) best_k = ks[np.argmax(perfs)] best_thr = thrs[np.argmax(perfs)] print('best K: {}, best thr: {}'.format(best_k, best_thr)) detected_lies_mask_test = [] for v in ldata_test: closest_vecs = get_k_closest_vecs(v, hdata_test, best_k) curr_detected_lies = compute_detected_lies_mask(v, closest_vecs, thr=best_thr) detected_lies_mask_test.append(curr_detected_lies) detected_lies_mask_test = np.array(detected_lies_mask_test) p, r, f1 = compute_precs_recs_f1s(true_lies_mask_test, detected_lies_mask_test) print('Prec: {}, Recall: {}, F1Score: {}'.format(np.mean(p), np.mean(r), np.mean(f1))) print('{:.4f} & {:.4f} & {:.4f}'.format(np.mean(p), np.mean(r), np.mean(f1))) create_hist_by_n_lies(true_lies_mask_test, p, fname=fnames_mapper[test_set] + '_prec', measure_name='Precision', opath='./output/figures/knn/') create_hist_by_n_lies(true_lies_mask_test, r, fname=fnames_mapper[test_set] + '_rec', measure_name='Recall', opath='./output/figures/knn/') create_hist_by_n_lies(true_lies_mask_test, f1, fname=fnames_mapper[test_set] + '_f1', measure_name='F1 Score', opath='./output/figures/knn/') def compute_faked_answ_mask(pred_n_lies_per_test, tfidfs_faked_test, thresholds): new_lies_masks = [] for i in range(tfidfs_faked_test.shape[0]): n_pred_lies = pred_n_lies_per_test[i] lies_indices = np.argsort(-np.where(tfidfs_faked_test[i] >= thresholds, tfidfs_faked_test[i], 0))[ :int(np.ceil(n_pred_lies))] curr_lies_mask = np.zeros_like(tfidfs_faked_test[i]) for k in lies_indices: curr_lies_mask[k] = 1 new_lies_masks.append(curr_lies_mask) return np.array(new_lies_masks) def compute_per_question_accuracy(true_lies_mask, detected_lies_mask): per_question_accuracy = [] for question_index in range(true_lies_mask.shape[1]): accuracy = np.mean(np.where(true_lies_mask[:, question_index] == detected_lies_mask[:, question_index], np.ones_like(detected_lies_mask[:, question_index]), 0)) per_question_accuracy.append(accuracy) return np.array(per_question_accuracy) def compute_n_lies_per_sample_dist(honest, dishonest): true_lies_mask = np.where(np.abs(honest - dishonest) > 0, np.ones_like(honest), 0) n_lies = np.sum(true_lies_mask, axis=-1) import collections counter = collections.Counter(n_lies) return counter def create_hist_by_n_lies(true_lies_mask, per_test_perf, measure_name, fname, opath='./output/figures/tfidf/'): if not os.path.exists(opath): os.makedirs(opath) # n_lies_map = collections.Counter(np.sum(true_lies_mask, axis=-1)) n_lies_map = {} for i in range(true_lies_mask.shape[0]): key = np.sum(true_lies_mask[i]) if key not in n_lies_map.keys(): n_lies_map[key] = [i] else: n_lies_map[key].append(i) per_test_perf = np.array(per_test_perf) y = [] x = [] gsize = [] n_lies_all = sorted(list(n_lies_map.keys())) for n_lies in n_lies_all: if n_lies > 0: indices = n_lies_map[n_lies] group_acc = np.mean(per_test_perf[indices]) x.append(n_lies) y.append(group_acc) gsize.append(len(indices) / len(true_lies_mask)) plt.figure() plt.rcParams.update({'font.size': 20, 'legend.fontsize': 20}) ax = plt.gca() # plt.title('Faking detection {} by number of faked answers'.format(measure_name)) plt.bar(x=x, height=y, label='{}'.format(measure_name)) plt.xlabel('Number of faked answers per sample', fontsize=20) plt.ylabel('{}'.format(measure_name), fontsize=20) plt.plot(sorted(list(x)), gsize, color='r', label='Group sizes PDF') plt.xticks(np.arange(min(x), max(x) + 1, 1.0)) plt.yticks(np.arange(0, 1, 0.1)) plt.ylim(0, 1) plt.xlim(0.5, max(x) + 1) leg = ax.legend(prop={'size': 20}) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), fancybox=True, shadow=True, ncol=5) plt.grid(True) plt.savefig(opath + fname + '-{}-by-n-lies.png'.format(measure_name), bbox_inches='tight', pad_inches=0.01) def create_perf_histogram(avgd_perfs_by_question, fname, measure_name, opath='./output/figures/tfidf/'): if not os.path.exists(opath): os.makedirs(opath) x = [i + 1 for i in range(len(avgd_perfs_by_question))] plt.figure() ax = plt.gca() plt.title('Faking detection {}'.format(measure_name)) plt.bar(x=x, height=avgd_perfs_by_question, label=measure_name) plt.xticks(np.arange(min(x), max(x) + 1, 1.0)) plt.yticks(np.arange(0, 1, 0.1)) plt.grid(True) plt.savefig(opath + fname + '.png') def run(): for test_set in ['data/BF_CTU.csv', 'data/BF_V.csv', 'data/BF_OU.csv']: print(test_set) compute_perf_distr_model(test_set) # compute_perf_knn_model(test_set) if __name__ == '__main__': run()
[ "matplotlib.pyplot.grid", "numpy.argsort", "numpy.array", "numpy.linalg.norm", "numpy.arange", "numpy.mean", "os.path.exists", "numpy.where", "matplotlib.pyplot.xlabel", "numpy.dot", "matplotlib.pyplot.ylim", "numpy.abs", "numpy.ceil", "matplotlib.pyplot.savefig", "matplotlib.pyplot.gca"...
[((2210, 2236), 'numpy.arange', 'np.arange', (['(50)', '(100)'], {'step': '(1)'}), '(50, 100, step=1)\n', (2219, 2236), True, 'import numpy as np\n'), ((3192, 3229), 'numpy.array', 'np.array', (['hdata_train'], {'dtype': 'np.float'}), '(hdata_train, dtype=np.float)\n', (3200, 3229), True, 'import numpy as np\n'), ((3248, 3285), 'numpy.array', 'np.array', (['ldata_train'], {'dtype': 'np.float'}), '(ldata_train, dtype=np.float)\n', (3256, 3285), True, 'import numpy as np\n'), ((3355, 3391), 'numpy.array', 'np.array', (['hdata_test'], {'dtype': 'np.float'}), '(hdata_test, dtype=np.float)\n', (3363, 3391), True, 'import numpy as np\n'), ((3409, 3445), 'numpy.array', 'np.array', (['ldata_test'], {'dtype': 'np.float'}), '(ldata_test, dtype=np.float)\n', (3417, 3445), True, 'import numpy as np\n'), ((4333, 4343), 'numpy.mean', 'np.mean', (['p'], {}), '(p)\n', (4340, 4343), True, 'import numpy as np\n'), ((4352, 4362), 'numpy.mean', 'np.mean', (['r'], {}), '(r)\n', (4359, 4362), True, 'import numpy as np\n'), ((4372, 4383), 'numpy.mean', 'np.mean', (['f1'], {}), '(f1)\n', (4379, 4383), True, 'import numpy as np\n'), ((4775, 4804), 'numpy.mean', 'np.mean', (['closest_vecs'], {'axis': '(0)'}), '(closest_vecs, axis=0)\n', (4782, 4804), True, 'import numpy as np\n'), ((5413, 5431), 'numpy.arange', 'np.arange', (['(1)', '(5)', '(1)'], {}), '(1, 5, 1)\n', (5422, 5431), True, 'import numpy as np\n'), ((6548, 6581), 'numpy.array', 'np.array', (['detected_lies_mask_test'], {}), '(detected_lies_mask_test)\n', (6556, 6581), True, 'import numpy as np\n'), ((7899, 7923), 'numpy.array', 'np.array', (['new_lies_masks'], {}), '(new_lies_masks)\n', (7907, 7923), True, 'import numpy as np\n'), ((8350, 8381), 'numpy.array', 'np.array', (['per_question_accuracy'], {}), '(per_question_accuracy)\n', (8358, 8381), True, 'import numpy as np\n'), ((8539, 8570), 'numpy.sum', 'np.sum', (['true_lies_mask'], {'axis': '(-1)'}), '(true_lies_mask, axis=-1)\n', (8545, 8570), True, 'import numpy as np\n'), ((8608, 8635), 'collections.Counter', 'collections.Counter', (['n_lies'], {}), '(n_lies)\n', (8627, 8635), False, 'import collections\n'), ((9155, 9178), 'numpy.array', 'np.array', (['per_test_perf'], {}), '(per_test_perf)\n', (9163, 9178), True, 'import numpy as np\n'), ((9542, 9554), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9552, 9554), True, 'import matplotlib.pyplot as plt\n'), ((9559, 9620), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 20, 'legend.fontsize': 20}"], {}), "({'font.size': 20, 'legend.fontsize': 20})\n", (9578, 9620), True, 'import matplotlib.pyplot as plt\n'), ((9630, 9639), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (9637, 9639), True, 'import matplotlib.pyplot as plt\n'), ((9791, 9852), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of faked answers per sample"""'], {'fontsize': '(20)'}), "('Number of faked answers per sample', fontsize=20)\n", (9801, 9852), True, 'import matplotlib.pyplot as plt\n'), ((10074, 10088), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (10082, 10088), True, 'import matplotlib.pyplot as plt\n'), ((10260, 10274), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (10268, 10274), True, 'import matplotlib.pyplot as plt\n'), ((10636, 10648), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (10646, 10648), True, 'import matplotlib.pyplot as plt\n'), ((10658, 10667), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (10665, 10667), True, 'import matplotlib.pyplot as plt\n'), ((10730, 10793), 'matplotlib.pyplot.bar', 'plt.bar', ([], {'x': 'x', 'height': 'avgd_perfs_by_question', 'label': 'measure_name'}), '(x=x, height=avgd_perfs_by_question, label=measure_name)\n', (10737, 10793), True, 'import matplotlib.pyplot as plt\n'), ((10886, 10900), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (10894, 10900), True, 'import matplotlib.pyplot as plt\n'), ((10905, 10940), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(opath + fname + '.png')"], {}), "(opath + fname + '.png')\n", (10916, 10940), True, 'import matplotlib.pyplot as plt\n'), ((694, 715), 'numpy.array', 'np.array', (['honest_data'], {}), '(honest_data)\n', (702, 715), True, 'import numpy as np\n'), ((717, 741), 'numpy.array', 'np.array', (['dishonest_data'], {}), '(dishonest_data)\n', (725, 741), True, 'import numpy as np\n'), ((806, 832), 'numpy.sum', 'np.sum', (['detected_lies_mask'], {}), '(detected_lies_mask)\n', (812, 832), True, 'import numpy as np\n'), ((1096, 1118), 'numpy.sum', 'np.sum', (['true_lies_mask'], {}), '(true_lies_mask)\n', (1102, 1118), True, 'import numpy as np\n'), ((2015, 2053), 'numpy.percentile', 'np.percentile', (['tfidf_scores[:, j]', 'thr'], {}), '(tfidf_scores[:, j], thr)\n', (2028, 2053), True, 'import numpy as np\n'), ((2776, 2792), 'numpy.argmax', 'np.argmax', (['perfs'], {}), '(perfs)\n', (2785, 2792), True, 'import numpy as np\n'), ((3729, 3754), 'numpy.ones_like', 'np.ones_like', (['hdata_train'], {}), '(hdata_train)\n', (3741, 3754), True, 'import numpy as np\n'), ((3820, 3844), 'numpy.ones_like', 'np.ones_like', (['ldata_test'], {}), '(ldata_test)\n', (3832, 3844), True, 'import numpy as np\n'), ((4657, 4671), 'numpy.array', 'np.array', (['pool'], {}), '(pool)\n', (4665, 4671), True, 'import numpy as np\n'), ((4912, 4927), 'numpy.ones_like', 'np.ones_like', (['v'], {}), '(v)\n', (4924, 4927), True, 'import numpy as np\n'), ((5236, 5261), 'numpy.ones_like', 'np.ones_like', (['hdata_train'], {}), '(hdata_train)\n', (5248, 5261), True, 'import numpy as np\n'), ((5327, 5351), 'numpy.ones_like', 'np.ones_like', (['ldata_test'], {}), '(ldata_test)\n', (5339, 5351), True, 'import numpy as np\n'), ((5450, 5469), 'numpy.arange', 'np.arange', (['(1)', '(50)', '(5)'], {}), '(1, 50, 5)\n', (5459, 5469), True, 'import numpy as np\n'), ((6129, 6145), 'numpy.argmax', 'np.argmax', (['perfs'], {}), '(perfs)\n', (6138, 6145), True, 'import numpy as np\n'), ((6167, 6183), 'numpy.argmax', 'np.argmax', (['perfs'], {}), '(perfs)\n', (6176, 6183), True, 'import numpy as np\n'), ((7741, 7776), 'numpy.zeros_like', 'np.zeros_like', (['tfidfs_faked_test[i]'], {}), '(tfidfs_faked_test[i])\n', (7754, 7776), True, 'import numpy as np\n'), ((8501, 8521), 'numpy.ones_like', 'np.ones_like', (['honest'], {}), '(honest)\n', (8513, 8521), True, 'import numpy as np\n'), ((8780, 8801), 'os.path.exists', 'os.path.exists', (['opath'], {}), '(opath)\n', (8794, 8801), False, 'import os\n'), ((8811, 8829), 'os.makedirs', 'os.makedirs', (['opath'], {}), '(opath)\n', (8822, 8829), False, 'import os\n'), ((8981, 9006), 'numpy.sum', 'np.sum', (['true_lies_mask[i]'], {}), '(true_lies_mask[i])\n', (8987, 9006), True, 'import numpy as np\n'), ((10048, 10068), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(0.1)'], {}), '(0, 1, 0.1)\n', (10057, 10068), True, 'import numpy as np\n'), ((10521, 10542), 'os.path.exists', 'os.path.exists', (['opath'], {}), '(opath)\n', (10535, 10542), False, 'import os\n'), ((10552, 10570), 'os.makedirs', 'os.makedirs', (['opath'], {}), '(opath)\n', (10563, 10570), False, 'import os\n'), ((10860, 10880), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(0.1)'], {}), '(0, 1, 0.1)\n', (10869, 10880), True, 'import numpy as np\n'), ((528, 547), 'numpy.array', 'np.array', (['data[:10]'], {}), '(data[:10])\n', (536, 547), True, 'import numpy as np\n'), ((1034, 1060), 'numpy.sum', 'np.sum', (['detected_lies_mask'], {}), '(detected_lies_mask)\n', (1040, 1060), True, 'import numpy as np\n'), ((1315, 1337), 'numpy.sum', 'np.sum', (['true_lies_mask'], {}), '(true_lies_mask)\n', (1321, 1337), True, 'import numpy as np\n'), ((4672, 4689), 'numpy.argsort', 'np.argsort', (['dists'], {}), '(dists)\n', (4682, 4689), True, 'import numpy as np\n'), ((4880, 4904), 'numpy.abs', 'np.abs', (['(avg_neighbor - v)'], {}), '(avg_neighbor - v)\n', (4886, 4904), True, 'import numpy as np\n'), ((5816, 5851), 'numpy.array', 'np.array', (['detected_lies_masks_train'], {}), '(detected_lies_masks_train)\n', (5824, 5851), True, 'import numpy as np\n'), ((5963, 5973), 'numpy.mean', 'np.mean', (['p'], {}), '(p)\n', (5970, 5973), True, 'import numpy as np\n'), ((5990, 6000), 'numpy.mean', 'np.mean', (['r'], {}), '(r)\n', (5997, 6000), True, 'import numpy as np\n'), ((6018, 6029), 'numpy.mean', 'np.mean', (['f1'], {}), '(f1)\n', (6025, 6029), True, 'import numpy as np\n'), ((6719, 6729), 'numpy.mean', 'np.mean', (['p'], {}), '(p)\n', (6726, 6729), True, 'import numpy as np\n'), ((6731, 6741), 'numpy.mean', 'np.mean', (['r'], {}), '(r)\n', (6738, 6741), True, 'import numpy as np\n'), ((6743, 6754), 'numpy.mean', 'np.mean', (['f1'], {}), '(f1)\n', (6750, 6754), True, 'import numpy as np\n'), ((6801, 6811), 'numpy.mean', 'np.mean', (['p'], {}), '(p)\n', (6808, 6811), True, 'import numpy as np\n'), ((6813, 6823), 'numpy.mean', 'np.mean', (['r'], {}), '(r)\n', (6820, 6823), True, 'import numpy as np\n'), ((6825, 6836), 'numpy.mean', 'np.mean', (['f1'], {}), '(f1)\n', (6832, 6836), True, 'import numpy as np\n'), ((8469, 8495), 'numpy.abs', 'np.abs', (['(honest - dishonest)'], {}), '(honest - dishonest)\n', (8475, 8495), True, 'import numpy as np\n'), ((9383, 9414), 'numpy.mean', 'np.mean', (['per_test_perf[indices]'], {}), '(per_test_perf[indices])\n', (9390, 9414), True, 'import numpy as np\n'), ((2660, 2692), 'numpy.ones_like', 'np.ones_like', (['detected_lies_mask'], {}), '(detected_lies_mask)\n', (2672, 2692), True, 'import numpy as np\n'), ((4561, 4573), 'numpy.dot', 'np.dot', (['v', 'p'], {}), '(v, p)\n', (4567, 4573), True, 'import numpy as np\n'), ((8234, 8285), 'numpy.ones_like', 'np.ones_like', (['detected_lies_mask[:, question_index]'], {}), '(detected_lies_mask[:, question_index])\n', (8246, 8285), True, 'import numpy as np\n'), ((994, 1026), 'numpy.ones_like', 'np.ones_like', (['detected_lies_mask'], {}), '(detected_lies_mask)\n', (1006, 1026), True, 'import numpy as np\n'), ((1275, 1307), 'numpy.ones_like', 'np.ones_like', (['detected_lies_mask'], {}), '(detected_lies_mask)\n', (1287, 1307), True, 'import numpy as np\n'), ((4577, 4601), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {'ord': '(2)'}), '(v, ord=2)\n', (4591, 4601), True, 'import numpy as np\n'), ((4604, 4628), 'numpy.linalg.norm', 'np.linalg.norm', (['p'], {'ord': '(2)'}), '(p, ord=2)\n', (4618, 4628), True, 'import numpy as np\n'), ((7593, 7662), 'numpy.where', 'np.where', (['(tfidfs_faked_test[i] >= thresholds)', 'tfidfs_faked_test[i]', '(0)'], {}), '(tfidfs_faked_test[i] >= thresholds, tfidfs_faked_test[i], 0)\n', (7601, 7662), True, 'import numpy as np\n'), ((7693, 7713), 'numpy.ceil', 'np.ceil', (['n_pred_lies'], {}), '(n_pred_lies)\n', (7700, 7713), True, 'import numpy as np\n'), ((4147, 4177), 'numpy.ones_like', 'np.ones_like', (['hdata_test[:, j]'], {}), '(hdata_test[:, j])\n', (4159, 4177), True, 'import numpy as np\n'), ((942, 970), 'numpy.ones_like', 'np.ones_like', (['true_lies_mask'], {}), '(true_lies_mask)\n', (954, 970), True, 'import numpy as np\n'), ((1214, 1242), 'numpy.ones_like', 'np.ones_like', (['true_lies_mask'], {}), '(true_lies_mask)\n', (1226, 1242), True, 'import numpy as np\n'), ((2413, 2443), 'numpy.ones_like', 'np.ones_like', (['faked_data[:, j]'], {}), '(faked_data[:, j])\n', (2425, 2443), True, 'import numpy as np\n')]
from abc import abstractmethod from numpy import eye, shape from numpy.linalg import pinv class Kernel(object): def __init__(self): pass @abstractmethod def kernel(self, X, Y=None): raise NotImplementedError() @staticmethod def centering_matrix(n): """ Returns the centering matrix eye(n) - 1.0 / n """ return eye(n) - 1.0 / n @staticmethod def center_kernel_matrix(K): """ Centers the kernel matrix via a centering matrix H=I-1/n and returns HKH """ n = shape(K)[0] H = eye(n) - 1.0 / n return H.dot(K.dot(H)) def center_kernel_matrix_regression(K, Kz, epsilon): """ Centers the kernel matrix via a centering matrix R=I-Kz(Kz+\epsilonI)^{-1} and returns RKR """ n = shape(K)[0] Rz = epsilon * pinv(Kz + epsilon * eye(n)) return Rz.dot(K.dot(Rz))
[ "numpy.shape", "numpy.eye" ]
[((383, 389), 'numpy.eye', 'eye', (['n'], {}), '(n)\n', (386, 389), False, 'from numpy import eye, shape\n'), ((569, 577), 'numpy.shape', 'shape', (['K'], {}), '(K)\n', (574, 577), False, 'from numpy import eye, shape\n'), ((593, 599), 'numpy.eye', 'eye', (['n'], {}), '(n)\n', (596, 599), False, 'from numpy import eye, shape\n'), ((834, 842), 'numpy.shape', 'shape', (['K'], {}), '(K)\n', (839, 842), False, 'from numpy import eye, shape\n'), ((889, 895), 'numpy.eye', 'eye', (['n'], {}), '(n)\n', (892, 895), False, 'from numpy import eye, shape\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import nibabel as nb import numpy as np import image_funcs as imf import vis_funcs as vf def main(): SHOW_WINDOW = True SHOW_AXES = True COMP_ACT_SEED = True SEED_OFFSET = 25 data_dir = os.environ.get('OneDrive') + r'\data\dti_navigation\joonas' # markers_20210304_all_before_rep_scan filenames = {'MKSS': 'markers_20210304_rep_left_m1_dlpfc_broca_V1_final_scan_seed', 'COIL': 'magstim_fig8_coil', 'BRAINSIM': 'wm', 'HEADSIM': 'skin', 'ACT': 'trekkerACTlabels', 'T1': 'sub-S1_ses-S8741_T1w'} mkss_path = os.path.join(data_dir, filenames['MKSS'] + '.mkss') head_sim_path = os.path.join(data_dir, filenames['HEADSIM'] + '.stl') brain_sim_path = os.path.join(data_dir, filenames['BRAINSIM'] + '.stl') coil_path = os.path.join(data_dir, filenames['COIL'] + '.stl') act_path = os.path.join(data_dir, filenames['ACT'] + '.nii') # img_path = os.path.join(data_dir, filenames['T1'] + '.nii') coord_list, orient_list, colour_list, size_list, id_list, seed_list, tg_list = imf.load_mks(mkss_path) id_fids = ['LEI', 'REI', 'NAI'] index_coord = id_list.index('v1-right') index_fids = [id_list.index(n) for n in id_fids] if COMP_ACT_SEED: imagedata, affine = imf.load_image(act_path) # imagedata2, affine2 = imf.load_image(img_path) img_shape = imagedata.header.get_data_shape() act_data = imagedata.get_fdata() mri2inv_mat = imf.mri2inv(imagedata, affine) if SHOW_WINDOW: # Create a rendering window and renderer ren, ren_win, iren = vf.create_window() # 0: red, 1: green, 2: blue, 3: maroon (dark red), # 4: purple, 5: teal (petrol blue), 6: yellow, 7: orange colours = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [1., .0, 1.], [0.45, 0., 0.5], [0., .5, .5], [1., 1., 0.], [1., .4, .0]] repos = [0., 0., 0., 0., 0., 0.] _ = vf.load_stl(head_sim_path, ren, opacity=.4, colour="SkinColor", replace=repos, user_matrix=np.identity(4)) _ = vf.load_stl(brain_sim_path, ren, opacity=.6, colour=[1., 1., 1.], replace=repos, user_matrix=np.identity(4)) # if COMP_ACT_SEED: # _ = vf.load_stl(brain_sim_path, ren, opacity=.6, colour=[1., 1., 1.], replace=repos, # user_matrix=np.linalg.inv(affine)) # _ = vf.load_stl(brain_sim_path, ren, opacity=.6, colour=[1., 1., 0.], replace=repos, # user_matrix=mri2inv_mat) # create fiducial markers for n in index_fids: _ = vf.add_marker(coord_list[n], ren, colours[n], radius=2) # --- fiducial markers # create coil vectors coil_pos = np.hstack((coord_list[index_coord], orient_list[index_coord])) m_coil = imf.coil_transform_matrix(coil_pos) vec_length = 75 repos_coil = [0., 0., 0., 0., 0., 90.] # coil vectors in invesalius 3D space p1 = m_coil[:-1, -1] coil_dir = m_coil[:-1, 0] coil_face = m_coil[:-1, 1] p2_face = p1 + vec_length * coil_face p2_dir = p1 + vec_length * coil_dir coil_norm = np.cross(coil_dir, coil_face) p2_norm = p1 - vec_length * coil_norm if COMP_ACT_SEED: coord_list_w = imf.create_grid((-2, 2), (0, 20), SEED_OFFSET - 5, 1) coord_list_w_tr = m_coil @ coord_list_w coord_offset = imf.grid_offset(act_data, coord_list_w_tr, affine=affine) # coord_list_w_tr_inv = mri2inv_mat @ m_coil @ coord_list_w # coord_list_inv = imf.grid_offset_inv(act_data, coord_list_w_tr_inv, img_shape[1]) # coord_list_mri = np.squeeze(coord_list_inv + np.array([[0, img_shape[1], 0]])) # offset = 40 # coil_norm = coil_norm/np.linalg.norm(coil_norm) # coord_offset = p1 - offset * coil_norm # _ = vf.load_stl(coil_path, ren, opacity=.6, replace=repos_coil, colour=[1., 1., 1.], user_matrix=m_coil) _ = vf.add_line(ren, p1, p2_dir, color=[1.0, .0, .0]) _ = vf.add_line(ren, p1, p2_face, color=[.0, 1.0, .0]) _ = vf.add_line(ren, p1, p2_norm, color=[.0, .0, 1.0]) _ = vf.add_marker(p1, ren, colours[4], radius=2) # --- coil vectors # seed markers _ = vf.add_marker(seed_list[index_coord], ren, colours[5], radius=.5) _ = vf.add_marker(coord_offset, ren, colours[6], radius=.5) # _ = vf.add_marker(coord_list_inv, ren, colours[0], radius=.5) # _ = vf.add_marker(coord_list_mri, ren, colours[0], radius=.5) # for n in coord_list_w_tr.T: # _ = vf.add_marker(n[:3], ren, colours[7], radius=.5, opacity=.2) # --- seed markers # Add axes to scene origin if SHOW_AXES: _ = vf.add_line(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0]) _ = vf.add_line(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0]) _ = vf.add_line(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0]) # Initialize window and interactor iren.Initialize() ren_win.Render() iren.Start() if __name__ == '__main__': np.set_printoptions(suppress=True) # np.set_printoptions(suppress=True, precision=2) main()
[ "numpy.identity", "image_funcs.coil_transform_matrix", "vis_funcs.add_line", "image_funcs.load_mks", "image_funcs.load_image", "numpy.hstack", "numpy.cross", "vis_funcs.add_marker", "os.environ.get", "os.path.join", "image_funcs.grid_offset", "image_funcs.create_grid", "image_funcs.mri2inv",...
[((634, 685), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['MKSS'] + '.mkss')"], {}), "(data_dir, filenames['MKSS'] + '.mkss')\n", (646, 685), False, 'import os\n'), ((706, 759), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['HEADSIM'] + '.stl')"], {}), "(data_dir, filenames['HEADSIM'] + '.stl')\n", (718, 759), False, 'import os\n'), ((781, 835), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['BRAINSIM'] + '.stl')"], {}), "(data_dir, filenames['BRAINSIM'] + '.stl')\n", (793, 835), False, 'import os\n'), ((852, 902), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['COIL'] + '.stl')"], {}), "(data_dir, filenames['COIL'] + '.stl')\n", (864, 902), False, 'import os\n'), ((918, 967), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['ACT'] + '.nii')"], {}), "(data_dir, filenames['ACT'] + '.nii')\n", (930, 967), False, 'import os\n'), ((1118, 1141), 'image_funcs.load_mks', 'imf.load_mks', (['mkss_path'], {}), '(mkss_path)\n', (1130, 1141), True, 'import image_funcs as imf\n'), ((5295, 5329), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (5314, 5329), True, 'import numpy as np\n'), ((269, 295), 'os.environ.get', 'os.environ.get', (['"""OneDrive"""'], {}), "('OneDrive')\n", (283, 295), False, 'import os\n'), ((1327, 1351), 'image_funcs.load_image', 'imf.load_image', (['act_path'], {}), '(act_path)\n', (1341, 1351), True, 'import image_funcs as imf\n'), ((1526, 1556), 'image_funcs.mri2inv', 'imf.mri2inv', (['imagedata', 'affine'], {}), '(imagedata, affine)\n', (1537, 1556), True, 'import image_funcs as imf\n'), ((1656, 1674), 'vis_funcs.create_window', 'vf.create_window', ([], {}), '()\n', (1672, 1674), True, 'import vis_funcs as vf\n'), ((2843, 2905), 'numpy.hstack', 'np.hstack', (['(coord_list[index_coord], orient_list[index_coord])'], {}), '((coord_list[index_coord], orient_list[index_coord]))\n', (2852, 2905), True, 'import numpy as np\n'), ((2923, 2958), 'image_funcs.coil_transform_matrix', 'imf.coil_transform_matrix', (['coil_pos'], {}), '(coil_pos)\n', (2948, 2958), True, 'import image_funcs as imf\n'), ((3286, 3315), 'numpy.cross', 'np.cross', (['coil_dir', 'coil_face'], {}), '(coil_dir, coil_face)\n', (3294, 3315), True, 'import numpy as np\n'), ((4127, 4178), 'vis_funcs.add_line', 'vf.add_line', (['ren', 'p1', 'p2_dir'], {'color': '[1.0, 0.0, 0.0]'}), '(ren, p1, p2_dir, color=[1.0, 0.0, 0.0])\n', (4138, 4178), True, 'import vis_funcs as vf\n'), ((4189, 4241), 'vis_funcs.add_line', 'vf.add_line', (['ren', 'p1', 'p2_face'], {'color': '[0.0, 1.0, 0.0]'}), '(ren, p1, p2_face, color=[0.0, 1.0, 0.0])\n', (4200, 4241), True, 'import vis_funcs as vf\n'), ((4252, 4304), 'vis_funcs.add_line', 'vf.add_line', (['ren', 'p1', 'p2_norm'], {'color': '[0.0, 0.0, 1.0]'}), '(ren, p1, p2_norm, color=[0.0, 0.0, 1.0])\n', (4263, 4304), True, 'import vis_funcs as vf\n'), ((4316, 4360), 'vis_funcs.add_marker', 'vf.add_marker', (['p1', 'ren', 'colours[4]'], {'radius': '(2)'}), '(p1, ren, colours[4], radius=2)\n', (4329, 4360), True, 'import vis_funcs as vf\n'), ((4425, 4491), 'vis_funcs.add_marker', 'vf.add_marker', (['seed_list[index_coord]', 'ren', 'colours[5]'], {'radius': '(0.5)'}), '(seed_list[index_coord], ren, colours[5], radius=0.5)\n', (4438, 4491), True, 'import vis_funcs as vf\n'), ((4503, 4559), 'vis_funcs.add_marker', 'vf.add_marker', (['coord_offset', 'ren', 'colours[6]'], {'radius': '(0.5)'}), '(coord_offset, ren, colours[6], radius=0.5)\n', (4516, 4559), True, 'import vis_funcs as vf\n'), ((2706, 2761), 'vis_funcs.add_marker', 'vf.add_marker', (['coord_list[n]', 'ren', 'colours[n]'], {'radius': '(2)'}), '(coord_list[n], ren, colours[n], radius=2)\n', (2719, 2761), True, 'import vis_funcs as vf\n'), ((3416, 3469), 'image_funcs.create_grid', 'imf.create_grid', (['(-2, 2)', '(0, 20)', '(SEED_OFFSET - 5)', '(1)'], {}), '((-2, 2), (0, 20), SEED_OFFSET - 5, 1)\n', (3431, 3469), True, 'import image_funcs as imf\n'), ((3549, 3606), 'image_funcs.grid_offset', 'imf.grid_offset', (['act_data', 'coord_list_w_tr'], {'affine': 'affine'}), '(act_data, coord_list_w_tr, affine=affine)\n', (3564, 3606), True, 'import image_funcs as imf\n'), ((4922, 4985), 'vis_funcs.add_line', 'vf.add_line', (['ren', '[0, 0, 0]', '[150, 0, 0]'], {'color': '[1.0, 0.0, 0.0]'}), '(ren, [0, 0, 0], [150, 0, 0], color=[1.0, 0.0, 0.0])\n', (4933, 4985), True, 'import vis_funcs as vf\n'), ((5002, 5065), 'vis_funcs.add_line', 'vf.add_line', (['ren', '[0, 0, 0]', '[0, 150, 0]'], {'color': '[0.0, 1.0, 0.0]'}), '(ren, [0, 0, 0], [0, 150, 0], color=[0.0, 1.0, 0.0])\n', (5013, 5065), True, 'import vis_funcs as vf\n'), ((5082, 5145), 'vis_funcs.add_line', 'vf.add_line', (['ren', '[0, 0, 0]', '[0, 0, 150]'], {'color': '[0.0, 0.0, 1.0]'}), '(ren, [0, 0, 0], [0, 0, 150], color=[0.0, 0.0, 1.0])\n', (5093, 5145), True, 'import vis_funcs as vf\n'), ((2120, 2134), 'numpy.identity', 'np.identity', (['(4)'], {}), '(4)\n', (2131, 2134), True, 'import numpy as np\n'), ((2263, 2277), 'numpy.identity', 'np.identity', (['(4)'], {}), '(4)\n', (2274, 2277), True, 'import numpy as np\n')]
import pandas as pd import numpy as np import glob import sys import re from astropy.cosmology import Planck15 as cosmo import rate_functions as functions ### Mike's code import astropy.units as u import scipy #-----------------------------------------------------------------------------------# ## analytic approximation for P(omega) from Dominik et al. 2015 def P_omega(omega_values): return 0.374222*(1-omega_values)**2 + 2.04216*(1-omega_values)**4 - 2.63948*(1-omega_values)**8 + 1.222543*(1-omega_values)**10 #-----------------------------------------------------------------------------------# ### Monte Carlo sampling for detections above the given SNR threshold def calc_detection_prob(m1, m2, z_merge): ## constants that reflect LIGO design sensitivity d_L8 = 1 ## in Gpc M_8 = 10 ## in Msun SNR_thresh = 8 ## approximate typical SNR from Fishbach et al. 2018 M_chirp = (m1*m2)**(3./5)/(m1+m2)**(1./5) d_C = cosmo.comoving_distance(z_merge).to(u.Gpc).value d_L = (1+z_merge)*d_C rho_0 = 8*(M_chirp*(1+z_merge)/M_8)**(5./6)*d_L8/d_L ## this is the "typical/optimal" SNR if (rho_0 < SNR_thresh): return 0 ## sample omega according to distribution for omega ## sample omega according to distribution for omega via inverse CDF method dist_size = 10000 sample_size = 1000 P_omega_dist = P_omega(np.linspace(0, 1, dist_size)) inv_P_omega = scipy.interpolate.interp1d(P_omega_dist, np.linspace(0, 1, dist_size), fill_value="extrapolate") omega = inv_P_omega(np.random.uniform(0, 1, sample_size)) ## find the true SNRs given sky location rho = omega*rho_0 accept_SNR_num = len(rho[np.where(rho >= SNR_thresh)]) p_det = accept_SNR_num/sample_size return p_det #-----------------------------------------------------------------------------------# ## calculate the mass fraction of mergers for this merger redshift bin def find_f_z(pop, zmbin_low, zmbin_high, zf_mid, this_Z, mets, M_tot): Zsun = 0.017 sigmaZ = 0.5 lowZ = Zsun/200 highZ = 2*Zsun # assuming all systems are born in this formation bin, find how many merge in this merger bin if zmbin_low==0: # special treatment for the first merger bin tdelay_max = 0 tdelay_min = cosmo.lookback_time(zmbin_high).to(u.Myr).value else: tdelay_max = cosmo.lookback_time(zf_mid).to(u.Myr).value - cosmo.lookback_time(zmbin_low).to(u.Myr).value tdelay_min = cosmo.lookback_time(zf_mid).to(u.Myr).value - cosmo.lookback_time(zmbin_high).to(u.Myr).value N_merge_CP = len(pop.loc[(pop['tphys']<=tdelay_max) & (pop['tphys']>tdelay_min)]) # the relative weight of this metallicity at this particular redshift this_Z_prob = functions.metal_disp_z(zf_mid, this_Z, sigmaZ, lowZ, highZ) ### sum of conditional probabilities: P(Z|zf_mid) all_Z_prob_sum = np.sum(functions.metal_disp_z(np.ones(len(mets))*zf_mid, mets, sigmaZ, lowZ, highZ)) N_merge = N_merge_CP*this_Z_prob/all_Z_prob_sum f_zm = float(N_merge)/M_tot return f_zm #-----------------------------------------------------------------------------------# ## calculate the detection rate for the given population ## returns array of detection rates across mass bins def detection_rates(population, this_Z, M_tot, mets, m1bins, m2bins, zfbins, zmbins): f_loc_Z = [] ## constants c = 3e8 ## speed of light in m/s prefactor = 4*np.pi*c / cosmo.H(0).to(u.m * u.Gpc**-1 * u.s**-1).value merge_z_rates = [] ## merger rates for each redshift bin merge_mbin_rates = [] ## merger rates, summed over redshifts, for each mass bin for m1bin_low, m1bin_high in zip(m1bins[:-1], m1bins[1:]): for m2bin_low, m2bin_high in zip(m2bins[:-1], m2bins[1:]): merge_mbin = population.loc[(population['mass0_2']<=m2bin_high) & (population['mass0_2']>m2bin_low) \ & (population['mass0_1']<=m1bin_high) & (population['mass0_1']>m1bin_low)] #print ("# mergers in this mass bin: ", len(merge_mbin)) for zfbin_low, zfbin_high in zip(zfbins[::-1][1:], zfbins[::-1][:-1]): zmbin_low_max = np.where(zmbins == zfbin_low)[0][0] zmbin_high_max = np.where(zmbins == zfbin_high)[0][0] for zmbin_low, zmbin_high in zip(zmbins[::-1][1:zmbin_low_max], zmbins[::-1][:zmbin_high_max]): ### calculate redshift/metallicity weighting # get redshift in the middle of this log-spaced formation redshift interval zf_mid = 10**(np.log10(zfbin_low) + (np.log10(zfbin_high)-np.log10(zfbin_low))/2.0) zm_mid = 10**(np.log10(zmbin_low) + (np.log10(zmbin_high)-np.log10(zmbin_low))/2.0) # get masses in the middle of each mass bin for detection prob calc m1_mid = (m1bin_low + m1bin_high)/2.0 m2_mid = (m2bin_low + m2bin_high)/2.0 f_zm = find_f_z(merge_mbin, zmbin_low, zmbin_high, zf_mid, this_Z, mets, M_tot) # cosmological factor E_zm = (cosmo._Onu0*(1+zm_mid)**4 + cosmo._Om0*(1+zm_mid)**3 + cosmo._Ok0*(1+zm_mid)**2 + \ cosmo._Ode0)**(1./2) ### calculate source-frame merger rate for this formation, merger redshift ## detection rate for source with component masses m1, m2 p_det = calc_detection_prob(m1_mid, m2_mid, zm_mid) SFR = functions.sfr_z(zf_mid, mdl='2017')*(u.Mpc**-3).to(u.Gpc**-3) D_c = cosmo.comoving_distance(zm_mid).to(u.Gpc).value ## merger rate for this [zf, zm] in yr^-1 this_merge_Rate = prefactor * f_zm * SFR* p_det * D_c**2 / ((1+zm_mid)*E_zm)* \ (zmbin_high - zmbin_low) #print (this_merge_Rate) merge_z_rates.append(this_merge_Rate) ## sum rates across all redshifts merge_mbin_rate = np.sum(merge_z_rates) merge_mbin_rates.append(merge_mbin_rate) #print ("merger rate for m1=", m1_mid, " m2=", m2_mid, ": ", merge_mbin_rate ## empty the array for redshift-dependent rates merge_z_rates = [] return merge_mbin_rates, f_loc_Z #-----------------------------------------------------------------------------------# ### path to folder with COSMIC metallicity runs COSMIC_path = "pessimistic_CE_runs/*" all_COSMIC_runs = glob.glob(COSMIC_path) ## data frame to store rate output columns=['metallicity', 'BBH_detection_rate', 'tot_detection_rate'] df = pd.DataFrame(columns=columns) ## define parameters Zsun = 0.017 ## Solar metallicity N_zbins = 100 ## number of redshift bins zmin = 0 ## lower bound of redshift space zmax = 20 ## upper bound of redshift space N_mbins_BBH = 10 ## number of mass bins N_mbins_tot = 10 m1bin_low_BBH = 0 m2bin_low_BBH = 0 m1bin_low_tot = 0 m2bin_low_tot = 0 m1bin_high_BBH = 100 m2bin_high_BBH = 100 m1bin_high_tot = 100 m2bin_high_tot = 100 m1bins_BBH = np.linspace(m1bin_low_BBH, m1bin_high_BBH, N_mbins_BBH) m2bins_BBH = np.linspace(m2bin_low_BBH, m2bin_high_BBH ,N_mbins_BBH) m1bins_tot = np.linspace(m1bin_low_tot, m1bin_high_tot, N_mbins_tot) m2bins_tot = np.linspace(m2bin_low_tot, m2bin_high_tot ,N_mbins_tot) ### array of metallicities, should match those of COSMIC_runs metallicities = [Zsun/200, Zsun/100, Zsun/20, Zsun/10, Zsun/5, Zsun/2, Zsun] ### create log-spaced redshift bins if zmin==0: # account for log-spaced bins zmin = 1e-3 zfbins = np.logspace(np.log10(zmin), np.log10(zmax), N_zbins+1) zmbins = np.logspace(np.log10(zmin), np.log10(zmax), N_zbins+1) ## loop through all COSMIC populations and calculate BBHm merger rates ## 2D arrays storing mass distribution and f_loc values for all metallicites all_BBH_pop_mbin_rates = [] all_tot_pop_mbin_rates = [] all_BBH_f_loc = [] all_tot_f_loc = [] read_mets = [] for pop_dir in all_COSMIC_runs: data = glob.glob(pop_dir + "/*.h5")[0] this_Z_frac = float(re.findall('\d+.\d+', data)[0]) ## parse population metallicity from filename this_Z = round(this_Z_frac*Zsun, 6) read_mets.append(this_Z_frac) ### get total sampled mass of this population Mtot_arr = pd.read_hdf(data, key='mass_stars') Mtot = Mtot_arr.iloc[-1].values[0] bpp = pd.read_hdf(data, key='bpp') ## find BBH mergers using bcm array bcm = pd.read_hdf(data, key='bcm') BBHm_bcm = bcm.loc[bcm["merger_type"] == "1414"] BBHm_bin = BBHm_bcm['bin_num'].values BBHm_bpp = bpp.loc[BBHm_bin] all_mergers = bpp.loc[(bpp['evol_type']==6)] BBH_mergers = BBHm_bpp.loc[BBHm_bpp["evol_type"]==6] ## detection rates for this metallicity population, separated by mass bin mbin_BBH_rate_array, f_loc_BBH_array = detection_rates(BBH_mergers, this_Z, Mtot, metallicities, m1bins_BBH, m2bins_BBH, zfbins, zmbins) mbin_tot_rate_array, f_loc_tot_array = detection_rates(all_mergers, this_Z, Mtot, metallicities, m1bins_tot, m2bins_tot, zfbins, zmbins) print ("population: ", pop_dir) print ("total BBH detection rate: ", np.sum(mbin_BBH_rate_array)) print ("total DCO detection rate: ", np.sum(mbin_tot_rate_array)) all_BBH_pop_mbin_rates.append(mbin_BBH_rate_array) all_tot_pop_mbin_rates.append(mbin_tot_rate_array) all_BBH_f_loc.append(f_loc_BBH_array) all_tot_f_loc.append(f_loc_tot_array) mbin_BBH_rate_array = [] mbin_tot_rate_array = [] f_loc_BBH_array = [] f_loc_tot_array = [] ## to get final rates for each population, sum across all mass bins j = 0 for BBH_rate_vals, tot_rate_vals in zip(all_BBH_pop_mbin_rates, all_tot_pop_mbin_rates): full_BBH_rate = np.sum(BBH_rate_vals) full_tot_rate = np.sum(tot_rate_vals) this_df = pd.DataFrame([[read_mets[j], full_BBH_rate, full_tot_rate]], columns=columns) df = df.append(this_df, sort=False, ignore_index=True) j += 1 df.to_csv("Z_pop_rates.csv", index=False)
[ "numpy.log10", "astropy.cosmology.Planck15.H", "astropy.cosmology.Planck15.lookback_time", "numpy.where", "numpy.sum", "numpy.linspace", "rate_functions.metal_disp_z", "pandas.read_hdf", "numpy.random.uniform", "pandas.DataFrame", "re.findall", "rate_functions.sfr_z", "astropy.cosmology.Plan...
[((8212, 8234), 'glob.glob', 'glob.glob', (['COSMIC_path'], {}), '(COSMIC_path)\n', (8221, 8234), False, 'import glob\n'), ((8344, 8373), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (8356, 8373), True, 'import pandas as pd\n'), ((8958, 9013), 'numpy.linspace', 'np.linspace', (['m1bin_low_BBH', 'm1bin_high_BBH', 'N_mbins_BBH'], {}), '(m1bin_low_BBH, m1bin_high_BBH, N_mbins_BBH)\n', (8969, 9013), True, 'import numpy as np\n'), ((9027, 9082), 'numpy.linspace', 'np.linspace', (['m2bin_low_BBH', 'm2bin_high_BBH', 'N_mbins_BBH'], {}), '(m2bin_low_BBH, m2bin_high_BBH, N_mbins_BBH)\n', (9038, 9082), True, 'import numpy as np\n'), ((9096, 9151), 'numpy.linspace', 'np.linspace', (['m1bin_low_tot', 'm1bin_high_tot', 'N_mbins_tot'], {}), '(m1bin_low_tot, m1bin_high_tot, N_mbins_tot)\n', (9107, 9151), True, 'import numpy as np\n'), ((9165, 9220), 'numpy.linspace', 'np.linspace', (['m2bin_low_tot', 'm2bin_high_tot', 'N_mbins_tot'], {}), '(m2bin_low_tot, m2bin_high_tot, N_mbins_tot)\n', (9176, 9220), True, 'import numpy as np\n'), ((3237, 3296), 'rate_functions.metal_disp_z', 'functions.metal_disp_z', (['zf_mid', 'this_Z', 'sigmaZ', 'lowZ', 'highZ'], {}), '(zf_mid, this_Z, sigmaZ, lowZ, highZ)\n', (3259, 3296), True, 'import rate_functions as functions\n'), ((9570, 9584), 'numpy.log10', 'np.log10', (['zmin'], {}), '(zmin)\n', (9578, 9584), True, 'import numpy as np\n'), ((9586, 9600), 'numpy.log10', 'np.log10', (['zmax'], {}), '(zmax)\n', (9594, 9600), True, 'import numpy as np\n'), ((9634, 9648), 'numpy.log10', 'np.log10', (['zmin'], {}), '(zmin)\n', (9642, 9648), True, 'import numpy as np\n'), ((9650, 9664), 'numpy.log10', 'np.log10', (['zmax'], {}), '(zmax)\n', (9658, 9664), True, 'import numpy as np\n'), ((10305, 10340), 'pandas.read_hdf', 'pd.read_hdf', (['data'], {'key': '"""mass_stars"""'}), "(data, key='mass_stars')\n", (10316, 10340), True, 'import pandas as pd\n'), ((10397, 10425), 'pandas.read_hdf', 'pd.read_hdf', (['data'], {'key': '"""bpp"""'}), "(data, key='bpp')\n", (10408, 10425), True, 'import pandas as pd\n'), ((10477, 10505), 'pandas.read_hdf', 'pd.read_hdf', (['data'], {'key': '"""bcm"""'}), "(data, key='bcm')\n", (10488, 10505), True, 'import pandas as pd\n'), ((11792, 11813), 'numpy.sum', 'np.sum', (['BBH_rate_vals'], {}), '(BBH_rate_vals)\n', (11798, 11813), True, 'import numpy as np\n'), ((11834, 11855), 'numpy.sum', 'np.sum', (['tot_rate_vals'], {}), '(tot_rate_vals)\n', (11840, 11855), True, 'import numpy as np\n'), ((11870, 11947), 'pandas.DataFrame', 'pd.DataFrame', (['[[read_mets[j], full_BBH_rate, full_tot_rate]]'], {'columns': 'columns'}), '([[read_mets[j], full_BBH_rate, full_tot_rate]], columns=columns)\n', (11882, 11947), True, 'import pandas as pd\n'), ((1690, 1718), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'dist_size'], {}), '(0, 1, dist_size)\n', (1701, 1718), True, 'import numpy as np\n'), ((1779, 1807), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'dist_size'], {}), '(0, 1, dist_size)\n', (1790, 1807), True, 'import numpy as np\n'), ((1859, 1895), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'sample_size'], {}), '(0, 1, sample_size)\n', (1876, 1895), True, 'import numpy as np\n'), ((9987, 10015), 'glob.glob', 'glob.glob', (["(pop_dir + '/*.h5')"], {}), "(pop_dir + '/*.h5')\n", (9996, 10015), False, 'import glob\n'), ((11196, 11223), 'numpy.sum', 'np.sum', (['mbin_BBH_rate_array'], {}), '(mbin_BBH_rate_array)\n', (11202, 11223), True, 'import numpy as np\n'), ((11266, 11293), 'numpy.sum', 'np.sum', (['mbin_tot_rate_array'], {}), '(mbin_tot_rate_array)\n', (11272, 11293), True, 'import numpy as np\n'), ((1994, 2021), 'numpy.where', 'np.where', (['(rho >= SNR_thresh)'], {}), '(rho >= SNR_thresh)\n', (2002, 2021), True, 'import numpy as np\n'), ((7559, 7580), 'numpy.sum', 'np.sum', (['merge_z_rates'], {}), '(merge_z_rates)\n', (7565, 7580), True, 'import numpy as np\n'), ((10043, 10072), 're.findall', 're.findall', (['"""\\\\d+.\\\\d+"""', 'data'], {}), "('\\\\d+.\\\\d+', data)\n", (10053, 10072), False, 'import re\n'), ((1253, 1285), 'astropy.cosmology.Planck15.comoving_distance', 'cosmo.comoving_distance', (['z_merge'], {}), '(z_merge)\n', (1276, 1285), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((2707, 2738), 'astropy.cosmology.Planck15.lookback_time', 'cosmo.lookback_time', (['zmbin_high'], {}), '(zmbin_high)\n', (2726, 2738), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((4056, 4066), 'astropy.cosmology.Planck15.H', 'cosmo.H', (['(0)'], {}), '(0)\n', (4063, 4066), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((2787, 2814), 'astropy.cosmology.Planck15.lookback_time', 'cosmo.lookback_time', (['zf_mid'], {}), '(zf_mid)\n', (2806, 2814), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((2833, 2863), 'astropy.cosmology.Planck15.lookback_time', 'cosmo.lookback_time', (['zmbin_low'], {}), '(zmbin_low)\n', (2852, 2863), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((2901, 2928), 'astropy.cosmology.Planck15.lookback_time', 'cosmo.lookback_time', (['zf_mid'], {}), '(zf_mid)\n', (2920, 2928), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((2947, 2978), 'astropy.cosmology.Planck15.lookback_time', 'cosmo.lookback_time', (['zmbin_high'], {}), '(zmbin_high)\n', (2966, 2978), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((4820, 4849), 'numpy.where', 'np.where', (['(zmbins == zfbin_low)'], {}), '(zmbins == zfbin_low)\n', (4828, 4849), True, 'import numpy as np\n'), ((4889, 4919), 'numpy.where', 'np.where', (['(zmbins == zfbin_high)'], {}), '(zmbins == zfbin_high)\n', (4897, 4919), True, 'import numpy as np\n'), ((6890, 6925), 'rate_functions.sfr_z', 'functions.sfr_z', (['zf_mid'], {'mdl': '"""2017"""'}), "(zf_mid, mdl='2017')\n", (6905, 6925), True, 'import rate_functions as functions\n'), ((5510, 5529), 'numpy.log10', 'np.log10', (['zfbin_low'], {}), '(zfbin_low)\n', (5518, 5529), True, 'import numpy as np\n'), ((5614, 5633), 'numpy.log10', 'np.log10', (['zmbin_low'], {}), '(zmbin_low)\n', (5622, 5633), True, 'import numpy as np\n'), ((6978, 7009), 'astropy.cosmology.Planck15.comoving_distance', 'cosmo.comoving_distance', (['zm_mid'], {}), '(zm_mid)\n', (7001, 7009), True, 'from astropy.cosmology import Planck15 as cosmo\n'), ((5533, 5553), 'numpy.log10', 'np.log10', (['zfbin_high'], {}), '(zfbin_high)\n', (5541, 5553), True, 'import numpy as np\n'), ((5554, 5573), 'numpy.log10', 'np.log10', (['zfbin_low'], {}), '(zfbin_low)\n', (5562, 5573), True, 'import numpy as np\n'), ((5637, 5657), 'numpy.log10', 'np.log10', (['zmbin_high'], {}), '(zmbin_high)\n', (5645, 5657), True, 'import numpy as np\n'), ((5658, 5677), 'numpy.log10', 'np.log10', (['zmbin_low'], {}), '(zmbin_low)\n', (5666, 5677), True, 'import numpy as np\n')]
""" Classes for Bayesian optimization Created on Jul 9, 2019 @author: <NAME> (<EMAIL>) Copyright 2019 Xilinx, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ ####################################################################################################################### from opentuner.search.technique import register from opentuner.search.bandittechniques import AUCBanditMetaTechnique from opentuner.search.differentialevolution import DifferentialEvolutionAlt from opentuner.search.evolutionarytechniques import NormalGreedyMutation, UniformGreedyMutation from opentuner.search.objective import SearchObjective from opentuner.search.simplextechniques import RandomNelderMead from .gaussianprocess import GaussianProcess from .modeltuner import ModelTuner from .learningtechniques import LearningTechnique import math import numpy from scipy.stats import norm ####################################################################################################################### class BayesianOptimization(LearningTechnique): """Search technique that selects the optimizal configuration using Bayesian optimization of the provided models""" def select_configuration(self): """Suggest a new configuration to evaluate. Returns ------- Configuration Suggested configuration """ for result in self._data_set: if result.state == 'OK': break else: return self.driver.get_configuration(self.manipulator.random()) technique = AUCBanditMetaTechnique([ DifferentialEvolutionAlt(), UniformGreedyMutation(), NormalGreedyMutation(mutation_rate = 0.3), RandomNelderMead(), ], log_freq = 0) objective = MaximizeExpecImpr(self.objective, self.driver.best_result) tuner = ModelTuner(self._models, technique, objective, self.manipulator, self._data_set) cfg = tuner.tune() return self.driver.get_configuration(cfg) if cfg is not None else None ####################################################################################################################### class MaximizeExpecImpr(SearchObjective): """This class is used to maximize the expected improvement of a model.""" def __init__(self, objective, best_result): """Constructor Parameters ---------- objective : SearchObjective Objective best_result Best result found so far """ self.objective = objective self.best_result = best_result def result_order_by_terms(self): """Return database columns required to order the results by the objective. """ raise RuntimeError("Columns cannot be ordered by expected improvement because it is a derived metric.") def result_compare(self, result1, result2): """Compare `result1` and `result2`. Parameters ---------- result1 : Result Measurement 1 result2 : Result Measurement 2 Returns ------- integer Negative if `result1` < `result2`, 0 if `result1` == `result2`, positive if `result1` > `result2`. """ # result1 and result2 are intentionally reversed because we want to maximize instead of minimize (the default). return cmp(self.compute_expec_impr(result2), self.compute_expec_impr(result1)) def result_relative(self, result1, result2): """Returns the ratio of the objective function values of `result1` and `result2`. Parameters ---------- result1 : Result Measurement 1 result2 : Result Measurement 2 Returns ------- float Ratio """ value1 = self.objective.get_mean(result1) value2 = self.objective.get_mean(result2) if value2 == 0: return float('inf') * value1 return value1 / value2 def compute_expec_impr(self, result): """Computes the expected improvement of a result. Parameters ---------- result : Result Measurement Returns ------- float Expected improvement """ means = self.objective.get_means(result) std_devs = self.objective.get_std_devs(result) best = self.objective.get_means(self.best_result) constraints = self.objective.get_constraints() if constraints is not None: probs = [self.safe_cdf(constraints[metric], means[metric], std_devs[metric]) for metric in range(1, len(means))] prob = numpy.prod(probs) else: prob = 1.0 diff = best[0] - means[0] if std_devs[0] != 0.0: expec_impr = prob * (diff * norm.cdf(best[0], means[0], std_devs[0]) + \ std_devs[0] * norm.pdf(best[0], means[0], std_devs[0])) else: expec_impr = prob * diff if best[0] > means[0] else 0.0 if math.isinf(expec_impr) or math.isnan(expec_impr): raise RuntimeError("Invalid expected improvement.") # Due to rounding errors, the expected improvement is occasionally negative. I suspect that this doesn't matter. return expec_impr def safe_cdf(self, value, mean, std_dev): """Return the probability density of a normal distribution for a given value. Parameters ---------- value : float Value for which the probability density must be determined. mean : float Mean of distribution std_dev : float Standard deviation of distribution Returns ------- float Probability density """ if std_dev != 0.0: return norm.cdf(value, mean, std_dev) elif value < mean: return 0.0 elif value > mean: return 1.0 else: return 0.5 ####################################################################################################################### register(BayesianOptimization([GaussianProcess("run_time"), GaussianProcess("luts"), GaussianProcess("regs"), GaussianProcess("dsps"), GaussianProcess("brams")], name = "BayesianOptimization"))
[ "opentuner.search.differentialevolution.DifferentialEvolutionAlt", "numpy.prod", "opentuner.search.evolutionarytechniques.UniformGreedyMutation", "scipy.stats.norm.pdf", "math.isinf", "opentuner.search.evolutionarytechniques.NormalGreedyMutation", "opentuner.search.simplextechniques.RandomNelderMead", ...
[((5352, 5369), 'numpy.prod', 'numpy.prod', (['probs'], {}), '(probs)\n', (5362, 5369), False, 'import numpy\n'), ((5707, 5729), 'math.isinf', 'math.isinf', (['expec_impr'], {}), '(expec_impr)\n', (5717, 5729), False, 'import math\n'), ((5733, 5755), 'math.isnan', 'math.isnan', (['expec_impr'], {}), '(expec_impr)\n', (5743, 5755), False, 'import math\n'), ((6421, 6451), 'scipy.stats.norm.cdf', 'norm.cdf', (['value', 'mean', 'std_dev'], {}), '(value, mean, std_dev)\n', (6429, 6451), False, 'from scipy.stats import norm\n'), ((2522, 2548), 'opentuner.search.differentialevolution.DifferentialEvolutionAlt', 'DifferentialEvolutionAlt', ([], {}), '()\n', (2546, 2548), False, 'from opentuner.search.differentialevolution import DifferentialEvolutionAlt\n'), ((2558, 2581), 'opentuner.search.evolutionarytechniques.UniformGreedyMutation', 'UniformGreedyMutation', ([], {}), '()\n', (2579, 2581), False, 'from opentuner.search.evolutionarytechniques import NormalGreedyMutation, UniformGreedyMutation\n'), ((2591, 2630), 'opentuner.search.evolutionarytechniques.NormalGreedyMutation', 'NormalGreedyMutation', ([], {'mutation_rate': '(0.3)'}), '(mutation_rate=0.3)\n', (2611, 2630), False, 'from opentuner.search.evolutionarytechniques import NormalGreedyMutation, UniformGreedyMutation\n'), ((2642, 2660), 'opentuner.search.simplextechniques.RandomNelderMead', 'RandomNelderMead', ([], {}), '()\n', (2658, 2660), False, 'from opentuner.search.simplextechniques import RandomNelderMead\n'), ((5493, 5533), 'scipy.stats.norm.cdf', 'norm.cdf', (['best[0]', 'means[0]', 'std_devs[0]'], {}), '(best[0], means[0], std_devs[0])\n', (5501, 5533), False, 'from scipy.stats import norm\n'), ((5579, 5619), 'scipy.stats.norm.pdf', 'norm.pdf', (['best[0]', 'means[0]', 'std_devs[0]'], {}), '(best[0], means[0], std_devs[0])\n', (5587, 5619), False, 'from scipy.stats import norm\n')]
import pytest import numpy as np from ._parametrize import optimizers_noSBOM def objective_function(para): return 1 @pytest.mark.parametrize(*optimizers_noSBOM) def test_large_search_space_0(Optimizer): search_space = { "x1": np.arange(0, 1000000), "x2": np.arange(0, 1000000), "x3": np.arange(0, 1000000), } opt = Optimizer(search_space, initialize={"random": 10}) opt.search(objective_function, n_iter=150, verbosity=False) @pytest.mark.parametrize(*optimizers_noSBOM) def test_large_search_space_1(Optimizer): search_space = { "x1": np.arange(0, 1000, 0.001), "x2": np.arange(0, 1000, 0.001), "x3": np.arange(0, 1000, 0.001), } opt = Optimizer(search_space, initialize={"random": 10}) opt.search(objective_function, n_iter=150, verbosity=False) @pytest.mark.parametrize(*optimizers_noSBOM) def test_large_search_space_2(Optimizer): search_space = {} for i in range(100): key = "x" + str(i) search_space[key] = np.arange(0, 100) opt = Optimizer(search_space, initialize={"random": 34, "vertices": 34, "grid": 34}) opt.search(objective_function, n_iter=1000, verbosity=False)
[ "pytest.mark.parametrize", "numpy.arange" ]
[((126, 169), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['*optimizers_noSBOM'], {}), '(*optimizers_noSBOM)\n', (149, 169), False, 'import pytest\n'), ((479, 522), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['*optimizers_noSBOM'], {}), '(*optimizers_noSBOM)\n', (502, 522), False, 'import pytest\n'), ((845, 888), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['*optimizers_noSBOM'], {}), '(*optimizers_noSBOM)\n', (868, 888), False, 'import pytest\n'), ((248, 269), 'numpy.arange', 'np.arange', (['(0)', '(1000000)'], {}), '(0, 1000000)\n', (257, 269), True, 'import numpy as np\n'), ((285, 306), 'numpy.arange', 'np.arange', (['(0)', '(1000000)'], {}), '(0, 1000000)\n', (294, 306), True, 'import numpy as np\n'), ((322, 343), 'numpy.arange', 'np.arange', (['(0)', '(1000000)'], {}), '(0, 1000000)\n', (331, 343), True, 'import numpy as np\n'), ((601, 626), 'numpy.arange', 'np.arange', (['(0)', '(1000)', '(0.001)'], {}), '(0, 1000, 0.001)\n', (610, 626), True, 'import numpy as np\n'), ((642, 667), 'numpy.arange', 'np.arange', (['(0)', '(1000)', '(0.001)'], {}), '(0, 1000, 0.001)\n', (651, 667), True, 'import numpy as np\n'), ((683, 708), 'numpy.arange', 'np.arange', (['(0)', '(1000)', '(0.001)'], {}), '(0, 1000, 0.001)\n', (692, 708), True, 'import numpy as np\n'), ((1034, 1051), 'numpy.arange', 'np.arange', (['(0)', '(100)'], {}), '(0, 100)\n', (1043, 1051), True, 'import numpy as np\n')]
import numpy as np from torch.utils.data import SubsetRandomSampler from torchvision.transforms import transforms from torchvision.datasets import CIFAR10 from dlex.datasets.torch import Dataset from dlex.torch import Batch from dlex.torch.utils.ops_utils import maybe_cuda class PytorchCIFAR10(Dataset): """CIFAR10 dataset""" def __init__(self, builder, mode): super().__init__(builder, mode) img_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261)) ]) self.cifar = CIFAR10( builder.get_working_dir(), train=mode == "train", transform=img_transform, download=True) if mode != "test": num_train = len(self.cifar) indices = list(range(num_train)) split = int(np.floor(0.2 * num_train)) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] self._sampler = SubsetRandomSampler(train_idx if mode == "train" else valid_idx) def collate_fn(self, batch) -> Batch: ret = super().collate_fn(batch) return Batch(X=maybe_cuda(ret[0]), Y=maybe_cuda(ret[1])) @property def num_classes(self): return 10 @property def num_channels(self): return 3 @property def input_shape(self): return 32, 32 def __len__(self): if self.mode == "test": return len(self.cifar) elif self.mode == "train": return int(len(self.cifar) * 0.8) else: return int(len(self.cifar) * 0.2) def __getitem__(self, idx): return self.cifar[idx]
[ "numpy.floor", "torch.utils.data.SubsetRandomSampler", "torchvision.transforms.transforms.Normalize", "torchvision.transforms.transforms.ToTensor", "dlex.torch.utils.ops_utils.maybe_cuda", "numpy.random.shuffle" ]
[((958, 984), 'numpy.random.shuffle', 'np.random.shuffle', (['indices'], {}), '(indices)\n', (975, 984), True, 'import numpy as np\n'), ((1083, 1147), 'torch.utils.data.SubsetRandomSampler', 'SubsetRandomSampler', (["(train_idx if mode == 'train' else valid_idx)"], {}), "(train_idx if mode == 'train' else valid_idx)\n", (1102, 1147), False, 'from torch.utils.data import SubsetRandomSampler\n'), ((487, 508), 'torchvision.transforms.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (506, 508), False, 'from torchvision.transforms import transforms\n'), ((523, 592), 'torchvision.transforms.transforms.Normalize', 'transforms.Normalize', (['(0.4914, 0.4822, 0.4465)', '(0.247, 0.243, 0.261)'], {}), '((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))\n', (543, 592), False, 'from torchvision.transforms import transforms\n'), ((918, 943), 'numpy.floor', 'np.floor', (['(0.2 * num_train)'], {}), '(0.2 * num_train)\n', (926, 943), True, 'import numpy as np\n'), ((1258, 1276), 'dlex.torch.utils.ops_utils.maybe_cuda', 'maybe_cuda', (['ret[0]'], {}), '(ret[0])\n', (1268, 1276), False, 'from dlex.torch.utils.ops_utils import maybe_cuda\n'), ((1280, 1298), 'dlex.torch.utils.ops_utils.maybe_cuda', 'maybe_cuda', (['ret[1]'], {}), '(ret[1])\n', (1290, 1298), False, 'from dlex.torch.utils.ops_utils import maybe_cuda\n')]
"""Functions to perform correlations""" import numpy as np from scipy.stats import norm def cross_corr(a, b): """Cross-correlation Calculate the cross correlation of array b against array a. Args: a (array): numpy vector. Reference against which cross correlation is calculated. b (array): numpy vector. The resulting cross-correlation function will show how b should be shifted to line up with vector a. Returns: array: cross-correlation function """ # noramlize a & b a = (a-np.min(a))/(np.max(a)-np.min(a)) b = (b-np.min(b))/(np.max(b)-np.min(b)) # compute the Fast Fourrier Transform f_a = np.fft.fft(a) f_b = np.fft.fft(b) # get the complex conjugate f_a_c = np.conj(f_a) # Convolution Theorem: The Fourier transform of the convolution is # the product of the two Fourier transforms # Correlation theorem: multiplying the Fourier transform of # one function by the complex conjugate of the Fourier transform of # the other gives the Fourier transform of their correlation # The inverse then brings us back to the original domain c_corr = np.fft.ifft(f_a_c*f_b) # FFT cross corr method gives the cyclic cross-correlation # "first n points in c_corr[0..2*n] stored in wrap-around order, # i.e., correlations at increasingly negative lags are in c_corr[n] # on down to c_corr[n/2+1], while correlations at increasingly # positive lags are in c_corr[0] (zero lag) on up to c_corr[n/2]." # --> Numerical Recipes in C to get the linear correlation, need to # circularly rotate the data this puts the peaks of the signal # together c_corr = np.abs(np.roll(c_corr, len(c_corr) // 2)) # above does the same as np.fft.fftshift # note that the shift occurs on a pixel/array element level, # so len/2 has to be an integer so enforce floor/int division here # normalizing, may help peak fitting c_corr = (c_corr-np.min(c_corr))/(np.max(c_corr)-np.min(c_corr)) return c_corr def find_shift(a, b): """Find offset between a and b. Find the offset between vector a and b that makes them line up as well as possible. Args: a (array): Reference vector b (array): Target vector Returns: float: the shift needed to be applied to vector b to best match vector a """ npt = len(a) c_corr = cross_corr(a, b) # define the lag grid that corresponds to the cross-correlation lag_grid = np.arange(npt) - npt // 2 # multiply by the pixel width to put in same units as the # original function x_lag = lag_grid*(x[1]-x[0]) # the peak or center of the cross-correlation gives us the shift # between the arrays fit 2nd order poly to peak of cross-corr ind_c_max = np.where(c_corr == np.max(c_corr))[0] ind_c_max = ind_c_max[0] result = np.polyfit(x_lag[ind_c_max-2:ind_c_max+2], c_corr[ind_c_max-2:ind_c_max+2], 2) # differentiate and set to zero to find peak shift_y2 = -result[1]/(2.*result[0]) return shift_y2 if __name__ == '__main__': # generate x-axis grid x = (np.arange(100)-50.23)*3.67 # generate Gaussian profile for that grid c1 = 2 c2 = -17.3 y1 = norm.pdf(x, c1, 7) y2 = norm.pdf(x, c2, 7) # do the cross-correlation shift = find_shift(y1, y2) print("Shift array b by {:.0f} pixels to line up with array a." \ .format(shift))
[ "numpy.polyfit", "numpy.conj", "numpy.fft.fft", "numpy.max", "scipy.stats.norm.pdf", "numpy.min", "numpy.fft.ifft", "numpy.arange" ]
[((688, 701), 'numpy.fft.fft', 'np.fft.fft', (['a'], {}), '(a)\n', (698, 701), True, 'import numpy as np\n'), ((712, 725), 'numpy.fft.fft', 'np.fft.fft', (['b'], {}), '(b)\n', (722, 725), True, 'import numpy as np\n'), ((771, 783), 'numpy.conj', 'np.conj', (['f_a'], {}), '(f_a)\n', (778, 783), True, 'import numpy as np\n'), ((1180, 1204), 'numpy.fft.ifft', 'np.fft.ifft', (['(f_a_c * f_b)'], {}), '(f_a_c * f_b)\n', (1191, 1204), True, 'import numpy as np\n'), ((2924, 3015), 'numpy.polyfit', 'np.polyfit', (['x_lag[ind_c_max - 2:ind_c_max + 2]', 'c_corr[ind_c_max - 2:ind_c_max + 2]', '(2)'], {}), '(x_lag[ind_c_max - 2:ind_c_max + 2], c_corr[ind_c_max - 2:\n ind_c_max + 2], 2)\n', (2934, 3015), True, 'import numpy as np\n'), ((3313, 3331), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', 'c1', '(7)'], {}), '(x, c1, 7)\n', (3321, 3331), False, 'from scipy.stats import norm\n'), ((3341, 3359), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', 'c2', '(7)'], {}), '(x, c2, 7)\n', (3349, 3359), False, 'from scipy.stats import norm\n'), ((2546, 2560), 'numpy.arange', 'np.arange', (['npt'], {}), '(npt)\n', (2555, 2560), True, 'import numpy as np\n'), ((558, 567), 'numpy.min', 'np.min', (['a'], {}), '(a)\n', (564, 567), True, 'import numpy as np\n'), ((570, 579), 'numpy.max', 'np.max', (['a'], {}), '(a)\n', (576, 579), True, 'import numpy as np\n'), ((580, 589), 'numpy.min', 'np.min', (['a'], {}), '(a)\n', (586, 589), True, 'import numpy as np\n'), ((602, 611), 'numpy.min', 'np.min', (['b'], {}), '(b)\n', (608, 611), True, 'import numpy as np\n'), ((614, 623), 'numpy.max', 'np.max', (['b'], {}), '(b)\n', (620, 623), True, 'import numpy as np\n'), ((624, 633), 'numpy.min', 'np.min', (['b'], {}), '(b)\n', (630, 633), True, 'import numpy as np\n'), ((1999, 2013), 'numpy.min', 'np.min', (['c_corr'], {}), '(c_corr)\n', (2005, 2013), True, 'import numpy as np\n'), ((2016, 2030), 'numpy.max', 'np.max', (['c_corr'], {}), '(c_corr)\n', (2022, 2030), True, 'import numpy as np\n'), ((2031, 2045), 'numpy.min', 'np.min', (['c_corr'], {}), '(c_corr)\n', (2037, 2045), True, 'import numpy as np\n'), ((3204, 3218), 'numpy.arange', 'np.arange', (['(100)'], {}), '(100)\n', (3213, 3218), True, 'import numpy as np\n'), ((2863, 2877), 'numpy.max', 'np.max', (['c_corr'], {}), '(c_corr)\n', (2869, 2877), True, 'import numpy as np\n')]
import ray from environment.rrt import RRTWrapper from environment import utils from environment import RealTimeEnv from utils import ( parse_args, load_config, create_policies, exit_handler ) from environment import TaskLoader import pickle from signal import signal, SIGINT from numpy import mean from distribute import Pool from os.path import exists from tqdm import tqdm if __name__ == "__main__": args = parse_args() args.gui = True config = load_config(args.config) env_conf = config['environment'] training_conf = config['training'] env_conf['min_ur5s_count'] = 1 env_conf['max_ur5s_count'] = 10 env_conf['task']['type'] = 'dynamic' ray.init() signal(SIGINT, lambda sig, frame: exit()) output_path = 'rrt_dynamic_benchmark_score.pkl' if args.load: output_path = 'policy_dynamic_benchmark_score.pkl' benchmark_results = [] continue_benchmark = False if exists(output_path): # continue benchmark benchmark_results = pickle.load(open(output_path, 'rb')) continue_benchmark = True finished_task_paths = [r['task']['task_path'] for r in benchmark_results] task_loader = TaskLoader( root_dir=args.tasks_path, shuffle=True, repeat=False) training_conf['task_loader'] = task_loader # set up policy if loaded if args.load: obs_dim = utils.get_observation_dimensions( training_conf['observations']) action_dim = 6 policy_manager = create_policies( args=args, training_config=config['training'], action_dim=action_dim, actor_obs_dim=obs_dim, critic_obs_dim=obs_dim, training=args.mode == 'train', logger=None, device='cpu') policy = policy_manager.get_inference_nodes()[ 'multiarm_motion_planner'] policy.policy.to('cpu') training_conf['policy'] = policy env = RealTimeEnv( env_config=env_conf, training_config=training_conf, gui=args.gui, logger=None) env.set_memory_cluster_map(policy_manager.memory_map) else: RealTimeEnv = ray.remote(RealTimeEnv) envs = [RealTimeEnv.remote( env_config=env_conf, training_config=training_conf, gui=args.gui, logger=None) for _ in range(args.num_processes)] env_pool = Pool(envs) def callback(result): benchmark_results.append(result) if len(benchmark_results) % 100 == 0\ and len(benchmark_results) > 0: print('Saving benchmark scores to ', output_path) with open(output_path, 'wb') as f: pickle.dump(benchmark_results, f) def pbar_update(pbar): pbar.set_description( 'Average Success Rate : {:.04f}'.format( mean([r['success_rate'] for r in benchmark_results]))) tasks = [t for t in task_loader if not continue_benchmark or t.task_path not in finished_task_paths] if args.load: with tqdm(tasks, dynamic_ncols=True, smoothing=0.01) as pbar: for task in pbar: callback(env.solve_task(task)) pbar_update(pbar) else: benchmark_results = env_pool.map( exec_fn=lambda env, task: env.solve_task.remote(task), iterable=tasks, pbar_update=pbar_update, callback_fn=callback )
[ "os.path.exists", "numpy.mean", "pickle.dump", "environment.TaskLoader", "distribute.Pool", "tqdm.tqdm", "utils.parse_args", "environment.utils.get_observation_dimensions", "utils.load_config", "environment.RealTimeEnv", "utils.create_policies", "ray.remote", "ray.init", "environment.RealT...
[((432, 444), 'utils.parse_args', 'parse_args', ([], {}), '()\n', (442, 444), False, 'from utils import parse_args, load_config, create_policies, exit_handler\n'), ((478, 502), 'utils.load_config', 'load_config', (['args.config'], {}), '(args.config)\n', (489, 502), False, 'from utils import parse_args, load_config, create_policies, exit_handler\n'), ((695, 705), 'ray.init', 'ray.init', ([], {}), '()\n', (703, 705), False, 'import ray\n'), ((948, 967), 'os.path.exists', 'exists', (['output_path'], {}), '(output_path)\n', (954, 967), False, 'from os.path import exists\n'), ((1229, 1293), 'environment.TaskLoader', 'TaskLoader', ([], {'root_dir': 'args.tasks_path', 'shuffle': '(True)', 'repeat': '(False)'}), '(root_dir=args.tasks_path, shuffle=True, repeat=False)\n', (1239, 1293), False, 'from environment import TaskLoader\n'), ((1432, 1495), 'environment.utils.get_observation_dimensions', 'utils.get_observation_dimensions', (["training_conf['observations']"], {}), "(training_conf['observations'])\n", (1464, 1495), False, 'from environment import utils\n'), ((1557, 1757), 'utils.create_policies', 'create_policies', ([], {'args': 'args', 'training_config': "config['training']", 'action_dim': 'action_dim', 'actor_obs_dim': 'obs_dim', 'critic_obs_dim': 'obs_dim', 'training': "(args.mode == 'train')", 'logger': 'None', 'device': '"""cpu"""'}), "(args=args, training_config=config['training'], action_dim=\n action_dim, actor_obs_dim=obs_dim, critic_obs_dim=obs_dim, training=\n args.mode == 'train', logger=None, device='cpu')\n", (1572, 1757), False, 'from utils import parse_args, load_config, create_policies, exit_handler\n'), ((2027, 2122), 'environment.RealTimeEnv', 'RealTimeEnv', ([], {'env_config': 'env_conf', 'training_config': 'training_conf', 'gui': 'args.gui', 'logger': 'None'}), '(env_config=env_conf, training_config=training_conf, gui=args.\n gui, logger=None)\n', (2038, 2122), False, 'from environment import RealTimeEnv\n'), ((2261, 2284), 'ray.remote', 'ray.remote', (['RealTimeEnv'], {}), '(RealTimeEnv)\n', (2271, 2284), False, 'import ray\n'), ((2515, 2525), 'distribute.Pool', 'Pool', (['envs'], {}), '(envs)\n', (2519, 2525), False, 'from distribute import Pool\n'), ((2301, 2403), 'environment.RealTimeEnv.remote', 'RealTimeEnv.remote', ([], {'env_config': 'env_conf', 'training_config': 'training_conf', 'gui': 'args.gui', 'logger': 'None'}), '(env_config=env_conf, training_config=training_conf, gui=\n args.gui, logger=None)\n', (2319, 2403), False, 'from environment import RealTimeEnv\n'), ((3232, 3279), 'tqdm.tqdm', 'tqdm', (['tasks'], {'dynamic_ncols': '(True)', 'smoothing': '(0.01)'}), '(tasks, dynamic_ncols=True, smoothing=0.01)\n', (3236, 3279), False, 'from tqdm import tqdm\n'), ((2832, 2865), 'pickle.dump', 'pickle.dump', (['benchmark_results', 'f'], {}), '(benchmark_results, f)\n', (2843, 2865), False, 'import pickle\n'), ((2993, 3045), 'numpy.mean', 'mean', (["[r['success_rate'] for r in benchmark_results]"], {}), "([r['success_rate'] for r in benchmark_results])\n", (2997, 3045), False, 'from numpy import mean\n')]
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for post export metrics. Note that we actually train and export models within these tests. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import apache_beam as beam from apache_beam.testing import util import numpy as np import tensorflow as tf from tensorflow_model_analysis.api.impl import evaluate from tensorflow_model_analysis.eval_saved_model import testutil from tensorflow_model_analysis.eval_saved_model.example_trainers import fixed_prediction_estimator from tensorflow_model_analysis.eval_saved_model.example_trainers import fixed_prediction_estimator_extra_fields from tensorflow_model_analysis.eval_saved_model.example_trainers import linear_classifier from tensorflow_model_analysis.eval_saved_model.example_trainers import linear_regressor from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics import tensorflow_model_analysis.eval_saved_model.post_export_metrics.metric_keys as metric_keys class PostExportMetricsTest(testutil.TensorflowModelAnalysisTest): def _getEvalExportDir(self): return os.path.join(self._getTempDir(), 'eval_export_dir') def _runTestWithCustomCheck(self, examples, eval_export_dir, metrics, custom_metrics_check=None, custom_plots_check=None): # make sure we are doing some checks self.assertTrue(custom_metrics_check is not None or custom_plots_check is not None) serialized_examples = [ex.SerializeToString() for ex in examples] with beam.Pipeline() as pipeline: metrics, plots = ( pipeline | beam.Create(serialized_examples) | evaluate.Evaluate( eval_saved_model_path=eval_export_dir, add_metrics_callbacks=metrics)) if custom_metrics_check is not None: util.assert_that(metrics, custom_metrics_check, label='metrics') if custom_plots_check is not None: util.assert_that(plots, custom_plots_check, label='plot') def _runTest(self, examples, eval_export_dir, metrics_to_check): metrics = [metric for (_, metric, _) in metrics_to_check] expected_values_dict = { name: expected for (name, _, expected) in metrics_to_check } def check_result(got): # pylint: disable=invalid-name try: self.assertEqual(1, len(got), 'got: %s' % got) (slice_key, value) = got[0] self.assertEqual((), slice_key) self.assertDictElementsAlmostEqual(value, expected_values_dict) except AssertionError as err: raise util.BeamAssertException(err) self._runTestWithCustomCheck( examples, eval_export_dir, metrics, custom_metrics_check=check_result) def testPostExportMetricsLinearClassifier(self): temp_eval_export_dir = self._getEvalExportDir() _, eval_export_dir = linear_classifier.simple_linear_classifier( None, temp_eval_export_dir) examples = [ self._makeExample(age=3.0, language='english', label=1.0), self._makeExample(age=3.0, language='chinese', label=0.0), self._makeExample(age=4.0, language='english', label=1.0), self._makeExample(age=5.0, language='chinese', label=0.0) ] metrics_to_check = [ (metric_keys.EXAMPLE_COUNT, post_export_metrics.example_count(), 4.0), (metric_keys.EXAMPLE_WEIGHT, post_export_metrics.example_weight('age'), 15.0), ] self._runTest(examples, eval_export_dir, metrics_to_check) def testPostExportMetricsLinearRegressor(self): temp_eval_export_dir = self._getEvalExportDir() _, eval_export_dir = linear_regressor.simple_linear_regressor( None, temp_eval_export_dir) examples = [ self._makeExample(age=3.0, language='english', label=1.0), self._makeExample(age=3.0, language='chinese', label=0.0), self._makeExample(age=4.0, language='english', label=1.0), self._makeExample(age=5.0, language='chinese', label=0.0) ] metrics_to_check = [ (metric_keys.EXAMPLE_COUNT, post_export_metrics.example_count(), 4.0), (metric_keys.EXAMPLE_WEIGHT, post_export_metrics.example_weight('age'), 15.0), ] self._runTest(examples, eval_export_dir, metrics_to_check) def testCalibrationPlotAndPredictionHistogramUnweighted(self): temp_eval_export_dir = self._getEvalExportDir() _, eval_export_dir = ( fixed_prediction_estimator.simple_fixed_prediction_estimator( None, temp_eval_export_dir)) examples = [ # For each example, we set label to prediction + 1. # These two go in bucket 0: (-inf, 0) self._makeExample(prediction=-10.0, label=-9.0), self._makeExample(prediction=-9.0, label=-8.0), # This goes in bucket 1: [0, 0.00100) self._makeExample(prediction=0.00000, label=1.00000), # These three go in bucket 1: [0.00100, 0.00110) self._makeExample(prediction=0.00100, label=1.00100), self._makeExample(prediction=0.00101, label=1.00101), self._makeExample(prediction=0.00102, label=1.00102), # These two go in bucket 10000: [0.99990, 1.00000) self._makeExample(prediction=0.99998, label=1.99998), self._makeExample(prediction=0.99999, label=1.99999), # These four go in bucket 10001: [1.0000, +inf) self._makeExample(prediction=1.0, label=2.0), self._makeExample(prediction=8.0, label=9.0), self._makeExample(prediction=9.0, label=10.0), self._makeExample(prediction=10.0, label=11.0), ] def check_result(got): # pylint: disable=invalid-name try: self.assertEqual(1, len(got), 'got: %s' % got) (slice_key, value) = got[0] self.assertEqual((), slice_key) self.assertIn(metric_keys.CALIBRATION_PLOT_MATRICES, value) buckets = value[metric_keys.CALIBRATION_PLOT_MATRICES] self.assertSequenceAlmostEqual(buckets[0], [-19.0, -17.0, 2.0]) self.assertSequenceAlmostEqual(buckets[1], [0.0, 1.0, 1.0]) self.assertSequenceAlmostEqual(buckets[11], [0.00303, 3.00303, 3.0]) self.assertSequenceAlmostEqual(buckets[10000], [1.99997, 3.99997, 2.0]) self.assertSequenceAlmostEqual(buckets[10001], [28.0, 32.0, 4.0]) self.assertIn(metric_keys.CALIBRATION_PLOT_BOUNDARIES, value) boundaries = value[metric_keys.CALIBRATION_PLOT_BOUNDARIES] self.assertAlmostEqual(0.0, boundaries[0]) self.assertAlmostEqual(0.001, boundaries[10]) self.assertAlmostEqual(0.005, boundaries[50]) self.assertAlmostEqual(0.010, boundaries[100]) self.assertAlmostEqual(0.100, boundaries[1000]) self.assertAlmostEqual(0.800, boundaries[8000]) self.assertAlmostEqual(1.000, boundaries[10000]) except AssertionError as err: raise util.BeamAssertException(err) self._runTestWithCustomCheck( examples, eval_export_dir, [post_export_metrics.calibration_plot_and_prediction_histogram()], custom_plots_check=check_result) def testCalibrationPlotAndPredictionHistogramWeighted(self): temp_eval_export_dir = self._getEvalExportDir() _, eval_export_dir = ( fixed_prediction_estimator_extra_fields. simple_fixed_prediction_estimator_extra_fields(None, temp_eval_export_dir)) examples = [ # For each example, we set label to prediction + 1. self._makeExample( prediction=-10.0, label=-9.0, fixed_float=1.0, fixed_string=''), self._makeExample( prediction=-9.0, label=-8.0, fixed_float=2.0, fixed_string=''), self._makeExample( prediction=0.0000, label=1.0000, fixed_float=0.0, fixed_string=''), self._makeExample( prediction=0.00100, label=1.00100, fixed_float=1.0, fixed_string=''), self._makeExample( prediction=0.00101, label=1.00101, fixed_float=2.0, fixed_string=''), self._makeExample( prediction=0.00102, label=1.00102, fixed_float=3.0, fixed_string=''), self._makeExample( prediction=10.0, label=11.0, fixed_float=7.0, fixed_string=''), ] def check_result(got): # pylint: disable=invalid-name try: self.assertEqual(1, len(got), 'got: %s' % got) (slice_key, value) = got[0] self.assertEqual((), slice_key) self.assertIn(metric_keys.CALIBRATION_PLOT_MATRICES, value) buckets = value[metric_keys.CALIBRATION_PLOT_MATRICES] self.assertSequenceAlmostEqual(buckets[0], [-28.0, -25.0, 3.0]) self.assertSequenceAlmostEqual(buckets[1], [0.0, 0.0, 0.0]) self.assertSequenceAlmostEqual(buckets[11], [0.00608, 6.00608, 6.0]) self.assertSequenceAlmostEqual(buckets[10001], [70.0, 77.0, 7.0]) except AssertionError as err: raise util.BeamAssertException(err) self._runTestWithCustomCheck( examples, eval_export_dir, [ post_export_metrics.calibration_plot_and_prediction_histogram( example_weight_key='fixed_float') ], custom_plots_check=check_result) def testAucPlotsUnweighted(self): temp_eval_export_dir = self._getEvalExportDir() _, eval_export_dir = ( fixed_prediction_estimator.simple_fixed_prediction_estimator( None, temp_eval_export_dir)) examples = [ self._makeExample(prediction=0.0000, label=0.0000), self._makeExample(prediction=0.0000, label=1.0000), self._makeExample(prediction=0.7000, label=1.0000), self._makeExample(prediction=0.8000, label=0.0000), self._makeExample(prediction=1.0000, label=1.0000), ] def check_result(got): # pylint: disable=invalid-name try: self.assertEqual(1, len(got), 'got: %s' % got) (slice_key, value) = got[0] self.assertEqual((), slice_key) self.assertIn(metric_keys.AUC_PLOTS_MATRICES, value) matrices = value[metric_keys.AUC_PLOTS_MATRICES] # | | --------- Threshold ----------- # true label | pred | -1e-6 | 0.0 | 0.7 | 0.8 | 1.0 # - | 0.0 | FP | TN | TN | TN | TN # + | 0.0 | TP | FN | FN | FN | FN # + | 0.7 | TP | TP | FN | FN | FN # - | 0.8 | FP | FP | FP | TN | TN # + | 1.0 | TP | TP | TP | TP | FN self.assertSequenceAlmostEqual(matrices[0], [0, 0, 2, 3, 3.0 / 5.0, 1.0]) self.assertSequenceAlmostEqual(matrices[1], [1, 1, 1, 2, 2.0 / 3.0, 2.0 / 3.0]) self.assertSequenceAlmostEqual(matrices[7001], [2, 1, 1, 1, 1.0 / 2.0, 1.0 / 3.0]) self.assertSequenceAlmostEqual(matrices[8001], [2, 2, 0, 1, 1.0 / 1.0, 1.0 / 3.0]) self.assertSequenceAlmostEqual( matrices[10001], [3, 2, 0, 0, float('nan'), 0.0]) self.assertIn(metric_keys.AUC_PLOTS_THRESHOLDS, value) thresholds = value[metric_keys.AUC_PLOTS_THRESHOLDS] self.assertAlmostEqual(0.0, thresholds[1]) self.assertAlmostEqual(0.001, thresholds[11]) self.assertAlmostEqual(0.005, thresholds[51]) self.assertAlmostEqual(0.010, thresholds[101]) self.assertAlmostEqual(0.100, thresholds[1001]) self.assertAlmostEqual(0.800, thresholds[8001]) self.assertAlmostEqual(1.000, thresholds[10001]) except AssertionError as err: raise util.BeamAssertException(err) self._runTestWithCustomCheck( examples, eval_export_dir, [post_export_metrics.auc_plots()], custom_plots_check=check_result) def testCalibrationPlotAndPredictionHistogramLinearClassifier(self): temp_eval_export_dir = self._getEvalExportDir() _, eval_export_dir = ( linear_classifier.simple_linear_classifier(None, temp_eval_export_dir)) examples = [ self._makeExample(age=3.0, language='english', label=1.0), self._makeExample(age=3.0, language='chinese', label=0.0), self._makeExample(age=4.0, language='english', label=1.0), self._makeExample(age=5.0, language='chinese', label=0.0) ] def check_result(got): # pylint: disable=invalid-name try: self.assertEqual(1, len(got), 'got: %s' % got) (slice_key, value) = got[0] self.assertEqual((), slice_key) self.assertIn(metric_keys.CALIBRATION_PLOT_MATRICES, value) # We just check that the bucket sums look sane, since we don't know # the exact predictions of the model. # # Note that the correctness of the bucketing is tested in the other # two tests with the fixed prediction estimator. This test is more # for ensuring that this metric is compatible with the canned # Estimators, for which the prediction Tensor returned for a batch # of examples will be a N x 1 Tensor, rather than just an N element # vector. buckets = value[metric_keys.CALIBRATION_PLOT_MATRICES] bucket_sums = np.sum(buckets, axis=0) self.assertAlmostEqual(bucket_sums[1], 2.0) # label sum self.assertAlmostEqual(bucket_sums[2], 4.0) # weight sum except AssertionError as err: raise util.BeamAssertException(err) self._runTestWithCustomCheck( examples, eval_export_dir, [post_export_metrics.calibration_plot_and_prediction_histogram()], custom_plots_check=check_result) if __name__ == '__main__': tf.test.main()
[ "tensorflow_model_analysis.eval_saved_model.example_trainers.fixed_prediction_estimator.simple_fixed_prediction_estimator", "tensorflow_model_analysis.eval_saved_model.example_trainers.fixed_prediction_estimator_extra_fields.simple_fixed_prediction_estimator_extra_fields", "tensorflow_model_analysis.api.impl.ev...
[((14448, 14462), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (14460, 14462), True, 'import tensorflow as tf\n'), ((3586, 3656), 'tensorflow_model_analysis.eval_saved_model.example_trainers.linear_classifier.simple_linear_classifier', 'linear_classifier.simple_linear_classifier', (['None', 'temp_eval_export_dir'], {}), '(None, temp_eval_export_dir)\n', (3628, 3656), False, 'from tensorflow_model_analysis.eval_saved_model.example_trainers import linear_classifier\n'), ((4353, 4421), 'tensorflow_model_analysis.eval_saved_model.example_trainers.linear_regressor.simple_linear_regressor', 'linear_regressor.simple_linear_regressor', (['None', 'temp_eval_export_dir'], {}), '(None, temp_eval_export_dir)\n', (4393, 4421), False, 'from tensorflow_model_analysis.eval_saved_model.example_trainers import linear_regressor\n'), ((5143, 5235), 'tensorflow_model_analysis.eval_saved_model.example_trainers.fixed_prediction_estimator.simple_fixed_prediction_estimator', 'fixed_prediction_estimator.simple_fixed_prediction_estimator', (['None', 'temp_eval_export_dir'], {}), '(None,\n temp_eval_export_dir)\n', (5203, 5235), False, 'from tensorflow_model_analysis.eval_saved_model.example_trainers import fixed_prediction_estimator\n'), ((7947, 8066), 'tensorflow_model_analysis.eval_saved_model.example_trainers.fixed_prediction_estimator_extra_fields.simple_fixed_prediction_estimator_extra_fields', 'fixed_prediction_estimator_extra_fields.simple_fixed_prediction_estimator_extra_fields', (['None', 'temp_eval_export_dir'], {}), '(\n None, temp_eval_export_dir)\n', (8033, 8066), False, 'from tensorflow_model_analysis.eval_saved_model.example_trainers import fixed_prediction_estimator_extra_fields\n'), ((10075, 10167), 'tensorflow_model_analysis.eval_saved_model.example_trainers.fixed_prediction_estimator.simple_fixed_prediction_estimator', 'fixed_prediction_estimator.simple_fixed_prediction_estimator', (['None', 'temp_eval_export_dir'], {}), '(None,\n temp_eval_export_dir)\n', (10135, 10167), False, 'from tensorflow_model_analysis.eval_saved_model.example_trainers import fixed_prediction_estimator\n'), ((12748, 12818), 'tensorflow_model_analysis.eval_saved_model.example_trainers.linear_classifier.simple_linear_classifier', 'linear_classifier.simple_linear_classifier', (['None', 'temp_eval_export_dir'], {}), '(None, temp_eval_export_dir)\n', (12790, 12818), False, 'from tensorflow_model_analysis.eval_saved_model.example_trainers import linear_classifier\n'), ((2278, 2293), 'apache_beam.Pipeline', 'beam.Pipeline', ([], {}), '()\n', (2291, 2293), True, 'import apache_beam as beam\n'), ((2408, 2499), 'tensorflow_model_analysis.api.impl.evaluate.Evaluate', 'evaluate.Evaluate', ([], {'eval_saved_model_path': 'eval_export_dir', 'add_metrics_callbacks': 'metrics'}), '(eval_saved_model_path=eval_export_dir,\n add_metrics_callbacks=metrics)\n', (2425, 2499), False, 'from tensorflow_model_analysis.api.impl import evaluate\n'), ((2577, 2641), 'apache_beam.testing.util.assert_that', 'util.assert_that', (['metrics', 'custom_metrics_check'], {'label': '"""metrics"""'}), "(metrics, custom_metrics_check, label='metrics')\n", (2593, 2641), False, 'from apache_beam.testing import util\n'), ((2691, 2748), 'apache_beam.testing.util.assert_that', 'util.assert_that', (['plots', 'custom_plots_check'], {'label': '"""plot"""'}), "(plots, custom_plots_check, label='plot')\n", (2707, 2748), False, 'from apache_beam.testing import util\n'), ((4017, 4052), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.example_count', 'post_export_metrics.example_count', ([], {}), '()\n', (4050, 4052), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((4097, 4138), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.example_weight', 'post_export_metrics.example_weight', (['"""age"""'], {}), "('age')\n", (4131, 4138), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((4782, 4817), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.example_count', 'post_export_metrics.example_count', ([], {}), '()\n', (4815, 4817), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((4862, 4903), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.example_weight', 'post_export_metrics.example_weight', (['"""age"""'], {}), "('age')\n", (4896, 4903), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((7689, 7752), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.calibration_plot_and_prediction_histogram', 'post_export_metrics.calibration_plot_and_prediction_histogram', ([], {}), '()\n', (7750, 7752), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((9786, 9886), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.calibration_plot_and_prediction_histogram', 'post_export_metrics.calibration_plot_and_prediction_histogram', ([], {'example_weight_key': '"""fixed_float"""'}), "(\n example_weight_key='fixed_float')\n", (9847, 9886), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((12514, 12545), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.auc_plots', 'post_export_metrics.auc_plots', ([], {}), '()\n', (12543, 12545), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((13988, 14011), 'numpy.sum', 'np.sum', (['buckets'], {'axis': '(0)'}), '(buckets, axis=0)\n', (13994, 14011), True, 'import numpy as np\n'), ((14310, 14373), 'tensorflow_model_analysis.eval_saved_model.post_export_metrics.post_export_metrics.calibration_plot_and_prediction_histogram', 'post_export_metrics.calibration_plot_and_prediction_histogram', ([], {}), '()\n', (14371, 14373), False, 'from tensorflow_model_analysis.eval_saved_model.post_export_metrics import post_export_metrics\n'), ((2363, 2395), 'apache_beam.Create', 'beam.Create', (['serialized_examples'], {}), '(serialized_examples)\n', (2374, 2395), True, 'import apache_beam as beam\n'), ((3313, 3342), 'apache_beam.testing.util.BeamAssertException', 'util.BeamAssertException', (['err'], {}), '(err)\n', (3337, 3342), False, 'from apache_beam.testing import util\n'), ((7572, 7601), 'apache_beam.testing.util.BeamAssertException', 'util.BeamAssertException', (['err'], {}), '(err)\n', (7596, 7601), False, 'from apache_beam.testing import util\n'), ((9664, 9693), 'apache_beam.testing.util.BeamAssertException', 'util.BeamAssertException', (['err'], {}), '(err)\n', (9688, 9693), False, 'from apache_beam.testing import util\n'), ((12405, 12434), 'apache_beam.testing.util.BeamAssertException', 'util.BeamAssertException', (['err'], {}), '(err)\n', (12429, 12434), False, 'from apache_beam.testing import util\n'), ((14193, 14222), 'apache_beam.testing.util.BeamAssertException', 'util.BeamAssertException', (['err'], {}), '(err)\n', (14217, 14222), False, 'from apache_beam.testing import util\n')]
# -*- coding: utf-8 -*- import numpy as np import binarybrain as bb import binarybrain.core as core # ----- LUT Layer ----- def make_verilog_lut_layers(module_name: str, net, device=""): layers = bb.get_model_list(net, flatten=True) core_layers = [] for layer in layers: core_layers.append(layer.get_core()) return core.make_verilog_lut_layers(module_name, core_layers, device) def dump_verilog_lut_layers(f, module_name: str, net, device=""): ''' make verilog source of LUT layers 変換できないモデルは影響ない層とみなして無視するので注意 Args: f (StreamIO) : 出力先ストリーム module_name (str): モジュール名 net (Model): 変換するネット Returns: Verilog source code (str) ''' f.write(make_verilog_lut_layers(module_name=module_name, net=net, device=device)) def export_verilog_lut_layers(file_name: str, module_name: str, net): with open(file_name, 'w') as f: dump_verilog_lut_layers(f, module_name, net) # ----- Convolutional LUT Layer ----- def make_verilog_lut_cnv_layers(module_name: str, net, device=""): layers = bb.get_model_list_for_rtl(net) core_layers = [] for layer in layers: core_layers.append(layer.get_core()) return core.make_verilog_lut_cnv_layers(module_name, core_layers, device) def dump_verilog_lut_cnv_layers(f, module_name: str, net, device=""): ''' dump verilog source of Convolutional LUT layers 畳み込み層を含むネットを AXI4 Stream Video 形式のVerilogソースコードして 出力する。 縮小を伴う MaxPooling 層は最後に1個だけ挿入を許される Args: f (StreamIO) : 出力先ストリーム module_name (str): モジュール名 net (Model): 変換するネット ''' f.write(make_verilog_lut_cnv_layers(module_name, net, device)) def export_verilog_lut_cnv_layers(file_name: str, module_name: str, net, device=""): with open(file_name, 'w') as f: dump_verilog_lut_cnv_layers(f, module_name, net, device) # ----- For Simuration ----- def __dump_bin_digit(f, v): if v: f.write('1') else: f.write('0') def __dump_bin_int(f, v, digits): for i in range(digits): __dump_bin_digit(f, ((v >> (digits-1-i)) & 1)) def __dump_bin_img(f, img): img = np.array(img).flatten()[::-1] for v in img: __dump_bin_digit(f, v > 0.5) def dump_verilog_readmemb_image_classification(f, loader, *, class_digits=8): """verilog用データダンプ verilog の $readmemb() での読み込み用データ作成 クラスID + 画像データの形式で出力する Args: f (StreamIO): 出力先 loader (Loader): モジュール名 class_digits (int): クラス分類のbit数 """ for images, labels in loader: for x, t in zip(images, labels): __dump_bin_int(f, t, class_digits) f.write('_') __dump_bin_img(f, x) f.write('\n') def make_image_tile(rows, cols, img_gen): """画像をタイル状に並べて大きな画像にする 学習用の c, h, w 順の画像データをタイル状に結合する Args: rows (int)): 縦の結合枚数 cols (int)): 横の結合枚数 gen (ndarray): 画像を返すジェネレータ Returns: img (ndarray) : 作成した画像 """ def make_image_tile_h(cols, img_gen): img = img_gen.__next__() for _ in range(1, cols): img = np.concatenate((img, img_gen.__next__()), axis=img.ndim-1) return img img = make_image_tile_h(cols, img_gen) for _ in range(1, rows): img = np.concatenate((img, make_image_tile_h(cols, img_gen)), axis=img.ndim-2) return img def write_ppm(fname, img): """ppmファイルの出力 学習用の c, h, w 順の画像データを ppm形式で保存する Args: fname (str): 出力ファイル名 img (ndarray): モジュール名 """ # gray to color if img.ndim == 3 and img.shape[0] == 1: img = np.tile(img, (3, 1, 1)) elif img.ndim == 2: img = np.stack((img, img, img)) # shpe check assert(img.ndim == 3 and img.shape[0] >= 3) # write with open(fname, 'w') as f: f.write('P3\n') f.write('%d %d\n' % (img.shape[2], img.shape[1])) f.write('255\n') img = img.transpose(1, 2, 0).reshape(-1, 3) for v in img: f.write('%d %d %d\n' % (v[0], v[1], v[2]))
[ "numpy.tile", "binarybrain.core.make_verilog_lut_cnv_layers", "binarybrain.get_model_list_for_rtl", "numpy.stack", "numpy.array", "binarybrain.get_model_list", "binarybrain.core.make_verilog_lut_layers" ]
[((210, 246), 'binarybrain.get_model_list', 'bb.get_model_list', (['net'], {'flatten': '(True)'}), '(net, flatten=True)\n', (227, 246), True, 'import binarybrain as bb\n'), ((349, 411), 'binarybrain.core.make_verilog_lut_layers', 'core.make_verilog_lut_layers', (['module_name', 'core_layers', 'device'], {}), '(module_name, core_layers, device)\n', (377, 411), True, 'import binarybrain.core as core\n'), ((1129, 1159), 'binarybrain.get_model_list_for_rtl', 'bb.get_model_list_for_rtl', (['net'], {}), '(net)\n', (1154, 1159), True, 'import binarybrain as bb\n'), ((1262, 1328), 'binarybrain.core.make_verilog_lut_cnv_layers', 'core.make_verilog_lut_cnv_layers', (['module_name', 'core_layers', 'device'], {}), '(module_name, core_layers, device)\n', (1294, 1328), True, 'import binarybrain.core as core\n'), ((3711, 3734), 'numpy.tile', 'np.tile', (['img', '(3, 1, 1)'], {}), '(img, (3, 1, 1))\n', (3718, 3734), True, 'import numpy as np\n'), ((3773, 3798), 'numpy.stack', 'np.stack', (['(img, img, img)'], {}), '((img, img, img))\n', (3781, 3798), True, 'import numpy as np\n'), ((2244, 2257), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (2252, 2257), True, 'import numpy as np\n')]
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import configparser import argparse import visdom import tqdm from os import path import numpy as np from tabulate import tabulate from torchvision import datasets, transforms, models from torchlib.dataloader import PPPP from torchlib.models import vgg16, resnet18, conv_at_resolution from torchlib.utils import LearningRateScheduler, Arguments, train, test, save_model if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--config", type=str, required=True, default="configs/pneumonia.ini", help="Path to config", ) parser.add_argument( "--train_federated", action="store_true", help="Train in federated setting" ) parser.add_argument( "--dataset", type=str, default="pneumonia", choices=["pneumonia", "mnist"], help="which dataset?", ) parser.add_argument( "--no_visdom", action="store_false", help="dont use a visdom server" ) parser.add_argument( "--no_cuda", action="store_true", help="dont use a visdom server" ) parser.add_argument( "--start_at_epoch", type=int, default=1, help="At which epoch should the training start?", ) parser.add_argument( "--resume_checkpoint", type=str, default=None, help="Start training from older model checkpoint", ) cmd_args = parser.parse_args() config = configparser.ConfigParser() assert path.isfile(cmd_args.config), "config file not found" config.read(cmd_args.config) args = Arguments(cmd_args, config, mode='train') if args.train_federated: import syft as sy hook = sy.TorchHook( torch ) # <-- NEW: hook PyTorch ie add extra functionalities to support Federated Learning bob = sy.VirtualWorker(hook, id="bob") # <-- NEW: define remote worker bob alice = sy.VirtualWorker(hook, id="alice") # <-- NEW: and alice charlie = sy.VirtualWorker(hook, id="charlie") # <-- NEW: and alice use_cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) device = torch.device("cuda" if use_cuda else "cpu") # pylint: disable=no-member kwargs = {"num_workers": 1, "pin_memory": True} if use_cuda else {} if args.dataset == "mnist": num_classes = 10 dataset = datasets.MNIST( "../data", train=True, download=True, transform=transforms.Compose( [ transforms.Resize(args.train_resolution), transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), ] ), ) testset = datasets.MNIST( "../data", train=False, transform=transforms.Compose( [ transforms.Resize(args.inference_resolution), transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), ] ), ) elif args.dataset == "pneumonia": num_classes = 3 train_tf = transforms.Compose( [ transforms.Resize(args.inference_resolution), transforms.RandomCrop(args.train_resolution), transforms.ToTensor(), ] ) # TODO: Add normalization test_tf = transforms.Compose( [ transforms.Resize(args.inference_resolution), transforms.CenterCrop(args.inference_resolution), transforms.ToTensor(), ] ) dataset = PPPP("data/Labels.csv", train=True, transform=train_tf) testset = PPPP("data/Labels.csv", train=False, transform=test_tf) else: raise NotImplementedError("dataset not implemented") if args.train_federated: train_loader = sy.FederatedDataLoader( dataset.federate((bob, alice, charlie)), batch_size=args.batch_size, shuffle=True, **kwargs ) else: train_loader = torch.utils.data.DataLoader( dataset, batch_size=args.batch_size, shuffle=True, **kwargs ) test_loader = torch.utils.data.DataLoader( testset, batch_size=args.test_batch_size, shuffle=True, **kwargs ) cw = None if args.class_weights: occurances = {} if hasattr(dataset, "get_class_occurances"): occurances = dataset.get_class_occurances() else: for _, c in tqdm.tqdm( dataset, total=len(dataset), leave=False, desc="calc class weights" ): if c.item() in occurances: occurances[c] += 1 else: occurances[c] = 1 cw = torch.zeros((len(occurances))) # pylint: disable=no-member for c, n in occurances.items(): cw[c] = 1.0 / float(n) cw /= torch.sum(cw) # pylint: disable=no-member scheduler = LearningRateScheduler( args.epochs, np.log10(args.lr), np.log10(args.end_lr) ) ## visdom if args.visdom: vis = visdom.Visdom() assert vis.check_connection( timeout_seconds=3 ), "No connection could be formed quickly" vis_env = "{:s}/{:s}".format( "federated" if args.train_federated else "vanilla", args.dataset ) plt_dict = dict( name="training loss", ytickmax=10, xlabel="epoch", ylabel="loss", legend=["train_loss"], ) vis.line( X=np.zeros((1, 3)), Y=np.zeros((1, 3)), win="loss_win", opts={ "legend": ["train_loss", "val_loss", "accuracy"], "xlabel": "epochs", "ylabel": "loss / accuracy [%]", }, env=vis_env, ) vis.line( X=np.zeros((1, 1)), Y=np.zeros((1, 1)), win="lr_win", opts={"legend": ["learning_rate"], "xlabel": "epochs", "ylabel": "lr"}, env=vis_env, ) vis_params = {"vis": vis, "vis_env": vis_env} # model = Net().to(device) if args.model == 'vgg16': model = vgg16(pretrained=False, num_classes=num_classes, in_channels=1, adptpool=False) elif args.model == 'simpleconv': model = conv_at_resolution[args.train_resolution](num_classes=num_classes) elif args.model == 'resnet-18': model = resnet18(pretrained=False, num_classes=num_classes, in_channels=1, adptpool=False) else: raise NotImplementedError('model unknown') # model = resnet18(pretrained=False, num_classes=num_classes, in_channels=1) # model = models.vgg16(pretrained=False, num_classes=3) # model.classifier = vggclassifier() if args.optimizer == "SGD": optimizer = optim.SGD( model.parameters(), lr=args.lr, weight_decay=args.weight_decay, ) # TODO momentum is not supported at the moment elif args.optimizer == "Adam": optimizer = optim.Adam( model.parameters(), lr=args.lr, betas=(args.beta1, args.beta2), weight_decay=args.weight_decay, ) else: raise NotImplementedError("optimization not implemented") loss_fn = nn.CrossEntropyLoss(weight=cw, reduction="mean") if cmd_args.resume_checkpoint: state = torch.load(cmd_args.resume_checkpoint, map_location=device) if "optim_state_dict" in state: optimizer.load_state_dict(state["optim_state_dict"]) model.load_state_dict(state["model_state_dict"]) else: model.load_state_dict(state) model.to(device) test( args, model, device, test_loader, cmd_args.start_at_epoch - 1, loss_fn, num_classes, vis_params=vis_params, ) for epoch in range(cmd_args.start_at_epoch, args.epochs + 1): new_lr = scheduler.adjust_learning_rate(optimizer, epoch - 1) if args.visdom: vis.line( X=np.asarray([epoch - 1]), Y=np.asarray([new_lr]), win="lr_win", name="learning_rate", update="append", env=vis_env, ) train( args, model, device, train_loader, optimizer, epoch, loss_fn, vis_params=vis_params, ) if (epoch % args.test_interval) == 0: test( args, model, device, test_loader, epoch, loss_fn, num_classes=num_classes, vis_params=vis_params, ) if args.save_model and (epoch % args.save_interval) == 0: save_model( model, optimizer, "model_weights/{:s}_{:s}_epoch_{:03d}.pt".format( "federated" if args.train_federated else "vanilla", args.dataset, epoch, ), ) if args.save_model: save_model( model, optimizer, "model_weights/{:s}_{:s}_final.pt".format( "federated" if args.train_federated else "vanilla", args.dataset ), )
[ "numpy.log10", "torchlib.utils.Arguments", "configparser.ConfigParser", "torch.nn.CrossEntropyLoss", "torchlib.models.vgg16", "torch.cuda.is_available", "torch.sum", "visdom.Visdom", "syft.VirtualWorker", "argparse.ArgumentParser", "numpy.asarray", "torchvision.transforms.ToTensor", "torchli...
[((507, 532), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (530, 532), False, 'import argparse\n'), ((1559, 1586), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1584, 1586), False, 'import configparser\n'), ((1598, 1626), 'os.path.isfile', 'path.isfile', (['cmd_args.config'], {}), '(cmd_args.config)\n', (1609, 1626), False, 'from os import path\n'), ((1697, 1738), 'torchlib.utils.Arguments', 'Arguments', (['cmd_args', 'config'], {'mode': '"""train"""'}), "(cmd_args, config, mode='train')\n", (1706, 1738), False, 'from torchlib.utils import LearningRateScheduler, Arguments, train, test, save_model\n'), ((2239, 2267), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (2256, 2267), False, 'import torch\n'), ((2282, 2325), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (2294, 2325), False, 'import torch\n'), ((4405, 4502), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['testset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(True)'}), '(testset, batch_size=args.test_batch_size,\n shuffle=True, **kwargs)\n', (4432, 4502), False, 'import torch\n'), ((7556, 7604), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'weight': 'cw', 'reduction': '"""mean"""'}), "(weight=cw, reduction='mean')\n", (7575, 7604), True, 'import torch.nn as nn\n'), ((7972, 8088), 'torchlib.utils.test', 'test', (['args', 'model', 'device', 'test_loader', '(cmd_args.start_at_epoch - 1)', 'loss_fn', 'num_classes'], {'vis_params': 'vis_params'}), '(args, model, device, test_loader, cmd_args.start_at_epoch - 1, loss_fn,\n num_classes, vis_params=vis_params)\n', (7976, 8088), False, 'from torchlib.utils import LearningRateScheduler, Arguments, train, test, save_model\n'), ((1811, 1830), 'syft.TorchHook', 'sy.TorchHook', (['torch'], {}), '(torch)\n', (1823, 1830), True, 'import syft as sy\n'), ((1951, 1983), 'syft.VirtualWorker', 'sy.VirtualWorker', (['hook'], {'id': '"""bob"""'}), "(hook, id='bob')\n", (1967, 1983), True, 'import syft as sy\n'), ((2037, 2071), 'syft.VirtualWorker', 'sy.VirtualWorker', (['hook'], {'id': '"""alice"""'}), "(hook, id='alice')\n", (2053, 2071), True, 'import syft as sy\n'), ((2112, 2148), 'syft.VirtualWorker', 'sy.VirtualWorker', (['hook'], {'id': '"""charlie"""'}), "(hook, id='charlie')\n", (2128, 2148), True, 'import syft as sy\n'), ((2208, 2233), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2231, 2233), False, 'import torch\n'), ((4275, 4368), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(dataset, batch_size=args.batch_size, shuffle=\n True, **kwargs)\n', (4302, 4368), False, 'import torch\n'), ((5139, 5152), 'torch.sum', 'torch.sum', (['cw'], {}), '(cw)\n', (5148, 5152), False, 'import torch\n'), ((5243, 5260), 'numpy.log10', 'np.log10', (['args.lr'], {}), '(args.lr)\n', (5251, 5260), True, 'import numpy as np\n'), ((5262, 5283), 'numpy.log10', 'np.log10', (['args.end_lr'], {}), '(args.end_lr)\n', (5270, 5283), True, 'import numpy as np\n'), ((5339, 5354), 'visdom.Visdom', 'visdom.Visdom', ([], {}), '()\n', (5352, 5354), False, 'import visdom\n'), ((6470, 6549), 'torchlib.models.vgg16', 'vgg16', ([], {'pretrained': '(False)', 'num_classes': 'num_classes', 'in_channels': '(1)', 'adptpool': '(False)'}), '(pretrained=False, num_classes=num_classes, in_channels=1, adptpool=False)\n', (6475, 6549), False, 'from torchlib.models import vgg16, resnet18, conv_at_resolution\n'), ((7657, 7716), 'torch.load', 'torch.load', (['cmd_args.resume_checkpoint'], {'map_location': 'device'}), '(cmd_args.resume_checkpoint, map_location=device)\n', (7667, 7716), False, 'import torch\n'), ((8573, 8667), 'torchlib.utils.train', 'train', (['args', 'model', 'device', 'train_loader', 'optimizer', 'epoch', 'loss_fn'], {'vis_params': 'vis_params'}), '(args, model, device, train_loader, optimizer, epoch, loss_fn,\n vis_params=vis_params)\n', (8578, 8667), False, 'from torchlib.utils import LearningRateScheduler, Arguments, train, test, save_model\n'), ((3814, 3869), 'torchlib.dataloader.PPPP', 'PPPP', (['"""data/Labels.csv"""'], {'train': '(True)', 'transform': 'train_tf'}), "('data/Labels.csv', train=True, transform=train_tf)\n", (3818, 3869), False, 'from torchlib.dataloader import PPPP\n'), ((3888, 3943), 'torchlib.dataloader.PPPP', 'PPPP', (['"""data/Labels.csv"""'], {'train': '(False)', 'transform': 'test_tf'}), "('data/Labels.csv', train=False, transform=test_tf)\n", (3892, 3943), False, 'from torchlib.dataloader import PPPP\n'), ((8829, 8936), 'torchlib.utils.test', 'test', (['args', 'model', 'device', 'test_loader', 'epoch', 'loss_fn'], {'num_classes': 'num_classes', 'vis_params': 'vis_params'}), '(args, model, device, test_loader, epoch, loss_fn, num_classes=\n num_classes, vis_params=vis_params)\n', (8833, 8936), False, 'from torchlib.utils import LearningRateScheduler, Arguments, train, test, save_model\n'), ((5814, 5830), 'numpy.zeros', 'np.zeros', (['(1, 3)'], {}), '((1, 3))\n', (5822, 5830), True, 'import numpy as np\n'), ((5846, 5862), 'numpy.zeros', 'np.zeros', (['(1, 3)'], {}), '((1, 3))\n', (5854, 5862), True, 'import numpy as np\n'), ((6144, 6160), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (6152, 6160), True, 'import numpy as np\n'), ((6176, 6192), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (6184, 6192), True, 'import numpy as np\n'), ((6722, 6809), 'torchlib.models.resnet18', 'resnet18', ([], {'pretrained': '(False)', 'num_classes': 'num_classes', 'in_channels': '(1)', 'adptpool': '(False)'}), '(pretrained=False, num_classes=num_classes, in_channels=1, adptpool\n =False)\n', (6730, 6809), False, 'from torchlib.models import vgg16, resnet18, conv_at_resolution\n'), ((3355, 3399), 'torchvision.transforms.Resize', 'transforms.Resize', (['args.inference_resolution'], {}), '(args.inference_resolution)\n', (3372, 3399), False, 'from torchvision import datasets, transforms, models\n'), ((3417, 3461), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['args.train_resolution'], {}), '(args.train_resolution)\n', (3438, 3461), False, 'from torchvision import datasets, transforms, models\n'), ((3479, 3500), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3498, 3500), False, 'from torchvision import datasets, transforms, models\n'), ((3621, 3665), 'torchvision.transforms.Resize', 'transforms.Resize', (['args.inference_resolution'], {}), '(args.inference_resolution)\n', (3638, 3665), False, 'from torchvision import datasets, transforms, models\n'), ((3683, 3731), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['args.inference_resolution'], {}), '(args.inference_resolution)\n', (3704, 3731), False, 'from torchvision import datasets, transforms, models\n'), ((3749, 3770), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3768, 3770), False, 'from torchvision import datasets, transforms, models\n'), ((8356, 8379), 'numpy.asarray', 'np.asarray', (['[epoch - 1]'], {}), '([epoch - 1])\n', (8366, 8379), True, 'import numpy as np\n'), ((8399, 8419), 'numpy.asarray', 'np.asarray', (['[new_lr]'], {}), '([new_lr])\n', (8409, 8419), True, 'import numpy as np\n'), ((2674, 2714), 'torchvision.transforms.Resize', 'transforms.Resize', (['args.train_resolution'], {}), '(args.train_resolution)\n', (2691, 2714), False, 'from torchvision import datasets, transforms, models\n'), ((2736, 2757), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2755, 2757), False, 'from torchvision import datasets, transforms, models\n'), ((2779, 2821), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.1307,)', '(0.3081,)'], {}), '((0.1307,), (0.3081,))\n', (2799, 2821), False, 'from torchvision import datasets, transforms, models\n'), ((3028, 3072), 'torchvision.transforms.Resize', 'transforms.Resize', (['args.inference_resolution'], {}), '(args.inference_resolution)\n', (3045, 3072), False, 'from torchvision import datasets, transforms, models\n'), ((3094, 3115), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3113, 3115), False, 'from torchvision import datasets, transforms, models\n'), ((3137, 3179), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.1307,)', '(0.3081,)'], {}), '((0.1307,), (0.3081,))\n', (3157, 3179), False, 'from torchvision import datasets, transforms, models\n')]
from __future__ import absolute_import, division, print_function __project__ = "Electrical Pre-Conditioning of Convective Clouds" __title__ = "Plotting Radiosonde Data" __author__ = "<NAME>" __email__ = "<EMAIL>" __version__ = "1.14" __date__ = "28/02/2019" __status__ = "Stable" __changelog__ = "Added in Case Study sections" # Standard libraries import os import sys import time import warnings import glob import argparse import urllib import urllib2 # Data analysis modules import numpy as np import scipy as sp import pandas as pd # Plotting modules import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, MinuteLocator from matplotlib.ticker import MaxNLocator from matplotlib.dates import date2num # Mapping modules #from mpl_toolkits.basemap import Basemap # Datetime handelling modules from datetime import datetime, timedelta sys.path.insert(0, '/home/users/th863480/PhD/Global_Functions') # User Processing Modules import Gilly_Utilities as gu # Data Set-up Modules from Data_Importer import EPCC_Importer from Data_Quality import Radiosonde_Checks_v2 as Radiosonde_Checks from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots # Import Global Variables import PhD_Config as PhD_Global import statsmodels.api as sm # Allow relative imports sys.path.append("..") # Import Tephigram Plotter from Extras.Tephigram import Tephigram as SPTephigram # Import PG Plotter from PG_Quickplotter import PG_Plotter # Import WC3 Extras (for GPS2UTC) from Extras.WC3_Extras import GPS2UTC, CloudDrift, Radiosonde_Launch with warnings.catch_warnings(): warnings.simplefilter("ignore") #Import javascript handler sys.path.insert(0,'/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/') from selenium import webdriver from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True class Radiosonde(EPCC_Importer, Radiosonde_Checks, SPRadiosonde, SPTephigram): def __init__(self, sensor_package='All', height_range=(0,14), calibrate='Counts', reload=False, verbose=False): """ Set-up radiosonde data. Parameters ---------- sensor_package : int The sensor package number flown for the PhD. height_range : array_like The height range used to limit the data. Must be array_like with two elements specifying the lower and upper bands in kilometres. e.g. height_range = (<lower_bound_in_km>, <upper_bound_in_km>), calibrate : str, optional The type of data to plot. Either 'Counts', 'Volts' or 'Units' are acceptable. reload : bool, optional Specify whether to re-process the radiosonde data. N.B. if data has not already proccessed at the particular height_range specified, the data will be reprocessed. verbose : bool, optional Specify whether to output extra information about the processing to the console. """ ############################################################################ """Prerequisites""" # Time Controls t_begin = time.time() # Error Checks if sensor_package is None: sys.exit("[Error] You must specify either the sensor_package number") if height_range is None: sys.exit("[Error] You must specify either the height_range number") # Storage Locations self.Storage_Path = PhD_Global.Storage_Path_WC3 self.Processed_Data_Path = 'Processed_Data/Radiosonde/' self.Raw_Data_Path = 'Raw_Data/' self.Radiosonde_Plots_Path = 'Plots/Radiosonde/' self.Tephigram_Plots_Path = 'Plots/Tephigram/' # Bound classes self.importer = EPCC_Importer() self.sensor_package = str(sensor_package) self.height_range = height_range self.calibrate = calibrate self.reload = reload self.verbose = verbose self.data = PhD_Global.Data # Real name for all Pandora Channels for each radiosonde launch self.RawChannelList = { #0: ['Lin', 'Log', 'Cyan/PLL', 'IR', 'Parity'], 1: ['Lin', 'Log', 'Cyan/PLL', 'IR', 'Parity'], 2: ['Lin', 'Log', 'Cyan/PLL', 'IR', 'Parity'], 3: ['Lin', 'Log', 'Cyan/PLL', 'IR', 'Parity'], 4: ['Lin', 'Log', 'Cyan/PLL', 'IR', 'Parity'], 5: ['Lin', 'Log', 'Cyan/PLL', 'IR', 'Parity'], 6: ['Lin', 'Log/Turbulence', 'Cyan', 'IR/Parity'], 7: ['Lin', 'Log/Turbulence', 'Cyan', 'IR/Parity'], # Not Launched Yet 8: ['Lin', 'Log/Turbulence', 'Cyan', 'IR/Parity'], # Not Launched Yet 9: ['Lin', 'Log', 'Cyan', 'IR', 'Turbulence'], 10: ['Lin', 'Log', 'Cyan', 'IR', 'Turbulence'] } # Number of bits (2^n) self.NumofBits = { #0: 12, 1: 12, 2: 12, 3: 12, 4: 12, 5: 12, 6: 16, 7: 16, # Not Launched Yet 8: 16, # Not Launched Yet 9: 12, 10: 12 } # Launch Time (UTC) self.LaunchTime = { #0: np.datetime64('NaT'), 1: np.datetime64("2018-03-02 15:43:00"), 2: np.datetime64("2018-03-02 17:16:00"), 3: np.datetime64("2018-05-24 15:10:00"), 4: np.datetime64("2018-05-31 15:38:30"), # np.datetime64("2018-05-31 14:20:00"), 5: np.datetime64("2018-07-27 15:39:00"), 6: np.datetime64("2019-01-29 17:20:16"), 7: np.datetime64('NaT'), # Not Launched Yet 8: np.datetime64('NaT'), # Not Launched Yet 9: np.datetime64("2018-12-05 16:12:00"), 10: np.datetime64("2018-12-05 09:22:30") } # Reading University Atmospheric Observatory Coordinates self.RUAO_Coords = (51.441491, -0.937897) ############################################################################ # Import Radiosonde Data self.Radiosonde_Data, self.Launch_Datetime, self.Radiosonde_File = self._RadiosondeImporter('All') # Identify clouds within data self.Clouds_ID, self.LayerType = self._CloudIdentifier('All') # Calculate the space charge density using the log charge sensor # self.Calibration_Log = self._ChargeCalibrator(self.calibrate, self.sensor_package, self.Clouds_ID, self.LayerType) if np.any(np.in1d(self.calibrate, ['Volts', 'Units'])) else None return def _RadiosondeImporter(self, Sensor_Package=None): """ Check and Import Data """ # Error check that either Radiosonde_File or Sensor_Package has been specified if Sensor_Package is None: sys.exit("[Error] You must specify either the Sensor_Package number") t1 = time.time() #Sensor_Package = [3,4,5,6,7,8,9,10] if Sensor_Package == 'All' else [Sensor_Package] Sensor_Package = [1,2,3,4,5,6,7,8,9,10] if Sensor_Package == 'All' else [Sensor_Package] Radiosonde_Data_All = {} Launch_Datetime_All = {} Radiosonde_File_All = {} for sensor in Sensor_Package: if self.verbose is True: print("[INFO] Loading Flight No.%s..." % sensor, end="") sys.stdout.flush() # First check if any NumPy processed files are available for this sensor package file_check = glob.glob(self.Storage_Path + self.Processed_Data_Path + 'Radiosonde_Flight_No.' + str(sensor).rjust(2,'0') + '_*/Radiosonde_Flight_PhD_James_No.' + str(sensor) + '*.npy') tester = ['No.' + str(sensor), str(self.height_range[0]) + 'km', str(self.height_range[1]) + 'km'] if np.any(gu.string_checker(file_check, tester, condition='all')) and self.reload is False: #if self.verbose is True: print("[INFO] Getting radiosonde data from file") # Find correct file to import Radiosonde_File_All[str(sensor)] = file_check[gu.bool2int(gu.string_checker(file_check, tester, condition='all'))[0]] # Load data using careful method (see: https://stackoverflow.com/a/45661259/8765762) Radiosonde_Data = np.load(Radiosonde_File_All[str(sensor)]).item() # Get launch time of ascent Launch_Datetime = Radiosonde_Data['Date'].astype(datetime) else: #if self.verbose is True: print("[INFO] Processing radiosonde data from scratch") # Attempt to find the radiosonde file either directly or from glob Radiosonde_File = glob.glob(self.Storage_Path + self.Processed_Data_Path + 'Radiosonde_Flight_No.' + str(sensor).rjust(2,'0') + '_*/Radiosonde_Flight_PhD_James_No.' + str(sensor) + '*a.txt') # If no radiosonde file was found we end program if (len(Radiosonde_File) == 0) and (len(Sensor_Package) > 1): if self.verbose is True: print("Failed\n[Warning] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (sensor)) continue # else: # sys.exit("[Warning] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (sensor)) # If the radiosonde file was found via glob we need to convert to str from list if isinstance(Radiosonde_File, list): Radiosonde_File_All[str(sensor)] = Radiosonde_File[0] # Once the radiosonde file is found we can attempt to find the GPS file in the raw file section self.GPS_File = glob.glob(self.Storage_Path + self.Raw_Data_Path + 'Radiosonde_Flight_No.' + str(sensor).rjust(2,'0') + '_*/GPSDCC_RESULT*.tsv') # Import all the data if sensor in [6,7,8]: # Has slightly different layout. Unlike the RS92 extractor, # the MW41 extractor has layout CH0, CH1, CH2, CH3 Radiosonde_Data = pd.read_csv(Radiosonde_File_All[str(sensor)], sep=r"\s*", header=None, engine='python', names=('time', 'height', 'P', 'Tdry', 'RH', self.RawChannelList[sensor][0], self.RawChannelList[sensor][1], self.RawChannelList[sensor][2], self.RawChannelList[sensor][3], 'long', 'lat', 'range', 'bearing', 'Tdew', 'u', 'v', 'MR'), dtype={'time': np.float64, 'height': np.float64, 'P': np.float64, 'Tdry': np.float64, 'RH': np.float64, self.RawChannelList[sensor][0]: np.float64, self.RawChannelList[sensor][1]: np.float64, self.RawChannelList[sensor][2]: np.float64, self.RawChannelList[sensor][3]: np.float64, 'long': np.float64, 'lat': np.float64, 'range': np.float64, 'bearing': np.float64, 'Tdew': np.float64, 'u': np.float64, 'v': np.float64, 'MR': np.float64}, na_values=-32768, comment='#', index_col=False).to_records(index=False) # Fix np.recarray issue Radiosonde_Data = gu.fix_recarray(Radiosonde_Data) # Import comments residing within the Radiosonde file File_Comments = gu.readcomments(Radiosonde_File_All[str(sensor)], comment='#') # Using the File_Comments, get the launch time Launch_Datetime = datetime.strptime(File_Comments[-2][18:37], "%Y-%m-%dT%H:%M:%S") else: # Has slightly different layout. Unlike the MW41 extractor, # the RS92 extractor has layout CH0, CH1, CH2, CH3, CH$ Radiosonde_Data = pd.read_csv(Radiosonde_File_All[str(sensor)], sep=r"\s*", header=None, engine='python', names=('time', 'height', 'P', 'Tdry', 'RH', self.RawChannelList[sensor][0], self.RawChannelList[sensor][1], self.RawChannelList[sensor][2], self.RawChannelList[sensor][3], self.RawChannelList[sensor][4], 'long', 'lat', 'range', 'bearing', 'Tdew', 'u', 'v', 'MR'), dtype={'time': np.float64, 'height': np.float64, 'P': np.float64, 'Tdry': np.float64, 'RH': np.float64, self.RawChannelList[sensor][0]: np.float64, self.RawChannelList[sensor][1]: np.float64, self.RawChannelList[sensor][2]: np.float64, self.RawChannelList[sensor][3]: np.float64, self.RawChannelList[sensor][4]: np.float64, 'long': np.float64, 'lat': np.float64, 'range': np.float64, 'bearing': np.float64, 'Tdew': np.float64, 'u': np.float64, 'v': np.float64, 'MR': np.float64}, na_values=-32768, comment='#', index_col=False).to_records(index=False) GPS_Data = pd.read_csv(self.GPS_File[0], sep="\t", skiprows=51, header=None, usecols=(1,2,4), names=('GPS_Week', 'GPS_Second', 'SondeX'), dtype={'GPS_Week': np.int32, 'GPS_Second': np.float64, 'SondeX': np.float64}, na_values=-32768, comment='#', index_col=False).to_records(index=False) if len(self.GPS_File) != 0 else None # Fix np.recarray issue Radiosonde_Data = gu.fix_recarray(Radiosonde_Data) GPS_Data = gu.fix_recarray(GPS_Data) # Estimate the launch time from the data if self.GPS_File is not None: GPS_Data = GPS_Data[~np.isnan(GPS_Data['SondeX'])] Launch_Datetime = GPS2UTC(GPS_Data['GPS_Week'][0], GPS_Data['GPS_Second'][0]) # Calibrate Height, Temperature and Convert PANDORA channels from counts to volts if required. Radiosonde_Cal_Basic = Radiosonde_Checks( data=Radiosonde_Data.copy(), calibrate='Basic', package_no=sensor, height_range=self.height_range, bits=self.NumofBits[sensor], verbose=self.verbose) Radiosonde_Cal_Counts = Radiosonde_Checks( data=Radiosonde_Data.copy(), calibrate='Counts', package_no=sensor, height_range=self.height_range, bits=self.NumofBits[sensor], verbose=self.verbose) Radiosonde_Cal_Volts = Radiosonde_Checks( data=Radiosonde_Data.copy(), calibrate='Volts', package_no=sensor, height_range=self.height_range, bits=self.NumofBits[sensor], verbose=self.verbose) Radiosonde_Cal_Units = Radiosonde_Checks( data=Radiosonde_Data.copy(), calibrate='Units', package_no=sensor, height_range=self.height_range, bits=self.NumofBits[sensor], verbose=self.verbose) # Calibrate RH Radiosonde_Cal_Counts.RH() Radiosonde_Cal_Volts.RH() Radiosonde_Cal_Units.RH() # Calibrate Cloud Sensor Radiosonde_Cal_Counts.Cloud(method='offset') Radiosonde_Cal_Volts.Cloud(method='offset') Radiosonde_Cal_Units.Cloud(method='offset') # Calibrate Charge Radiosonde_Cal_Volts.Charge() Radiosonde_Cal_Units.Charge(lab_calibration=True) # Calibrate Vibrating Wire Radiosonde_Cal_Volts.Liquid_Water() Radiosonde_Cal_Units.Liquid_Water() # Calibrate Turbulence Radiosonde_Cal_Units.Turbulence() # Nest Radiosonde_Cal into Radiosonde_Data Radiosonde_Data = {'Date': np.datetime64(Launch_Datetime).astype('datetime64[s]'), 'Raw': Radiosonde_Data, 'Basic': Radiosonde_Cal_Basic.finalise(), 'Counts': Radiosonde_Cal_Counts.finalise(), 'Volts': Radiosonde_Cal_Volts.finalise(), 'Units': Radiosonde_Cal_Units.finalise()} # Save Radiosonde_Data to file. N.B. numpy is not perfect for saving dictionaries. Becareful when loading data again! Save_Loc = self.Storage_Path + self.Processed_Data_Path + 'Radiosonde_Flight_No.' + \ str(sensor).rjust(2,'0') + '_' + Launch_Datetime.strftime('%Y%m%d') + \ '/Radiosonde_Flight_PhD_James_No.' + str(sensor) + '_' + Launch_Datetime.strftime('%Y%m%d') + \ '_' + str(self.height_range[0]) + 'km_to_' + str(self.height_range[1]) + 'km_Ascent.npy' np.save(Save_Loc, Radiosonde_Data) # Save GPS data if sensor not in [6]: Save_Loc = self.Storage_Path + self.Processed_Data_Path + 'Radiosonde_Flight_No.' + \ str(sensor).rjust(2,'0') + '_' + Launch_Datetime.strftime('%Y%m%d') + \ '/Radiosonde_Flight_PhD_James_No.' + str(sensor) + '_' + Launch_Datetime.strftime('%Y%m%d') + \ '_' + 'GPSdata.npy' np.save(Save_Loc, GPS_Data) if self.verbose is True: print("Done") # Append Radiosonde_Data to master array Radiosonde_Data_All[str(sensor)] = Radiosonde_Data Launch_Datetime_All[str(sensor)] = Launch_Datetime # return gu.dict2array(Radiosonde_Data_All), gu.dict2array(Launch_Datetime_All) return Radiosonde_Data_All, Launch_Datetime_All, Radiosonde_File_All def _CloudIdentifier(self, Sensor_Package): """ This function will identify the cloud layers within a radiosonde ascent using the Zhange et al. (2010) algorithm. This algorithm uses the cloud sensor and relative humidity with respects to ice measurements. Parameters ---------- Sensor_Package : str The radiosonde flight number relating to the data as provided by _RadiosondeImporter. Other options are 'All' which will identify the clouds for all radisonde flights. Returns ------- Cloud_ID : ndarray, dtype = np.int8 An array with the same size of the input data (e.g. 'height') which contains the identifier for each cloud. Starting with 1, for all height positions where a cloud was identified a 1 will be used to identify the first cloud for all height positions. Sequentially, the next cloud identified will be marked by a 2. N.B. The moist layer clouds are not identified within this array. Layer_Type : ndarray, dtype = np.int8 An array with the same size of the input data (e.g. 'height') which contains the layer type at each height level (see notes for layer type classification). This is very similar to Cloud_ID but does not differentiate between cloud layers. Notes ----- Layer Type : Classification 0 = Clear Air, 1 = Moist Layer, 2 = Cloud Layer. Reference --------- <NAME>., <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> (2010). Analysis of cloud layer structure in Shouxian, China using RS92 radiosonde aided by 95 GHz cloud radar. J. Geophys. Res., 115, D00K30, doi: 10.1029/2010JD014030. WMO, 2017. Clouds. In: Internal Cloud Atlas Manual on the Observation of Clouds and Other Meteors. Hong Kong: WMO, Section 2.2.1.2. """ # If not errors then print to console we are running # _CloudIdentifier if self.verbose is True: gu.cprint("[INFO] You are running CloudIdentifier from the" " STABLE release", type='bold') # Specify the sensors we want to process Sensor_Package = np.arange(1,11).astype('S2') if Sensor_Package\ == 'All' else [Sensor_Package] Clouds_ID_All = {} LayerType_All = {} for sensor in Sensor_Package: # Check the sensor has been processed by # _RadiosondeImporter try: self.Radiosonde_Data[sensor] except KeyError: if self.verbose is True: RuntimeError("[Warning] Radiosonde package No.%s" " does not exist. Has the radiosonde" " been launched yet or has the data" "been misplaced?" % sensor) continue # Define data into new variables Z = self.Radiosonde_Data[sensor]['Counts']['height'].copy() RH = self.Radiosonde_Data[sensor]['Counts']['RHice'].copy() # Identify the clouds within the ascent profile (Clouds_ID_All[sensor], LayerType_All[sensor]) = gu.cloud_identifer_ascent( Z, RH, method='Zhang', verbose=False) return Clouds_ID_All, LayerType_All def _ChargeCalibrator(self, Calibrate=None, Sensor_Package=None, Clouds_ID=None, LayerType=None): if self.verbose is True: gu.cprint("[INFO] You are running Radiosonde_ChargeCalibrator from the DEV release", type='bold') ############################################################################ """Prerequisites""" #Time Controls t_begin = time.time() #Plotting requirements import matplotlib.pyplot as plt plt.style.use('classic') #necessary if Matplotlib version is >= 2.0.0 #Calibration boundaries Height_Boundaries = {0 : [], 1 : [], 2 : [], 3 : [], 4 : [10.0,12.0], 5 : [10.5,12.0], 6 : [], 7 : [], 8 : [], 9 : [6,12.0], 10 : [12,18.0]} # Make data local to method Radiosonde_File = self.Radiosonde_File[Sensor_Package] ############################################################################ """[Step 1] Calibrate bespoke sensors""" Radiosonde_Data = self.Radiosonde_Data['Units'].copy() Linear = gu.moving_average(Radiosonde_Data['Lin_Current'], 11) Log = gu.moving_average(Radiosonde_Data['Log_Current'], 11) PosMask = Linear >= 0 NegMask = Linear < 0 LinearPos = np.log10(Linear[PosMask]) LogPos = Log[PosMask] LinearNeg = -np.log10(-Linear[NegMask]) LogNeg = Log[NegMask] #Calculate Linear Regressions slope_all, intercept_all, r_value_all, p_value_all, std_err_all = sp.stats.linregress(Log, Linear) slope_pos, intercept_pos, r_value_pos, p_value_pos, std_err_pos = sp.stats.linregress(LogPos, LinearPos) try: slope_neg, intercept_neg, r_value_neg, p_value_neg, std_err_neg = sp.stats.linregress(LogNeg, LinearNeg) except: slope_neg, intercept_neg, r_value_neg, p_value_neg, std_err_neg = (0,0,0,0,0) if self.verbose is True: print(slope_all, intercept_all, r_value_all, p_value_all, std_err_all) if self.verbose is True: print(slope_pos, intercept_pos, r_value_pos, p_value_pos, std_err_pos) if self.verbose is True: print(slope_neg, intercept_neg, r_value_neg, p_value_neg, std_err_neg) ############################################################################ """[Step 2] Plot the calibration values for positive and negative linear currents""" plt.clf() plt.close() f, ax = plt.subplots(1,3) ax[0].plot(Log, Linear , 'p', ms=1, marker='o', markeredgecolor='None', markerfacecolor='black', alpha=1, label="Clouds") ax[1].plot(LogPos, LinearPos , 'p', ms=1, marker='o', markeredgecolor='None', markerfacecolor='black', alpha=1, label="Clouds") ax[2].plot(LogNeg, LinearNeg , 'p', ms=1, marker='o', markeredgecolor='None', markerfacecolor='black', alpha=1, label="Clouds") ax[0].plot(Log, slope_all*Log+intercept_all, lw=0.5, c='red') ax[1].plot(LogPos, slope_pos*LogPos+intercept_pos, lw=0.5, c='red') ax[2].plot(LogNeg, slope_neg*LogNeg+intercept_neg, lw=0.5, c='red') ax[0].set_ylabel("Linear Sensor Current (A)", fontsize=8) ax[1].set_ylabel("Linear Sensor Current (log10(pA))", fontsize=8) ax[2].set_ylabel("Linear Sensor Current (-log10(-pA))", fontsize=8) for subplot in ax: subplot.minorticks_on() for subplot in ax: subplot.set_xlabel("Log Sensor Current (Counts)", fontsize=8) for subplot in ax: subplot.grid(which='major',axis='both',c='grey') for subplot in ax: subplot.tick_params(axis='both', which='major', labelsize=8) for subplot in ax: subplot.tick_params(axis='both', which='minor', labelsize=8) f.suptitle("Linear and Log Charge Sensors for Radiosonde Flight No.5", y=0.90) ax[0].get_xaxis().get_major_formatter().labelOnlyBase = False for subplot in ax: x0, x1 = subplot.get_xlim() y0, y1 = subplot.get_ylim() subplot.set_aspect(np.abs((x1-x0)/(y1-y0))) ax[0].annotate("All Data", xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=8) ax[1].annotate("Positive Linear Current", xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=8) ax[2].annotate("Negative Linear Current", xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=8) ax[0].annotate("$R^{2}$ = %.4f\n$Counts$ = %.0f" % (r_value_all**2, Log.size), xy=(1, 1), xycoords='axes fraction', fontsize=8, xytext=(-3, -3), textcoords='offset points', ha='right', va='top') ax[1].annotate("$R^{2}$ = %.4f\n$Counts$ = %.0f" % (r_value_pos**2, LogPos.size), xy=(1, 1), xycoords='axes fraction', fontsize=8, xytext=(-3, -3), textcoords='offset points', ha='right', va='top') ax[2].annotate("$R^{2}$ = %.4f\n$Counts$ = %.0f" % (r_value_neg**2, LogNeg.size), xy=(1, 1), xycoords='axes fraction', fontsize=8, xytext=(-3, -3), textcoords='offset points', ha='right', va='top') f.set_size_inches(11.7, 4.3) ############################################################################ """[Step 3] Save plot to file""" #Specify the directory the plots are stored in path = os.path.dirname(Radiosonde_File).replace(self.Storage_Path + self.Processed_Data_Path,"") #Find any other plots stored in this directory previous_plots = glob.glob(self.Storage_Path + self.Radiosonde_Plots_Path + path + "/*") #Find the biggest 'v' number in plots plot_version = [] for plots in previous_plots: try: plot_version.append(int(os.path.basename(plots)[34:37])) except ValueError: plot_version.append(int(os.path.basename(plots)[34:36])) plot_version = str(np.max(plot_version)+1) if len(plot_version) != 0 else '1' #Create full directory and file name Save_Location = self.Storage_Path + self.Radiosonde_Plots_Path + path + '/' + path + '_v' + plot_version.rjust(2,'0') + '_ChargeCalibrator.png' #Ensure the directory exists on file system and save to that location gu.ensure_dir(os.path.dirname(Save_Location)) plt.savefig(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300) #Return regression of positive current, regression of negative current and the boundary for counts return (slope_all, intercept_all), (slope_pos, intercept_pos), (slope_neg, intercept_neg), (PosMask, NegMask) def _CloudHeights(self, sensor, method='Zhang'): """ Gets the cloud and clear-air heights using either the Zhang or IR method. Parameters ---------- sensor : int or str The sensor number of the radiosonde flight. method : str, optional, default = 'Zhang' The method to compute the cloud and clear-air heights. Options are 'Zhang' or 'IR'. Returns ------- Cloud_Heights : 2D numpy array The start and end heights for all clouds detected. Clear_Heights : 2D numpy array The start and end heights for all clear air detected. """ # Quality control args and kwargs. sensor = str(sensor) # Get a copy of the Radiosonde and Clouds_ID data. Radiosonde_Data = self.Radiosonde_Data.copy() Clouds_ID = self.Clouds_ID[sensor].copy() LayerType = self.LayerType.copy() # Calculate cloud and clear-air heights. if method == 'Zhang': # Get cloud base and cloud top heights for each identified cloud Cloud_Heights = np.array([[Radiosonde_Data[sensor]['Units']['height'][Clouds_ID == Cloud][0], Radiosonde_Data[sensor]['Units']['height'][Clouds_ID == Cloud][-1]] for Cloud in np.unique(Clouds_ID)[1:]], dtype=np.float64) # Get clear-air base and clear-air top heights from each clear-air region. Clear_ID = gu.argcontiguous(LayerType[sensor], valid=0) Clear_Heights = np.array([[Radiosonde_Data[sensor]['Units']['height'][Clear_ID == Cloud][0], Radiosonde_Data[sensor]['Units']['height'][Clear_ID == Cloud][-1]] for Cloud in np.unique(Clear_ID)[1:]], dtype=np.float64) elif method == 'IR': # Determine cloud regions from IR data. IR = Radiosonde_Data[sensor]['Units']['IR'] Clouds_ID = gu.contiguous((IR > np.nanpercentile(IR, 80)).astype(int), invalid=0) # Determine clear-air regions from IR data. Clear_ID = gu.contiguous((IR < np.nanpercentile(IR, 20)).astype(int), invalid=0) # Get cloud base and cloud top heights for each identified cloud. Cloud_Heights = np.array([[Radiosonde_Data[sensor]['Units']['height'][Clouds_ID == Cloud][0], Radiosonde_Data[sensor]['Units']['height'][Clouds_ID == Cloud][-1]] for Cloud in np.unique(Clouds_ID)[1:]], dtype=np.float64) # Get clear-air base and clear-air top heights from each clear-air region. Clear_Heights = np.array([[Radiosonde_Data[sensor]['Units']['height'][Clear_ID == Cloud][0], Radiosonde_Data[sensor]['Units']['height'][Clear_ID == Cloud][-1]] for Cloud in np.unique(Clear_ID)[1:]], dtype=np.float64) else: raise ValueError("[_CloudHeights] method parameter can only take the optinos 'Zhang' or 'IR'") return Cloud_Heights, Clear_Heights def _ElectricField_Estimator(self, Radiosonde_Data, Cloud_Heights, LaunchTime, method='static', verbose=False): """ This function calculates the electric field. Parameters ---------- Radiosonde_Data : dict The data of the ascent profile. Must specifiy base dataset for the specific ascent you want to process (e.g. Radiosonde_Data[<sensor>] Cloud_Heights : 2D numpy array The start and end heights for all clouds detected. LaunchTime : np.datetime64 The launchtime of the radiosonde representing time 0 in the radiosonde_data. The format must be in numpy datetime64. method : str, optional, default='static' The method of calculating the electric field. Two options are: 'static' : All point charges are placed in the same temporal and spatial position. This is under the assumption that the evolution of the charge is static and has changed negligbile during the ascent through the cloud. 'dynamic' : All point charges are place is specific temporal and spatial poisitions calculated from the time and position of the radiosonde upon measurement. This is under the assumption that the charge is developing and a better representation of the charge. Returns ------- Cloud_DateTime : ndarray A one dimensional time-series with the same dimensions as Cloud_ElectricField_Total. Cloud_ElectricField : ndarray A multidimensional array of the estimated PG for each individual point charge that was placed. Therefore the size of this array has the form (Cloud_DateTime.size, PointCharges.size) Cloud_ElectricField_Total : ndarray A one dimensional array of the estimated PG. """ # Constants PG0 = 0 # Background potential gradient k = 2500000/22468879568420441 #Coulombs Constant (exact value!) kn2ms = 0.5144 #Conversion between knots and m/s ############################################################################ """Pre-Condition Data""" # Remove nan's from Time, Height, Wind, SpaceCharge Time, Height, Wind, SpaceCharge = gu.antifinite((Radiosonde_Data['Units']['time'], Radiosonde_Data['Units']['height'], Radiosonde_Data['Units']['WindSpeed'], Radiosonde_Data['Units']['SpaceCharge']), unpack=True) # Detect sign changes in data SignChange = np.where(np.diff(np.sign(SpaceCharge)))[0] # Get index of lowest cloud CloudIndex = gu.searchsorted(Radiosonde_Data['Units']['height'], Cloud_Heights[0]) # CloudIndex = gu.searchsorted(Radiosonde_Data['Units']['height'], [0,12]) # Get SignChange position for cloud Cloud_SignChange = SignChange[(SignChange >= CloudIndex[0]) & (SignChange <= CloudIndex[1])] # Get time stamps of sign change Cloud_TimeChange = Time[Cloud_SignChange] # Broadcast Cloud_SignChange into a 2D array which is easier to # use with for loops. Cloud_SignChange = gu.broadcast(Cloud_SignChange,2,1) + 1 ############################################################################ """Set-up electric field environment""" # [1] SPACE CHARGE DENSITY # Calculate the 95th percentile of the space charge density between # each polarity inversion. Making sure to conserve local sign. Cloud_SpaceCharge = np.zeros(Cloud_SignChange.shape[0]) for i, space in enumerate(Cloud_SignChange): Local_SpaceCharge = SpaceCharge[space[0]:space[1]] Local_Sign = sp.stats.mode(np.sign(Local_SpaceCharge))[0][0] Cloud_SpaceCharge[i] = Local_Sign*np.nanpercentile(np.abs(Local_SpaceCharge), 100) # Convert space charge from pC to C Cloud_SpaceCharge /= 10**12 # [2] POINT CHARGE HEIGHT # Calculate the height positions for each point charge. i.e. between # each sign change the absolute maximum space charge value is found # and then indexed onto the height array. Cloud_Height = np.zeros(Cloud_SignChange.shape[0]) for i, space in enumerate(Cloud_SignChange): # Get the local index of the absolute maximum space charge density mask = np.argmax(np.abs(SpaceCharge[space[0]:space[1]])) # Find the height using 'mask' on the same subsetted data PC_Height = Height[space[0]:space[1]][mask] # Determine the horizontal distance between RUAO and Point Charge. if method == 'static': Cloud_Height[i] = PC_Height elif method == 'dynamic': Cloud_Height[i] = ((Radiosonde_Data['Units']['range'][space[0]:space[1]][mask]/1000)**2 + PC_Height**2)**0.5 # Convert heights from km to m Cloud_Height *= 1000 # [3] POINT CHARGE AREA # Calculate the area that each point charge corresponds to. Here # we use the vertical height gained between sign changes. Cloud_AscentArea = np.array([Height[space[1]] - Height[space[0]] for space in Cloud_SignChange], dtype=np.float64)*1000 # [4] CLOUD CHARGE # Now calculate the charge within the area. Cloud_Charge = Cloud_SpaceCharge * (4/3)*np.pi*Cloud_AscentArea**3 # * 3 # [5] CLOUD VELOCITY # Calculate the velocity of each point charge. Cloud_Velocity = np.array([np.nanmean(Wind[space[0]:space[1]]) for space in Cloud_SignChange], dtype=np.float64) # /4.5 # [6] CLOUD TIME # Specify the time range in seconds to calculate the electric field over. # The time range revolves around the first point charge specified, # therefore, Cloud_Time is typically specified with +- bounds. Cloud_Time = np.arange(-3000, 3000, 1) # [7] CLOUD TIME DIFFERENCE # Get the time for each point charge. Cloud_TimeDiff = np.zeros(Cloud_SignChange.shape[0]) if method == 'dynamic': for i, space in enumerate(Cloud_SignChange): # Get the local index of the absolute maximum space charge density mask = np.argmax(np.abs(SpaceCharge[space[0]:space[1]])) # Find the height using 'mask' on the same subsetted data Cloud_TimeDiff[i] = Time[space[0]:space[1]][mask] Cloud_TimeDiff -= Cloud_TimeDiff[0] ############################################################################ """Calculate the electric field""" # [8] ELECTRIC FIELD CALCULATION # Now the Cloud_Time, Cloud_TimeDiff, Cloud_Velocity, Cloud_Height and # Cloud_Charge has been calculated, the electric field can now be found Cloud_ElectricField = zip(np.zeros(Cloud_SignChange.shape[0])) for i, (time_diff, height, velocity, charge) in enumerate( zip(Cloud_TimeDiff, Cloud_Height, Cloud_Velocity, Cloud_Charge)): #Cloud_ElectricField[i] = (gu.cosarctan(((Cloud_Time+time_diff)*velocity)/height)*charge)/(k*height**2) Cloud_ElectricField[i] = (gu.cosarctan(((Cloud_Time-time_diff)*velocity)/height)*charge)/(k*height**2) # Add the background electric field to the calculations. For now we can # assume the background electric field is 100 V/m. Cloud_ElectricField_Total = PG0 + np.nansum(Cloud_ElectricField, axis=0) ############################################################################ """Determine the time stamp data for the flight""" # Get the time when the radiosonde reached the cloud base Cloud_BaseTime = LaunchTime + np.timedelta64(int(Radiosonde_Data['Units']['time'][CloudIndex[0]]), 's') # Calculate datetimes for each calculation in Cloud_ElectricField_Total Cloud_DateTime = Cloud_BaseTime + Cloud_Time.astype('timedelta64[s]') if verbose: print("Number of Point Charges =", Cloud_SignChange.shape[0]) return Cloud_DateTime, Cloud_ElectricField, Cloud_ElectricField_Total def Superplotter(self): """ This function will plot the data from a single radiosonde flight """ if self.verbose: gu.cprint("[INFO] You are running Superplotter from the DEV release", type='bold') ############################################################################ """Prerequisites""" # Time Controls t_begin = time.time() # Make data local to method Radiosonde_File = self.Radiosonde_File[self.sensor_package] ############################################################################ """[Step 1] Plot radiosonde data""" # Specify plot title plot_title = 'Radiosonde Flight No.' + self.sensor_package + ' (' + self.Launch_Datetime[self.sensor_package].strftime("%d/%m/%Y %H%MUTC") + ')' # Set-up radiosonde plotter Superplotter = SPRadiosonde(self.Radiosonde_Data, numplots=7, which_ascents=(self.sensor_package,), plot_title=plot_title, height_range=self.height_range, calibrate=self.calibrate) if self.calibrate in ['Counts', 'Volts']: Superplotter.Charge(linear=True, log=False) Superplotter.Charge(linear=False, log=True) else: Superplotter.Charge(type='space_charge') if int(self.sensor_package) in [1,2,3,4,5]: # Plot cloud sensor data Superplotter.Cloud(ir=True, cyan=True) # Plot liquid water sensor data if int(self.sensor_package) < 3: Superplotter.Liquid_Water(type='Liquid_Water', point=False) else: Superplotter.Liquid_Water(type='Liquid_Water', point=True) # Plot calibrated liquid water sensor data if self.calibrate in ['Units']: if int(self.sensor_package) < 3: Superplotter.Liquid_Water(type='SLWC', point=False) else: Superplotter.Liquid_Water(type='SLWC', point=True) else: # Plot cloud sensor data Superplotter.Cloud() # Plot turbulence sensor data if self.calibrate in ['Units']: Superplotter.Turbulence(type='Turbulence') Superplotter.Turbulence(type='Eddy Dissipation Rate') else: Superplotter.Turbulence(type='Turbulence') # Plot the processed Liquid_Water data #if (self.calibrate == "units") & (int(self.sensor_package) < 8): Superplotter.ch(14, 'SLWC $(g$ $m^{-3})$', 'Supercooled Liquid\nWater Concentration', check=1112, point=True) # Plot the cloud boundaries if specified if self.Clouds_ID is not None: Superplotter.Cloud_Boundaries(self.Clouds_ID, self.LayerType, CloudOnly=True) ############################################################################ """[Step 2] Save plot and return""" # Specify the directory the plots are stored in path = os.path.dirname(Radiosonde_File).replace(self.Storage_Path + self.Processed_Data_Path,"") # Find any other plots stored in this directory previous_plots = glob.glob(self.Storage_Path + self.Radiosonde_Plots_Path + path + "/*") # Find the biggest 'v' number in plots plot_version = [] for plots in previous_plots: try: plot_version.append(int(os.path.basename(plots)[34:37])) except ValueError: plot_version.append(int(os.path.basename(plots)[34:36])) plot_version = str(np.max(plot_version)+1) if len(plot_version) != 0 else '1' # Create full directory and file name Save_Location = self.Storage_Path + self.Radiosonde_Plots_Path + path + '/' + path + '_v' + plot_version.rjust(2,'0') + '_' + str(self.height_range[0]).rjust(2,'0') + 'km_to_' + str(self.height_range[1]).rjust(2,'0') + 'km.png' # Ensure the directory exists on file system and save to that location gu.ensure_dir(os.path.dirname(Save_Location)) Superplotter.savefig(Save_Location) if self.verbose is True: print("[INFO] Superplotter completed successfully (In %.2fs)" % (time.time()-t_begin)) def Tephigram(self, plot_tephigram=False, plot_larkhill=False): """ The Radiosonde_Tephigram function will plot a tephigram from the dry bulb temperature, T_dry and the Dew point Temperature, T_dew for pressure values, P at each corresponding height. Certain tephigram outputs are available from this function including: 1) Lower Condensation Level (LCL) in m 2) Level of Free Convection (LFC) in m 3) Environmental Level (EL) in m 4) Convective Available Potential Energy (CAPE) in J/kg 5) Convective INhibition (CIN) in J/kg Parameters ---------- plot_tephigram : bool, optional, default is False Specify True to plot a tephigram of the sounding data. Otherwise just calculate the sounding indices plot_larkhill : bool, optional, default is False Specify True to add the sounding from Camborne at the closest time to the launch time. Only used if plot_tephigram is True. Outputs ------- References ---------- <NAME>., 2010. Water in the Atmosphere. In: Thermal Physics of the Atmosphere. Oxford: Wiley & Sons, pp. 93-109 <NAME>. 2018. Tephigram. Original Matlab code found in Matlab_Code directory <NAME>. 2018. Tephigram. Original Python code found in the same directory. """ if self.verbose is True: gu.cprint("[INFO] You are running Radiosonde_Tephigram from the STABLE release", type='bold') ############################################################################ """Prerequisites""" # Time Controls t_begin = time.time() # Set-up data importer EPCC_Data = EPCC_Importer() ############################################################################ """[Step 1] Calibrate bespoke sensors""" # Return Data (make local to function only. i.e. DON'T use self.Radiosonde_Data) Radiosonde_Data = self.Radiosonde_Data[self.sensor_package]['Counts'].copy() Radiosonde_File = self.Radiosonde_File[self.sensor_package] # Extract data into easy to read variables Z = Radiosonde_Data['height'][1:] Tdry = Radiosonde_Data['Tdry'][1:] Tdew = Radiosonde_Data['Tdew'][1:] Pres = Radiosonde_Data['P'][1:] RH = Radiosonde_Data['RH'][1:]/100; RH -= np.max(RH) - 0.01 Wind_Mag = (Radiosonde_Data['u'][1:]**2 + Radiosonde_Data['v'][1:]**2)**0.5 Wind_Dir = np.arctan2(Radiosonde_Data['u'][1:], Radiosonde_Data['v'][1:]) * 180 / np.pi ############################################################################ """[Step 2] Create Tephigram""" if plot_tephigram is True: if self.verbose is True: print("[INFO] Plotting Tephigram...") print("plot_larkhill", plot_larkhill) # Unpack variables Z_Plot = Radiosonde_Data['height'] Tdry_Plot = Radiosonde_Data['Tdry'] Tdew_Plot = Radiosonde_Data['Tdew'] Pres_Plot = Radiosonde_Data['P'] # Subset the tephigram to specified location locator = gu.argneararray(Z_Plot, np.array(self.height_range)*1000) anchor = np.array([(Pres_Plot[locator]),(Tdry_Plot[locator])]).T Pres_Plot_Antinan, Tdry_Plot_Antinan, Tdew_Plot_Antinan = gu.antinan(np.array([Pres_Plot, Tdry_Plot, Tdew_Plot]), unpack=True) # Group the dews, temps and wind profile measurements dews = zip(Pres_Plot_Antinan, Tdew_Plot_Antinan) temps = zip(Pres_Plot_Antinan, Tdry_Plot_Antinan) barb_vals = zip(Pres,Wind_Dir,Pres_Plot) # Create Tephigram plot Tephigram = SPTephigram() # Plot Reading sounding data profile_t1 = Tephigram.plot(temps, color="red", linewidth=1, label='Reading Dry Bulb Temperature', zorder=5) profile_d1 = Tephigram.plot(dews, color="blue", linewidth=1, label='Reading Dew Bulb Temperature', zorder=5) # Plot Larkhill sounding data if plot_larkhill is True: # Determine ULS data ULS_File = sorted(glob.glob(PhD_Global.Raw_Data_Path + 'Met_Data/ULS/03743/*')) # Check any files were found if len(ULS_File) > 0: ULS_Date = np.zeros(len(ULS_File), dtype=object) for i, file in enumerate(ULS_File): try: ULS_Date[i] = datetime.strptime(os.path.basename(file), '%Y%m%d_%H_03743_UoW_ULS.csv') except: ULS_Date[i] = datetime(1900,1,1) # Find Nearest Upper Level Sounding Flight to Radiosonde Flight ID = gu.argnear(ULS_Date, self.Launch_Datetime[self.sensor_package]) # Check the amount of time between Reading and Larkhill # soundings does not exceed 24 hrs. if np.abs(self.Launch_Datetime[self.sensor_package] - ULS_Date[ID]).seconds < 86400: print("[INFO] Radiosonde Launch Time:", self.Launch_Datetime[self.sensor_package], "Larkhill Launch Time:", ULS_Date[ID]) # Import Larkhill Radiosonde Data press_larkhill, temps_larkhill, dews_larkhill = EPCC_Data.ULS_Calibrate(ULS_File[ID], unpack=True, PRES=True, TEMP=True, DWPT=True) # Match Larkhill pressures with Reading pressures mask = [gu.argnear(press_larkhill, Pres_Plot[0]), gu.argnear(press_larkhill, Pres_Plot[-1])] press_larkhill = press_larkhill[mask[0]:mask[1]] temps_larkhill = temps_larkhill[mask[0]:mask[1]] dews_larkhill = dews_larkhill[mask[0]:mask[1]] dews_larkhill = zip(press_larkhill, dews_larkhill) temps_larkhill = zip(press_larkhill, temps_larkhill) # Plot Larkhill sounding data profile_t1 = Tephigram.plot(temps_larkhill, color="red", linestyle=':', linewidth=1, label='Larkhill Dry Bulb Temperature', zorder=5) profile_d1 = Tephigram.plot(dews_larkhill, color="blue", linestyle=':', linewidth=1, label='Larkhill Dew Bulb Temperature', zorder=5) else: #warnings.warn("[WARNING] No Larkhill (03743) sounding data was found within 24hrs of the ascent!", ImportWarning) gu.cprint("[WARNING] No Larkhill (03743) sounding data was found within 24hrs of the ascent!", type='warning') else: #warnings.warn("[WARNING] No Larkhill (03743) sounding data was found!", ImportWarning) gu.cprint("[WARNING] No Larkhill (03743) sounding data was found!", type='warning') # Add extra information to Tephigram plot # Tephigram.axes.set(title=Title, xlabel="Potential Temperature $(^\circ C)$", ylabel="Dry Bulb Temperature $(^\circ C)$") Title = 'Radiosonde Tephigram Flight No.' + str(self.sensor_package) + ' (' + self.Launch_Datetime[self.sensor_package].strftime("%d/%m/%Y %H%MUTC") + ')' if self.GPS_File is not None else 'Radiosonde Tephigram Flight (N/A)' Tephigram.axes.set(title=Title) # [OPTIONAL] Add wind profile information to Tephigram. # profile_t1.barbs(barb_vals) ############################################################################ """Save plot to file""" # Specify the directory the plots are stored in path = os.path.dirname(Radiosonde_File).replace(self.Storage_Path + self.Processed_Data_Path,"") # Find any other plots stored in this directory previous_plots = glob.glob(self.Storage_Path + self.Tephigram_Plots_Path + path + "/*") # Find the biggest 'v' number in plots plot_version = [] for plots in previous_plots: try: plot_version.append(int(os.path.basename(plots)[34:37])) except ValueError: plot_version.append(int(os.path.basename(plots)[34:36])) plot_version = str(np.max(plot_version)+1) if len(plot_version) != 0 else '1' # Create full directory and file name Save_Location = self.Storage_Path + self.Tephigram_Plots_Path + path + '/' + path + '_v' + plot_version.rjust(2,'0') + '_' + str(self.height_range[0]).rjust(2,'0') + 'km_to_' + str(self.height_range[1]).rjust(2,'0') + 'km.png' # Ensure the directory exists on file system and save to that location gu.ensure_dir(os.path.dirname(Save_Location)) print("Save_Location", Save_Location) Tephigram.savefig(Save_Location) ############################################################################ """[Step 3] Calculate Stability Indices""" print("[INFO] Calculating Stability Indices...") # Common Pressure Levels P_500 = gu.argnear(Pres, 500) P_700 = gu.argnear(Pres, 700) P_850 = gu.argnear(Pres, 850) # Showalter stability index #S = Tdry[P_500] - Tl # K-Index K = (Tdry[P_850] - Tdry[P_500]) + Tdew[P_850] - (Tdry[P_700] - Tdew[P_700]) # Cross Totals Index CT = Tdew[P_850] - Tdry[P_500] # Vertical Totals Index VT = Tdry[P_850] - Tdry[P_500] # Total Totals Index TT = VT + CT # SWEAT Index ms2kn = 1.94384 # Conversion between m/s to knots SW_1 = 20*(TT-49) SW_2 = 12*Tdew[P_850] SW_3 = 2*Wind_Mag[P_850]*ms2kn SW_4 = Wind_Mag[P_500]*ms2kn SW_5 = 125*(np.sin(Wind_Dir[P_500]-Wind_Dir[P_850]) + 0.2) # Condition SWEAT Term 1 from several conditions SW_1 = 0 if SW_1 < 49 else SW_1 # Condition SWEAT Term 5 with several conditions if (Wind_Dir[P_850] > 130) & (Wind_Dir[P_850] < 250): if (Wind_Dir[P_500] > 210) & (Wind_Dir[P_500] < 310): if Wind_Dir[P_500]-Wind_Dir[P_850] > 0: if (Wind_Mag[P_500]*ms2kn > 15) & (Wind_Mag[P_850]*ms2kn > 15): SW_5 = SW_5 else: SW_5 = 0 else: SW_5 = 0 else: SW_5 = 0 else: SW_5 = 0 # Calulate Final Product SW = SW_1 + SW_2 + SW_3 + SW_4 + SW_5 print("Stability Indices") print("-----------------") print("K-Index:", K) print("Cross Totals Index:", CT) print("Vettical Totals Index:", VT) print("Total Totals Index:", TT) print("SWEAT Index:", SW) print("\n") ############################################################################ """[Step 4] Calculate Tephigram Indices""" # Convert Temperature back to Kelvin Tdry += 273.15 Tdew += 273.15 # Convert Height into metres Z *= 1000 print("Tdry", Tdry, Tdry.shape) print("Tdew", Tdew, Tdew.shape) print("Z", Z, Z.shape) # Constants over27 = 0.286 # Value used for calculating potential temperature 2/7 L = 2.5e6 #Latent evaporation 2.5x10^6 epsilon = 0.622 E = 6.014 #e in hpa Rd = 287 #R constant for dry air # Equations es = lambda T: 6.112*np.exp((17.67*(T-273.15))/(T-29.65)) #Teten's Formula for Saturated Vapour Pressure converted for the units of T in Kelvin rather than Centigrade # Calculate Theta and Theta Dew theta = Tdry*(1000/Pres)**over27 thetadew = Tdew*(1000/Pres)**over27 # Find the Lifting Condensation Level (LCL) qs_base = 0.622*es(Tdew[0])/Pres[0] theta_base = theta[0] Pqs_base = 0.622*es(Tdry)/qs_base #Calculate a pressure for constant qs Pqs_base = Tdry*(1000/Pqs_base)**(2/7) #Calculates pressure in term of P temp # print("Tdew[0]", Tdew[0]) # print("Pres[0]", Pres[0]) # print("qs_base",qs_base) # print("theta_base", theta_base) # print("Pqs_base", Pqs_base) # Find first location where Pqs_base > theta_base y1 = np.arange(Pqs_base.size)[Pqs_base > theta_base][0] # print(Pqs_base[y1]) # print(y1) # print(gu.argnear(Pqs_base, theta_base)) LCL = Z[y1] Tarr = np.zeros(Tdry.size) thetaarr = np.zeros(Tdry.size) T_temp = Tdry[y1] P_temp = 1000*(T_temp/Pqs_base[y1])**3.5 qs0 = 0.622*es(T_temp)/P_temp thetaarr[y1] = Pqs_base[y1] Tarr[y1] = T_temp for i in xrange(y1+1, y1+100): T_temp -= 1 P_temp = 1000*(T_temp/thetaarr[i-1])**3.5 qs = 0.622*es(T_temp)/P_temp thetaarr[i] = thetaarr[i-1] - ((2.5E6/1004)*(thetaarr[i-1]/T_temp) * (qs-qs0)) qs0 = qs Tarr[i] = T_temp # Now need to integrate back to 1000hpa T_temp = Tdry[y1] P_temp = 1000*(T_temp/Pqs_base[y1])**3.5 qs0 = 0.622*es(T_temp)/P_temp thetaarr[y1] = Pqs_base[y1] Tarr[y1] = T_temp for i in xrange(y1-1): T_temp += 1 P_temp = 1000*(T_temp/thetaarr[(y1-i)+1])**3.5 qs = 0.622*es(T_temp)/P_temp thetaarr[y1-i] = thetaarr[(y1-i)+1] - ((2.5E6/1004)*(thetaarr[(y1-i)+1]/T_temp) * (qs-qs0)) qs0 = qs Tarr[y1-i] = T_temp y8 = (thetaarr>253) & (thetaarr<380) thetaarr = thetaarr[y8] Tarr = Tarr[y8] # Now find environmental levels and LFC begin by converting thetaarr into P Pthetaeq = 1000/(thetaarr/Tarr)**3.5 l5 = np.isnan(Pthetaeq) Pthetaeq[l5] = [] # Now interpolate on to rs height co-ordinates TEMP = sp.interpolate.interp1d(Pthetaeq,[thetaarr,Tarr], fill_value="extrapolate")(Pres) thetaarr = TEMP[0] Tarr = TEMP[1] del(TEMP) y5 = np.arange(Tdry.size)[Tdry < Tarr] print("y5", y5) if np.any(y5): LFC = Z[y5[0]] EL = Z[y5[-1]] # Finds CIN area above LCL y6 = np.arange(Tdry.size)[(Z < LFC) & (Z >= LCL) & (Tdry > Tarr)] y7 = np.arange(Tdry.size)[(Z < LCL) & (Tdry > Tarr)] Pstart = Pres[y5[-1]] # Now need to calculate y5 temperatures into virtual temperatures Tvdash = Tarr/(1-(E/Pres)*(1-epsilon)) Tv = Tdry/(1-(E/Pres)*(1-epsilon)) T_adiabat = ((theta_base/(1000/Pres)**over27)) Tv_adiabat = T_adiabat/(1-(E/Pres)*(1-epsilon)) # Now need to calculate CAPE... and CIN to use CAPE = R_d = intergral(LFC,EL)(T'_v - T_v) d ln p CAPE = 0 for i in xrange(y5[-2], y5[0], -1): CAPE += (Rd*(Tvdash[i] - Tv[i]) * np.log(Pres[i]/Pres[i+1])); # Now we use same technique to calculate CIN CIN=0; if len(y6) != 0: for i in xrange(y6[-2], y6[0], -1): CIN += (Rd*(Tvdash[i] - Tv[i]) * np.log(Pres[i]/Pres[i+1])) # Now calculate temperature along the dry adiabat y7 = np.arange(Tdry.size)[(Z < LCL) & (Tv > Tv_adiabat)] if len(y7) != 0: for i in xrange(y7[-2], y7[0], -1): CIN += (Rd*(Tv_adiabat[i] - Tv[i]) * np.log(Pres[i]/Pres[i+1])); else: LFC = np.nan EL = np.nan CAPE = 0 CIN = 0 # Print out information print("Parcel Information") print("------------------") print("LCL = %.2fm" % LCL) print("LFC = %.2fm" % LFC) print("EL = %.2fm" % EL) print("CAPE %.2f J/kg" % CAPE) print("CIN %.2f J/kg" % CIN) print("\n") print("[INFO] Radiosonde_Tephigram has been completed successfully (In %.2fs)" % (time.time()-t_begin)) return LCL, LFC, EL, CAPE, CIN def CaseStudy_Overview(self): """ This method will be used to plot an overview of the PG timeseries and the Radiosonde datasets. For the satellite imagery, this should be completed manually. """ # Print the name of the method to the terminal if self.verbose is True: gu.cprint("[INFO] You are running CaseStudy_Overview from the \ DEV release", type='bold') ############################################################### """Prerequisites""" # Time Controls t_begin = time.time() # Conditionals Plot_PG = False Plot_Radiosonde = True Plot_Satellite = False # Variables Sensor_Package = np.arange(1,11) PG_Lag = 1 # Hours # Credentials username = 'jgilmore' password = '<PASSWORD>' # Plotting conditions gu.backend_changer() #Initalise Selenium driver driver = webdriver.PhantomJS(executable_path='/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/phantomjs/bin/phantomjs') ############################################################### """Sort the radiosonde ascent data in ascending time order""" with warnings.catch_warnings(): warnings.simplefilter("ignore") # Make a copy of the self.LaunchTime for comparison LaunchTime_Temp = self.LaunchTime.copy() # Find ascents which have not been flown yet NoFly = np.array(LaunchTime_Temp.keys())[gu.isnat(np.array(LaunchTime_Temp.values()))] # Change NoFly ascents to really high datetime to correct ordering bug for val in NoFly: LaunchTime_Temp[val] = np.datetime64("2100-01-01 00:00:00") # Sort LaunchTime_Temp in datetime order Sensor_Package_TimeOrder = np.array(sorted(LaunchTime_Temp, key=LaunchTime_Temp.get)) # Only select values in Sensor_Package Sensor_Package_TimeOrder = Sensor_Package_TimeOrder[np.in1d(Sensor_Package_TimeOrder, Sensor_Package)] print("Sensor_Package_TimeOrder", Sensor_Package_TimeOrder) for i in xrange(Sensor_Package_TimeOrder.size): print(i+1, Sensor_Package_TimeOrder[i], self.LaunchTime.get(Sensor_Package_TimeOrder[i])) ############################################################### if Plot_PG is True: ############################################################### """[Step 1] Plot all PG timeseries""" # Print information to console print("[INFO] Plotting all PG Timeseries") # Retrieve the PG data using PG_Plotter PG_Data_All = zip(np.zeros(Sensor_Package_TimeOrder.size)) for i, sensor in enumerate(Sensor_Package_TimeOrder): # Check LaunchTime has been specified if gu.isnat(self.LaunchTime[sensor]): PG_Data_All[i] = None continue # Define start and end times for PG plotting in python datetime Date_Start = (self.LaunchTime[sensor] - np.timedelta64(1,'h'))\ .astype(datetime) Date_End = (self.LaunchTime[sensor] + np.timedelta64(1,'h'))\ .astype(datetime) # Plot PG Data from RUAO PG_Data_All[i] = PG_Plotter( Location="RUAO", Date_Start=Date_Start, Date_End=Date_End, Print_Progress=False, Return_Data=True )._RUAO(Return_Data=True) # Plot the data plt.clf() plt.close() f, ax = plt.subplots(5,2) ax = ax.ravel() #for subplot in ax.ravel(): subplot.grid(which='major',axis='both',c='grey') for subplot in ax.ravel(): subplot.minorticks_on() for subplot in ax.ravel(): subplot.set_ylabel("PG (Vm$^{-1}$)") for i, sensor in enumerate(Sensor_Package_TimeOrder): if PG_Data_All[i] is not None: ax[i].plot(PG_Data_All[i][:,0], PG_Data_All[i][:,1], lw=1, c='dodgerblue') #Define time axis xticks = gu.time_axis((PG_Data_All[i][0,0], PG_Data_All[i][-1,0]), ax=ax[i], xlabel='Time (UTC)', format='auto', rotation=45) ax[i].axvline(x=self.LaunchTime[sensor].astype(datetime), c='black', ls='--', lw=1) else: ax[i].text(0.5, 0.5, "Data Unavailable", horizontalalignment='center', verticalalignment='center', fontsize=20, color='red', transform=ax[i].transAxes, alpha=0.5) # Annotate the subplots LaunchDate = self.LaunchTime[sensor].astype(datetime).strftime('%Y/%m/%d') if not gu.isnat(self.LaunchTime[sensor]) else 'TBL' ax[i].annotate("(%s) %s" % (gu.alphabet[i], 'Ascent No.%s (%s)' % (i + 1, LaunchDate)), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10) # Define plot size f.set_size_inches(10, 16) #A4 Size # Make sure all plotting elements are tight and don't overlap plt.tight_layout() # Make the launch time tick label BOLD labels = [[] for _ in range(Sensor_Package_TimeOrder.size)] for i, (sensor, subplot) in enumerate(zip(Sensor_Package_TimeOrder, ax.ravel())): if not gu.isnat(self.LaunchTime[sensor]): for item in subplot.get_xticklabels(): labels[i].append(item._text) # Find index where launchtime matches tick label index = gu.bool2int(np.array(labels[i]) == self.LaunchTime[sensor].astype(datetime).strftime('%H:%M'))[0] # Set the launch time label tick bold subplot.get_xticklabels()[index].set_fontweight('bold') # Save plot filename = gu.ensure_dir(self.Storage_Path + 'Plots/CaseStudy/Overview/PG_Timeseries_AllRadiosondes.png', dir_or_file='file') plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) if Plot_Radiosonde is True: ############################################################### """[Step 2] Plot all radiosonde datasets""" # Print information to console print("[INFO] Plot all Radiosonde Datasets") # Convert Sensor_Package to string which_ascents = Sensor_Package_TimeOrder.astype('S2') print("which_ascents", which_ascents) subplot = 0 ascent_num = 0 for page, ascents in enumerate(gu.broadcast(which_ascents, 2, 2)): # Create Titles plot_title = [] for ascent in ascents: # Update ascent number ascent_num += 1 if not gu.isnat(self.LaunchTime[int(ascent)]): plot_title.append("(" + gu.alphabet[subplot] + ") Flight No.%s" % str(ascent_num).rjust(2,"0") + ' (' + self.LaunchTime[int(ascent)].astype(datetime).strftime("%d/%m/%Y %H%MUTC") + ')') else: plot_title.append("(" + gu.alphabet[subplot] + ") Flight No.%s" % str(ascent_num).rjust(2,"0")) subplot += 1 # Plot all ascents together Superplotter = SPRadiosonde(self.Radiosonde_Data, numplots=7, which_ascents=ascents, height_range=[0,12], calibrate="Units", plot_title=plot_title) Superplotter.Cloud_Boundaries(self.Clouds_ID, self.LayerType, CloudOnly=True) # Plot data from charge instrument Superplotter.Charge(type='space_charge') # Plot data from cloud instrument Superplotter.Cloud(ir=True, cyan=True) # Plot data from liquid water instrument Superplotter.Liquid_Water(type='Liquid_Water', point=True) Superplotter.Liquid_Water(type='SLWC', point=True) # Plot data from turbulence instrument Superplotter.Turbulence(type='Turbulence') Superplotter.Turbulence(type='Eddy Dissipation Rate') # Save radiosonde plots filename = gu.ensure_dir(self.Storage_Path + 'Plots/CaseStudy/Overview/Radiosonde_Ascent_Page' + str(page).rjust(2,"0") + '.png', dir_or_file='file') Superplotter.savefig(filename) if Plot_Satellite is True: ############################################################### """[Step 3] Plot all Satellite Imagery""" # Print information to console print("[INFO] Plot all Satellite Imagery") Satellite_Imagery = np.full(Sensor_Package_TimeOrder.size, fill_value=None, dtype=object) Closest_Pass_All = np.full(Sensor_Package_TimeOrder.size, fill_value=None, dtype=object) for i, sensor in enumerate(Sensor_Package_TimeOrder): # Select launch time for radiosonde ascent number launch_time = self.LaunchTime[sensor] # Skip satellite retrievals for radiosondes that have not been launched yet if gu.isnat(launch_time): continue driver.get('http://' + username + ':' + password + '@www.sat.dundee.ac.uk/abin/browse/avhrr/' + \ launch_time.astype(datetime).strftime('%Y/%-m/%d')) # Get all bullet point elements Bullet_Points = np.array([str(item.text) for item in driver.find_elements_by_tag_name("li")]) Satellite_Passes = {'datetime': [], 'location': []} for bullet in Bullet_Points: try: Satellite_Passes['datetime'].append(datetime.strptime(bullet[:23], '%d %b %Y at %H%M UTC')) Satellite_Passes['location'].append(bullet[24:]) except: continue # Convert dictionary values to numpy arrays Satellite_Passes['datetime'] = np.array(Satellite_Passes['datetime'], dtype='datetime64[m]') Satellite_Passes['location'] = np.array(Satellite_Passes['location']) # Search for UK in location description index = [j for j, s in enumerate(Satellite_Passes['location']) if 'UK' in s] # Get possible passes in Satellite imagery Possible_Passes = Satellite_Passes['datetime'][index] # Find closest pass to launch time index = index[gu.argnear(Possible_Passes, launch_time)] # Get closest pass Closest_Pass = Satellite_Passes['datetime'][index] #print("Closest Pass", Satellite_Passes['datetime'][index], Satellite_Passes['location'][index], 'Delay = %.0fs' % (Satellite_Passes['datetime'][index] - launch_time).astype(int)) # Grab satellite imagery url = 'http://www.sat.dundee.ac.uk/abin/piccyjpeg/avhrr/' + launch_time.astype(datetime).strftime('%Y/%-m/%d') + \ '/' + Closest_Pass.astype(datetime).strftime('%H%M') + '/ch13.png' # Before grabbing image you need to authenticate yourself! gu.urllib_authentication(url, username, password) Satellite_Imagery[i] = urllib2.urlopen(url) # Save Closest_Pass to be used for plotting Closest_Pass_All[i] = Closest_Pass ############################################################################ """Plot the satellite images""" gu.backend_changer() # Set-up figure f, axes = plt.subplots(5,2) # Global attributes of subplots for subplot in axes.ravel(): subplot.minorticks_on() f.subplots_adjust(wspace=-0.70, hspace=0) f.set_size_inches(15,15) # Provide dimensions of map coinciding with UK map projection on DSRS lonW = -16.5 lonE = 12.1 latN = 62.0 latS = 46.4 #Map Resolution map_res = 'h' with warnings.catch_warnings(): warnings.simplefilter("ignore") for i, (sensor, ax) in enumerate(zip(Sensor_Package_TimeOrder, axes.flat)): # Create Basemap map = Basemap(projection='stere', lat_0=55, lon_0=-5, resolution=map_res, llcrnrlon=lonW, llcrnrlat=latS, urcrnrlon=lonE, urcrnrlat=latN, ax=ax) # Add overlays to map if i % 2 == 0: # Left-hand plots map.drawparallels(np.arange(-50, 90, 5),linewidth=0.5,color='DarkGrey',labels=[1,0,0,0], zorder=0) else: # Right-hand plots map.drawparallels(np.arange(-50, 90, 5),linewidth=0.5,color='DarkGrey',labels=[0,1,0,0], zorder=0) if i < 2: # Top row plots map.drawmeridians(np.arange(-50, 50, 10),linewidth=0.5,color='DarkGrey',labels=[0,0,1,0], zorder=0) elif i > 7: # Bottom row plots map.drawmeridians(np.arange(-50, 50, 5),linewidth=0.5,color='DarkGrey',labels=[0,0,0,1], zorder=0) if Satellite_Imagery[i] is not None: # Plot satellite image over the top now the coordinate reference frame # has been matched up image = plt.imread(Satellite_Imagery[i], 0) map.imshow(np.flipud(image), cmap='gray', vmin=0, vmax=255, interpolation='bilinear') # Draw countries map.drawcoastlines(color='dodgerblue', linewidth=0.5, zorder=1000) # Put red box marking out Reading # lat/lon coordinates to plot lats = [51.441314] lons = [-0.937447] # compute the native map projection coordinates x,y = map(lons,lats) map.scatter(x,y,s=30, edgecolors='red', marker='s', facecolors='none', alpha=1, zorder=5) launch_date = self.LaunchTime[sensor].astype(datetime).strftime('%Y/%m/%d %H:%M') if self.LaunchTime[sensor] is not None else 'TBL' satellite_date = Closest_Pass_All[i].astype(datetime).strftime('%Y/%m/%d %H:%M') if self.LaunchTime[sensor] is not None else 'TBL' ax.annotate("(%s) %s" % (gu.alphabet[i], 'Ascent No.%s' % (i + 1)), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10, color='white') ax.annotate("Launch Time: %s\nSatellite Time: %s" % ( launch_date, satellite_date), xy=(0, 0), xycoords='axes fraction', xytext=(20, 20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='bottom', fontsize=9, color='white') else: map.drawmapboundary(fill_color='white', zorder=0) map.fillcontinents(color='DimGrey', lake_color='white', zorder=0) map.drawcoastlines(color='DimGrey', linewidth=0.5, zorder=0) map.drawcountries(color='Grey', linewidth=0.5, zorder=0) ax.text(0.5, 0.5, "Radiosonde\nNot\nLaunched", horizontalalignment='center', verticalalignment='center', fontsize=20, color='red', transform=ax.transAxes, alpha=1.0) ax.annotate("(%s) %s" % (gu.alphabet[i], 'Ascent No.%s' % (i + 1)), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10, color='black') # Save satellite imagery filename = gu.ensure_dir(self.Storage_Path + 'Plots/CaseStudy/Overview/SatelliteImagery_AVHRR_AllRadiosondes.png', dir_or_file='file') plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) print("[INFO] CaseStudy_Overview has been completed successfully (In %.0fs)" % (time.time()-t_begin)) def CaseStudy_Specific(self): """ This method will be used for plotting all the required figures for the individual case studies that will be discussed in detail. """ # Print the name of the method to the terminal if self.verbose is True: gu.cprint("[INFO] You are running CaseStudy_Specific from the " "DEV release", type='bold') ############################################################### """Prerequisites""" # Time Controls t_begin = time.time() # Variables Sensor_Package = np.arange(1,11).astype('S2') # Conditionals Plot_PG = True Plot_Radiosonde = False Plot_Satellite = False Plot_SurfacePressure = False # Credentials username = 'jgilmore' password = '<PASSWORD>' # Plotting conditions gu.backend_changer() #Initalise Selenium driver driver = webdriver.PhantomJS(executable_path='/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/phantomjs/bin/phantomjs') ############################################################### """Sort the radiosonde ascent data in ascending time order""" with warnings.catch_warnings(): warnings.simplefilter("ignore") # Make a copy of the self.LaunchTime for comparison LaunchTime_Temp = self.LaunchTime.copy() # Find ascents which have not been flown yet NoFly = np.array(LaunchTime_Temp.keys())[gu.isnat(np.array(LaunchTime_Temp.values()))] # Change NoFly ascents to really high datetime to correct ordering bug for val in NoFly: LaunchTime_Temp[val] = np.datetime64("2100-01-01 00:00:00") # Sort LaunchTime_Temp in datetime order Sensor_Package_TimeOrder = np.array(sorted(LaunchTime_Temp, key=LaunchTime_Temp.get)) # Only select values in Sensor_Package Sensor_Package_TimeOrder = Sensor_Package_TimeOrder[np.in1d(Sensor_Package_TimeOrder, Sensor_Package.astype(int))] ############################################################### if Plot_PG is True: ############################################################### """[Step 1] PG Plots""" # Print information to console print("[INFO] Plot all PG Datasets for Case Studies") for sensor, sensor_sorted in zip(Sensor_Package.astype(int), Sensor_Package_TimeOrder): # Check LaunchTime has been specified if gu.isnat(self.LaunchTime[sensor]): continue # Define start and end times for PG plotting in python datetime Date_Start = (self.LaunchTime[sensor] - np.timedelta64(60,'m'))\ .astype(datetime) Date_End = (self.LaunchTime[sensor] + np.timedelta64(60,'m'))\ .astype(datetime) # Define save directory and filename Save_Dir = gu.ensure_dir(self.Storage_Path + 'Plots/CaseStudy/AscentNo.' + str(sensor).rjust(2,"0") + '/', dir_or_file='dir') File_Name = 'PG_AscentNo.' + str(sensor).rjust(2,"0") + '_CaseStudyVersion.png' # Plot PG Data from RUAO PG_Data = PG_Plotter( Location="RUAO", Date_Start=Date_Start, Date_End=Date_End, Print_Progress=False, Return_Data=True )._RUAO(Return_Data=True) # Plot the data plt.clf() plt.close() f, ax = plt.subplots() ax.grid(which='major',axis='both',c='grey') ax.minorticks_on() ax.set_ylabel("PG (Vm$^{-1}$)") if PG_Data is not None: ax.plot(PG_Data[:,0], PG_Data[:,1], lw=0.5, c='dodgerblue') #Define time axis xticks = gu.time_axis((PG_Data[0,0], PG_Data[-1,0]), ax=ax, xlabel='Time (UTC)', format='auto', rotation=0) ax.axvline(x=self.LaunchTime[sensor].astype(datetime), c='black', ls='--', lw=1) else: ax.text(0.5, 0.5, "Data Unavailable", horizontalalignment='center', verticalalignment='center', fontsize=20, color='red', transform=ax.transAxes, alpha=0.5) # Annotate the subplots LaunchDate = self.LaunchTime[sensor].astype(datetime).strftime('%Y/%m/%d') if not gu.isnat(self.LaunchTime[sensor]) else 'TBL' ax.annotate('(%s) Ascent No.%s (%s)' % (gu.alphabet[1], sensor_sorted, LaunchDate), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10) # Define plot size f.set_size_inches(8, 8) #A4 Size # Fix aspect ratio gu.fixed_aspect_ratio(ax=ax, ratio=1/4, adjustable=None) # Make sure all plotting elements are tight and don't overlap plt.tight_layout() # Format ticks launch_tick = np.append(ax.get_xticks(), date2num(self.LaunchTime[sensor].astype(datetime))) launch_tick = np.delete(launch_tick, gu.argnear(launch_tick, date2num(self.LaunchTime[sensor].astype(datetime)))) ax.set_xticks(launch_tick) ax.set_xticklabels(launch_tick) ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) # Make the launch time tick label BOLD labels = [] if not gu.isnat(self.LaunchTime[sensor]): for item in ax.get_xticklabels(): labels.append(item._text) # Find index where launchtime matches tick label index = gu.argnear(np.array(labels).astype(float), date2num(self.LaunchTime[sensor].astype(datetime))) # Set the launch time label tick bold ax.get_xticklabels()[index].set_fontweight('bold') # Save plot filename = Save_Dir + File_Name plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) if Plot_Radiosonde is True: ############################################################### """[Step 2] Radiosonde Plots""" # Print information to console print("[INFO] Plot all Radiosonde Datasets for Case Studies") for sensor in Sensor_Package: # Define plot title plot_title = ("(a) Raw Data", "(b) Processed Data") # Plot all ascents together Superplotter = SPRadiosonde(self.Radiosonde_Data, numplots=7, which_ascents=sensor, height_range=[0,12], calibrate=("Basic", "Units"), plot_title=plot_title) Superplotter.Cloud_Boundaries(self.Clouds_ID, self.LayerType, CloudOnly=True) # Plot data from charge instrument Superplotter.Charge(type='space_charge') # Plot data from cloud instrument Superplotter.Cloud(ir=True, cyan=True) # Plot data from liquid water instrument Superplotter.Liquid_Water(type='Liquid_Water', point=True) Superplotter.Liquid_Water(type='SLWC', point=True) # Plot data from turbulence instrument Superplotter.Turbulence(type='Turbulence') Superplotter.Turbulence(type='Eddy Dissipation Rate') # Save radiosonde plots filename = gu.ensure_dir(self.Storage_Path + 'Plots/CaseStudy/AscentNo.' + sensor.rjust(2,"0") + '/Radiosonde_AscentNo.' + sensor.rjust(2,"0") + '_CaseStudyVersion.png', dir_or_file='file') Superplotter.savefig(filename) if Plot_Satellite is True: ############################################################### """[Step 3] Get satellite images""" # Print information to console print("[INFO] Plot all Satellite Imagery for Case Studies") # Log in to Dundee driver.get('http://' + username + ':' + password + '@www.sat.dundee.ac.uk/abin/browse/avhrr/') for i, sensor in enumerate(Sensor_Package.astype(int)): # Select launch time for radiosonde ascent number launch_time = self.LaunchTime[sensor] # Skip satellite retrievals for radiosondes that have not been launched yet if gu.isnat(launch_time): continue driver.get('http://www.sat.dundee.ac.uk/abin/browse/avhrr/' + \ launch_time.astype(datetime).strftime('%Y/%-m/%d')) # Get all bullet point elements Bullet_Points = np.array([str(item.text) for item in driver.find_elements_by_tag_name("li")]) Satellite_Passes = {'datetime': [], 'location': []} for bullet in Bullet_Points: try: Satellite_Passes['datetime'].append(datetime.strptime(bullet[:23], '%d %b %Y at %H%M UTC')) Satellite_Passes['location'].append(bullet[24:]) except: continue # Convert dictionary values to numpy arrays Satellite_Passes['datetime'] = np.array(Satellite_Passes['datetime'], dtype='datetime64[m]') Satellite_Passes['location'] = np.array(Satellite_Passes['location']) # Search for UK in location description index = [j for j, s in enumerate(Satellite_Passes['location']) if 'UK' in s] # Get possible passes in Satellite imagery Possible_Passes = Satellite_Passes['datetime'][index] # Find closest pass to launch time index = index[gu.argnear(Possible_Passes, launch_time)] # Get closest pass Closest_Pass = Satellite_Passes['datetime'][index] #print("Closest Pass", Satellite_Passes['datetime'][index], Satellite_Passes['location'][index], 'Delay = %.0fs' % (Satellite_Passes['datetime'][index] - launch_time).astype(int)) # Grab satellite imagery url = 'http://www.sat.dundee.ac.uk/abin/piccyjpeg/avhrr/' + launch_time.astype(datetime).strftime('%Y/%-m/%d') + \ '/' + Closest_Pass.astype(datetime).strftime('%H%M') + '/ch13.png' # Before grabbing image you need to authenticate yourself! gu.urllib_authentication(url, username, password) # Download satellite imagery Satellite_Imagery = urllib2.urlopen(url) # Save Closest_Pass to be used for plotting Closest_Pass_All = Closest_Pass with warnings.catch_warnings(): warnings.simplefilter("ignore") # Set-up figure f, ax = plt.subplots() # Global attributes of subplots ax.minorticks_on() f.subplots_adjust(wspace=-0.70, hspace=0) f.set_size_inches(8,8) # Provide dimensions of map coinciding with UK map projection on DSRS lonW = -16.5 lonE = 12.1 latN = 62.0 latS = 46.4 #Map Resolution map_res = 'f' # Create Basemap map = Basemap(projection='stere', lat_0=55, lon_0=-5, resolution=map_res, llcrnrlon=lonW, llcrnrlat=latS, urcrnrlon=lonE, urcrnrlat=latN, ax=ax) # Add overlays to map map.drawparallels(np.arange(-50, 90, 5),linewidth=0.5,color='DarkGrey',labels=[1,0,0,0], zorder=0) map.drawmeridians(np.arange(-50, 50, 5),linewidth=0.5,color='DarkGrey',labels=[0,0,0,1], zorder=0) if Satellite_Imagery is not None: # Plot satellite image over the top now the coordinate reference frame # has been matched up image = plt.imread(Satellite_Imagery, 0) image = np.flipud(image) map.imshow(image, cmap='gray', vmin=0, vmax=255, interpolation='bilinear') # Draw countries map.drawcoastlines(color='dodgerblue', linewidth=0.5, zorder=1000) # Put red box marking out Reading # lat/lon coordinates to plot lats = [51.441314] lons = [-0.937447] # compute the native map projection coordinates x,y = map(lons,lats) map.scatter(x,y,s=30, edgecolors='red', marker='s', facecolors='none', alpha=1, zorder=5) launch_date = self.LaunchTime[sensor].astype(datetime).strftime('%Y/%m/%d %H:%M') if self.LaunchTime[sensor] is not None else 'TBL' satellite_date = Closest_Pass_All.astype(datetime).strftime('%Y/%m/%d %H:%M') if self.LaunchTime[sensor] is not None else 'TBL' ax.annotate("(%s) %s" % (gu.alphabet[i], 'Ascent No.%s' % (i + 1)), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10, color='white', bbox=dict(facecolor='black')) ax.annotate("Launch Time: %s\nSatellite Time: %s" % ( launch_date, satellite_date), xy=(0, 0), xycoords='axes fraction', xytext=(20, 20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='bottom', fontsize=9, color='white', bbox=dict(facecolor='black')) else: map.drawmapboundary(fill_color='white', zorder=0) map.fillcontinents(color='DimGrey', lake_color='white', zorder=0) map.drawcoastlines(color='DimGrey', linewidth=0.5, zorder=0) map.drawcountries(color='Grey', linewidth=0.5, zorder=0) ax.text(0.5, 0.5, "Radiosonde\nNot\nLaunched", horizontalalignment='center', verticalalignment='center', fontsize=20, color='red', transform=ax.transAxes, alpha=1.0) ax.annotate("(%s) %s" % (gu.alphabet[i], 'Ascent No.%s' % (i + 1)), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10, color='black') # Save satellite imagery filename = gu.ensure_dir(self.Storage_Path + 'Plots/CaseStudy/AscentNo.' + str(sensor).rjust(2,"0") + '/SatelliteImagery_AscentNo.' + str(sensor).rjust(2,"0") + '_CaseStudyVersion.png', dir_or_file='file') plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) if Plot_SurfacePressure is True: ############################################################### """[Step 4] Get surface pressure analysis""" # Print information to console print("[INFO] Plot all Surface Pressure Analysis Charts for Case Studies") for i, sensor in enumerate(Sensor_Package.astype(int)): # Select launch time for radiosonde ascent number launch_time = self.LaunchTime[sensor] # Skip satellite retrievals for radiosondes that have not been launched yet if gu.isnat(launch_time): continue # Find closest surface pressure analysis chart available Date = launch_time.astype(datetime).strftime('%y%m%d') Hour = gu.near(np.array([0, 6, 12, 18]), int(launch_time.astype(datetime).strftime('%H'))) # Download surface pressure chart filename_download = 'http://www1.wetter3.de/Archiv/UKMet/' + Date + Hour.astype(str).rjust(2,"0") + '_UKMet_Analyse.gif' filename_save = self.Storage_Path + 'Plots/CaseStudy/AscentNo.' + str(sensor).rjust(2,"0") + '/SurfacePressure_AscentNo.' + str(sensor).rjust(2,"0") + '_CaseStudyVersion.png' urllib.urlretrieve(filename_download, filename_save) print("[INFO] CaseStudy_Specific has been completed successfully (In %.0fs)" % (time.time()-t_begin)) def CaseStudy_Statistics(self): """ Outputs some bespoke statistics for the case studies. """ print("Looking at Sensor No.%s" % self.sensor_package) # Define the types of layers that can be detected. Cloud_Types = {0 : 'Clear Air', 1 : 'Moist (Not Cloud)', 2 : 'Cloud'} Tdry = self.Radiosonde_Data[self.sensor_package]["Units"]["Tdry"] Z = self.Radiosonde_Data[self.sensor_package]["Units"]["height"] for cloud in np.unique(self.Clouds_ID[self.sensor_package])[1:]: Cloud_Range = Z[self.Clouds_ID[self.sensor_package] == cloud] Cloud_Tdry = Tdry[self.Clouds_ID[self.sensor_package] == cloud] Freezing_Level = Z[gu.argnear(Tdry, 0)] if np.all(Cloud_Tdry > 0): print("Cloud %s. Cloud Base = %.2fkm, Cloud Top = %.2fkm, Cloud Depth = %.2fkm, Cloud Liquid Depth = %.2fkm, Cloud Ice Depth = 0.00km, Layer Type: %s" % (cloud, Cloud_Range[0], Cloud_Range[-1], Cloud_Range[-1]-Cloud_Range[0], Cloud_Range[-1]-Cloud_Range[0], Cloud_Types[self.LayerType[self.sensor_package][self.Clouds_ID[self.sensor_package] == cloud][0]])) elif np.all(Cloud_Tdry < 0): print("Cloud %s. Cloud Base = %.2fkm, Cloud Top = %.2fkm, Cloud Depth = %.2fkm, Cloud Liquid Depth = 0.00km, Cloud Ice Depth = %.2fkm, Layer Type: %s" % (cloud, Cloud_Range[0], Cloud_Range[-1], Cloud_Range[-1]-Cloud_Range[0], Cloud_Range[-1]-Cloud_Range[0], Cloud_Types[self.LayerType[self.sensor_package][self.Clouds_ID[self.sensor_package] == cloud][0]])) else: print("Cloud %s. Cloud Base = %.2fkm, Cloud Top = %.2fkm, Cloud Depth = %.2fkm, Cloud Liquid Depth = %.2fkm, Cloud Ice Depth = %.2fkm, Layer Type: %s" % (cloud, Cloud_Range[0], Cloud_Range[-1], Cloud_Range[-1]-Cloud_Range[0], Freezing_Level-Cloud_Range[0], Cloud_Range[-1]-Freezing_Level, Cloud_Types[self.LayerType[self.sensor_package][self.Clouds_ID[self.sensor_package] == cloud][0]])) def Hypothesis1(self): """ HYPOTHESIS 1: Convective clouds containing an ice phase and a high relative humidity with respects to ice will contain more charge. """ # Print the name of the method to the terminal if self.verbose is True: gu.cprint("[INFO] You are running Hypothesis1 from the DEV \ release", type='bold') ############################################################### """Prerequisites""" # Time Controls t_begin = time.time() # Radiosonde Data Radiosonde_Data = self.Radiosonde_Data.copy() Clouds_ID = self.Clouds_ID.copy() LayerType = self.LayerType.copy() # Set-up data importer EPCC_Data = EPCC_Importer() # Set-up plotting gu.backend_changer() # Conditionals section1 = True plot_spacecharge = False plot_cloud = True plot_ir = False plot_cyan = False plot_ircyan_diff = False plot_ircyan_div = False section2 = False ############################################################################ # Arrays Cloud_Type = [] Cloud_SpaceCharge = [] Cloud_IR = [] Cloud_Cyan = [] Cloud_IRdiffCyan = [] Cloud_IRdivCyan = [] Air_Type = [] Air_SpaceCharge = [] Air_IR = [] Air_Cyan = [] Air_IRdiffCyan = [] Air_IRdivCyan = [] Cloud_SpaceCharge_Liquid = [] Cloud_IR_Liquid = [] Cloud_Cyan_Liquid = [] Cloud_IRdiffCyan_Liquid = [] Cloud_IRdivCyan_Liquid = [] Cloud_RH_Liquid = [] Cloud_SpaceCharge_Ice = [] Cloud_IR_Ice = [] Cloud_Cyan_Ice = [] Cloud_IRdiffCyan_Ice = [] Cloud_IRdivCyan_Ice = [] Cloud_RH_Ice = [] Cloud_SpaceCharge_Mixed = [] Cloud_IR_Mixed = [] Cloud_Cyan_Mixed = [] Cloud_IRdiffCyan_Mixed = [] Cloud_IRdivCyan_Mixed = [] Cloud_RH_Mixed = [] Cloud_SpaceCharge_Mixed_Ice = [] Cloud_IR_Mixed_Ice = [] Cloud_Cyan_Mixed_Ice = [] Cloud_IRdiffCyan_Mixed_Ice = [] Cloud_IRdivCyan_Mixed_Ice = [] Cloud_RH_Mixed_Ice = [] Cloud_SpaceCharge_Mixed_Liquid = [] Cloud_IR_Mixed_Liquid = [] Cloud_Cyan_Mixed_Liquid = [] Cloud_IRdiffCyan_Mixed_Liquid = [] Cloud_IRdivCyan_Mixed_Liquid = [] Cloud_RH_Mixed_Liquid = [] Air_SpaceCharge_Liquid = [] Air_IR_Liquid = [] Air_Cyan_Liquid = [] Air_IRdiffCyan_Liquid = [] Air_IRdivCyan_Liquid = [] Air_RH_Liquid = [] Air_SpaceCharge_Ice = [] Air_IR_Ice = [] Air_Cyan_Ice = [] Air_IRdiffCyan_Ice = [] Air_IRdivCyan_Ice = [] Air_RH_Ice = [] Air_SpaceCharge_Mixed = [] Air_IR_Mixed = [] Air_Cyan_Mixed = [] Air_IRdiffCyan_Mixed = [] Air_IRdivCyan_Mixed = [] Air_RH_Mixed = [] Air_SpaceCharge_Mixed_Ice = [] Air_IR_Mixed_Ice = [] Air_Cyan_Mixed_Ice = [] Air_IRdiffCyan_Mixed_Ice = [] Air_IRdivCyan_Mixed_Ice = [] Air_RH_Mixed_Ice = [] Air_SpaceCharge_Mixed_Liquid = [] Air_IR_Mixed_Liquid = [] Air_Cyan_Mixed_Liquid = [] Air_IRdiffCyan_Mixed_Liquid = [] Air_IRdivCyan_Mixed_Liquid = [] Air_RH_Mixed_Liquid = [] Sensor_Package = np.arange(1,11).astype('S2') # Use for Space Charge Plots Only Sensor_Package = ['4', '5', '6', '9'] # Use for Space Charge Plots Only (Convective Subset) Sensor_Package = ['3', '4', '5', '9', '10'] # Use for Cloud Sensor Plots Only #Sensor_Package = ['9', '10'] #Sensor_Package = ['4'] for sensor in Sensor_Package: # Check the sensor has been processed by _RadiosondeImporter try: Radiosonde_Data[sensor] except KeyError: if self.verbose is True: print("[Warning] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (sensor)) continue # Get Cloud and Clear-Air Heights Cloud_Heights, Clear_Heights = self._CloudHeights(sensor=sensor, method='Zhang') # Remove nan's from data Time, Height, Tdry, RH, SpaceCharge, IR, Cyan = gu.antifinite((Radiosonde_Data[sensor]['Units']['time'], Radiosonde_Data[sensor]['Units']['height'], Radiosonde_Data[sensor]['Units']['Tdry'], Radiosonde_Data[sensor]['Units']['RHice'], np.abs(Radiosonde_Data[sensor]['Units']['SpaceCharge']), Radiosonde_Data[sensor]['Units']['IR_NC'], Radiosonde_Data[sensor]['Units']['Cyan_NC']), unpack=True) IRdiffCyan = IR - Cyan IRdivCyan = IR / Cyan for cloud in Cloud_Heights: # Get index of lowest cloud CloudIndex = gu.searchsorted(Height, cloud) # Subset data Tdry_Subset = Tdry[CloudIndex[0]:CloudIndex[1]] Height_Subset = Height[CloudIndex[0]:CloudIndex[1]] RH_Subset = RH[CloudIndex[0]:CloudIndex[1]] SpaceCharge_Subset = SpaceCharge[CloudIndex[0]:CloudIndex[1]] IR_Subset = IR[CloudIndex[0]:CloudIndex[1]] Cyan_Subset = Cyan[CloudIndex[0]:CloudIndex[1]] IRdiffCyan_Subset = IRdiffCyan[CloudIndex[0]:CloudIndex[1]] IRdivCyan_Subset = IRdivCyan[CloudIndex[0]:CloudIndex[1]] # Test whether cloud is a liquid, mixed or ice phase if np.all(Tdry_Subset > 0): Cloud_Type.append("Liquid") Cloud_SpaceCharge_Liquid.append(SpaceCharge_Subset) Cloud_IR_Liquid.append(IR_Subset) Cloud_Cyan_Liquid.append(Cyan_Subset) Cloud_IRdiffCyan_Liquid.append(IRdiffCyan_Subset) Cloud_IRdivCyan_Liquid.append(IRdivCyan_Subset) Cloud_RH_Liquid.append(RH_Subset) elif np.all(Tdry_Subset < 0): Cloud_Type.append("Ice") Cloud_SpaceCharge_Ice.append(SpaceCharge_Subset) Cloud_IR_Ice.append(IR_Subset) Cloud_Cyan_Ice.append(Cyan_Subset) Cloud_IRdiffCyan_Ice.append(IRdiffCyan_Subset) Cloud_IRdivCyan_Ice.append(IRdivCyan_Subset) Cloud_RH_Ice.append(RH_Subset) else: Cloud_Type.append("Mixed") Cloud_SpaceCharge_Mixed.append(SpaceCharge_Subset) Cloud_IR_Mixed.append(IR_Subset) Cloud_Cyan_Mixed.append(Cyan_Subset) Cloud_IRdiffCyan_Mixed.append(IRdiffCyan_Subset) Cloud_IRdivCyan_Mixed.append(IRdivCyan_Subset) Cloud_RH_Mixed.append(RH_Subset) # Subset data further into ice and liquid parts of the mixed phase cloud mask = Tdry_Subset < 0 Height_Subset2 = Height_Subset[mask] Cloud_SpaceCharge_Mixed_Ice.append(SpaceCharge_Subset[mask]) Cloud_IR_Mixed_Ice.append(IR_Subset[mask]) Cloud_Cyan_Mixed_Ice.append(Cyan_Subset[mask]) Cloud_IRdiffCyan_Mixed_Ice.append(IRdiffCyan_Subset[mask]) Cloud_IRdivCyan_Mixed_Ice.append(IRdivCyan_Subset[mask]) Cloud_RH_Mixed_Ice.append(RH_Subset[mask]) Height_Subset2 = Height_Subset[~mask] Cloud_SpaceCharge_Mixed_Liquid.append(SpaceCharge_Subset[~mask]) Cloud_IR_Mixed_Liquid.append(IR_Subset[~mask]) Cloud_Cyan_Mixed_Liquid.append(Cyan_Subset[~mask]) Cloud_IRdiffCyan_Mixed_Liquid.append(IRdiffCyan_Subset[~mask]) Cloud_IRdivCyan_Mixed_Liquid.append(IRdivCyan_Subset[~mask]) Cloud_RH_Mixed_Liquid.append(RH_Subset[~mask]) with warnings.catch_warnings(): warnings.simplefilter("ignore") Cloud_SpaceCharge.append(np.nanpercentile(SpaceCharge_Subset, 95)) Cloud_IR.append(np.nanpercentile(IR_Subset, 95)) Cloud_Cyan.append(np.nanpercentile(Cyan_Subset, 95)) Cloud_IRdiffCyan.append(np.nanpercentile(IRdiffCyan_Subset, 95)) Cloud_IRdivCyan.append(np.nanpercentile(IRdiffCyan_Subset, 95)) for air in Clear_Heights: # Get index of lowest air AirIndex = gu.searchsorted(Height, air) # Subset data Tdry_Subset = Tdry[AirIndex[0]:AirIndex[1]] Height_Subset = Height[AirIndex[0]:AirIndex[1]] RH_Subset = RH[AirIndex[0]:AirIndex[1]] SpaceCharge_Subset = SpaceCharge[AirIndex[0]:AirIndex[1]] IR_Subset = IR[AirIndex[0]:AirIndex[1]] Cyan_Subset = Cyan[AirIndex[0]:AirIndex[1]] IRdiffCyan_Subset = IRdiffCyan[AirIndex[0]:AirIndex[1]] IRdivCyan_Subset = IRdivCyan[AirIndex[0]:AirIndex[1]] #Test whether air is a liquid, mixed or ice phase if np.all(Tdry_Subset > 0): Air_Type.append("Liquid") Air_SpaceCharge_Liquid.append(SpaceCharge_Subset) Air_IR_Liquid.append(IR_Subset) Air_Cyan_Liquid.append(Cyan_Subset) Air_IRdiffCyan_Liquid.append(IRdiffCyan_Subset) Air_IRdivCyan_Liquid.append(IRdivCyan_Subset) Air_RH_Liquid.append(RH_Subset) elif np.all(Tdry_Subset < 0): Air_Type.append("Ice") Air_SpaceCharge_Ice.append(SpaceCharge_Subset) Air_IR_Ice.append(IR_Subset) Air_Cyan_Ice.append(Cyan_Subset) Air_IRdiffCyan_Ice.append(IRdiffCyan_Subset) Air_IRdivCyan_Ice.append(IRdivCyan_Subset) Air_RH_Ice.append(RH_Subset) else: Air_Type.append("Mixed") Air_SpaceCharge_Mixed.append(SpaceCharge_Subset) Air_IR_Mixed.append(IR_Subset) Air_Cyan_Mixed.append(Cyan_Subset) Air_IRdiffCyan_Mixed.append(IRdiffCyan_Subset) Air_IRdivCyan_Mixed.append(IRdivCyan_Subset) Air_RH_Mixed.append(RH_Subset) # Subset data further into ice and liquid parts of the mixed phase cloud mask = Tdry_Subset < 0 Height_Subset2 = Height_Subset[mask] Air_SpaceCharge_Mixed_Ice.append(SpaceCharge_Subset[mask]) Cloud_IR_Mixed_Ice.append(IR_Subset[mask]) Cloud_Cyan_Mixed_Ice.append(Cyan_Subset[mask]) Cloud_IRdiffCyan_Mixed_Ice.append(IRdiffCyan_Subset[mask]) Cloud_IRdivCyan_Mixed_Ice.append(IRdivCyan_Subset[mask]) Cloud_RH_Mixed_Ice.append(RH_Subset[mask]) Height_Subset2 = Height_Subset[~mask] Cloud_SpaceCharge_Mixed_Liquid.append(SpaceCharge_Subset[~mask]) Cloud_IR_Mixed_Liquid.append(IR_Subset[~mask]) Cloud_Cyan_Mixed_Liquid.append(Cyan_Subset[~mask]) Cloud_IRdiffCyan_Mixed_Liquid.append(IRdiffCyan_Subset[~mask]) Cloud_IRdivCyan_Mixed_Liquid.append(IRdivCyan_Subset[~mask]) Cloud_RH_Mixed_Liquid.append(RH_Subset[~mask]) with warnings.catch_warnings(): warnings.simplefilter("ignore") Air_SpaceCharge.append(np.nanpercentile(SpaceCharge_Subset, 95)) Air_IR.append(np.nanpercentile(IR_Subset, 95)) Air_Cyan.append(np.nanpercentile(Cyan_Subset, 95)) Air_IRdiffCyan.append(np.nanpercentile(IRdiffCyan_Subset, 95)) Air_IRdivCyan.append(np.nanpercentile(IRdivCyan_Subset, 95)) #Flatten arrays Cloud_SpaceCharge_Liquid = gu.flatten(Cloud_SpaceCharge_Liquid, type='ndarray', dtype=np.float64) Cloud_SpaceCharge_Ice = gu.flatten(Cloud_SpaceCharge_Ice, type='ndarray', dtype=np.float64) Cloud_SpaceCharge_Mixed = gu.flatten(Cloud_SpaceCharge_Mixed, type='ndarray', dtype=np.float64) Cloud_SpaceCharge_Mixed_Ice = gu.flatten(Cloud_SpaceCharge_Mixed_Ice, type='ndarray', dtype=np.float64) Cloud_SpaceCharge_Mixed_Liquid = gu.flatten(Cloud_SpaceCharge_Mixed_Liquid, type='ndarray', dtype=np.float64) Cloud_IR_Liquid = np.round(gu.flatten(Cloud_IR_Liquid, type='ndarray', dtype=np.float64)).astype(int) Cloud_IR_Ice = np.round(gu.flatten(Cloud_IR_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_IR_Mixed = np.round(gu.flatten(Cloud_IR_Mixed, type='ndarray', dtype=np.float64)).astype(int) Cloud_IR_Mixed_Ice = np.round(gu.flatten(Cloud_IR_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_IR_Mixed_Liquid = np.round(gu.flatten(Cloud_IR_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) Cloud_Cyan_Liquid = np.round(gu.flatten(Cloud_Cyan_Liquid, type='ndarray', dtype=np.float64)).astype(int) Cloud_Cyan_Ice = np.round(gu.flatten(Cloud_Cyan_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_Cyan_Mixed = np.round(gu.flatten(Cloud_Cyan_Mixed, type='ndarray', dtype=np.float64)).astype(int) Cloud_Cyan_Mixed_Ice = np.round(gu.flatten(Cloud_Cyan_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_Cyan_Mixed_Liquid = np.round(gu.flatten(Cloud_Cyan_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdiffCyan_Liquid = np.round(gu.flatten(Cloud_IRdiffCyan_Liquid, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdiffCyan_Ice = np.round(gu.flatten(Cloud_IRdiffCyan_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdiffCyan_Mixed = np.round(gu.flatten(Cloud_IRdiffCyan_Mixed, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdiffCyan_Mixed_Ice = np.round(gu.flatten(Cloud_IRdiffCyan_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdiffCyan_Mixed_Liquid = np.round(gu.flatten(Cloud_IRdiffCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdivCyan_Liquid = np.round(gu.flatten(Cloud_IRdivCyan_Liquid, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdivCyan_Ice = np.round(gu.flatten(Cloud_IRdivCyan_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdivCyan_Mixed = np.round(gu.flatten(Cloud_IRdivCyan_Mixed, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdivCyan_Mixed_Ice = np.round(gu.flatten(Cloud_IRdivCyan_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Cloud_IRdivCyan_Mixed_Liquid = np.round(gu.flatten(Cloud_IRdivCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_SpaceCharge_Liquid = gu.flatten(Air_SpaceCharge_Liquid, type='ndarray', dtype=np.float64) Air_SpaceCharge_Ice = gu.flatten(Air_SpaceCharge_Ice, type='ndarray', dtype=np.float64) Air_SpaceCharge_Mixed = gu.flatten(Air_SpaceCharge_Mixed, type='ndarray', dtype=np.float64) Air_SpaceCharge_Mixed_Ice = gu.flatten(Air_SpaceCharge_Mixed_Ice, type='ndarray', dtype=np.float64) Air_SpaceCharge_Mixed_Liquid = gu.flatten(Air_SpaceCharge_Mixed_Liquid, type='ndarray', dtype=np.float64) Air_IR_Liquid = np.round(gu.flatten(Air_IR_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_IR_Ice = np.round(gu.flatten(Air_IR_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_IR_Mixed = np.round(gu.flatten(Air_IR_Mixed, type='ndarray', dtype=np.float64)).astype(int) Air_IR_Mixed_Ice = np.round(gu.flatten(Air_IR_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_IR_Mixed_Liquid = np.round(gu.flatten(Air_IR_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_Cyan_Liquid = np.round(gu.flatten(Air_Cyan_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_Cyan_Ice = np.round(gu.flatten(Air_Cyan_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_Cyan_Mixed = np.round(gu.flatten(Air_Cyan_Mixed, type='ndarray', dtype=np.float64)).astype(int) Air_Cyan_Mixed_Ice = np.round(gu.flatten(Air_Cyan_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_Cyan_Mixed_Liquid = np.round(gu.flatten(Air_Cyan_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_IRdiffCyan_Liquid = np.round(gu.flatten(Air_IRdiffCyan_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_IRdiffCyan_Ice = np.round(gu.flatten(Air_IRdiffCyan_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_IRdiffCyan_Mixed = np.round(gu.flatten(Air_IRdiffCyan_Mixed, type='ndarray', dtype=np.float64)).astype(int) Air_IRdiffCyan_Mixed_Ice = np.round(gu.flatten(Air_IRdiffCyan_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_IRdiffCyan_Mixed_Liquid = np.round(gu.flatten(Air_IRdiffCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_IRdivCyan_Liquid = np.round(gu.flatten(Air_IRdivCyan_Liquid, type='ndarray', dtype=np.float64)).astype(int) Air_IRdivCyan_Ice = np.round(gu.flatten(Air_IRdivCyan_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_IRdivCyan_Mixed = np.round(gu.flatten(Air_IRdivCyan_Mixed, type='ndarray', dtype=np.float64)).astype(int) Air_IRdivCyan_Mixed_Ice = np.round(gu.flatten(Air_IRdivCyan_Mixed_Ice, type='ndarray', dtype=np.float64)).astype(int) Air_IRdivCyan_Mixed_Liquid = np.round(gu.flatten(Air_IRdivCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)).astype(int) if section1 is True: """Plots the back-to-back histograms of the space charge, IR and cyan for liquid, mixed and ice clouds""" if plot_spacecharge is True: ############################################################################# """Space Charge""" # Calculate the Mann-Whitney and Wilcoxon statistical tests print("Liquid-Ice Clouds\n" "-----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_SpaceCharge_Liquid, np.random.choice(Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Liquid.size))) print("Liquid-Mixed Clouds\n" "-------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_SpaceCharge_Liquid, np.random.choice(Cloud_SpaceCharge_Mixed, Cloud_SpaceCharge_Liquid.size))) print("Ice-Mixed Clouds\n" "----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_SpaceCharge_Ice, np.random.choice(Cloud_SpaceCharge_Mixed, Cloud_SpaceCharge_Ice.size))) print("Mixed (Liquid) - Mixed (Ice) Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_SpaceCharge_Mixed_Liquid, Cloud_SpaceCharge_Mixed_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_SpaceCharge_Mixed_Liquid, np.random.choice(Cloud_SpaceCharge_Mixed_Ice, Cloud_SpaceCharge_Mixed_Liquid.size))) print("Liquid Air - Liquid Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_SpaceCharge_Liquid, Cloud_SpaceCharge_Liquid, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_SpaceCharge_Liquid, np.random.choice(Cloud_SpaceCharge_Liquid, Air_SpaceCharge_Liquid.size))) print("Ice Air - Ice Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_SpaceCharge_Ice, Cloud_SpaceCharge_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_SpaceCharge_Ice, np.random.choice(Cloud_SpaceCharge_Ice, Air_SpaceCharge_Ice.size))) print("Mixed Air - Mixed Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_SpaceCharge_Mixed, Cloud_SpaceCharge_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_SpaceCharge_Mixed, np.random.choice(Cloud_SpaceCharge_Mixed, Air_SpaceCharge_Mixed.size))) ### Back2Back_Histogram ### data = [[Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Mixed], [Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Ice], [Cloud_SpaceCharge_Mixed, Cloud_SpaceCharge_Ice]] ylabel = [["Space Charge (pC m$^{-3}$)", "Space Charge (pC m$^{-3}$)"], ["Space Charge (pC m$^{-3}$)", "Space Charge (pC m$^{-3}$)"], ["Space Charge (pC m$^{-3}$)", "Space Charge (pC m$^{-3}$)"]] annotate = [["Liquid Clouds", "Mixed Clouds"], ["Liquid Clouds", "Ice Clouds"], ["Mixed Clouds", "Ice Clouds"]] name = [["Liquid", "Mixed"], ["Liquid", "Ice"], ["Mixed", "Ice"]] bins = [[20,20], [20,20], [20,20]] ylim = [[[0.001,6000],[0.001,6000]], [[0.001,6000],[0.001,6000]], [[0.001,6000],[0.001,6000]]] xscale = [['log', 'log'], ['log', 'log'], ['log', 'log']] yscale = [['linear', 'linear'], ['linear', 'linear'], ['linear', 'linear']] filename = self.Storage_Path + 'Plots/Hypothesis_1/SpaceCharge_AllPhasesClouds_Histogram.png' Histogram_Back2Back( data, filename, bins, ylabel, annotate, None, xscale, yscale) ### Side2Side histogram ### data = [Cloud_SpaceCharge_Liquid/1000, Cloud_SpaceCharge_Ice/1000, [Cloud_SpaceCharge_Mixed_Liquid/1000, Cloud_SpaceCharge_Mixed_Ice/1000]] annotate = ["Liquid Cloud Layer", "Ice Cloud Layer", "Mixed Cloud Layer"] bins = 'doane' ylabel = ["Space Charge Density (nC m$^{-3}$)", "Space Charge Density (nC m$^{-3}$)", "Space Charge Density (nC m$^{-3}$)"] xscale = ['log', 'log', 'log'] yscale = ['linear', 'linear', 'linear'] ylim = [[0.001,25], [0.001,25], [0.001,25]] color = ["green", "blue", ["green", "blue"]] filename = self.Storage_Path + 'Plots/Hypothesis_1/SpaceCharge_AllPhasesClouds_Histogram_Ravel.png' bins = Histogram_Side2Side( data, filename, bins, ylabel, annotate, ylim, xscale, yscale, color, plot_stats=False, fontsize=14) #data = [Air_SpaceCharge_Liquid/1000, Air_SpaceCharge_Ice/1000, Air_SpaceCharge_Mixed/1000] print("Lengths") print("Air_SpaceCharge_Liquid", Air_SpaceCharge_Liquid.size) print("Air_SpaceCharge_Ice", Air_SpaceCharge_Ice.size) print("Air_SpaceCharge_Mixed", Air_SpaceCharge_Mixed.size) print("Air_SpaceCharge_Mixed_Liquid", Air_SpaceCharge_Mixed_Liquid.size) print("Air_SpaceCharge_Mixed_Ice", Air_SpaceCharge_Mixed_Ice.size) data = [Air_SpaceCharge_Liquid/1000, Air_SpaceCharge_Ice/1000, [Air_SpaceCharge_Mixed_Liquid/1000, Air_SpaceCharge_Mixed_Ice/1000]] annotate = ["Super-Zero\n Dry-Air Layer", "Sub-Zero\n Dry-Air Layer", "Mixed Dry-Air Layer"] filename = self.Storage_Path + 'Plots/Hypothesis_1/SpaceCharge_AllPhasesAir_Histogram_Ravel.png' Histogram_Side2Side( data, filename, bins, ylabel, annotate, ylim, xscale, yscale, color, plot_stats=False, fontsize=14) data = [Cloud_SpaceCharge_Mixed_Liquid/1000, Cloud_SpaceCharge_Mixed_Ice/1000] annotate = ["Mixed Clouds (Liquid Phase)", "Mixed Clouds (Ice Phase)"] bins = 'doane' ylabel = ["Space Charge Density (nC m$^{-3}$)", "Space Charge Density (nC m$^{-3}$)"] xscale = ['log', 'log'] yscale = ['linear', 'linear'] ylim = [[0.001,10], [0.001,10]] color = ["green", "blue"] filename = self.Storage_Path + 'Plots/Hypothesis_1/SpaceCharge_AllPhasesMixedClouds_Histogram_Ravel.png' Histogram_Side2Side( data, filename, bins, ylabel, annotate, None, xscale, yscale, color, plot_stats=False) #### BOXPLOT ### # Liquid, Ice, Mixed Clouds data = [Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Mixed] filename = self.Storage_Path + 'Plots/Hypothesis_1/SpaceCharge_AllPhasesClouds_BoxPlot.png' positions = [3, 6, 9] colors = [gu.rgb2hex(210,0,46), gu.rgb2hex(0,112,192), gu.rgb2hex(146,208,80)] xticklabel = ['Liquid Clouds', 'Ice Clouds', 'Mixed Clouds'] xlabel = "Cloud Type" ylabel = "Space Charge Density(pC m$^{-3}$)" yscale = 'log' BoxPlots( plot_data=data, plot_filename=filename, plot_xlabel=xlabel, plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None, plot_yscale=yscale, plot_group_color=colors, plot_indivdual_color=None, plot_positions=positions, plot_legend=None) # Liquid Air - Liquid Clouds data = [Air_SpaceCharge_Liquid, Cloud_SpaceCharge_Liquid] filename = self.Storage_Path + 'Plots/Hypothesis_1/SpaceCharge_LiquidPhases_BoxPlot.png' positions = [2.5, 4.5] colors = [gu.rgb2hex(210,0,46), gu.rgb2hex(0,112,192)] xticklabel = ['Liquid Air', 'Liquid Clouds'] xlabel = "Cloud Type" ylabel = "Space Charge Density (pC m$^{-3}$)" yscale = 'log' BoxPlots( plot_data=data, plot_filename=filename, plot_xlabel=xlabel, plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None, plot_yscale=yscale, plot_group_color=colors, plot_indivdual_color=None, plot_positions=positions, plot_legend=None) # Liquid, Ice, Mixed Air/Clouds data = [[Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Mixed], [Air_SpaceCharge_Liquid, Air_SpaceCharge_Ice, Air_SpaceCharge_Mixed]] filename = self.Storage_Path + 'Plots/Hypothesis_1/SpaceCharge_AllPhases_AllTypes_BoxPlot.png' positions = [[1, 6, 11], [3, 8, 13]] group_colors = ["green", "blue", "pink"] individual_colors = ["dodgerblue", "purple"] legend = ['Cloud', 'Air'] xticklabel = ['Liquid Phase', 'Ice Phase', 'Mixed Phase'] xlabel = "Cloud Type" ylabel = "Space Charge Density (pC m$^{-3}$)" yscale = 'log' BoxPlots( plot_data=data, plot_filename=filename, plot_xlabel=xlabel, plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None, plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color=individual_colors, plot_positions=positions, plot_legend=legend) if plot_cloud: data = [[Cloud_IR_Liquid, Cloud_IR_Ice, [Cloud_IR_Mixed_Liquid, Cloud_IR_Mixed_Ice]], [Cloud_Cyan_Liquid, Cloud_Cyan_Ice, [Cloud_Cyan_Mixed_Liquid, Cloud_Cyan_Mixed_Ice]], [Cloud_IRdiffCyan_Liquid, Cloud_IRdiffCyan_Ice, [Cloud_IRdiffCyan_Mixed_Liquid, Cloud_IRdiffCyan_Mixed_Ice]]] gu.stats(gu.flatten(data, type='ndarray', dtype=float, level=-1), output=True) annotate = [["Liquid Cloud Layers", "Ice Cloud Layers", "Mixed Cloud Layers"], ["Liquid Cloud Layers", "Ice Cloud Layers", "Mixed Cloud Layers"], ["Liquid Cloud Layers", "Ice Cloud Layers", "Mixed Cloud Layers"]] bins = [[23,23,23], [23,23,23], [23,23,23]] bins = 'doane' ylabel = [["Infrared $N_{con}$ (cm$^{-3}$)", "Infrared $N_{con}$ (cm$^{-3}$)", "Infrared $N_{con}$ (cm$^{-3}$)"], ["Cyan $N_{con}$ (cm$^{-3}$)", "Cyan $N_{con}$ (cm$^{-3}$)", "Cyan $N_{con}$ (cm$^{-3}$)"], ["Infrared - Cyan $N_{con}$ (cm$^{-3}$)", "Infrared - Cyan $N_{con}$ (cm$^{-3}$)", "Infrared - Cyan $N_{con}$ (cm$^{-3}$)"]] xscale = [['log', 'log', 'log'], ['log', 'log', 'log'], ['log', 'log', 'log']] yscale = [['linear', 'linear', 'linear'], ['linear', 'linear', 'linear'], ['linear', 'linear', 'linear']] ylim = [[[0,500], [0,500], [0,500]], [[0,500], [0,500], [0,500]], [[-350,350], [-350,350], [-350,350]]] color = [["green", "blue", ["green", "blue"]], ["green", "blue", ["green", "blue"]], ["green", "blue", ["green", "blue"]]] filename = self.Storage_Path + 'Plots/Hypothesis_1/Cloud_AllPhasesClouds_Histogram_Ravel.png' bins = Histogram_Side2Side( data, filename, bins, ylabel, annotate, ylim, xscale, yscale, color, plot_stats=False, fontsize=14) if plot_ir is True: ############################################################################ """IR""" # Calculate the Mann-Whitney and Wilcoxon statistical tests print("Liquid-Ice Clouds\n" "-----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_IR_Liquid, Cloud_IR_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_IR_Liquid, np.random.choice(Cloud_IR_Ice, Cloud_IR_Liquid.size))) print("Liquid-Mixed Clouds\n" "-------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_IR_Liquid, Cloud_IR_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_IR_Liquid, np.random.choice(Cloud_IR_Mixed, Cloud_IR_Liquid.size))) print("Ice-Mixed Clouds\n" "----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_IR_Ice, Cloud_IR_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_IR_Ice, np.random.choice(Cloud_IR_Mixed, Cloud_IR_Ice.size))) print("Mixed (Liquid) - Mixed (Ice) Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_IR_Mixed_Liquid, Cloud_IR_Mixed_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_IR_Mixed_Liquid, np.random.choice(Cloud_IR_Mixed_Ice, Cloud_IR_Mixed_Liquid.size))) print("Liquid Air - Liquid Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_IR_Liquid, Cloud_IR_Liquid, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_IR_Liquid, np.random.choice(Cloud_IR_Liquid, Air_IR_Liquid.size))) print("Ice Air - Ice Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_IR_Ice, Cloud_IR_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_IR_Ice, np.random.choice(Cloud_IR_Ice, Air_IR_Ice.size))) print("Mixed Air - Mixed Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_IR_Mixed, Cloud_IR_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_IR_Mixed, np.random.choice(Cloud_IR_Mixed, Air_IR_Mixed.size))) ### Side2Side histogram ### data = [Cloud_IR_Liquid, Cloud_IR_Ice, Cloud_IR_Mixed] annotate = ["Liquid Clouds", "Ice Clouds", "Mixed Clouds"] bins = 'doane' ylabel = ["Number Concentration by IR sensor (cm$^{-3}$)", "Number Concentration by IR sensor (cm$^{-3}$)", "Number Concentration by IR sensor (cm$^{-3}$)"] xscale = ['log', 'log', 'log'] yscale = ['linear', 'linear', 'linear'] ylim = [[1,500], [1,500], [1,500]] color = ["green", "blue", "pink"] filename = self.Storage_Path + 'Plots/Hypothesis_1/IR_AllPhasesClouds_Histogram_Ravel.png' bins = Histogram_Side2Side( data, filename, bins, ylabel, annotate, ylim, xscale, yscale, color, plot_stats=False) # Mixed Liquid-Ice data = [Cloud_IR_Mixed_Liquid, Cloud_IR_Mixed_Ice] annotate = ["Mixed Clouds (Liquid Phase)", "Mixed Clouds (Ice Phase)"] bins = 'doane' ylabel = ["Number Concentration by IR sensor (cm$^{-3}$)", "Number Concentration by IR sensor (cm$^{-3}$)"] xscale = ['log', 'log'] yscale = ['linear', 'linear'] ylim = [[0.001,10], [0.001,10]] color = ["green", "blue"] filename = self.Storage_Path + 'Plots/Hypothesis_1/IR_AllPhasesMixedClouds_Histogram_Ravel.png' Histogram_Side2Side( data, filename, bins, ylabel, annotate, None, xscale, yscale, color, plot_stats=False) ### Box Plot ### # Liquid, Ice, Mixed Air/Clouds data = [[Cloud_IR_Liquid, Cloud_IR_Ice, Cloud_IR_Mixed], [Air_IR_Liquid, Air_IR_Ice, Air_IR_Mixed]] filename = self.Storage_Path + 'Plots/Hypothesis_1/IR_AllPhases_AllTypes_BoxPlot.png' positions = [[1, 6, 11], [3, 8, 13]] group_colors = ["green", "blue", "pink"] individual_colors = ["dodgerblue", "purple"] legend = ['Cloud', 'Air'] xticklabel = ['Liquid Phase', 'Ice Phase', 'Mixed Phase'] xlabel = "Cloud Type" ylabel = "Number Concentration by IR sensor (cm$^{-3}$)" yscale = 'log' BoxPlots( plot_data=data, plot_filename=filename, plot_xlabel=xlabel, plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None, plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color=individual_colors, plot_positions=positions, plot_legend=legend) if plot_cyan is True: ############################################################################ """Cyan""" # Calculate the Mann-Whitney and Wilcoxon statistical tests print("Liquid-Ice Clouds\n" "-----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_Cyan_Liquid, Cloud_Cyan_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Liquid, np.random.choice(Cloud_Cyan_Ice, Cloud_Cyan_Liquid.size))) print("Liquid-Mixed Clouds\n" "-------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_Cyan_Liquid, Cloud_Cyan_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Liquid, np.random.choice(Cloud_Cyan_Mixed, Cloud_Cyan_Liquid.size))) print("Ice-Mixed Clouds\n" "----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_Cyan_Ice, Cloud_Cyan_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Ice, np.random.choice(Cloud_Cyan_Mixed, Cloud_Cyan_Ice.size))) print("Mixed (Liquid) - Mixed (Ice) Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_Cyan_Mixed_Liquid, Cloud_Cyan_Mixed_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Mixed_Liquid, np.random.choice(Cloud_Cyan_Mixed_Ice, Cloud_Cyan_Mixed_Liquid.size))) print("Liquid Air - Liquid Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_Cyan_Liquid, Cloud_Cyan_Liquid, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_Cyan_Liquid, np.random.choice(Cloud_Cyan_Liquid, Air_Cyan_Liquid.size))) print("Ice Air - Ice Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_Cyan_Ice, Cloud_Cyan_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_Cyan_Ice, np.random.choice(Cloud_Cyan_Ice, Air_Cyan_Ice.size))) print("Mixed Air - Mixed Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_Cyan_Mixed, Cloud_Cyan_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_Cyan_Mixed, np.random.choice(Cloud_Cyan_Mixed, Air_Cyan_Mixed.size))) ### Side2Side histogram ### data = [Cloud_Cyan_Liquid, Cloud_Cyan_Ice, Cloud_Cyan_Mixed] annotate = ["Liquid Clouds", "Ice Clouds", "Mixed Clouds"] bins = 'doane' ylabel = ["Number Concentration by Cyan sensor (cm$^{-3}$)", "Number Concentration by Cyan sensor (cm$^{-3}$)", "Number Concentration by Cyan sensor (cm$^{-3}$)"] xscale = ['log', 'log', 'log'] yscale = ['linear', 'linear', 'linear'] ylim = [[1,500], [1,500], [1,500]] color = ["green", "blue", "pink"] filename = self.Storage_Path + 'Plots/Hypothesis_1/Cyan_AllPhasesClouds_Histogram_Ravel.png' bins = Histogram_Side2Side( data, filename, bins, ylabel, annotate, ylim, xscale, yscale, color, plot_stats=False) # Mixed Liquid-Ice data = [Cloud_Cyan_Mixed_Liquid, Cloud_Cyan_Mixed_Ice] annotate = ["Mixed Clouds (Liquid Phase)", "Mixed Clouds (Ice Phase)"] bins = 'doane' ylabel = ["Number Concentration by Cyan sensor (cm$^{-3}$)", "Number Concentration by Cyan sensor (cm$^{-3}$)"] xscale = ['log', 'log'] yscale = ['linear', 'linear'] ylim = [[0.001,10], [0.001,10]] color = ["green", "blue"] filename = self.Storage_Path + 'Plots/Hypothesis_1/Cyan_AllPhasesMixedClouds_Histogram_Ravel.png' Histogram_Side2Side( data, filename, bins, ylabel, annotate, None, xscale, yscale, color, plot_stats=False) ### Box Plot ### # Liquid, Ice, Mixed Air/Clouds data = [[Cloud_Cyan_Liquid, Cloud_Cyan_Ice, Cloud_Cyan_Mixed], [Air_Cyan_Liquid, Air_Cyan_Ice, Air_Cyan_Mixed]] filename = self.Storage_Path + 'Plots/Hypothesis_1/Cyan_AllPhases_AllTypes_BoxPlot.png' positions = [[1, 6, 11], [3, 8, 13]] group_colors = ["green", "blue", "pink"] individual_colors = ["dodgerblue", "purple"] legend = ['Cloud', 'Air'] xticklabel = ['Liquid Phase', 'Ice Phase', 'Mixed Phase'] xlabel = "Cloud Type" ylabel = "Number Concentration by Cyan sensor (cm$^{-3}$)" yscale = 'log' BoxPlots( plot_data=data, plot_filename=filename, plot_xlabel=xlabel, plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None, plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color=individual_colors, plot_positions=positions, plot_legend=legend) if plot_ircyan_diff is True: ############################################################################ """IR - Cyan""" print("[INFO] Plotting IR - Cyan") # Calculate the Mann-Whitney and Wilcoxon statistical tests print("Liquid-Ice Clouds\n" "-----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_IRdiffCyan_Liquid, Cloud_IRdiffCyan_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Liquid, np.random.choice(Cloud_Cyan_Ice, Cloud_Cyan_Liquid.size))) print("Liquid-Mixed Clouds\n" "-------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_Cyan_Liquid, Cloud_Cyan_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Liquid, np.random.choice(Cloud_Cyan_Mixed, Cloud_Cyan_Liquid.size))) print("Ice-Mixed Clouds\n" "----------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_Cyan_Ice, Cloud_Cyan_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Ice, np.random.choice(Cloud_Cyan_Mixed, Cloud_Cyan_Ice.size))) print("Mixed (Liquid) - Mixed (Ice) Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Cloud_Cyan_Mixed_Liquid, Cloud_Cyan_Mixed_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Cloud_Cyan_Mixed_Liquid, np.random.choice(Cloud_Cyan_Mixed_Ice, Cloud_Cyan_Mixed_Liquid.size))) print("Liquid Air - Liquid Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_Cyan_Liquid, Cloud_Cyan_Liquid, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_Cyan_Liquid, np.random.choice(Cloud_Cyan_Liquid, Air_Cyan_Liquid.size))) print("Ice Air - Ice Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_Cyan_Ice, Cloud_Cyan_Ice, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_Cyan_Ice, np.random.choice(Cloud_Cyan_Ice, Air_Cyan_Ice.size))) print("Mixed Air - Mixed Clouds\n" "-----------------------------------") print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_Cyan_Mixed, Cloud_Cyan_Mixed, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_Cyan_Mixed, np.random.choice(Cloud_Cyan_Mixed, Air_Cyan_Mixed.size))) ### Side2Side histogram ### data = [Cloud_IRdiffCyan_Liquid, Cloud_IRdiffCyan_Ice, Cloud_IRdiffCyan_Mixed] annotate = ["Liquid Clouds", "Ice Clouds", "Mixed Clouds"] bins = 'doane' ylabel = ["Number Concentration by IR - Cyan sensor (cm$^{-3}$)", "Number Concentration by IR - Cyan sensor (cm$^{-3}$)", "Number Concentration by IR - Cyan sensor (cm$^{-3}$)"] xscale = ['log', 'log', 'log'] yscale = ['linear', 'linear', 'linear'] ylim = [[-350,350], [-350,350], [-350,350]] color = ["green", "blue", "pink"] filename = self.Storage_Path + 'Plots/Hypothesis_1/IRdiffCyan_AllPhasesClouds_Histogram_Ravel.png' bins = Histogram_Side2Side( data, filename, bins, ylabel, annotate, ylim, xscale, yscale, color, plot_stats=False) # Mixed Liquid-Ice data = [Cloud_IRdiffCyan_Mixed_Liquid, Cloud_IRdiffCyan_Mixed_Ice] annotate = ["Mixed Clouds (Liquid Phase)", "Mixed Clouds (Ice Phase)"] bins = 'doane' ylabel = ["Number Concentration by IR - Cyan sensor (cm$^{-3}$)", "Number Concentration by IR - Cyan sensor (cm$^{-3}$)"] xscale = ['log', 'log'] yscale = ['linear', 'linear'] ylim = [[0.001,10], [0.001,10]] color = ["green", "blue"] filename = self.Storage_Path + 'Plots/Hypothesis_1/IRdiffCyan_AllPhasesMixedClouds_Histogram_Ravel.png' Histogram_Side2Side( data, filename, bins, ylabel, annotate, None, xscale, yscale, color, plot_stats=False) ### Box Plot ### # Liquid, Ice, Mixed Air/Clouds data = [[Cloud_IRdiffCyan_Liquid, Cloud_IRdiffCyan_Ice, Cloud_IRdiffCyan_Mixed], [Air_IRdiffCyan_Liquid, Air_IRdiffCyan_Ice, Air_IRdiffCyan_Mixed]] filename = self.Storage_Path + 'Plots/Hypothesis_1/IRdiffCyan_AllPhases_AllTypes_BoxPlot.png' positions = [[1, 6, 11], [3, 8, 13]] group_colors = ["green", "blue", "pink"] individual_colors = ["dodgerblue", "purple"] legend = ['Cloud', 'Air'] xticklabel = ['Liquid Phase', 'Ice Phase', 'Mixed Phase'] xlabel = "Cloud Type" ylabel = "Number Concentration by IR - Cyan sensor (cm$^{-3}$)" yscale = 'linear' BoxPlots( plot_data=data, plot_filename=filename, plot_xlabel=xlabel, plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None, plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color=individual_colors, plot_positions=positions, plot_legend=legend) if plot_ircyan_div is True: ############################################################################ """IR - Cyan""" data = [[Cloud_IRdivCyan_Liquid, Cloud_IRdivCyan_Mixed], [Cloud_IRdivCyan_Liquid, Cloud_IRdivCyan_Ice], [Cloud_IRdivCyan_Mixed, Cloud_IRdivCyan_Ice]] ylabel = [["Number Concentration by IR/Cyan sensor (cm$^{-3}$)", "Number Concentration by IR/Cyan sensor (cm$^{-3}$)"], ["Number Concentration by IR/Cyan sensor (cm$^{-3}$)", "Number Concentration by IR/Cyan sensor (cm$^{-3}$)"], ["Number Concentration by IR/Cyan sensor (cm$^{-3}$)", "Number Concentration by IR/Cyan sensor (cm$^{-3}$)"]] annotate = [["Liquid Clouds", "Mixed Clouds"], ["Liquid Clouds", "Ice Clouds"], ["Mixed Clouds", "Ice Clouds"]] name = [["Liquid", "Mixed"], ["Liquid", "Ice"], ["Mixed", "Ice"]] bins = [[20,20], [20,20], [20,20]] ylim = [[[-0.1,0.1],[-0.1,0.1]], [[-0.1,0.1],[-0.1,0.1]], [[-0.1,0.1],[-0.1,0.1]]] xscale = [['log', 'log'], ['log', 'log'], ['log', 'log']] yscale = [['log', 'log'], ['log', 'log'], ['log', 'log']] filename = self.Storage_Path + 'Plots/Hypothesis_1/IRdivCyan_AllPhasesClouds_Histogram.png' # Call Back2Back_Histogram with plot parameters Back2Back_Histogram( data, filename, bins, ylabel, annotate, None, xscale, yscale) #Parameters DependentVars = [Cloud_IRdivCyan_Ice, Cloud_IRdivCyan_Liquid, Cloud_IRdivCyan_Mixed] Plot_Colours = ['black', 'purple', 'dodgerblue'] Plot_Positions = [2, 6, 10] colours = [gu.rgb2hex(210,0,46), gu.rgb2hex(0,112,192), gu.rgb2hex(146,208,80)] plt.clf() plt.close() f, ax = plt.subplots(figsize=(8,6)) for var, color, pos in zip(DependentVars, colours, Plot_Positions): ax.boxplot(var, 1, meanline=True, showmeans=True, boxprops=dict(color=color), meanprops=dict(linewidth=2, color=color), whiskerprops=dict(color=color), positions=(pos,), medianprops=dict(color=color), patch_artist=True, widths=1) with warnings.catch_warnings(): warnings.simplefilter("ignore") anderson_test = sp.stats.anderson_ksamp((Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Mixed)) print("anderson_test", anderson_test) anderson_test_print = "<0.0001" if anderson_test[2] < 0.0001 else "%.4f" % anderson_test[2] #Set the name, colour and size for each box plot label ax.xaxis.set_ticks(Plot_Positions) ax.set_xticklabels(['Ice Clouds', 'Liquid Clouds', 'Mixed Clouds']) [ticklabel.set_color(colour) for (colour, ticklabel) in zip(colours, ax.xaxis.get_ticklabels())] plt.tick_params(labelsize=14) ax.set_xlabel("Cloud Type", fontsize=14) ax.set_ylabel("Number Concentration by IR/Cyan sensor (cm$^{-3}$)", fontsize=14) #ax.set_title("Box Plot of Max. Reflectivity for Convective Classifications 1,2,3", fontsize=14) ax.set_yscale("log") ax.set_xlim([0,12]) #ax.set_ylim([-5,15]) ax.grid(which='major',axis='both',c='grey') ax.annotate("<NAME> P-Value = %s " % (anderson_test_print), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=12) filename = self.Storage_Path + 'Plots/Hypothesis_1/IRdivCyan_AllPhasesClouds_BoxPlot.png' plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) if section2 is True: """Plots the relationship between space charge, ir and cyan with RHice""" plot_data = [[[Air_RH_Liquid, Air_SpaceCharge_Liquid],[Cloud_RH_Liquid, Cloud_SpaceCharge_Liquid]], [[Air_RH_Mixed, Air_SpaceCharge_Mixed],[Cloud_RH_Mixed, Cloud_SpaceCharge_Mixed]], [[Air_RH_Ice, Air_SpaceCharge_Ice],[Cloud_RH_Ice, Cloud_SpaceCharge_Ice]]] plot_xlabel = [["RH$_{ice}$ (%)", "RH$_{ice}$ (%)"], ["RH$_{ice}$ (%)", "RH$_{ice}$ (%)"], ["RH$_{ice}$ (%)", "RH$_{ice}$ (%)"]] plot_ylabel = [["Space Charge (nC m$^{-3}$)", "Space Charge (nC m$^{-3}$)"], ["Space Charge (nC m$^{-3}$)", "Space Charge (nC m$^{-3}$)"], ["Space Charge (nC m$^{-3}$)", "Space Charge (nC m$^{-3}$)"]] plot_annotate = [["Liquid Phase Air", "Liquid Phase Cloud"], ["Mixed Phase Air", "Mixed Phase Cloud"], ["Ice Phase Air", "Ice Phase Cloud"]] plot_color = [["purple", "dodgerblue"], ["purple", "dodgerblue"], ["purple", "dodgerblue"]] filename = self.Storage_Path + 'Plots/Hypothesis_1/RHice_SpaceCharge_AllPhasesClouds_Scatter.png' fontsize = 12 plt.close() plt.clf() f, ax = plt.subplots(3,2,sharex=False,sharey=True) #Global attributes of subplots for subplot in ax.ravel(): subplot.minorticks_on() for subplot in ax.ravel(): subplot.grid(which='major',axis='both',c='grey') f.subplots_adjust(wspace=0, hspace=0) #Plot over each data in turn plot_num = 0 for row, (data_row, xlabel_row, ylabel_row, annotate_row, color_row) in enumerate( zip(plot_data, plot_xlabel, plot_ylabel, plot_annotate, plot_color)): hist_plot = zip(np.zeros(2)) for col, (data, xlabel, ylabel, annotation, color) in enumerate( zip(data_row, xlabel_row, ylabel_row, annotate_row, color_row)): lm = sp.stats.linregress(*data) plot_num += 1 color = 'purple' if col == 0 else 'dodgerblue' #Plot data as Points ax[row,col].plot(data[0], data[1], 'p', ms=5, marker='o', markeredgecolor='None', markerfacecolor=color, alpha=1) if col == 0: ax[row,col].set_ylabel(ylabel) if row == 2: ax[row,col].set_xlabel(xlabel) #Names annotation = "" if annotation is None else annotation ax[row,col].annotate("(%s) %s" % (gu.alphabet[plot_num-1], annotation), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=fontsize) #Counts ax[row,col].annotate("Counts = %.0f\nr = %.5f" % (len(data[0]), lm[2]), xy=(1, 1), xycoords='axes fraction', xytext=(-20, -20), textcoords='offset pixels', horizontalalignment='right', verticalalignment='top', fontsize=fontsize) ax[row,col].set_xlim([0,100]) if col == 0 else ax[row,col].set_xlim([70,130]) ax[row,col].set_ylim([0,100]) ax[row,col].set_yscale('log') #ax[row,col].set_xscale('log') if row != 2: gu.hide_axis(ax=ax[row,col], x_or_y='x') if col == 1: ax[row,col].xaxis.set_major_locator(MaxNLocator(nbins=len(ax[row,col].get_xticklabels()), prune='lower')) f.set_size_inches(9, 12) #A4 Size #Save figure plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) def Hypothesis2_v2(self): """ HYPOTHESIS 2: The charge present within a convective cloud is proportional to the change in PG measured at the surface. THIS METHOD WILL USE THE SIGN CHANGE TO PLACE THE POINT CHARGES """ if self.verbose is True: gu.cprint("[INFO] You are running PointCharge from the DEV release", type='bold') ############################################################################ """Prerequisites""" # Time Controls t_begin = time.time() Sensor = self.sensor_package # Radiosonde Data Radiosonde_Data = self.Radiosonde_Data[Sensor]['Units'].copy() Clouds_ID = self.Clouds_ID[Sensor].copy() # Set-up data importer EPCC_Data = EPCC_Importer() # Get Cloud and Clear-Air Heights Cloud_Heights, Clear_Heights = self._CloudHeights(sensor=Sensor, method='Zhang') # Conditionals ElectricField_Method = 'static' ############################################################################ """Estimate Potential Gradeint""" Cloud_DateTime, Cloud_ElectricField, Cloud_ElectricField_Total = self._ElectricField_Estimator( self.Radiosonde_Data[Sensor], Cloud_Heights, self.LaunchTime[int(Sensor)], method=ElectricField_Method) print("11111111111111111") ############################################################################ """Import measured PG data from the RUAO""" # Import PG data from the RUAO. ID = np.where(Data['Date_ID'] == self.LaunchTime[int(Sensor)].astype('datetime64[D]').astype('datetime64[s]').astype(datetime))[0][0] print(self.data['FieldMill_RUAO_1sec_Processed_File'][ID]) print(self.LaunchTime[int(Sensor)].astype('datetime64[D]').astype('datetime64[s]').astype(datetime)) Field_Mill_Time, Field_Mill_PG = EPCC_Data.FieldMill_Calibrate(self.data['FieldMill_RUAO_1sec_Processed_File'][ID], hours2dt=True) # Subset PG to match Estimated Electric Field mask = (Field_Mill_Time >= Cloud_DateTime[0]) & (Field_Mill_Time <= Cloud_DateTime[-1]) Field_Mill_Time = Field_Mill_Time[mask] Field_Mill_PG = Field_Mill_PG[mask] ############################################################################ """Calculate Statistics""" Test = gu.antifinite((Field_Mill_PG, Cloud_ElectricField_Total)) print("Test", Test) print("R-Squared =", gu.R1to1(*Test)) #print(sp.stats.anderson_ksamp((Test[0], Test[1]))) print("PearsonrResult", sp.stats.pearsonr(*Test)) print(sp.stats.spearmanr(*Test)) ############################################################################ """Plot the electric field""" #Plot the data gu.backend_changer() plt.close() plt.clf() f, ax1 = plt.subplots() ax1.plot(Cloud_DateTime, Cloud_ElectricField_Total) ax2 = ax1.twinx() ax2.plot(Field_Mill_Time, Field_Mill_PG, lw=0.5, color='black') ax1.grid(which='major',axis='both',c='grey') ax1.set_xlabel('Time (Hour)') ax1.set_ylabel('Estimated Potential Gradient (V/m)') ax2.set_ylabel('Measured Potential Gradient (V/m)') ax1.set_title('Radiosonde Package No.%s' % Sensor) ax1.set_xlim(np.min(Cloud_DateTime), np.max(Cloud_DateTime)) ax2.set_xlim(np.min(Cloud_DateTime), np.max(Cloud_DateTime)) ax1.set_ylim(np.nanmin(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG])), np.nanmax(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG]))) ax2.set_ylim(np.nanmin(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG])), np.nanmax(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG]))) ax1.xaxis.set_major_formatter(DateFormatter('%H:%M')) ax1.get_yaxis().get_major_formatter().set_useOffset(False) ax1.get_yaxis().get_major_formatter().set_scientific(False) #plt.gcf().set_size_inches((11.7/6), 8.3) #Save figure filename = self.Storage_Path + 'Plots/Hypothesis_2/ElectricField_Estimate_RadiosondeNo.%s_%s.png' % (Sensor.rjust(2, '0'), ElectricField_Method.capitalize()) plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) ############################################################################ """Plot the decoupled Electric Field""" plt.close() plt.clf() f, ax1 = plt.subplots() for ElectricField in Cloud_ElectricField: ax1.plot(Cloud_DateTime, ElectricField, lw=0.5, color='black') ax1.grid(which='major',axis='both',c='grey') ax1.set_xlabel('Time (Hour)') ax1.set_ylabel('Estimated Potential Gradient (V/m)') ax1.set_title('Radiosonde Package No.%s' % Sensor) ax1.set_xlim(np.min(Cloud_DateTime), np.max(Cloud_DateTime)) ax1.set_ylim(np.nanmin(Cloud_ElectricField), np.nanmax(Cloud_ElectricField)) ax1.xaxis.set_major_formatter(DateFormatter('%H:%M')) ax1.get_yaxis().get_major_formatter().set_useOffset(False) ax1.get_yaxis().get_major_formatter().set_scientific(False) #Save figure filename = self.Storage_Path + 'Plots/Hypothesis_2/ElectricField_Estimate_RadiosondeNo.%s_%s_Decoupled.png' % (Sensor.rjust(2, '0'), ElectricField_Method.capitalize()) plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) def Hypothesis2(self): """ HYPOTHESIS 2: The charge present within a convective cloud is proportional to the change in PG measured at the surface. """ if self.verbose is True: gu.cprint("[INFO] You are running PointCharge from the DEV release", type='bold') ############################################################################ """Prerequisites""" #Time Controls t_begin = time.time() #Constants k = 2500000/22468879568420441 #Coulombs Constant (exact value!) kn2ms = 0.5144 #Conversion between knots and m/s #Radiosonde Data Radiosonde_Data = self.Radiosonde_Data['5']['Units'].copy() Clouds_ID = self.Clouds_ID['5'].copy() #Set-up data importer EPCC_Data = EPCC_Importer() # Get Cloud and Clear-Air Heights Cloud_Heights, Clear_Heights = self._CloudHeights(sensor=5, method='Zhang') ############################################################################ print("Cloud_Heights", Cloud_Heights) #Get index of lowest cloud CloudIndex = gu.searchsorted(Radiosonde_Data['height'], Cloud_Heights[0]) elem = 1 #Find total charge Cloud_SpaceChargeDensity = Radiosonde_Data['Log_SpaceCharge'][CloudIndex[0]:CloudIndex[1]] Cloud_AscentArea = np.diff(Radiosonde_Data['height'][CloudIndex[0]:CloudIndex[1]+1])*1000#/np.diff(Radiosonde_Data['time'][CloudIndex[0]:CloudIndex[1]+1]) Cloud_Charge = gu.interavg(Cloud_SpaceChargeDensity, elem, type='nansum') * gu.interavg(Cloud_AscentArea, elem, type='nansum') gu.stats(Cloud_Charge, output=True) #Get Cloud Height [m] Cloud_Height = gu.interavg(Radiosonde_Data['height'][CloudIndex[0]:CloudIndex[1]]*1000, elem, type='nanmean') #Get Cloud Velocity [m/s] Cloud_Velocity = gu.interavg(np.sqrt(Radiosonde_Data['u']**2+Radiosonde_Data['v']**2)[CloudIndex[0]:CloudIndex[1]], elem, type='nanmean') #Get Cloud Time Cloud_Time = np.datetime64(self.Radiosonde_Data['5']['Date']) Cloud_Date = Cloud_Time.astype('datetime64[D]') Cloud_BaseTime = Cloud_Time + np.timedelta64(int(Radiosonde_Data['time'][CloudIndex[0]]), 's') #Get Cloud Time Difference Cloud_TimeDiff = gu.interavg(Radiosonde_Data['time'][CloudIndex[0]:CloudIndex[1]], elem, type='nanmean') Cloud_TimeDiff -= Cloud_TimeDiff[0] #Calculate Electric Field print(Cloud_Height.shape, Cloud_Velocity.shape, Cloud_Charge.shape) Cloud_Time = np.arange(-2000, 2000, 10) Cloud_ElectricField = np.array([(gu.cosarctan(((Cloud_Time+time_diff)*velocity)/height)*charge)/(k*height**2) for time_diff, height, velocity, charge in zip(Cloud_TimeDiff, Cloud_Height, Cloud_Velocity, Cloud_Charge)]) print("Cloud_ElectricField", Cloud_ElectricField.shape) Cloud_ElectricField_Total = 100 + np.nansum(Cloud_ElectricField, axis=0) print("Cloud_ElectricField_Total", Cloud_ElectricField_Total.shape) #Calculate datetimes for each calculation in Cloud_ElectricField Cloud_DateTime = Cloud_BaseTime + Cloud_Time.astype('timedelta64[s]') #Import PG data ID = np.where(Data['Date_ID'] == Cloud_BaseTime.astype('datetime64[D]').astype('datetime64[s]').astype(datetime))[0][0] Field_Mill_Time, Field_Mill_PG = EPCC_Data.FieldMill_Calibrate(self.data['FieldMill_RUAO_1sec_Processed_File'][ID]) #Plot the data gu.backend_changer() plt.close() plt.clf() f, ax1 = plt.subplots() ax1.plot(Cloud_DateTime, Cloud_ElectricField_Total) ax2 = ax1.twinx() Field_Mill_Time = gu.addHourFrac(Cloud_Date, Field_Mill_Time) print("Field_Mill_Time", Field_Mill_Time) ax2.plot(Field_Mill_Time, Field_Mill_PG, lw=0.5, color='black') ax1.grid(which='major',axis='both',c='grey') ax1.set_xlabel('Time (Hour)') ax1.set_ylabel('Estimated Potential Gradient (V/m)') ax2.set_ylabel('Measured Potential Gradient (V/m)') ax1.set_xlim(np.min(Cloud_DateTime), np.max(Cloud_DateTime)) ax2.set_xlim(np.min(Cloud_DateTime), np.max(Cloud_DateTime)) #ax1.set_ylim(np.nanmin(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG])), np.nanmax(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG]))) #ax2.set_ylim(np.nanmin(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG])), np.nanmax(gu.flatten([Cloud_ElectricField_Total,Field_Mill_PG]))) ax1.xaxis.set_major_formatter(DateFormatter('%H:%M')) ax1.get_yaxis().get_major_formatter().set_useOffset(False) ax1.get_yaxis().get_major_formatter().set_scientific(False) #plt.gcf().set_size_inches((11.7/6), 8.3) plt.show() sys.exit() def Hypothesis3(self): """ HYPOTHESIS 3: The charge present within a convective clouds has a positive correlation with optical thickness caused by an increase in the hydrometeor collision efficiency which in turn increases the amount of charge separation. """ if self.verbose is True: gu.cprint("[INFO] You are running PointCharge from the DEV" " release", type='bold') ############################################################### """Prerequisites""" # Time Controls t_begin = time.time() # Radiosonde Data Radiosonde_Data = self.Radiosonde_Data.copy() Clouds_ID = self.Clouds_ID.copy() LayerType = self.LayerType.copy() # Set-up data importer EPCC_Data = EPCC_Importer() # Set-up plotting gu.backend_changer() # Conditionals section1 = True section2 = False section3 = False if section1 is True: ############################################################### """[SECTION 1] Space Charge vs. IR""" data_method = 'unique_average' #Arrays Cloud_SpaceCharge = gu.array() Cloud_IR = gu.array() Cloud_Cyan = gu.array() Cloud_IRdiffCyan = gu.array() Cloud_IRdivCyan = gu.array() #Sensor_Package = np.arange(3,11).astype('S2') Sensor_Package = np.array(['3', '4', '9', '10']) #Sensor_Package = np.array(['4']) for sensor in Sensor_Package: # Check the sensor has been processed by _RadiosondeImporter try: Radiosonde_Data[sensor] except KeyError: if self.verbose is True: print("[Warning] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (sensor)) continue # Get Cloud and Clear-Air Heights Cloud_Heights, Clear_Heights = self._CloudHeights(sensor=sensor, method='Zhang') # Remove nan's from data Time, Height, SpaceCharge, IR, Cyan = gu.antival(gu.antifinite((Radiosonde_Data[sensor]['Units']['time'], Radiosonde_Data[sensor]['Units']['height'], np.abs(Radiosonde_Data[sensor]['Units']['SpaceCharge']), Radiosonde_Data[sensor]['Units']['IR_NC'], Radiosonde_Data[sensor]['Units']['Cyan_NC'])), val=0, unpack=True) IRdiffCyan = IR - Cyan IRdivCyan = IR / Cyan # Remove negative values mask = (IR > 0) & (Cyan > 0) Time = Time[mask] Height = Height[mask] SpaceCharge = SpaceCharge[mask] IR = IR[mask] Cyan = Cyan[mask] IRdiffCyan = IRdiffCyan[mask] IRdivCyan = IRdivCyan[mask] #for cloud in [Cloud_Heights[0]]: for cloud in Cloud_Heights: #Get index of lowest cloud CloudIndex = gu.searchsorted(Height, cloud) #Subset data SpaceCharge_Subset = SpaceCharge[CloudIndex[0]:CloudIndex[1]] IR_Subset = IR[CloudIndex[0]:CloudIndex[1]] Cyan_Subset = Cyan[CloudIndex[0]:CloudIndex[1]] IRdiffCyan_Subset = IRdiffCyan[CloudIndex[0]:CloudIndex[1]] IRdivCyan_Subset = IRdivCyan[CloudIndex[0]:CloudIndex[1]] #Add to master array Cloud_SpaceCharge.update([SpaceCharge_Subset]) Cloud_IR.update([IR_Subset]) Cloud_Cyan.update([Cyan_Subset]) Cloud_IRdiffCyan.update([IRdiffCyan_Subset]) Cloud_IRdivCyan.update([IRdivCyan_Subset]) #Finalize arrays Cloud_SpaceCharge = Cloud_SpaceCharge.finalize(dtype=np.float64) # Now in units of pC/m**3 Cloud_IR = Cloud_IR.finalize(dtype=np.float64) Cloud_Cyan = Cloud_Cyan.finalize(dtype=np.float64) Cloud_IRdiffCyan = Cloud_IRdiffCyan.finalize(dtype=np.float64) Cloud_IRdivCyan = Cloud_IRdivCyan.finalize(dtype=np.float64) mask = (Cloud_SpaceCharge < 500) & (Cloud_SpaceCharge > 1) Cloud_SpaceCharge = Cloud_SpaceCharge[mask] Cloud_IR = Cloud_IR[mask] Cloud_Cyan = Cloud_Cyan[mask] Cloud_IRdiffCyan = Cloud_IRdiffCyan[mask] Cloud_IRdivCyan = Cloud_IRdivCyan[mask] Cloud_SpaceCharge_Ensemble_Unique = gu.ensemble(Cloud_SpaceCharge, Cloud_IR, 15, method='unique', average='mean', undersample=False, slim=False) Cloud_SpaceCharge_Ensemble_MA = gu.ensemble(Cloud_SpaceCharge, Cloud_IR, 15, method='ma', average='mean', undersample=True, slim=False) gu.backend_changer() f, ax = plt.subplots() #ax.plot(Cloud_SpaceCharge_Ensemble_MA[:,0], Cloud_SpaceCharge_Ensemble_MA[:,1], lw=1, color='dodgerblue', label='moving average') #ax.plot(Cloud_SpaceCharge_Ensemble_Unique[:,0], Cloud_SpaceCharge_Ensemble_Unique[:,1], 'p', ms=5, marker='o', markeredgecolor='None', markerfacecolor='black', alpha=1, label='unique') ax.errorbar(Cloud_SpaceCharge_Ensemble_Unique[:,0], Cloud_SpaceCharge_Ensemble_Unique[:,1], yerr=Cloud_SpaceCharge_Ensemble_Unique[:,1]/1.96, fmt='p', ms=5, marker='o', markeredgecolor='None', markerfacecolor='black', alpha=1, label='unique') lm = sp.stats.linregress(Cloud_SpaceCharge_Ensemble_Unique[:,0], Cloud_SpaceCharge_Ensemble_Unique[:,1]) LinRegress_All = sm.WLS(Cloud_SpaceCharge_Ensemble_Unique[:,1], sm.add_constant(Cloud_SpaceCharge_Ensemble_Unique[:,0]), weights=(1/Cloud_SpaceCharge_Ensemble_Unique[:,1])).fit() print(LinRegress_All.summary()) print("LM", lm) # fill_kwargs = {'lw':0.0, 'edgecolor':None} # ax.fill_between(Cloud_SpaceCharge_Ensemble_MA[:,0], # Cloud_SpaceCharge_Ensemble_MA[:,1] + Cloud_SpaceCharge_Ensemble_MA[:,2], # Cloud_SpaceCharge_Ensemble_MA[:,1] - Cloud_SpaceCharge_Ensemble_MA[:,2], # facecolor='dodgerblue', alpha=0.3, interpolate=True, **fill_kwargs) #ax.set_xlim([1,10**4]) ax.set_xscale('log') plt.show() sys.exit() # Average data if data_method == 'unique_average': Cloud_SpaceCharge_Ensemble = gu.ensemble(Cloud_SpaceCharge, Cloud_IR, 15, method='unique', average='mean', undersample=False, slim=False) elif data_method == 'full_average': print("Cloud_SpaceCharge", Cloud_SpaceCharge.shape, "Cloud_IR", Cloud_IR.shape) Cloud_SpaceCharge_Ensemble = gu.ensemble(Cloud_SpaceCharge, Cloud_IR, 15, method='ma', average='mean', undersample=True, slim=False) else: Cloud_SpaceCharge2 = Cloud_SpaceCharge Ensemble_Kwargs = { 'xlabel' : "Space Charge (pC m$^{-3}$)", 'ylabel' : "Number Concentration\nby IR sensor (cm$^{-3}$)", 'raw' : False, 'histogram' : False, 'averaged' : True, 'averaged_method' : 'undersampled', 'xlim': [1,10**4], 'xscale' : 'log', 'embedded_colorbar': False} filename = self.Storage_Path + 'Plots/Hypothesis_3/CrossCorrelation_SpaceCharge_IR_RadiosondesNo.' + str(Sensor_Package.astype(int).tolist())[1:-1] + '_' + data_method + '.png' SPEnsemble(Cloud_SpaceCharge, Cloud_IR, Cloud_SpaceCharge_Ensemble, filename, **Ensemble_Kwargs) sys.exit() # filename = self.Storage_Path + 'Plots/Hypothesis_3/CrossCorrelation_SpaceCharge_IR_RadiosondesNo.' + str(Sensor_Package.astype(int).tolist())[1:-1] + '_' + data_method + '.png' # Cloud_SpaceCharge_Best, Cloud_IR_Best = CrossCorrelation_Scatter_Plot( # Cloud_SpaceCharge2, # Cloud_IR, # filename=filename, # xlabel="Space Charge (nC m$^{-3}$)", # ylabel="Number Concentration by IR sensor (cm$^{-3}$)", # title="Cross Correlation (Radiosonde No." + str(Sensor_Package.astype(int).tolist())[1:-1] + ")", # xlim='auto', # ylim=[0,'auto'], # xscale="log", # yscale="linear", # verbose=True) if data_method == 'unique_average': Cloud_SpaceCharge2, Cloud_Cyan, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_Cyan, 50, method='unique', undersample=True, slim=True) elif data_method == 'full_average': Cloud_SpaceCharge2, Cloud_Cyan, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_Cyan, 2, method='ma', average='mean', undersample=True, slim=True) else: Cloud_SpaceCharge2 = Cloud_SpaceCharge filename = self.Storage_Path + 'Plots/Hypothesis_3/CrossCorrelation_SpaceCharge_Cyan_RadiosondesNo.' + str(Sensor_Package.astype(int).tolist())[1:-1] + '_' + data_method + '.png' Cloud_SpaceCharge_Best, Cloud_IR_Best = CrossCorrelation_Scatter_Plot( Cloud_SpaceCharge2, Cloud_Cyan, filename=filename, xlabel="Space Charge (nC m$^{-3}$)", ylabel="Number Concentration by Cyan sensor (cm$^{-3}$)", title="Cross Correlation (Radiosonde No." + str(Sensor_Package.astype(int).tolist())[1:-1] + ")", xlim='auto', ylim=[0,'auto'], xscale="log", yscale="linear", verbose=True) if data_method == 'unique_average': Cloud_SpaceCharge2, Cloud_IRdiffCyan, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_IRdiffCyan, 100, method='unique', undersample=True, slim=True) elif data_method == 'full_average': Cloud_SpaceCharge2, Cloud_IRdiffCyan, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_IRdiffCyan, 2, method='ma', average='mean', undersample=True, slim=True) else: Cloud_SpaceCharge2 = Cloud_SpaceCharge filename = self.Storage_Path + 'Plots/Hypothesis_3/CrossCor' \ 'relation_SpaceCharge_IRdiffCyan_RadiosondesNo.' + \ str(Sensor_Package.astype(int).tolist())[1:-1] + \ '_' + data_method + '.png' Cloud_SpaceCharge_Best, Cloud_IR_Best = CrossCorrelation_Scatter_Plot( Cloud_SpaceCharge2, Cloud_IRdiffCyan, filename=filename, xlabel="Space Charge (nC m$^{-3}$)", ylabel="Number Concentration by IR - Cyan sensor (cm$^{-3}$)", title="Cross Correlation (Radiosonde No." + str(Sensor_Package.astype(int).tolist())[1:-1] + ")", xlim='auto', ylim=[0,'auto'], xscale="linear", yscale="linear", verbose=True) if data_method == 'unique_average': Cloud_SpaceCharge2, Cloud_IRdivCyan, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_IRdivCyan, 100, method='unique', undersample=True, slim=True) elif data_method == 'full_average': Cloud_SpaceCharge2, Cloud_IRdivCyan, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_IRdivCyan, 2, method='ma', average='mean', undersample=True, slim=True) else: Cloud_SpaceCharge2 = Cloud_SpaceCharge filename = self.Storage_Path + 'Plots/Hypothesis_3/CrossCorrelation_SpaceCharge_IRdivCyan_RadiosondesNo.' + str(Sensor_Package.astype(int).tolist())[1:-1] + '_' + data_method + '.png' Cloud_SpaceCharge_Best, Cloud_IR_Best = CrossCorrelation_Scatter_Plot( Cloud_SpaceCharge2, Cloud_IRdivCyan, filename=filename, xlabel="Space Charge (nC m$^{-3}$)", ylabel="Number Concentration by IR/Cyan sensor (cm$^{-3}$)", title="Cross Correlation (Radiosonde No." + str(Sensor_Package.astype(int).tolist())[1:-1] + ")", xlim='auto', ylim=[0,'auto'], xscale="linear", yscale="linear", verbose=True) #LR_IRSC2 = sp.stats.linregress(Cloud_SpaceCharge_Best,Cloud_IR_Best) LR_IRSC2 = gu.HuberRegression(Cloud_SpaceCharge_Best,Cloud_IR_Best) print("LR_IRSC2", LR_IRSC2) print("Correlation", sp.stats.spearmanr(Cloud_SpaceCharge_Best, Cloud_IR_Best)[0]) if section2 is True: ############################################################################ """[SECTION 1] Space Charge vs. SLWC""" #Arrays Cloud_Tdry = gu.array() Cloud_SpaceCharge = gu.array() Cloud_SLWC = gu.array() #Sensor_Package = np.arange(3,11).astype('S2') Sensor_Package = np.arange(3,6).astype('S2') #Sensor_Package = ['4'] for sensor in Sensor_Package: #Check the sensor has been processed by _RadiosondeImporter try: Radiosonde_Data[sensor] except KeyError: if self.verbose is True: print("[Warning] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (sensor)) continue ############################################################################ """Get limits of cloud and non cloud areas""" #IR = Radiosonde_Data[sensor]['Units']['IR'] #Clouds_ID[sensor] = gu.contiguous((IR > np.nanpercentile(IR, 80)).astype(int), invalid=0) # Get cloud base and cloud top heights for each identified cloud Cloud_Heights = np.array([[Radiosonde_Data[sensor]['Units']['height'][Clouds_ID[sensor] == Cloud][0], Radiosonde_Data[sensor]['Units']['height'][Clouds_ID[sensor] == Cloud][-1]] for Cloud in np.unique(Clouds_ID[sensor])[1:]], dtype=np.float64) # Get clear areas Clear_ID = gu.argcontiguous(LayerType[sensor], valid=0) #Clear_ID = gu.contiguous((IR < np.nanpercentile(IR, 20)).astype(int), invalid=0) Clear_Heights = np.array([[Radiosonde_Data[sensor]['Units']['height'][Clear_ID == Cloud][0], Radiosonde_Data[sensor]['Units']['height'][Clear_ID == Cloud][-1]] for Cloud in np.unique(Clear_ID)[1:]], dtype=np.float64) ############################################################################ #Remove nan's from data Time, Height, Tdry, SpaceCharge, SLWC = gu.antifinite((Radiosonde_Data[sensor]['Units']['time'], Radiosonde_Data[sensor]['Units']['height'], Radiosonde_Data[sensor]['Units']['Tdry'], np.abs(Radiosonde_Data[sensor]['Units']['SpaceCharge']), Radiosonde_Data[sensor]['Units']['SLWC']), unpack=True) for cloud in Cloud_Heights: #Get index of lowest cloud CloudIndex = gu.searchsorted(Height, cloud) #Subset data Tdry_Subset = Tdry[CloudIndex[0]:CloudIndex[1]] SpaceCharge_Subset = SpaceCharge[CloudIndex[0]:CloudIndex[1]] SLWC_Subset = SLWC[CloudIndex[0]:CloudIndex[1]] #Add to master array Cloud_Tdry.update([Tdry_Subset]) Cloud_SpaceCharge.update([SpaceCharge_Subset]) Cloud_SLWC.update([SLWC_Subset]) #Finalize arrays Cloud_Tdry = Cloud_Tdry.finalize(dtype=np.float64) Cloud_SpaceCharge = Cloud_SpaceCharge.finalize(dtype=np.float64)/1000 Cloud_SLWC = Cloud_SLWC.finalize(dtype=np.float64) #mask = (Cloud_IR < 5) & (Cloud_SpaceCharge < 40) mask = (Cloud_SpaceCharge < 40) Cloud_Tdry = Cloud_Tdry[mask] Cloud_SpaceCharge = Cloud_SpaceCharge[mask] Cloud_SLWC = Cloud_SLWC[mask] Cloud_SpaceCharge2, Cloud_SLWC, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_SLWC, 50, method='unique', undersample=True, slim=True) filename = self.Storage_Path + 'Plots/Hypothesis_3/CrossCorrelation_SpaceCharge_SLWC_AllRadiosondes_UnAveraged.png' Cloud_SpaceCharge_Best, Cloud_IR_Best = CrossCorrelation_Scatter_Plot( Cloud_SpaceCharge2, Cloud_SLWC, filename=filename, xlabel="Space Charge (nC m$^{-3}$)", ylabel="Liquid Water Sensor (g m$^{-1}$)", title="Cross Correlation (Radiosonde No.3,4,5)", xlim='auto', ylim=[0,'auto'], xscale="linear", yscale="linear", verbose=True) gu.stats(Cloud_Tdry, output=True) #Cloud_SpaceCharge2, Cloud_Tdry, _ = gu.ensemble(Cloud_SpaceCharge, Cloud_Tdry, 50, method='unique', undersample=True, slim=True) filename = self.Storage_Path + 'Plots/Hypothesis_3/CrossCorrelation_Tdry_SLWC_AllRadiosondes_UnAveraged.png' Cloud_SpaceCharge_Best, Cloud_IR_Best = CrossCorrelation_Scatter_Plot( Cloud_Tdry, Cloud_SLWC, filename=filename, xlabel="Temperature (C)", ylabel="Liquid Water Sensor (g m$^{-1}$)", title="Cross Correlation (Radiosonde No.3,4,5)", xlim='auto', ylim='auto', xscale="linear", yscale="linear", verbose=True) if section3 is True: ############################################################################ """[SECTION 3] Space Charge Fluctuations""" # Initalise the arrays to store the signchange and space charge data Cloud_SignChange_All = gu.array() Cloud_SpaceCharge_All = gu.array() Air_SignChange_All = gu.array() Air_SpaceCharge_All = gu.array() # Calculate 95th percentile of Space Charge between each sign change # for all sign changes that occur within clouds and clear air. Two # methods are used to define a "cloud". First, is the Zhang method # which used RH w.r.t. ice. Second, the IR cloud sensor which can # identify areas of the atmosphere with a high return signal. For # this method a 80-20 percentile split is used to differentiate # clearly between cloud and clear-air regions. #Sensor_Package = np.array(['3', '4', '9', '10']) Sensor_Package = np.arange(3,11).astype('S2') #Sensor_Package = ['4'] for sensor in Sensor_Package: # Check the sensor has been processed by _RadiosondeImporter try: Radiosonde_Data[sensor] except KeyError: if self.verbose is True: print("[Warning] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (sensor)) continue # Get limits of cloud and non cloud areas Cloud_Heights, Clear_Heights = self._CloudHeights(sensor, method='Zhang') ############################################################################ """Import data and calculate 95th percentile space charge""" #Remove nan's from data Time, Height, SpaceCharge = gu.antifinite((Radiosonde_Data[sensor]['Units']['time'], Radiosonde_Data[sensor]['Units']['height'], Radiosonde_Data[sensor]['Units']['SpaceCharge']), unpack=True) #Detect sign changes in data SignChange = np.where(np.diff(np.sign(SpaceCharge)))[0] # Cloudy Regions for cloud in Cloud_Heights: #Get index of lowest cloud CloudIndex = gu.searchsorted(Height, cloud) #Get SignChange position for cloud Cloud_SignChange = SignChange[(SignChange >= CloudIndex[0]) & (SignChange <= CloudIndex[1])] #Get time stamps of sign change Cloud_TimeChange = Time[Cloud_SignChange] #Get Space Charge Spacing = gu.broadcast(Cloud_SignChange,2,1) Cloud_SpaceCharge = np.array([np.nanpercentile(np.abs(SpaceCharge[space[0]:space[1]]), 95) for space in Spacing]) #Get difference Cloud_SignChange_All.update([np.diff(Cloud_TimeChange)]) Cloud_SpaceCharge_All.update([Cloud_SpaceCharge]) # Clear-Air Regions for air in Clear_Heights: #Get index of lowest cloud AirIndex = gu.searchsorted(Height, air) #Get SignChange position for cloud Air_SignChange = SignChange[(SignChange >= AirIndex[0]) & (SignChange <= AirIndex[1])] #Get time stamps of sign change Air_TimeChange = Time[Air_SignChange] #Get Space Charge Spacing = gu.broadcast(Air_SignChange,2,1) Air_SpaceCharge = np.array([np.nanpercentile(np.abs(SpaceCharge[space[0]:space[1]]), 95) for space in Spacing]) #Get difference Air_SignChange_All.update([np.diff(Air_TimeChange)]) Air_SpaceCharge_All.update([Air_SpaceCharge]) ############################################################################ # Finalise arrays Cloud_SignChange_All = Cloud_SignChange_All.finalize(dtype=np.float64) Cloud_SpaceCharge_All = Cloud_SpaceCharge_All.finalize(dtype=np.float64) Air_SignChange_All = Air_SignChange_All.finalize(dtype=np.float64) Air_SpaceCharge_All = Air_SpaceCharge_All.finalize(dtype=np.float64) ############################################################################ """Perform some statistical tests""" #Anderson-Darling Test print(sp.stats.anderson_ksamp((Cloud_SignChange_All, Air_SignChange_All))) print("PearsonrResult", sp.stats.pearsonr(Cloud_SignChange_All, Cloud_SpaceCharge_All)) print(sp.stats.spearmanr(Cloud_SignChange_All, Cloud_SpaceCharge_All)) #Linear Regressions Cloud_LM = sp.stats.linregress(Cloud_SignChange_All, Cloud_SpaceCharge_All) Air_LM = sp.stats.linregress(Air_SignChange_All, Air_SpaceCharge_All) All_LM = sp.stats.linregress(np.hstack((Cloud_SignChange_All, Air_SignChange_All)), np.hstack((Cloud_SpaceCharge_All, Air_SpaceCharge_All))) print("Cloud:", Cloud_LM, Cloud_SignChange_All.shape) print("Air:", Air_LM, Air_SignChange_All.shape) print("All:", All_LM, np.hstack((Cloud_SignChange_All, Air_SignChange_All)).shape) ############################################################################ """ Plot the results of the relationship between sign change and space charge for both cloud and clear-air regions """ fontsize = 10 # Set-up plot plt.clf() plt.close() f, ax = plt.subplots(1, 2) # Set global properties before the plotting of data for subplot in ax: subplot.grid(which='major',axis='both',c='grey') f.subplots_adjust(wspace=0) ax[1].axes.tick_params(left='off') # Plot data ax[1].plot(Cloud_SignChange_All, Cloud_SpaceCharge_All, 'p', ms=5, marker='o', markeredgecolor='None', markerfacecolor='dodgerblue', alpha=1) ax[0].plot(Air_SignChange_All, Air_SpaceCharge_All, 'p', ms=5, marker='o', markeredgecolor='None', markerfacecolor='purple', alpha=1) # Specify the x and y labels ax[0].set_xlabel("Time between Polarity Changes (s)") ax[0].set_ylabel("95th Percentile Space Charge Density (pC m$^{-3}$)") ax[1].set_xlabel("Time between Polarity Changes (s)") # Force both subplots to have same x and y limits all_xdata = np.hstack((Cloud_SignChange_All, Air_SignChange_All)) all_ydata = np.hstack((Cloud_SpaceCharge_All, Air_SpaceCharge_All)) ax[0].set_xlim([np.nanmin(all_xdata), np.nanmax(all_xdata)]) ax[0].set_ylim([np.nanmin(all_ydata), np.nanmax(all_ydata)]) ax[1].set_xlim([np.nanmin(all_xdata), np.nanmax(all_xdata)]) ax[1].set_ylim([np.nanmin(all_ydata), np.nanmax(all_ydata)]) #Calculate Linear Regression Models mask = (Cloud_SpaceCharge_All > np.percentile(Cloud_SpaceCharge_All, 0)) Cloud_lm = sp.stats.linregress(Cloud_SignChange_All[mask], Cloud_SpaceCharge_All[mask]) mask = (Air_SpaceCharge_All > np.percentile(Air_SpaceCharge_All, 0)) Air_lm = sp.stats.linregress(Air_SignChange_All[mask], Air_SpaceCharge_All[mask]) #Plot linear regression models ax[0].plot(np.sort(Air_SignChange_All, kind='mergesort'), np.sort(Air_SignChange_All, kind='mergesort')*Air_lm[0] + Air_lm[1], lw=0.5, color='black', linestyle='--') ax[1].plot(np.sort(Cloud_SignChange_All, kind='mergesort'), np.sort(Cloud_SignChange_All, kind='mergesort')*Cloud_lm[0] + Cloud_lm[1], lw=0.5, color='black', linestyle='--') #Annotate the scatter plot ax[1].annotate("Counts = %.0f\nR Value = %.4f" % (np.size(Cloud_SignChange_All), Cloud_lm[2]), xy=(1, 1), xycoords='axes fraction', xytext=(-20, -20), textcoords='offset pixels', horizontalalignment='right', verticalalignment='top', fontsize=10) ax[0].annotate("Counts = %.0f\nR Value = %.4f" % (np.size(Air_SignChange_All), Air_lm[2]), xy=(1, 1), xycoords='axes fraction', xytext=(-20, -20), textcoords='offset pixels', horizontalalignment='right', verticalalignment='top', fontsize=10) ax[0].annotate("(%s) %s" % (gu.alphabet[0], "Clear-Air"), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=fontsize) ax[1].annotate("(%s) %s" % (gu.alphabet[1], "Cloud"), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=fontsize) f.suptitle("Radiosonde Flight No.3,4,9,10 (IR-Identifier-80-20)", y=0.80) ax[0].set_xscale('linear') ax[1].set_xscale('linear') #Remove y axis on right-hand plot gu.hide_axis(ax=ax[1], x_or_y='y') #Set global properties after the plotting of data for subplot in ax: gu.fixed_aspect_ratio(ax=subplot, ratio=1, adjustable=None) #Save figure filename = self.Storage_Path + 'Plots/Hypothesis_3/SpaceCharge-Variability-PolarityChanges_Zhang-Identifier_All-Radiosondes.png' plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) ############################################################################ """ Plot the back-to-back histogram for time between polairty changes for both clear-air and cloud regions. """ print("Mann-Whitney U-Test", sp.stats.mannwhitneyu(Air_SignChange_All, Cloud_SignChange_All, alternative='two-sided')) print("Wilcoxon signed-rank test", sp.stats.wilcoxon(Air_SignChange_All, np.random.choice(Cloud_SignChange_All, Air_SignChange_All.size))) # Plot Parameters data = [[Air_SignChange_All, Cloud_SignChange_All]] ylabel = [["Time between Polarity Changes (s)", "Time between Polarity Changes (s)"]] annotate = [["Clear-Air", "Cloud"]] name = [["Clear-Air", "Cloud"]] bins = [[30,30]] ylim = [[[0,50],[0,50]]] xscale = [['log', 'log']] yscale = [['linear', 'linear']] filename = self.Storage_Path + 'Plots/Hypothesis_3/Histogram_PolarityChanges_Zhang-Identifier_All-Radiosondes.png' # Call Back2Back_Histogram with plot parameters Back2Back_Histogram( data, filename, bins, ylabel, annotate, None, xscale, yscale) def Hypothesis4(self): """ HYPOTHESIS 4: Areas of turbulence increase the amount of charge separation and act as a method to enhance the potential gradient. """ return def RH_Comparison(self): """ This function will plot the relative humidity with respects to ice using various calculations of the saturated vapour pressure """ if self.verbose is True: gu.cprint("[INFO] You are running RH_Comparison from the DEV release", type='bold') ############################################################################ """Prerequisites""" # Time Controls t_begin = time.time() # Set-up plotting gu.backend_changer() fill_kwargs = {'lw':0.0, 'edgecolor':None} # Conditionals method = 'Comparison' ############################################################################ if method == 'Individual': ############################################################################ """[Step 1] Calibrate bespoke sensors""" # Calibrate Height, Temperature and Convert PANDORA channels from counts to volts if required. Radiosonde_Cal = Radiosonde_Checks(self.Radiosonde_Data[self.sensor_package]['Raw'].copy(), None, self.sensor_package, height_range=[0,12]) Radiosonde_Cal_Goff = Radiosonde_Checks(self.Radiosonde_Data[self.sensor_package]['Raw'].copy(), None, self.sensor_package, height_range=[0,12]) Radiosonde_Cal_Buck = Radiosonde_Checks(self.Radiosonde_Data[self.sensor_package]['Raw'].copy(), None, self.sensor_package, height_range=[0,12]) Radiosonde_Cal_Wexler = Radiosonde_Checks(self.Radiosonde_Data[self.sensor_package]['Raw'].copy(), None, self.sensor_package, height_range=[0,12]) Radiosonde_Cal_Sonntag = Radiosonde_Checks(self.Radiosonde_Data[self.sensor_package]['Raw'].copy(), None, self.sensor_package, height_range=[0,12]) Radiosonde_Cal_Hardy = Radiosonde_Checks(self.Radiosonde_Data[self.sensor_package]['Raw'].copy(), None, self.sensor_package, height_range=[0,12]) # Calibrate Relative Humidity Sensor (e.g. find RH_ice) Radiosonde_Cal_Goff.RH(method='goff') Radiosonde_Cal_Buck.RH(method='arden-buck') Radiosonde_Cal_Wexler.RH(method='wexler') Radiosonde_Cal_Sonntag.RH(method='sonntag') Radiosonde_Cal_Hardy.RH(method='hardy') # Return Data (make local to function only. i.e. DON'T use self.Radiosonde_Data) Radiosonde_Data = Radiosonde_Cal.finalise() Radiosonde_Data_Goff = Radiosonde_Cal_Goff.finalise() Radiosonde_Data_Buck = Radiosonde_Cal_Buck.finalise() Radiosonde_Data_Wexler = Radiosonde_Cal_Wexler.finalise() Radiosonde_Data_Sonntag = Radiosonde_Cal_Sonntag.finalise() Radiosonde_Data_Hardy = Radiosonde_Cal_Hardy.finalise() ############################################################################ """[Step 2] Plot radiosonde data""" Title = 'Radiosonde Flight No.' + str(self.sensor_package) + ' (' + self.Launch_Datetime[self.sensor_package].strftime("%d/%m/%Y %H%MUTC") + ')' if self.GPS_File is not None else 'Radiosonde Flight (N/A)' Height = Radiosonde_Data['height'] Temperature = Radiosonde_Data['Tdry'] RH = Radiosonde_Data['RH'] #Plotting requirements plt.style.use('classic') #necessary if Matplotlib version is >= 2.0.0 #Make sure we are creating new plot from scratch plt.clf() plt.close() #Define number of subplots sharing y axis f, ax1 = plt.subplots() ax1.minorticks_on() ax1.grid(which='major',axis='both',c='grey') #Rotate xticks in all subplots for tick in ax1.get_xticklabels(): tick.set_rotation(90) #Remove random junk from the plot f.subplots_adjust(hspace=0) plt.setp([a.get_yticklabels() for a in f.axes[1:]], visible=False) #Set axis parameters ax1.set_ylabel('Height $(km)$') ax1.set_ylim([np.nanmin(Height), np.nanmax(Height)]) #Define plot size f.set_size_inches(8, 8) #Plot RH ax1.plot(RH, Height, label='Original', lw=0.5) ax1.plot(Radiosonde_Data_Goff['RHice'], Radiosonde_Data_Goff['height'], label='Goff-Gratch', lw=0.5) ax1.plot(Radiosonde_Data_Buck['RHice'], Radiosonde_Data_Buck['height'], label='Arden-Buck', lw=0.5) ax1.plot(Radiosonde_Data_Wexler['RHice'], Radiosonde_Data_Wexler['height'], label='Wexler', lw=0.5) ax1.plot(Radiosonde_Data_Sonntag['RHice'], Radiosonde_Data_Sonntag['height'], label='Sonntag', lw=0.5) ax1.plot(Radiosonde_Data_Hardy['RHice'], Radiosonde_Data_Hardy['height'], label='Hardy', lw=0.5) ax1.set_xlabel('RH $(\%)$') ax1.set_title(Title, fontsize=12) ax1.legend(loc='best') ax2 = ax1.twinx() ax2.plot(RH, Temperature, label='Original', lw=0.5, c='black') ax2.set_ylabel('Temperature ($^\circ$C)') ax2.set_ylim([np.nanmin(Temperature), np.nanmax(Temperature)]) ax2.invert_yaxis() Freezing_Height = Height[gu.argnear(Temperature, 0)] if np.any(Temperature < 0) else -1 print("Freezing_Height", Freezing_Height) ax1.axhline(y=Freezing_Height, c='black', ls='-', lw=1) ############################################################################ """[Step 3] Save plot and return""" #Specify the directory the plots are stored in path = os.path.dirname(self.Radiosonde_File[self.sensor_package]).replace(self.Storage_Path + self.Processed_Data_Path,"") #Find any other plots stored in this directory previous_plots = glob.glob(self.Storage_Path + 'Plots/RH_Comparison/' + path + "/*") #Find the biggest 'v' number in plots plot_version = [] for plots in previous_plots: try: plot_version.append(int(os.path.basename(plots)[34:37])) except ValueError: plot_version.append(int(os.path.basename(plots)[34:36])) plot_version = str(np.max(plot_version)+1) if len(plot_version) != 0 else '1' #Create full directory and file name Save_Location = self.Storage_Path + 'Plots/RH_Comparison/' + path + '/' + path + '_v' + plot_version.rjust(2,'0') + '_' + str(self.height_range[0]).rjust(2,'0') + 'km_to_' + str(self.height_range[1]).rjust(2,'0') + 'km.png' #Ensure the directory exists on file system and save to that location gu.ensure_dir(os.path.dirname(Save_Location)) plt.savefig(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300) ############################################################################ elif method == 'Comparison': data_points = 20000 data = gu.array2recarray((np.linspace(20,-100,data_points), np.full(data_points,50, dtype=np.float64)), names='Tdry, RH', formats='f8, f8') # Calibrate Height, Temperature and Convert PANDORA channels from counts to volts if required. Radiosonde_Cal = Radiosonde_Checks(data.copy(), None, self.sensor_package, quality_control=False) Radiosonde_Cal_Goff = Radiosonde_Checks(data.copy(), None, self.sensor_package, quality_control=False) Radiosonde_Cal_Buck = Radiosonde_Checks(data.copy(), None, self.sensor_package, quality_control=False) Radiosonde_Cal_Wexler = Radiosonde_Checks(data.copy(), None, self.sensor_package, quality_control=False) Radiosonde_Cal_Sonntag = Radiosonde_Checks(data.copy(), None, self.sensor_package, quality_control=False) Radiosonde_Cal_Hardy = Radiosonde_Checks(data.copy(), None, self.sensor_package, quality_control=False) # Calibrate Relative Humidity Sensor (e.g. find RH_ice) Radiosonde_Cal_Goff.RH(method='goff') Radiosonde_Cal_Buck.RH(method='arden-buck') Radiosonde_Cal_Wexler.RH(method='wexler') Radiosonde_Cal_Sonntag.RH(method='sonntag') Radiosonde_Cal_Hardy.RH(method='hardy') # Return Data (make local to function only. i.e. DON'T use self.Radiosonde_Data) Radiosonde_Data = Radiosonde_Cal.finalise() Radiosonde_Data_Goff = Radiosonde_Cal_Goff.finalise() Radiosonde_Data_Buck = Radiosonde_Cal_Buck.finalise() Radiosonde_Data_Wexler = Radiosonde_Cal_Wexler.finalise() Radiosonde_Data_Sonntag = Radiosonde_Cal_Sonntag.finalise() Radiosonde_Data_Hardy = Radiosonde_Cal_Hardy.finalise() #Plotting requirements plt.style.use('classic') #necessary if Matplotlib version is >= 2.0.0 #Make sure we are creating new plot from scratch plt.clf() plt.close() #Define number of subplots sharing y axis f, ax1 = plt.subplots() ax1.minorticks_on() ax1.grid(which='major',axis='both',c='grey') ax1.plot(Radiosonde_Data_Goff['Tdry'], Radiosonde_Data_Hardy['RHice']-Radiosonde_Data_Goff['RHice'], lw=0.5, label='Goff-Gratch') ax1.plot(Radiosonde_Data_Buck['Tdry'], Radiosonde_Data_Hardy['RHice']-Radiosonde_Data_Buck['RHice'], lw=0.5, label='Arden-Buck') ax1.plot(Radiosonde_Data_Wexler['Tdry'], Radiosonde_Data_Hardy['RHice']-Radiosonde_Data_Wexler['RHice'], lw=0.5, label='Wexler') ax1.plot(Radiosonde_Data_Sonntag['Tdry'], Radiosonde_Data_Hardy['RHice']-Radiosonde_Data_Sonntag['RHice'], lw=0.5, label='Sonntag') #ax1.plot(Radiosonde_Data_Hardy['Tdry'], Radiosonde_Data_Hardy['RHice']-Radiosonde_Data_Hardy['RHice'], lw=0.5, label='Hardy') ax1.set_xlabel('Temperature $(^\circ C)$') ax1.set_ylabel('RH difference from Hardy $(\%)$') ax1.legend(loc='upper right') ax1.set_xlim([-60,20]) ax1.set_yscale('log') ax1.axvline(x=0, c='black', ls='--', lw=1) # Fill in the total uncertainity of the Vaisala RH sensor warm_mask = Radiosonde_Data_Goff['Tdry'] >= 0 cold_mask = Radiosonde_Data_Goff['Tdry'] <= 0 ax1.fill_between(Radiosonde_Data_Goff['Tdry'][cold_mask], 0, 5, interpolate=False, color='dodgerblue', alpha=0.3, **fill_kwargs) filename = self.Storage_Path + 'Plots/RH_Comparison/All/RH_Comparison_EquationForm.png' plt.savefig(filename, bbox_inches='tight', pad_inches=0.1, dpi=300) if self.verbose is True: print("[INFO] RH_Comparison completed successfully (In %.2fs)" % (time.time()-t_begin)) def Ice_Concentration(self, Radiosonde_File=None, Calibrate=None, Height_Range=None, Sensor_Package=None): gu.cprint("[INFO] You are running Radiosonde_Ice_Concentration from the DEV release", type='bold') ############################################################################ """Prerequisites""" Storage_Path = '/storage/shared/glusterfs/phd/users/th863480/WC3_InSitu_Electrification/' Processed_Data_Path = 'Processed_Data/Radiosonde/' Raw_Data_Path = 'Raw_Data/' Plots_Path = 'Plots/Radiosonde/' t_begin = time.time() ############################################################################ """[Step 1] Check and Import Data""" #Error check that either Radiosonde_File or Sensor_Package has been specified if Radiosonde_File is None and Sensor_Package is None: sys.exit("[Error] You must specify either the Radiosonde_File location or the Sensor_Package number") #Attempt to find the radiosonde file either directly or from glob Radiosonde_File = Storage_Path + Processed_Data_Path + Radiosonde_File if Radiosonde_File is not None else glob.glob(Storage_Path + Processed_Data_Path + 'Radiosonde_Flight_No.' + str(Sensor_Package).rjust(2,'0') + '_*/Radiosonde_Flight_PhD_James_No.' + str(Sensor_Package) + '*a.txt') #If no radiosonde file was found we end program if len(Radiosonde_File) == 0: sys.exit("[Error] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (Sensor_Package)) #If the radiosonde file was found via glob we need to convert to str from list if isinstance(Radiosonde_File, list): Radiosonde_File = Radiosonde_File[0] #Import all the data if Radiosonde_File is not None: Radiosonde_Data = np.genfromtxt(Radiosonde_File, delimiter=None, skip_header=10, dtype=float, comments="#") Radiosonde_Cal = Radiosonde_Checks(Radiosonde_Data, Calibrate, Sensor_Package, Height_Range, check=1111) Radiosonde_Data = Radiosonde_Cal.return_data() Time = Radiosonde_Data[:,0][Radiosonde_Data[:,9] == 1112] PLL = Radiosonde_Data[:,7][Radiosonde_Data[:,9] == 1112] PLL[PLL == 0] = np.nan print(PLL) print(np.sum(np.isnan(PLL))) def Lightning(self, Data, Radiosonde_File=None, Calibrate=None, Height_Range=None, Sensor_Package=None): """Compares lightning data from ATDnet with the position of a radiosonde""" from matplotlib.ticker import MultipleLocator, FormatStrFormatter, MaxNLocator, LogLocator, ScalarFormatter from matplotlib.colors import LogNorm, ListedColormap from matplotlib.dates import DateFormatter, MinuteLocator, HourLocator, DayLocator gu.cprint("[INFO] You are running Radiosonde_Lightning from the STABLE release", type='bold') ############################################################################ """Prerequisites""" #Time Controls t_begin = time.time() #Storage Locations Storage_Path = PhD_Global.Storage_Path_WC3 Processed_Data_Path = 'Processed_Data/Radiosonde/' Raw_Data_Path = 'Raw_Data/' Plots_Path = 'Plots/Lightning/' #Plotting requirements plt.style.use('classic') #necessary if Matplotlib version is >= 2.0.0 #Set-up data importer EPCC_Data = EPCC_Importer() #Time Offset time_offset = 20.5 #s ############################################################################ """[Step 1] Check and Import Data""" t1 = time.time() #Error check that either Radiosonde_File or Sensor_Package has been specified if Radiosonde_File is None and Sensor_Package is None: sys.exit("[Error] You must specify either the Radiosonde_File location or the Sensor_Package number") #Attempt to find the radiosonde file either directly or from glob Radiosonde_File = Storage_Path + Processed_Data_Path + Radiosonde_File if Radiosonde_File is not None else glob.glob(Storage_Path + Processed_Data_Path + 'Radiosonde_Flight_No.' + str(Sensor_Package).rjust(2,'0') + '_*/Radiosonde_Flight_PhD_James_No.' + str(Sensor_Package) + '*a.txt') #If no radiosonde file was found we end program if len(Radiosonde_File) == 0: sys.exit("[Error] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?" % (Sensor_Package)) #If the radiosonde file was found via glob we need to convert to str from list if isinstance(Radiosonde_File, list): Radiosonde_File = Radiosonde_File[0] #Once the radiosonde file is found we can attempt to find the GPS file in the raw file section GPS_File = glob.glob(Storage_Path + Raw_Data_Path + 'Radiosonde_Flight_No.' + str(Sensor_Package).rjust(2,'0') + '_*/GPSDCC_RESULT*.tsv') #Import all the data if Radiosonde_File is not None: Radiosonde_Data = np.genfromtxt(Radiosonde_File, delimiter=None, skip_header=10, dtype=float, comments="#") #Get Launch Datetime Launch_Datetime, _ = Radiosonde_Launch(GPS_File, offset=time_offset) #Import ATDnet Data ID = np.where(Data['Date_ID'] == gu.toDateOnly(Launch_Datetime))[0][0] ATDnet_Time, ATDnet_LatLong = EPCC_Data.ATDnet(Data['ATDnet_File'][ID]) if ATDnet_Time is None: raise IOError("No ATDnet data found for this Radiosonde flight") ############################################################################ """[Step 2] Calibrate bespoke sensors""" t2 = time.time() #Calibrate Height, Temperature and Convert PANDORA channels from counts to volts if required. Radiosonde_Cal_Clean = Radiosonde_Checks(Radiosonde_Data.copy(), Calibrate, Sensor_Package, Height_Range, check=1111, enforce_parity=True) Radiosonde_Cal_Error = Radiosonde_Checks(Radiosonde_Data.copy(), Calibrate, Sensor_Package, Height_Range, check=1111, enforce_parity=False) #Return Data. _Clean : Enforce 1111/1112 parity, _Error: leave other parities alone. Used to identify link with lightning Radiosonde_Data_Clean = Radiosonde_Cal_Clean.return_data() Radiosonde_Data_Error = Radiosonde_Cal_Error.return_data() #Non 1111/1112 parity bits converted to nan (except time column) Radiosonde_Data_Error[~((Radiosonde_Data_Error[:,9] == 1111) ^ (Radiosonde_Data_Error[:,9] == 1112)),1:] = np.nan print("Launch_Datetime", Launch_Datetime) ############################################################################ """[Step 3] Compare ATDnet with Radiosonde""" t3 = time.time() #First, convert Radiosonde time in flight to datetime64 Radiosonde_Time = np.array(Launch_Datetime, dtype='datetime64[s]') + Radiosonde_Data_Clean[:,0].astype('timedelta64[s]') Radiosonde_LatLong = Radiosonde_Data_Clean[:,(11,10)] t4 = time.time() #Second, subset ATDnet for times when radiosonde was flying ATD_Mask = gu.bool2int((ATDnet_Time >= Radiosonde_Time[0]) & (ATDnet_Time <= Radiosonde_Time[-1])) ATDnet_Time = ATDnet_Time[ATD_Mask] ATDnet_LatLong = ATDnet_LatLong[ATD_Mask] #Third, join together the ATDnet timestamps and the Radiosonde timestamps mask = gu.mask(Radiosonde_Time, ATDnet_Time, approx=True) Radiosonde_Time = Radiosonde_Time[mask][0] Radiosonde_LatLong = Radiosonde_LatLong[mask][0] t5 = time.time() #Fourth, for each lightning detected, calculate the haversine between the latlong of the lightning and latlong of the radiosonde Lightning_Distance = np.array([gu.haversine(tuple(atdnet_latlong), tuple(radiosonde_latlong))[0] for atdnet_latlong, radiosonde_latlong in zip(ATDnet_LatLong, Radiosonde_LatLong)], dtype=np.float64) #Fifth, remove nan values from array (N.B can't use gu.antinan as ATDnet has datetime64 which can't be handled) nan_mask = np.isnan(Lightning_Distance) ATDnet_Time = ATDnet_Time[~nan_mask] Lightning_Distance = Lightning_Distance[~nan_mask] ############################################################################ """[Step 4]: Plot time series of lightning strikes""" Error_Mask = gu.contiguous(np.isnan(Radiosonde_Data_Error[:,5]), invalid=False) Error_Index = [[gu.bool2int(Error_Mask == val)[0], gu.bool2int(Error_Mask == val)[-1] + 0] for val in np.unique(Error_Mask)[1:]] Error_Length = np.diff(Error_Index).ravel() Radiosonde_Time_Error = np.array(Launch_Datetime, dtype='datetime64[s]') + Radiosonde_Data_Error[:,0].astype('timedelta64[s]') #Subset lightning distance to closest 100km strikes distance_mask = (Lightning_Distance/1000 < 100) ATDnet_Time = ATDnet_Time[distance_mask] Lightning_Distance = Lightning_Distance[distance_mask]/1000 #Clear any previous plots gu.backend_changer('nbAgg') plt.clf() plt.close() #Plot lightning data as time-series plt.plot(ATDnet_Time, Lightning_Distance, 'p', ms=3, marker='o', markeredgecolor='None', markerfacecolor='blue', alpha=1, label="Lightning", zorder=4) plt.ylim([0,100]) plt.grid(which='major',axis='both',c='grey', zorder=2) #Configure x axis ticks gu.date_ticks(plt.gca(), (ATDnet_Time[0], ATDnet_Time[-1])) #Write Plot Labels plt.ylabel("Distance from Radiosonde (km)") plt.title("Distance of Lightning Strikes from Radiosonde Flight No." + str(Sensor_Package)) plt.annotate("$Counts$ = %.0f\n$Closest$ $Strike$ = %.2fkm" % (Lightning_Distance.size, np.nanmin(Lightning_Distance)), xy=(1, 1), xycoords='axes fraction', fontsize=12, xytext=(-5, -5), textcoords='offset points', ha='right', va='top') #Add fill_between highlighting when communication was lost with the Radiosonde cmap = plt.cm.Set2 norm = plt.matplotlib.colors.Normalize(vmin=1, vmax=9) for i, (Error, Length) in enumerate(zip(Error_Index, Error_Length)): plt.axvspan(Radiosonde_Time_Error[Error[0]], Radiosonde_Time_Error[Error[1]], alpha=0.5, color=cmap(norm(Length)), zorder=3) plt.tight_layout() #Create colour bar for the communication black-out time sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) cb = plt.colorbar(sm, orientation='vertical', pad=0.01, ticks=[1,2,3,4,5,6,7,8,9]) cb.set_label('Comms. Blackout ($s$)', labelpad=1, fontsize=10) cb.ax.set_xticklabels(['1', '2', '3', '4', '5', '6', '7', '8','9']) cb.ax.tick_params(labelsize=10) ##SAVE PLOT### #Specify the directory the plots are stored in path = os.path.dirname(Radiosonde_File).replace(Storage_Path + Processed_Data_Path,"") #Find any other plots stored in this directory previous_plots = glob.glob(Storage_Path + Plots_Path + path + "Timeseries/*") #Find the biggest 'v' number in plots plot_version = [] for plots in previous_plots: try: plot_version.append(int(os.path.basename(plots)[34:37])) except ValueError: plot_version.append(int(os.path.basename(plots)[34:36])) plot_version = str(np.max(plot_version)+1) if len(plot_version) != 0 else '1' #Create full directory and file name Save_Location = Storage_Path + Plots_Path + path + '/Timeseries/' + path + '_v' + plot_version.rjust(2,'0') + '_LightningTimeseries.png' #Ensure the directory exists on file system and save to that location gu.ensure_dir(os.path.dirname(Save_Location)) plt.savefig(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300) print("Time series", Save_Location) ############################################################################ """[Step 5] Plot lightning strikes and position of radiosonde on a map OPTIONS: USE THE fNorth AND fEast VALUES IN GPSDCC_RESULT TO CALCULATE THE RADIOSONDE POSITION MORE ACCURATELY!""" from mpl_toolkits.basemap import Basemap from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import inset_axes from matplotlib.patches import Polygon from matplotlib.dates import date2num, num2date from matplotlib.collections import LineCollection gu.backend_changer() #Provide dimensions of map lonW_Small = -2.0 lonE_Small = 1.0 latN_Small = 52.5 latS_Small = 50.5 lonW_Large = -11.0 lonE_Large = 2.5 latN_Large = 61.0 latS_Large = 49.0 #Map positioning Position = {'upper right' : (lonE_Small-0.55, latN_Small-0.15), 'upper left' : (lonW_Small+0.2, latN_Small-0.15), 'lower right' : (lonE_Small-0.55, latS_Small+0.15), 'lower left' : (lonW_Small+0.2, latS_Small+0.15)} #Map Resolution map_res = 'f' #Create base map fig = plt.figure() ax = fig.add_subplot(111) map = Basemap(projection='merc', lat_0=51, lon_0=-3, resolution=map_res, llcrnrlon=lonW_Small, llcrnrlat=latS_Small, urcrnrlon=lonE_Small, urcrnrlat=latN_Small, ax=ax) #Define centre of map LatLong_Centre = [0.5*(latN_Small + latS_Small), 0.5*(lonE_Small + lonW_Small)] #Add overlays to map map.drawmapboundary(fill_color='LightBlue', zorder=0) map.fillcontinents(color='white', lake_color='LightBlue', zorder=0) map.drawcoastlines(color='DimGrey', linewidth=1, zorder=0) map.drawcountries(color='Grey', linewidth=1, zorder=0) map.drawmeridians(np.arange(-15, 5, 1),linewidth=0.5,color='DarkGrey',labels=[0,0,0,1], zorder=0) map.drawparallels(np.arange(-50, 70, 1),linewidth=0.5,color='DarkGrey',labels=[1,0,0,0], zorder=0) plt.title('Location of Lightning Strikes and Radiosonde Trajectory (Flight No.5)') city_labels = True if city_labels is True: # lat/lon coordinates to plot lats = [51.441314] lons = [-0.937447] # compute the native map projection coordinates x,y = map(lons,lats) map.scatter(x,y,s=30, edgecolors='DimGrey', marker='s', facecolors='none', alpha=1, zorder=5) label_txt = ['RUAO'] for lab in range(0,np.size(x)): plt.text(x[lab], y[lab], label_txt[lab], color='black', size=10, horizontalalignment='center', verticalalignment='top', zorder=6) #Create colour bar for plotting time progression Radiosonde_Time = date2num(Radiosonde_Time.astype(datetime)) ATDnet_Time = date2num(ATDnet_Time.astype(datetime)) #Configure colour-map setting cmap = plt.cm.rainbow norm = plt.matplotlib.colors.Normalize(vmin=Radiosonde_Time[0], vmax=Radiosonde_Time[-1]) scalarMap = plt.cm.ScalarMappable(norm=norm, cmap='rainbow') scalarMap.set_array([]) print("Radiosonde_Time", Radiosonde_Time.dtype, Radiosonde_Time.shape, Radiosonde_Time.size) print("ATDnet_Time", ATDnet_Time.dtype, ATDnet_Time.shape, ATDnet_Time.size) #Add ATDnet Lightning Strikes x, y = map(ATDnet_LatLong[:,1], ATDnet_LatLong[:,0]) map.scatter(x, y, s=5, marker='o', edgecolors='None', alpha=1, facecolor=cmap(norm(ATDnet_Time))) #Add Radiosonde Trajectory x, y = map(Radiosonde_LatLong[:,1], Radiosonde_LatLong[:,0]) xy = np.vstack((x,y)).T for rad_time, start, stop in zip(Radiosonde_Time, xy[:-1], xy[1:]): xval, yval = zip(start, stop) map.plot(xval, yval, '-', lw=1, color=cmap(norm(rad_time))) #Add scale bar map.drawmapscale(*Position['lower right'], lat0=LatLong_Centre[0], lon0=LatLong_Centre[1], length=100, units='km', barstyle='fancy', ax=ax) #Create inset map axes axin = inset_axes(map.ax, width="30%", height="30%", loc=3) #Create inset map on the same Mercator Geographic Coordinate System omap = Basemap(projection='merc', lat_0=51, lon_0=-3, resolution=map_res, llcrnrlon=lonW_Large, llcrnrlat=latS_Large, urcrnrlon=lonE_Large, urcrnrlat=latN_Large, ax=axin) #Add overlays to map omap.drawmapboundary(fill_color='LightBlue') omap.fillcontinents(color='white',lake_color='LightBlue') omap.drawcoastlines(color='DimGrey', linewidth=.5) omap.drawcountries(color='Grey', linewidth=.5) #Add Zoomed Box bx, by = omap(map.boundarylons, map.boundarylats) xy = list(zip(bx,by)) mapboundary = Polygon(xy,edgecolor='red',linewidth=2,fill=False) omap.ax.add_patch(mapboundary) #Create colour bar for the communication black-out time sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) myFmt = plt.matplotlib.dates.DateFormatter('%H:%M') cb = plt.colorbar(sm, orientation='vertical', pad=0.01, label="Time (UTC)", format=myFmt, fraction=0.04) cb.ax.tick_params(labelsize=10) ##SAVE PLOT### #Specify the directory the plots are stored in path = os.path.dirname(Radiosonde_File).replace(Storage_Path + Processed_Data_Path,"") #Find any other plots stored in this directory previous_plots = glob.glob(Storage_Path + Plots_Path + path + "/Map/*") print("LOOKING", Storage_Path + Plots_Path + path + "/Map/") print("previous_plots", previous_plots) #Find the biggest 'v' number in plots plot_version = [] for plots in previous_plots: try: plot_version.append(int(os.path.basename(plots)[34:37])) except ValueError: plot_version.append(int(os.path.basename(plots)[34:36])) plot_version = str(np.max(plot_version)+1) if len(plot_version) != 0 else '1' #Create full directory and file name Save_Location = Storage_Path + Plots_Path + path + '/Map/' + path + '_v' + plot_version.rjust(2,'0') + '_LightningMap.png' #Ensure the directory exists on file system and save to that location gu.ensure_dir(os.path.dirname(Save_Location)) plt.savefig(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300) print("Map", Save_Location) t6 = time.time() print("Time t2-t1 = %.2fs, t3-t2 = %.2fs, t4-t3 = %.2fs, t5-t4 = %.2fs, t6-t5 = %.2fs, Total = %.2fs" % (t2-t1, t3-t2, t4-t3, t5-t4, t6-t5, t6-t1)) print("[INFO] Radiosonde_Lightning completed successfully (In %.2fs)" % (time.time()-t_begin)) def LabCalibration_Charge(): """ This function will plot the labratory calibrations for the charge instrument for both linear and log sensors """ gu.cprint("[INFO] You are running LabCalibration_Charge from the STABLE release", type='bold') ############################################################################ """Prerequisites""" # Time Controls t_begin = time.time() # Storage Locations Storage_Path = PhD_Global.Storage_Path_WC3 Plots_Path = 'Plots/Data_Processing/' # Data Locations Linear_File = Storage_Path + 'Development/Calibration/Charge_Sensor/Charge_Calibration_All_Linear.csv' Log_File = Storage_Path + 'Development/Calibration/Charge_Sensor/Charge_Calibration_All_Log.csv' # Set-up plotting gu.backend_changer() ############################################################################ """Import Lab Calibration Data""" Linear_Cal = pd.read_csv( Linear_File, sep=",", header=None, engine='python', names=( 'Current_Sensor1', 'Current_Sensor2', 'Current_Sensor3+', 'Voltage_Sensor1', 'Voltage_Sensor2', 'Voltage_Sensor3', 'Voltage_Sensor4', 'Voltage_Sensor5', 'Voltage_Sensor6', 'Voltage_Sensor7', 'Voltage_Sensor8', 'Voltage_Sensor9', 'Voltage_Sensor10'), dtype={ 'Current_Sensor1': np.float64, 'Current_Sensor2': np.float64, 'Current_Sensor3+': np.float64, 'Voltage_Sensor1': np.float64, 'Voltage_Sensor2': np.float64, 'Voltage_Sensor3': np.float64, 'Voltage_Sensor4': np.float64, 'Voltage_Sensor5': np.float64, 'Voltage_Sensor6': np.float64, 'Voltage_Sensor7': np.float64, 'Voltage_Sensor8': np.float64, 'Voltage_Sensor9': np.float64, 'Voltage_Sensor10': np.float64}, skiprows=2, comment='#', index_col=False).to_records(index=False) Log_Cal = pd.read_csv( Log_File, sep=",", header=None, engine='python', names=( 'Current_Sensor1', 'Current_Sensor2', 'Current_Sensor3+', 'Voltage_Sensor1', 'Voltage_Sensor2', 'Voltage_Sensor3', 'Voltage_Sensor4', 'Voltage_Sensor5', 'Voltage_Sensor6', 'Voltage_Sensor7', 'Voltage_Sensor8', 'Voltage_Sensor9', 'Voltage_Sensor10'), dtype={ 'Current_Sensor1': np.float64, 'Current_Sensor2': np.float64, 'Current_Sensor3+': np.float64, 'Voltage_Sensor1': np.float64, 'Voltage_Sensor2': np.float64, 'Voltage_Sensor3': np.float64, 'Voltage_Sensor4': np.float64, 'Voltage_Sensor5': np.float64, 'Voltage_Sensor6': np.float64, 'Voltage_Sensor7': np.float64, 'Voltage_Sensor8': np.float64, 'Voltage_Sensor9': np.float64, 'Voltage_Sensor10': np.float64}, skiprows=2, comment='#', index_col=False).to_records(index=False) # Fix np.recarray issue Linear_Cal = gu.fix_recarray(Linear_Cal) Log_Cal = gu.fix_recarray(Log_Cal) ############################################################################ """Plot Lab Calibration Data""" plt.clf() plt.close() # Set up subplots with 2 coloumns f, ax = plt.subplots(1,2) f.subplots_adjust(wspace=0) # Global attributes of subplots for subplot in ax.ravel(): subplot.minorticks_on() for subplot in ax.ravel(): subplot.grid(which='major',axis='both',c='grey') # Specify plot layout config = [ ['Current_Sensor1', 'Voltage_Sensor1'], ['Current_Sensor2', 'Voltage_Sensor2'], ['Current_Sensor3+', 'Voltage_Sensor3'], ['Current_Sensor3+', 'Voltage_Sensor4'], ['Current_Sensor3+', 'Voltage_Sensor5'], ['Current_Sensor3+', 'Voltage_Sensor6'], ['Current_Sensor3+', 'Voltage_Sensor7'], ['Current_Sensor3+', 'Voltage_Sensor8'], ['Current_Sensor3+', 'Voltage_Sensor9'], ['Current_Sensor3+', 'Voltage_Sensor10'] ] names = [ "Package 1", "Package 2", "Package 3", "Package 4", "Package 5", "Package 6", "Package 7", "Package 8", "Package 9", "Package 10" ] colours = [ "black", "red", "darkorange", "yellow", "forestgreen", "aqua", "dodgerblue", "slategrey", "darkviolet", "orchid" ] # Plot all lab calibrations for col, sensor_type in enumerate(['Linear_Cal', 'Log_Cal']): for (current, voltage), color in zip(config, colours): #ax[col].plot(locals()[sensor_type][voltage], locals()[sensor_type][current], lw=0.5) ax[col].errorbar(locals()[sensor_type][voltage], locals()[sensor_type][current], xerr=0.01, yerr=10**-13, lw=0.5, color=color) # Set x-label and y-label for all subplots for subplot in ax.ravel(): subplot.set_xlabel("Voltage (V)") for subplot in ax.ravel(): subplot.set_ylabel("Current (pA)") # Set x-lim and y-lim for subpltos ax[0].set_xlim([0.5,4.5]) ax[0].set_ylim([-30,30]) ax[1].set_xlim([1.0,1.5]) ax[1].set_ylim([-1000,1000]) # Place y-label and y-ticks for right-hand plot on the right side ax[1].yaxis.set_label_position("right") ax[1].yaxis.tick_right() # Set annotations for both subplots ax[0].annotate("(%s) %s" % (gu.alphabet[0], "Linear Charge Sensor"), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10) ax[1].annotate("(%s) %s" % (gu.alphabet[1], "Logarithmic Charge Sensor"), xy=(0, 1), xycoords='axes fraction', xytext=(20, -20), textcoords='offset pixels', horizontalalignment='left', verticalalignment='top', fontsize=10) # Create custom legend lines = [] for i in xrange(len(config)): lines.append(ax[0].plot([1,1],'-', color=colours[i])[0]) f.legend(lines, names, loc='lower center', bbox_to_anchor=(0.49, -0.025), ncol=3) # Remove fake data to stop it unnecessarily being plotted for line in lines: line.set_visible(False) # Fix aspect ratio of both subplots for subplot in ax.ravel(): gu.fixed_aspect_ratio(ax=subplot, ratio=1, adjustable=None) plt.tight_layout() # Save figure plot_filename = Storage_Path + Plots_Path + "ChargeSensor_LinLog_LabCalibrations.png" plt.savefig(plot_filename, dpi=300, pad_inches=0.1, bbox_inches='tight') print("RMSE. Linear = %.4fV. Log = %.4fV" % (gu.rmse(gu.antinan(Linear_Cal['Voltage_Sensor3']), gu.antinan(Linear_Cal['Voltage_Sensor4'], unpack=True)), gu.rmse(gu.antinan(Log_Cal['Voltage_Sensor3']), gu.antinan(Log_Cal['Voltage_Sensor4'], unpack=True)))) if __name__ == "__main__": """Launch the Radiosonde_Analysis.py from the command line. This python script gives command line options which can be found using Radiosonde_Analysis.py --help. An example input for a radiosonde flight is given as, >>> python Radiosonde_Analysis.py --sensor 3 --height 0.0 2.0 --calibrate count if using Radiosonde_ChargeCalibrator use: >>> python Radiosonde_Analysis.py --sensor x --height zmin zmax --calibrate volts where x is the radiosonde flight number, zmin and zmax are the height boundaries where you want to perform the calibration and volts or units is required for calibrate to correctly get the linear current. Notes for zmin and zmax are to use an area of the ascent where both linear and log charge sensors did not saturate. Otherwise, the calibration will have a systematic bias. """ gu.cprint("Welcome to Radiosonde Analysis. Plotting the sounding data and calculating profile indices.", type='bold') ############################################################################ """Process Command Line Arguments""" parser = argparse.ArgumentParser(description='Plot the radiosonde \ data for each flight during my PhD. The calibration \ from counts to voltage to quantity is applied \ automatically if found in Radiosonde_Calibration.py') #Command Line Arguments parser.add_argument('-v','--height', action="store", dest="height_range", nargs='+', type=float, help="Specify the minimum height used for plotting the \ radiosonde data. The format should be '-h 0 18' where \ 0 and 18 are the lower and upper bound heights \ respectively.", default=(0.0,14.0), required=False) parser.add_argument('-s','--sensor', action="store", dest="sensor_package", type=str, help="Specify the radiosonde sensor package you want to plot.\ Ranges from 1+", default='All', required=False) parser.add_argument('-c', '--calibrate', action="store", dest="calibrate", type=str, help="Specify what level of calibration you want to apply to \ the research channels. Select either 'counts', 'volts',\ 'units' are available options", default='units', required=False) parser.add_argument('--tephigram', action='store_true', dest="plot_tephigram", help="Specify if you want to plot the tephigram of the specify \ radiosonde flight") parser.add_argument('--larkhill', action='store_true', dest="plot_larkhill", help="Specify if you want to plot the Larkhill Upper Level \ Sounding data on top of the radiosonde data") parser.add_argument('--casestudy', action='store_true', dest="casestudy", help="Specify if you want to plot the case study figures.") parser.add_argument('--stats', action='store_true', dest="stats", help="Specify if you want to plot the case study figures.") parser.add_argument('--hypothesis1', action='store_true', dest="hypothesis1", help="Specify if you want to plot the case study figures.") parser.add_argument('--hypothesis2', action='store_true', dest="hypothesis2", help="Specify if you want to plot the case study figures.") parser.add_argument('--hypothesis3', action='store_true', dest="hypothesis3", help="Specify if you want to plot the case study figures.") parser.add_argument('--hypothesis4', action='store_true', dest="hypothesis4", help="Specify if you want to plot the case study figures.") parser.add_argument('--reload', action='store_true', dest="reload", help="Specify if you want to reload the data processing of the \ chosen radiosonde flight.") parser.add_argument('--verbose', action='store_true', dest="verbose", help="Specify if you want output extra information about the \ data processing.") arg = parser.parse_args() arg.plot_tephigram = bool(arg.plot_tephigram) arg.plot_larkhill = bool(arg.plot_larkhill) if arg.calibrate not in ['volts', 'units', 'counts', 'basic', 'raw'] and arg.casestudy is not True: raise ValueError("[Error] Radiosonde_Analysis requires the \ Calibrate argument to be specified with \ either 'raw', 'counts', 'volts' or 'units") #Convert Calibrate and Height_Range into tuples arg.height_range = tuple(arg.height_range) arg.calibrate = arg.calibrate.capitalize() # If arg.sensor_package is not all, make sure its an integer if arg.sensor_package != 'All': arg.sensor_package = int(arg.sensor_package) #Initialise Clouds_ID, LayerType Clouds_ID = None LayerType = None ############################################################################ """Prerequisites""" # Output confirmation to console gu.cprint("Everything was set-up correctly. Let crunch some numbers!", type='okblue') # Time controls tstart_main = time.time() # Load data directory Data = PhD_Global.Data_CHIL # Initalising the Radiosonde Class Rad = Radiosonde(sensor_package=arg.sensor_package, height_range=arg.height_range, calibrate=arg.calibrate, reload=arg.reload, verbose=arg.verbose) ############################################################################ """Start of Main Function""" if arg.casestudy is True: Rad.CaseStudy_Overview() #if arg.casestudy is True: # Rad.CaseStudy_Specific() if arg.stats is True: Rad.CaseStudy_Statistics() if arg.hypothesis1 is True: Rad.Hypothesis1() if arg.hypothesis2 is True: Rad.Hypothesis2_v2() if arg.hypothesis3 is True: Rad.Hypothesis3() if arg.hypothesis4 is True: Rad.Hypothesis4() if arg.sensor_package != 'All': Rad.Superplotter() if arg.plot_tephigram is True: Rad.Tephigram(plot_tephigram=arg.plot_tephigram, plot_larkhill=arg.plot_larkhill) #Rad.RH_Comparison() #Rad.Hypothesis3() print("[INFO] All successful") sys.exit() sys.exit() # #Rad.Hypothesis2_v2() Rad.Hypothesis3() #print("FINISHED") sys.exit() #Identify the clouds within the radiosonde data Clouds_ID, LayerType = Radiosonde_CloudIdentifier(Height_Range=arg.Height_Range, Sensor_Package=arg.Sensor_Package) #Determine the charge calibration for the log sensor if np.any(np.in1d(arg.Calibrate, ['volts', 'units'])): Calibration_Log = Radiosonde_ChargeCalibrator(Calibrate=arg.Calibrate, Sensor_Package=arg.Sensor_Package) #Plot Radiosonde Data together in Cartesian Coordinates if np.any(np.in1d(arg.Calibrate, ['volts', 'units'])): Radiosonde_Superplotter(Calibrate=arg.Calibrate, Height_Range=arg.Height_Range, Sensor_Package=arg.Sensor_Package, Clouds_ID=Clouds_ID, LayerType=LayerType, Calibration_Log=Calibration_Log) else: Radiosonde_Superplotter(Calibrate=arg.Calibrate, Height_Range=arg.Height_Range, Sensor_Package=arg.Sensor_Package, Clouds_ID=Clouds_ID, LayerType=LayerType) sys.exit() #Plot Radiosonde Data together in Tephigram Coordinates Radiosonde_Tephigram(Height_Range=arg.Height_Range, Sensor_Package=arg.Sensor_Package, plot_tephigram=arg.plot_tephigram, plot_larkhill=arg.plot_larkhill) #Plot Lightning maps and comparison with Radiosonde Trajectory Radiosonde_Lightning(Data, Calibrate=arg.Calibrate, Height_Range=arg.Height_Range, Sensor_Package=arg.Sensor_Package) #IN THE FUTURE: #Radiosonde_ChargeCalibrator(Calibrate=arg.Calibrate, Height_Range=arg.Height_Range, Sensor_Package=arg.Sensor_Package) #Radiosonde_Ice_Concentration(Calibrate=arg.Calibrate, Height_Range=arg.Height_Range, Sensor_Package=arg.Sensor_Package) gu.cprint("[Radiosonde_Analysis]: All Tasks Completed, Time Taken (s): %.0f" % (time.time()-tstart_main), type='okgreen')
[ "Gilly_Utilities.argcontiguous", "pandas.read_csv", "Gilly_Utilities.antinan", "numpy.log", "Gilly_Utilities.HuberRegression", "Gilly_Utilities.fix_recarray", "Gilly_Utilities.flatten", "numpy.arctan2", "sys.exit", "numpy.sin", "numpy.arange", "urllib2.urlopen", "Gilly_Utilities.broadcast", ...
[((863, 926), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/users/th863480/PhD/Global_Functions"""'], {}), "(0, '/home/users/th863480/PhD/Global_Functions')\n", (878, 926), False, 'import sys\n'), ((1360, 1381), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (1375, 1381), False, 'import sys\n'), ((1634, 1659), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (1657, 1659), False, 'import warnings\n'), ((1662, 1693), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (1683, 1693), False, 'import warnings\n'), ((1725, 1815), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/"""'], {}), "(0,\n '/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/')\n", (1740, 1815), False, 'import sys\n'), ((195884, 195987), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running LabCalibration_Charge from the STABLE release"""'], {'type': '"""bold"""'}), "(\n '[INFO] You are running LabCalibration_Charge from the STABLE release',\n type='bold')\n", (195893, 195987), True, 'import Gilly_Utilities as gu\n'), ((196111, 196122), 'time.time', 'time.time', ([], {}), '()\n', (196120, 196122), False, 'import time\n'), ((196479, 196499), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (196497, 196499), True, 'import Gilly_Utilities as gu\n'), ((198467, 198494), 'Gilly_Utilities.fix_recarray', 'gu.fix_recarray', (['Linear_Cal'], {}), '(Linear_Cal)\n', (198482, 198494), True, 'import Gilly_Utilities as gu\n'), ((198506, 198530), 'Gilly_Utilities.fix_recarray', 'gu.fix_recarray', (['Log_Cal'], {}), '(Log_Cal)\n', (198521, 198530), True, 'import Gilly_Utilities as gu\n'), ((198647, 198656), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (198654, 198656), True, 'import matplotlib.pyplot as plt\n'), ((198658, 198669), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (198667, 198669), True, 'import matplotlib.pyplot as plt\n'), ((198716, 198734), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {}), '(1, 2)\n', (198728, 198734), True, 'import matplotlib.pyplot as plt\n'), ((201720, 201738), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (201736, 201738), True, 'import matplotlib.pyplot as plt\n'), ((201844, 201916), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_filename'], {'dpi': '(300)', 'pad_inches': '(0.1)', 'bbox_inches': '"""tight"""'}), "(plot_filename, dpi=300, pad_inches=0.1, bbox_inches='tight')\n", (201855, 201916), True, 'import matplotlib.pyplot as plt\n'), ((203034, 203161), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""Welcome to Radiosonde Analysis. Plotting the sounding data and calculating profile indices."""'], {'type': '"""bold"""'}), "(\n 'Welcome to Radiosonde Analysis. Plotting the sounding data and calculating profile indices.'\n , type='bold')\n", (203043, 203161), True, 'import Gilly_Utilities as gu\n'), ((203283, 203525), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Plot the radiosonde \t\t\t\tdata for each flight during my PhD. The calibration \t\t\t\tfrom counts to voltage to quantity is applied \t\t\t\tautomatically if found in Radiosonde_Calibration.py"""'}), "(description=\n 'Plot the radiosonde \\t\\t\\t\\tdata for each flight during my PhD. The calibration \\t\\t\\t\\tfrom counts to voltage to quantity is applied \\t\\t\\t\\tautomatically if found in Radiosonde_Calibration.py'\n )\n", (203306, 203525), False, 'import argparse\n'), ((206810, 206900), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""Everything was set-up correctly. Let crunch some numbers!"""'], {'type': '"""okblue"""'}), "('Everything was set-up correctly. Let crunch some numbers!', type\n ='okblue')\n", (206819, 206900), True, 'import Gilly_Utilities as gu\n'), ((206930, 206941), 'time.time', 'time.time', ([], {}), '()\n', (206939, 206941), False, 'import time\n'), ((207931, 207941), 'sys.exit', 'sys.exit', ([], {}), '()\n', (207939, 207941), False, 'import sys\n'), ((207953, 207963), 'sys.exit', 'sys.exit', ([], {}), '()\n', (207961, 207963), False, 'import sys\n'), ((208032, 208042), 'sys.exit', 'sys.exit', ([], {}), '()\n', (208040, 208042), False, 'import sys\n'), ((208923, 208933), 'sys.exit', 'sys.exit', ([], {}), '()\n', (208931, 208933), False, 'import sys\n'), ((3040, 3051), 'time.time', 'time.time', ([], {}), '()\n', (3049, 3051), False, 'import time\n'), ((3583, 3598), 'Data_Importer.EPCC_Importer', 'EPCC_Importer', ([], {}), '()\n', (3596, 3598), False, 'from Data_Importer import EPCC_Importer\n'), ((6225, 6236), 'time.time', 'time.time', ([], {}), '()\n', (6234, 6236), False, 'import time\n'), ((19360, 19371), 'time.time', 'time.time', ([], {}), '()\n', (19369, 19371), False, 'import time\n'), ((19437, 19461), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""classic"""'], {}), "('classic')\n", (19450, 19461), True, 'import matplotlib.pyplot as plt\n'), ((20001, 20054), 'Gilly_Utilities.moving_average', 'gu.moving_average', (["Radiosonde_Data['Lin_Current']", '(11)'], {}), "(Radiosonde_Data['Lin_Current'], 11)\n", (20018, 20054), True, 'import Gilly_Utilities as gu\n'), ((20063, 20116), 'Gilly_Utilities.moving_average', 'gu.moving_average', (["Radiosonde_Data['Log_Current']", '(11)'], {}), "(Radiosonde_Data['Log_Current'], 11)\n", (20080, 20116), True, 'import Gilly_Utilities as gu\n'), ((20184, 20209), 'numpy.log10', 'np.log10', (['Linear[PosMask]'], {}), '(Linear[PosMask])\n', (20192, 20209), True, 'import numpy as np\n'), ((20407, 20439), 'scipy.stats.linregress', 'sp.stats.linregress', (['Log', 'Linear'], {}), '(Log, Linear)\n', (20426, 20439), True, 'import scipy as sp\n'), ((20508, 20546), 'scipy.stats.linregress', 'sp.stats.linregress', (['LogPos', 'LinearPos'], {}), '(LogPos, LinearPos)\n', (20527, 20546), True, 'import scipy as sp\n'), ((21224, 21233), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (21231, 21233), True, 'import matplotlib.pyplot as plt\n'), ((21236, 21247), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (21245, 21247), True, 'import matplotlib.pyplot as plt\n'), ((21261, 21279), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {}), '(1, 3)\n', (21273, 21279), True, 'import matplotlib.pyplot as plt\n'), ((24257, 24328), 'glob.glob', 'glob.glob', (["(self.Storage_Path + self.Radiosonde_Plots_Path + path + '/*')"], {}), "(self.Storage_Path + self.Radiosonde_Plots_Path + path + '/*')\n", (24266, 24328), False, 'import glob\n'), ((24969, 25041), 'matplotlib.pyplot.savefig', 'plt.savefig', (['Save_Location'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (24980, 25041), True, 'import matplotlib.pyplot as plt\n'), ((30024, 30212), 'Gilly_Utilities.antifinite', 'gu.antifinite', (["(Radiosonde_Data['Units']['time'], Radiosonde_Data['Units']['height'],\n Radiosonde_Data['Units']['WindSpeed'], Radiosonde_Data['Units'][\n 'SpaceCharge'])"], {'unpack': '(True)'}), "((Radiosonde_Data['Units']['time'], Radiosonde_Data['Units'][\n 'height'], Radiosonde_Data['Units']['WindSpeed'], Radiosonde_Data[\n 'Units']['SpaceCharge']), unpack=True)\n", (30037, 30212), True, 'import Gilly_Utilities as gu\n'), ((30360, 30429), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (["Radiosonde_Data['Units']['height']", 'Cloud_Heights[0]'], {}), "(Radiosonde_Data['Units']['height'], Cloud_Heights[0])\n", (30375, 30429), True, 'import Gilly_Utilities as gu\n'), ((31192, 31227), 'numpy.zeros', 'np.zeros', (['Cloud_SignChange.shape[0]'], {}), '(Cloud_SignChange.shape[0])\n', (31200, 31227), True, 'import numpy as np\n'), ((31785, 31820), 'numpy.zeros', 'np.zeros', (['Cloud_SignChange.shape[0]'], {}), '(Cloud_SignChange.shape[0])\n', (31793, 31820), True, 'import numpy as np\n'), ((33317, 33342), 'numpy.arange', 'np.arange', (['(-3000)', '(3000)', '(1)'], {}), '(-3000, 3000, 1)\n', (33326, 33342), True, 'import numpy as np\n'), ((33435, 33470), 'numpy.zeros', 'np.zeros', (['Cloud_SignChange.shape[0]'], {}), '(Cloud_SignChange.shape[0])\n', (33443, 33470), True, 'import numpy as np\n'), ((35720, 35731), 'time.time', 'time.time', ([], {}), '()\n', (35729, 35731), False, 'import time\n'), ((36170, 36344), 'Data_Output.SPRadiosonde', 'SPRadiosonde', (['self.Radiosonde_Data'], {'numplots': '(7)', 'which_ascents': '(self.sensor_package,)', 'plot_title': 'plot_title', 'height_range': 'self.height_range', 'calibrate': 'self.calibrate'}), '(self.Radiosonde_Data, numplots=7, which_ascents=(self.\n sensor_package,), plot_title=plot_title, height_range=self.height_range,\n calibrate=self.calibrate)\n', (36182, 36344), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((38188, 38259), 'glob.glob', 'glob.glob', (["(self.Storage_Path + self.Radiosonde_Plots_Path + path + '/*')"], {}), "(self.Storage_Path + self.Radiosonde_Plots_Path + path + '/*')\n", (38197, 38259), False, 'import glob\n'), ((40656, 40667), 'time.time', 'time.time', ([], {}), '()\n', (40665, 40667), False, 'import time\n'), ((40710, 40725), 'Data_Importer.EPCC_Importer', 'EPCC_Importer', ([], {}), '()\n', (40723, 40725), False, 'from Data_Importer import EPCC_Importer\n'), ((47178, 47199), 'Gilly_Utilities.argnear', 'gu.argnear', (['Pres', '(500)'], {}), '(Pres, 500)\n', (47188, 47199), True, 'import Gilly_Utilities as gu\n'), ((47210, 47231), 'Gilly_Utilities.argnear', 'gu.argnear', (['Pres', '(700)'], {}), '(Pres, 700)\n', (47220, 47231), True, 'import Gilly_Utilities as gu\n'), ((47242, 47263), 'Gilly_Utilities.argnear', 'gu.argnear', (['Pres', '(850)'], {}), '(Pres, 850)\n', (47252, 47263), True, 'import Gilly_Utilities as gu\n'), ((50111, 50130), 'numpy.zeros', 'np.zeros', (['Tdry.size'], {}), '(Tdry.size)\n', (50119, 50130), True, 'import numpy as np\n'), ((50144, 50163), 'numpy.zeros', 'np.zeros', (['Tdry.size'], {}), '(Tdry.size)\n', (50152, 50163), True, 'import numpy as np\n'), ((51211, 51229), 'numpy.isnan', 'np.isnan', (['Pthetaeq'], {}), '(Pthetaeq)\n', (51219, 51229), True, 'import numpy as np\n'), ((51524, 51534), 'numpy.any', 'np.any', (['y5'], {}), '(y5)\n', (51530, 51534), True, 'import numpy as np\n'), ((53650, 53661), 'time.time', 'time.time', ([], {}), '()\n', (53659, 53661), False, 'import time\n'), ((53784, 53800), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (53793, 53800), True, 'import numpy as np\n'), ((53919, 53939), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (53937, 53939), True, 'import Gilly_Utilities as gu\n'), ((53983, 54119), 'selenium.webdriver.PhantomJS', 'webdriver.PhantomJS', ([], {'executable_path': '"""/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/phantomjs/bin/phantomjs"""'}), "(executable_path=\n '/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/phantomjs/bin/phantomjs'\n )\n", (54002, 54119), False, 'from selenium import webdriver\n'), ((68343, 68354), 'time.time', 'time.time', ([], {}), '()\n', (68352, 68354), False, 'import time\n'), ((68639, 68659), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (68657, 68659), True, 'import Gilly_Utilities as gu\n'), ((68703, 68839), 'selenium.webdriver.PhantomJS', 'webdriver.PhantomJS', ([], {'executable_path': '"""/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/phantomjs/bin/phantomjs"""'}), "(executable_path=\n '/home/users/th863480/PhD/Global_Functions/Prerequisites/modules/phantomjs/bin/phantomjs'\n )\n", (68722, 68839), False, 'from selenium import webdriver\n'), ((85127, 85138), 'time.time', 'time.time', ([], {}), '()\n', (85136, 85138), False, 'import time\n'), ((85322, 85337), 'Data_Importer.EPCC_Importer', 'EPCC_Importer', ([], {}), '()\n', (85335, 85337), False, 'from Data_Importer import EPCC_Importer\n'), ((85363, 85383), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (85381, 85383), True, 'import Gilly_Utilities as gu\n'), ((94793, 94863), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_SpaceCharge_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_SpaceCharge_Liquid, type='ndarray', dtype=np.float64)\n", (94803, 94863), True, 'import Gilly_Utilities as gu\n'), ((94890, 94957), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_SpaceCharge_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_SpaceCharge_Ice, type='ndarray', dtype=np.float64)\n", (94900, 94957), True, 'import Gilly_Utilities as gu\n'), ((94986, 95055), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_SpaceCharge_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_SpaceCharge_Mixed, type='ndarray', dtype=np.float64)\n", (94996, 95055), True, 'import Gilly_Utilities as gu\n'), ((95088, 95161), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_SpaceCharge_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_SpaceCharge_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (95098, 95161), True, 'import Gilly_Utilities as gu\n'), ((95197, 95273), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_SpaceCharge_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_SpaceCharge_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (95207, 95273), True, 'import Gilly_Utilities as gu\n'), ((97606, 97674), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_SpaceCharge_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_SpaceCharge_Liquid, type='ndarray', dtype=np.float64)\n", (97616, 97674), True, 'import Gilly_Utilities as gu\n'), ((97699, 97764), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_SpaceCharge_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_SpaceCharge_Ice, type='ndarray', dtype=np.float64)\n", (97709, 97764), True, 'import Gilly_Utilities as gu\n'), ((97791, 97858), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_SpaceCharge_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_SpaceCharge_Mixed, type='ndarray', dtype=np.float64)\n", (97801, 97858), True, 'import Gilly_Utilities as gu\n'), ((97889, 97960), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_SpaceCharge_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_SpaceCharge_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (97899, 97960), True, 'import Gilly_Utilities as gu\n'), ((97994, 98068), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_SpaceCharge_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_SpaceCharge_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (98004, 98068), True, 'import Gilly_Utilities as gu\n'), ((134289, 134300), 'time.time', 'time.time', ([], {}), '()\n', (134298, 134300), False, 'import time\n'), ((134509, 134524), 'Data_Importer.EPCC_Importer', 'EPCC_Importer', ([], {}), '()\n', (134522, 134524), False, 'from Data_Importer import EPCC_Importer\n'), ((136033, 136090), 'Gilly_Utilities.antifinite', 'gu.antifinite', (['(Field_Mill_PG, Cloud_ElectricField_Total)'], {}), '((Field_Mill_PG, Cloud_ElectricField_Total))\n', (136046, 136090), True, 'import Gilly_Utilities as gu\n'), ((136433, 136453), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (136451, 136453), True, 'import Gilly_Utilities as gu\n'), ((136459, 136470), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (136468, 136470), True, 'import matplotlib.pyplot as plt\n'), ((136473, 136482), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (136480, 136482), True, 'import matplotlib.pyplot as plt\n'), ((136497, 136511), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (136509, 136511), True, 'import matplotlib.pyplot as plt\n'), ((137738, 137805), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (137749, 137805), True, 'import matplotlib.pyplot as plt\n'), ((137937, 137948), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (137946, 137948), True, 'import matplotlib.pyplot as plt\n'), ((137951, 137960), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (137958, 137960), True, 'import matplotlib.pyplot as plt\n'), ((137975, 137989), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (137987, 137989), True, 'import matplotlib.pyplot as plt\n'), ((138816, 138883), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (138827, 138883), True, 'import matplotlib.pyplot as plt\n'), ((139298, 139309), 'time.time', 'time.time', ([], {}), '()\n', (139307, 139309), False, 'import time\n'), ((139617, 139632), 'Data_Importer.EPCC_Importer', 'EPCC_Importer', ([], {}), '()\n', (139630, 139632), False, 'from Data_Importer import EPCC_Importer\n'), ((139922, 139982), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (["Radiosonde_Data['height']", 'Cloud_Heights[0]'], {}), "(Radiosonde_Data['height'], Cloud_Heights[0])\n", (139937, 139982), True, 'import Gilly_Utilities as gu\n'), ((140405, 140440), 'Gilly_Utilities.stats', 'gu.stats', (['Cloud_Charge'], {'output': '(True)'}), '(Cloud_Charge, output=True)\n', (140413, 140440), True, 'import Gilly_Utilities as gu\n'), ((140485, 140585), 'Gilly_Utilities.interavg', 'gu.interavg', (["(Radiosonde_Data['height'][CloudIndex[0]:CloudIndex[1]] * 1000)", 'elem'], {'type': '"""nanmean"""'}), "(Radiosonde_Data['height'][CloudIndex[0]:CloudIndex[1]] * 1000,\n elem, type='nanmean')\n", (140496, 140585), True, 'import Gilly_Utilities as gu\n'), ((140787, 140835), 'numpy.datetime64', 'np.datetime64', (["self.Radiosonde_Data['5']['Date']"], {}), "(self.Radiosonde_Data['5']['Date'])\n", (140800, 140835), True, 'import numpy as np\n'), ((141034, 141125), 'Gilly_Utilities.interavg', 'gu.interavg', (["Radiosonde_Data['time'][CloudIndex[0]:CloudIndex[1]]", 'elem'], {'type': '"""nanmean"""'}), "(Radiosonde_Data['time'][CloudIndex[0]:CloudIndex[1]], elem,\n type='nanmean')\n", (141045, 141125), True, 'import Gilly_Utilities as gu\n'), ((141279, 141305), 'numpy.arange', 'np.arange', (['(-2000)', '(2000)', '(10)'], {}), '(-2000, 2000, 10)\n', (141288, 141305), True, 'import numpy as np\n'), ((142167, 142187), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (142185, 142187), True, 'import Gilly_Utilities as gu\n'), ((142193, 142204), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (142202, 142204), True, 'import matplotlib.pyplot as plt\n'), ((142207, 142216), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (142214, 142216), True, 'import matplotlib.pyplot as plt\n'), ((142231, 142245), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (142243, 142245), True, 'import matplotlib.pyplot as plt\n'), ((142346, 142389), 'Gilly_Utilities.addHourFrac', 'gu.addHourFrac', (['Cloud_Date', 'Field_Mill_Time'], {}), '(Cloud_Date, Field_Mill_Time)\n', (142360, 142389), True, 'import Gilly_Utilities as gu\n'), ((143351, 143361), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (143359, 143361), True, 'import matplotlib.pyplot as plt\n'), ((143366, 143376), 'sys.exit', 'sys.exit', ([], {}), '()\n', (143374, 143376), False, 'import sys\n'), ((143905, 143916), 'time.time', 'time.time', ([], {}), '()\n', (143914, 143916), False, 'import time\n'), ((144102, 144117), 'Data_Importer.EPCC_Importer', 'EPCC_Importer', ([], {}), '()\n', (144115, 144117), False, 'from Data_Importer import EPCC_Importer\n'), ((144143, 144163), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (144161, 144163), True, 'import Gilly_Utilities as gu\n'), ((169037, 169048), 'time.time', 'time.time', ([], {}), '()\n', (169046, 169048), False, 'import time\n'), ((169074, 169094), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (169092, 169094), True, 'import Gilly_Utilities as gu\n'), ((178388, 178495), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running Radiosonde_Ice_Concentration from the DEV release"""'], {'type': '"""bold"""'}), "(\n '[INFO] You are running Radiosonde_Ice_Concentration from the DEV release',\n type='bold')\n", (178397, 178495), True, 'import Gilly_Utilities as gu\n'), ((178836, 178847), 'time.time', 'time.time', ([], {}), '()\n', (178845, 178847), False, 'import time\n'), ((180155, 180246), 'Data_Quality.Radiosonde_Checks_v2', 'Radiosonde_Checks', (['Radiosonde_Data', 'Calibrate', 'Sensor_Package', 'Height_Range'], {'check': '(1111)'}), '(Radiosonde_Data, Calibrate, Sensor_Package, Height_Range,\n check=1111)\n', (180172, 180246), True, 'from Data_Quality import Radiosonde_Checks_v2 as Radiosonde_Checks\n'), ((180936, 181034), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running Radiosonde_Lightning from the STABLE release"""'], {'type': '"""bold"""'}), "('[INFO] You are running Radiosonde_Lightning from the STABLE release'\n , type='bold')\n", (180945, 181034), True, 'import Gilly_Utilities as gu\n'), ((181166, 181177), 'time.time', 'time.time', ([], {}), '()\n', (181175, 181177), False, 'import time\n'), ((181410, 181434), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""classic"""'], {}), "('classic')\n", (181423, 181434), True, 'import matplotlib.pyplot as plt\n'), ((181521, 181536), 'Data_Importer.EPCC_Importer', 'EPCC_Importer', ([], {}), '()\n', (181534, 181536), False, 'from Data_Importer import EPCC_Importer\n'), ((181710, 181721), 'time.time', 'time.time', ([], {}), '()\n', (181719, 181721), False, 'import time\n'), ((183175, 183222), 'Extras.WC3_Extras.Radiosonde_Launch', 'Radiosonde_Launch', (['GPS_File'], {'offset': 'time_offset'}), '(GPS_File, offset=time_offset)\n', (183192, 183222), False, 'from Extras.WC3_Extras import GPS2UTC, CloudDrift, Radiosonde_Launch\n'), ((183624, 183635), 'time.time', 'time.time', ([], {}), '()\n', (183633, 183635), False, 'import time\n'), ((184640, 184651), 'time.time', 'time.time', ([], {}), '()\n', (184649, 184651), False, 'import time\n'), ((184902, 184913), 'time.time', 'time.time', ([], {}), '()\n', (184911, 184913), False, 'import time\n'), ((184992, 185083), 'Gilly_Utilities.bool2int', 'gu.bool2int', (['((ATDnet_Time >= Radiosonde_Time[0]) & (ATDnet_Time <= Radiosonde_Time[-1]))'], {}), '((ATDnet_Time >= Radiosonde_Time[0]) & (ATDnet_Time <=\n Radiosonde_Time[-1]))\n', (185003, 185083), True, 'import Gilly_Utilities as gu\n'), ((185250, 185300), 'Gilly_Utilities.mask', 'gu.mask', (['Radiosonde_Time', 'ATDnet_Time'], {'approx': '(True)'}), '(Radiosonde_Time, ATDnet_Time, approx=True)\n', (185257, 185300), True, 'import Gilly_Utilities as gu\n'), ((185408, 185419), 'time.time', 'time.time', ([], {}), '()\n', (185417, 185419), False, 'import time\n'), ((185884, 185912), 'numpy.isnan', 'np.isnan', (['Lightning_Distance'], {}), '(Lightning_Distance)\n', (185892, 185912), True, 'import numpy as np\n'), ((186781, 186808), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', (['"""nbAgg"""'], {}), "('nbAgg')\n", (186799, 186808), True, 'import Gilly_Utilities as gu\n'), ((186814, 186823), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (186821, 186823), True, 'import matplotlib.pyplot as plt\n'), ((186826, 186837), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (186835, 186837), True, 'import matplotlib.pyplot as plt\n'), ((186881, 187040), 'matplotlib.pyplot.plot', 'plt.plot', (['ATDnet_Time', 'Lightning_Distance', '"""p"""'], {'ms': '(3)', 'marker': '"""o"""', 'markeredgecolor': '"""None"""', 'markerfacecolor': '"""blue"""', 'alpha': '(1)', 'label': '"""Lightning"""', 'zorder': '(4)'}), "(ATDnet_Time, Lightning_Distance, 'p', ms=3, marker='o',\n markeredgecolor='None', markerfacecolor='blue', alpha=1, label=\n 'Lightning', zorder=4)\n", (186889, 187040), True, 'import matplotlib.pyplot as plt\n'), ((187037, 187055), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 100]'], {}), '([0, 100])\n', (187045, 187055), True, 'import matplotlib.pyplot as plt\n'), ((187057, 187113), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'which': '"""major"""', 'axis': '"""both"""', 'c': '"""grey"""', 'zorder': '(2)'}), "(which='major', axis='both', c='grey', zorder=2)\n", (187065, 187113), True, 'import matplotlib.pyplot as plt\n'), ((187229, 187272), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Distance from Radiosonde (km)"""'], {}), "('Distance from Radiosonde (km)')\n", (187239, 187272), True, 'import matplotlib.pyplot as plt\n'), ((187723, 187770), 'matplotlib.pyplot.matplotlib.colors.Normalize', 'plt.matplotlib.colors.Normalize', ([], {'vmin': '(1)', 'vmax': '(9)'}), '(vmin=1, vmax=9)\n', (187754, 187770), True, 'import matplotlib.pyplot as plt\n'), ((187977, 187995), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (187993, 187995), True, 'import matplotlib.pyplot as plt\n'), ((188064, 188107), 'matplotlib.pyplot.cm.ScalarMappable', 'plt.cm.ScalarMappable', ([], {'cmap': 'cmap', 'norm': 'norm'}), '(cmap=cmap, norm=norm)\n', (188085, 188107), True, 'import matplotlib.pyplot as plt\n'), ((188110, 188126), 'statsmodels.api.set_array', 'sm.set_array', (['[]'], {}), '([])\n', (188122, 188126), True, 'import statsmodels.api as sm\n'), ((188134, 188223), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sm'], {'orientation': '"""vertical"""', 'pad': '(0.01)', 'ticks': '[1, 2, 3, 4, 5, 6, 7, 8, 9]'}), "(sm, orientation='vertical', pad=0.01, ticks=[1, 2, 3, 4, 5, 6,\n 7, 8, 9])\n", (188146, 188223), True, 'import matplotlib.pyplot as plt\n'), ((188614, 188674), 'glob.glob', 'glob.glob', (["(Storage_Path + Plots_Path + path + 'Timeseries/*')"], {}), "(Storage_Path + Plots_Path + path + 'Timeseries/*')\n", (188623, 188674), False, 'import glob\n'), ((189310, 189382), 'matplotlib.pyplot.savefig', 'plt.savefig', (['Save_Location'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (189321, 189382), True, 'import matplotlib.pyplot as plt\n'), ((190035, 190055), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (190053, 190055), True, 'import Gilly_Utilities as gu\n'), ((190558, 190570), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (190568, 190570), True, 'import matplotlib.pyplot as plt\n'), ((190610, 190779), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""merc"""', 'lat_0': '(51)', 'lon_0': '(-3)', 'resolution': 'map_res', 'llcrnrlon': 'lonW_Small', 'llcrnrlat': 'latS_Small', 'urcrnrlon': 'lonE_Small', 'urcrnrlat': 'latN_Small', 'ax': 'ax'}), "(projection='merc', lat_0=51, lon_0=-3, resolution=map_res,\n llcrnrlon=lonW_Small, llcrnrlat=latS_Small, urcrnrlon=lonE_Small,\n urcrnrlat=latN_Small, ax=ax)\n", (190617, 190779), False, 'from mpl_toolkits.basemap import Basemap\n'), ((191378, 191465), 'matplotlib.pyplot.title', 'plt.title', (['"""Location of Lightning Strikes and Radiosonde Trajectory (Flight No.5)"""'], {}), "(\n 'Location of Lightning Strikes and Radiosonde Trajectory (Flight No.5)')\n", (191387, 191465), True, 'import matplotlib.pyplot as plt\n'), ((192217, 192304), 'matplotlib.pyplot.matplotlib.colors.Normalize', 'plt.matplotlib.colors.Normalize', ([], {'vmin': 'Radiosonde_Time[0]', 'vmax': 'Radiosonde_Time[-1]'}), '(vmin=Radiosonde_Time[0], vmax=\n Radiosonde_Time[-1])\n', (192248, 192304), True, 'import matplotlib.pyplot as plt\n'), ((192314, 192362), 'matplotlib.pyplot.cm.ScalarMappable', 'plt.cm.ScalarMappable', ([], {'norm': 'norm', 'cmap': '"""rainbow"""'}), "(norm=norm, cmap='rainbow')\n", (192335, 192362), True, 'import matplotlib.pyplot as plt\n'), ((193245, 193297), 'mpl_toolkits.axes_grid1.inset_locator.inset_axes', 'inset_axes', (['map.ax'], {'width': '"""30%"""', 'height': '"""30%"""', 'loc': '(3)'}), "(map.ax, width='30%', height='30%', loc=3)\n", (193255, 193297), False, 'from mpl_toolkits.axes_grid1.inset_locator import inset_axes\n'), ((193378, 193549), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""merc"""', 'lat_0': '(51)', 'lon_0': '(-3)', 'resolution': 'map_res', 'llcrnrlon': 'lonW_Large', 'llcrnrlat': 'latS_Large', 'urcrnrlon': 'lonE_Large', 'urcrnrlat': 'latN_Large', 'ax': 'axin'}), "(projection='merc', lat_0=51, lon_0=-3, resolution=map_res,\n llcrnrlon=lonW_Large, llcrnrlat=latS_Large, urcrnrlon=lonE_Large,\n urcrnrlat=latN_Large, ax=axin)\n", (193385, 193549), False, 'from mpl_toolkits.basemap import Basemap\n'), ((193915, 193968), 'matplotlib.patches.Polygon', 'Polygon', (['xy'], {'edgecolor': '"""red"""', 'linewidth': '(2)', 'fill': '(False)'}), "(xy, edgecolor='red', linewidth=2, fill=False)\n", (193922, 193968), False, 'from matplotlib.patches import Polygon\n'), ((194067, 194110), 'matplotlib.pyplot.cm.ScalarMappable', 'plt.cm.ScalarMappable', ([], {'cmap': 'cmap', 'norm': 'norm'}), '(cmap=cmap, norm=norm)\n', (194088, 194110), True, 'import matplotlib.pyplot as plt\n'), ((194113, 194129), 'statsmodels.api.set_array', 'sm.set_array', (['[]'], {}), '([])\n', (194125, 194129), True, 'import statsmodels.api as sm\n'), ((194140, 194183), 'matplotlib.pyplot.matplotlib.dates.DateFormatter', 'plt.matplotlib.dates.DateFormatter', (['"""%H:%M"""'], {}), "('%H:%M')\n", (194174, 194183), True, 'import matplotlib.pyplot as plt\n'), ((194191, 194294), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sm'], {'orientation': '"""vertical"""', 'pad': '(0.01)', 'label': '"""Time (UTC)"""', 'format': 'myFmt', 'fraction': '(0.04)'}), "(sm, orientation='vertical', pad=0.01, label='Time (UTC)',\n format=myFmt, fraction=0.04)\n", (194203, 194294), True, 'import matplotlib.pyplot as plt\n'), ((194558, 194612), 'glob.glob', 'glob.glob', (["(Storage_Path + Plots_Path + path + '/Map/*')"], {}), "(Storage_Path + Plots_Path + path + '/Map/*')\n", (194567, 194612), False, 'import glob\n'), ((195342, 195414), 'matplotlib.pyplot.savefig', 'plt.savefig', (['Save_Location'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (195353, 195414), True, 'import matplotlib.pyplot as plt\n'), ((195458, 195469), 'time.time', 'time.time', ([], {}), '()\n', (195467, 195469), False, 'import time\n'), ((201657, 201716), 'Gilly_Utilities.fixed_aspect_ratio', 'gu.fixed_aspect_ratio', ([], {'ax': 'subplot', 'ratio': '(1)', 'adjustable': 'None'}), '(ax=subplot, ratio=1, adjustable=None)\n', (201678, 201716), True, 'import Gilly_Utilities as gu\n'), ((208296, 208338), 'numpy.in1d', 'np.in1d', (['arg.Calibrate', "['volts', 'units']"], {}), "(arg.Calibrate, ['volts', 'units'])\n", (208303, 208338), True, 'import numpy as np\n'), ((208519, 208561), 'numpy.in1d', 'np.in1d', (['arg.Calibrate', "['volts', 'units']"], {}), "(arg.Calibrate, ['volts', 'units'])\n", (208526, 208561), True, 'import numpy as np\n'), ((3101, 3170), 'sys.exit', 'sys.exit', (['"""[Error] You must specify either the sensor_package number"""'], {}), "('[Error] You must specify either the sensor_package number')\n", (3109, 3170), False, 'import sys\n'), ((3198, 3265), 'sys.exit', 'sys.exit', (['"""[Error] You must specify either the height_range number"""'], {}), "('[Error] You must specify either the height_range number')\n", (3206, 3265), False, 'import sys\n'), ((4773, 4809), 'numpy.datetime64', 'np.datetime64', (['"""2018-03-02 15:43:00"""'], {}), "('2018-03-02 15:43:00')\n", (4786, 4809), True, 'import numpy as np\n'), ((4817, 4853), 'numpy.datetime64', 'np.datetime64', (['"""2018-03-02 17:16:00"""'], {}), "('2018-03-02 17:16:00')\n", (4830, 4853), True, 'import numpy as np\n'), ((4861, 4897), 'numpy.datetime64', 'np.datetime64', (['"""2018-05-24 15:10:00"""'], {}), "('2018-05-24 15:10:00')\n", (4874, 4897), True, 'import numpy as np\n'), ((4905, 4941), 'numpy.datetime64', 'np.datetime64', (['"""2018-05-31 15:38:30"""'], {}), "('2018-05-31 15:38:30')\n", (4918, 4941), True, 'import numpy as np\n'), ((4990, 5026), 'numpy.datetime64', 'np.datetime64', (['"""2018-07-27 15:39:00"""'], {}), "('2018-07-27 15:39:00')\n", (5003, 5026), True, 'import numpy as np\n'), ((5034, 5070), 'numpy.datetime64', 'np.datetime64', (['"""2019-01-29 17:20:16"""'], {}), "('2019-01-29 17:20:16')\n", (5047, 5070), True, 'import numpy as np\n'), ((5078, 5098), 'numpy.datetime64', 'np.datetime64', (['"""NaT"""'], {}), "('NaT')\n", (5091, 5098), True, 'import numpy as np\n'), ((5125, 5145), 'numpy.datetime64', 'np.datetime64', (['"""NaT"""'], {}), "('NaT')\n", (5138, 5145), True, 'import numpy as np\n'), ((5172, 5208), 'numpy.datetime64', 'np.datetime64', (['"""2018-12-05 16:12:00"""'], {}), "('2018-12-05 16:12:00')\n", (5185, 5208), True, 'import numpy as np\n'), ((5217, 5253), 'numpy.datetime64', 'np.datetime64', (['"""2018-12-05 09:22:30"""'], {}), "('2018-12-05 09:22:30')\n", (5230, 5253), True, 'import numpy as np\n'), ((6145, 6214), 'sys.exit', 'sys.exit', (['"""[Error] You must specify either the Sensor_Package number"""'], {}), "('[Error] You must specify either the Sensor_Package number')\n", (6153, 6214), False, 'import sys\n'), ((17891, 17983), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running CloudIdentifier from the STABLE release"""'], {'type': '"""bold"""'}), "('[INFO] You are running CloudIdentifier from the STABLE release',\n type='bold')\n", (17900, 17983), True, 'import Gilly_Utilities as gu\n'), ((18849, 18912), 'Gilly_Utilities.cloud_identifer_ascent', 'gu.cloud_identifer_ascent', (['Z', 'RH'], {'method': '"""Zhang"""', 'verbose': '(False)'}), "(Z, RH, method='Zhang', verbose=False)\n", (18874, 18912), True, 'import Gilly_Utilities as gu\n'), ((19128, 19234), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running Radiosonde_ChargeCalibrator from the DEV release"""'], {'type': '"""bold"""'}), "(\n '[INFO] You are running Radiosonde_ChargeCalibrator from the DEV release',\n type='bold')\n", (19137, 19234), True, 'import Gilly_Utilities as gu\n'), ((20252, 20278), 'numpy.log10', 'np.log10', (['(-Linear[NegMask])'], {}), '(-Linear[NegMask])\n', (20260, 20278), True, 'import numpy as np\n'), ((20623, 20661), 'scipy.stats.linregress', 'sp.stats.linregress', (['LogNeg', 'LinearNeg'], {}), '(LogNeg, LinearNeg)\n', (20642, 20661), True, 'import scipy as sp\n'), ((24935, 24965), 'os.path.dirname', 'os.path.dirname', (['Save_Location'], {}), '(Save_Location)\n', (24950, 24965), False, 'import os\n'), ((26545, 26589), 'Gilly_Utilities.argcontiguous', 'gu.argcontiguous', (['LayerType[sensor]'], {'valid': '(0)'}), '(LayerType[sensor], valid=0)\n', (26561, 26589), True, 'import Gilly_Utilities as gu\n'), ((30840, 30876), 'Gilly_Utilities.broadcast', 'gu.broadcast', (['Cloud_SignChange', '(2)', '(1)'], {}), '(Cloud_SignChange, 2, 1)\n', (30852, 30876), True, 'import Gilly_Utilities as gu\n'), ((32626, 32727), 'numpy.array', 'np.array', (['[(Height[space[1]] - Height[space[0]]) for space in Cloud_SignChange]'], {'dtype': 'np.float64'}), '([(Height[space[1]] - Height[space[0]]) for space in\n Cloud_SignChange], dtype=np.float64)\n', (32634, 32727), True, 'import numpy as np\n'), ((34176, 34211), 'numpy.zeros', 'np.zeros', (['Cloud_SignChange.shape[0]'], {}), '(Cloud_SignChange.shape[0])\n', (34184, 34211), True, 'import numpy as np\n'), ((34728, 34766), 'numpy.nansum', 'np.nansum', (['Cloud_ElectricField'], {'axis': '(0)'}), '(Cloud_ElectricField, axis=0)\n', (34737, 34766), True, 'import numpy as np\n'), ((35500, 35587), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running Superplotter from the DEV release"""'], {'type': '"""bold"""'}), "('[INFO] You are running Superplotter from the DEV release', type=\n 'bold')\n", (35509, 35587), True, 'import Gilly_Utilities as gu\n'), ((38955, 38985), 'os.path.dirname', 'os.path.dirname', (['Save_Location'], {}), '(Save_Location)\n', (38970, 38985), False, 'import os\n'), ((40424, 40522), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running Radiosonde_Tephigram from the STABLE release"""'], {'type': '"""bold"""'}), "('[INFO] You are running Radiosonde_Tephigram from the STABLE release'\n , type='bold')\n", (40433, 40522), True, 'import Gilly_Utilities as gu\n'), ((41316, 41326), 'numpy.max', 'np.max', (['RH'], {}), '(RH)\n', (41322, 41326), True, 'import numpy as np\n'), ((42518, 42531), 'Extras.Tephigram.Tephigram', 'SPTephigram', ([], {}), '()\n', (42529, 42531), True, 'from Extras.Tephigram import Tephigram as SPTephigram\n'), ((46059, 46129), 'glob.glob', 'glob.glob', (["(self.Storage_Path + self.Tephigram_Plots_Path + path + '/*')"], {}), "(self.Storage_Path + self.Tephigram_Plots_Path + path + '/*')\n", (46068, 46129), False, 'import glob\n'), ((51312, 51389), 'scipy.interpolate.interp1d', 'sp.interpolate.interp1d', (['Pthetaeq', '[thetaarr, Tarr]'], {'fill_value': '"""extrapolate"""'}), "(Pthetaeq, [thetaarr, Tarr], fill_value='extrapolate')\n", (51335, 51389), True, 'import scipy as sp\n'), ((51461, 51481), 'numpy.arange', 'np.arange', (['Tdry.size'], {}), '(Tdry.size)\n', (51470, 51481), True, 'import numpy as np\n'), ((53429, 53539), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running CaseStudy_Overview from the \t\t\t\t\t\tDEV release"""'], {'type': '"""bold"""'}), "(\n '[INFO] You are running CaseStudy_Overview from the \\t\\t\\t\\t\\t\\tDEV release'\n , type='bold')\n", (53438, 53539), True, 'import Gilly_Utilities as gu\n'), ((54251, 54276), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (54274, 54276), False, 'import warnings\n'), ((54281, 54312), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (54302, 54312), False, 'import warnings\n'), ((54953, 55002), 'numpy.in1d', 'np.in1d', (['Sensor_Package_TimeOrder', 'Sensor_Package'], {}), '(Sensor_Package_TimeOrder, Sensor_Package)\n', (54960, 55002), True, 'import numpy as np\n'), ((56329, 56338), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (56336, 56338), True, 'import matplotlib.pyplot as plt\n'), ((56342, 56353), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (56351, 56353), True, 'import matplotlib.pyplot as plt\n'), ((56369, 56387), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(2)'], {}), '(5, 2)\n', (56381, 56387), True, 'import matplotlib.pyplot as plt\n'), ((57949, 57967), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (57965, 57967), True, 'import matplotlib.pyplot as plt\n'), ((58598, 58720), 'Gilly_Utilities.ensure_dir', 'gu.ensure_dir', (["(self.Storage_Path +\n 'Plots/CaseStudy/Overview/PG_Timeseries_AllRadiosondes.png')"], {'dir_or_file': '"""file"""'}), "(self.Storage_Path +\n 'Plots/CaseStudy/Overview/PG_Timeseries_AllRadiosondes.png',\n dir_or_file='file')\n", (58611, 58720), True, 'import Gilly_Utilities as gu\n'), ((58716, 58783), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (58727, 58783), True, 'import matplotlib.pyplot as plt\n'), ((61102, 61171), 'numpy.full', 'np.full', (['Sensor_Package_TimeOrder.size'], {'fill_value': 'None', 'dtype': 'object'}), '(Sensor_Package_TimeOrder.size, fill_value=None, dtype=object)\n', (61109, 61171), True, 'import numpy as np\n'), ((61194, 61263), 'numpy.full', 'np.full', (['Sensor_Package_TimeOrder.size'], {'fill_value': 'None', 'dtype': 'object'}), '(Sensor_Package_TimeOrder.size, fill_value=None, dtype=object)\n', (61201, 61263), True, 'import numpy as np\n'), ((63555, 63575), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (63573, 63575), True, 'import Gilly_Utilities as gu\n'), ((63609, 63627), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(2)'], {}), '(5, 2)\n', (63621, 63627), True, 'import matplotlib.pyplot as plt\n'), ((67556, 67687), 'Gilly_Utilities.ensure_dir', 'gu.ensure_dir', (["(self.Storage_Path +\n 'Plots/CaseStudy/Overview/SatelliteImagery_AVHRR_AllRadiosondes.png')"], {'dir_or_file': '"""file"""'}), "(self.Storage_Path +\n 'Plots/CaseStudy/Overview/SatelliteImagery_AVHRR_AllRadiosondes.png',\n dir_or_file='file')\n", (67569, 67687), True, 'import Gilly_Utilities as gu\n'), ((67683, 67750), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (67694, 67750), True, 'import matplotlib.pyplot as plt\n'), ((68120, 68212), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running CaseStudy_Specific from the DEV release"""'], {'type': '"""bold"""'}), "('[INFO] You are running CaseStudy_Specific from the DEV release',\n type='bold')\n", (68129, 68212), True, 'import Gilly_Utilities as gu\n'), ((68971, 68996), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (68994, 68996), False, 'import warnings\n'), ((69001, 69032), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (69022, 69032), False, 'import warnings\n'), ((83101, 83147), 'numpy.unique', 'np.unique', (['self.Clouds_ID[self.sensor_package]'], {}), '(self.Clouds_ID[self.sensor_package])\n', (83110, 83147), True, 'import numpy as np\n'), ((83342, 83364), 'numpy.all', 'np.all', (['(Cloud_Tdry > 0)'], {}), '(Cloud_Tdry > 0)\n', (83348, 83364), True, 'import numpy as np\n'), ((84913, 85011), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running Hypothesis1 from the DEV \t\t\t\t\t\trelease"""'], {'type': '"""bold"""'}), "('[INFO] You are running Hypothesis1 from the DEV \\t\\t\\t\\t\\t\\trelease'\n , type='bold')\n", (84922, 85011), True, 'import Gilly_Utilities as gu\n'), ((131358, 131369), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (131367, 131369), True, 'import matplotlib.pyplot as plt\n'), ((131373, 131382), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (131380, 131382), True, 'import matplotlib.pyplot as plt\n'), ((131398, 131443), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(2)'], {'sharex': '(False)', 'sharey': '(True)'}), '(3, 2, sharex=False, sharey=True)\n', (131410, 131443), True, 'import matplotlib.pyplot as plt\n'), ((133738, 133805), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (133749, 133805), True, 'import matplotlib.pyplot as plt\n'), ((134070, 134156), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running PointCharge from the DEV release"""'], {'type': '"""bold"""'}), "('[INFO] You are running PointCharge from the DEV release', type=\n 'bold')\n", (134079, 134156), True, 'import Gilly_Utilities as gu\n'), ((136139, 136154), 'Gilly_Utilities.R1to1', 'gu.R1to1', (['*Test'], {}), '(*Test)\n', (136147, 136154), True, 'import Gilly_Utilities as gu\n'), ((136236, 136260), 'scipy.stats.pearsonr', 'sp.stats.pearsonr', (['*Test'], {}), '(*Test)\n', (136253, 136260), True, 'import scipy as sp\n'), ((136270, 136295), 'scipy.stats.spearmanr', 'sp.stats.spearmanr', (['*Test'], {}), '(*Test)\n', (136288, 136295), True, 'import scipy as sp\n'), ((136923, 136945), 'numpy.min', 'np.min', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (136929, 136945), True, 'import numpy as np\n'), ((136947, 136969), 'numpy.max', 'np.max', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (136953, 136969), True, 'import numpy as np\n'), ((136986, 137008), 'numpy.min', 'np.min', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (136992, 137008), True, 'import numpy as np\n'), ((137010, 137032), 'numpy.max', 'np.max', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (137016, 137032), True, 'import numpy as np\n'), ((137361, 137383), 'matplotlib.dates.DateFormatter', 'DateFormatter', (['"""%H:%M"""'], {}), "('%H:%M')\n", (137374, 137383), False, 'from matplotlib.dates import DateFormatter, MinuteLocator, HourLocator, DayLocator\n'), ((138314, 138336), 'numpy.min', 'np.min', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (138320, 138336), True, 'import numpy as np\n'), ((138338, 138360), 'numpy.max', 'np.max', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (138344, 138360), True, 'import numpy as np\n'), ((138380, 138410), 'numpy.nanmin', 'np.nanmin', (['Cloud_ElectricField'], {}), '(Cloud_ElectricField)\n', (138389, 138410), True, 'import numpy as np\n'), ((138412, 138442), 'numpy.nanmax', 'np.nanmax', (['Cloud_ElectricField'], {}), '(Cloud_ElectricField)\n', (138421, 138442), True, 'import numpy as np\n'), ((138476, 138498), 'matplotlib.dates.DateFormatter', 'DateFormatter', (['"""%H:%M"""'], {}), "('%H:%M')\n", (138489, 138498), False, 'from matplotlib.dates import DateFormatter, MinuteLocator, HourLocator, DayLocator\n'), ((139080, 139166), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running PointCharge from the DEV release"""'], {'type': '"""bold"""'}), "('[INFO] You are running PointCharge from the DEV release', type=\n 'bold')\n", (139089, 139166), True, 'import Gilly_Utilities as gu\n'), ((140135, 140202), 'numpy.diff', 'np.diff', (["Radiosonde_Data['height'][CloudIndex[0]:CloudIndex[1] + 1]"], {}), "(Radiosonde_Data['height'][CloudIndex[0]:CloudIndex[1] + 1])\n", (140142, 140202), True, 'import numpy as np\n'), ((140288, 140346), 'Gilly_Utilities.interavg', 'gu.interavg', (['Cloud_SpaceChargeDensity', 'elem'], {'type': '"""nansum"""'}), "(Cloud_SpaceChargeDensity, elem, type='nansum')\n", (140299, 140346), True, 'import Gilly_Utilities as gu\n'), ((140349, 140399), 'Gilly_Utilities.interavg', 'gu.interavg', (['Cloud_AscentArea', 'elem'], {'type': '"""nansum"""'}), "(Cloud_AscentArea, elem, type='nansum')\n", (140360, 140399), True, 'import Gilly_Utilities as gu\n'), ((141630, 141668), 'numpy.nansum', 'np.nansum', (['Cloud_ElectricField'], {'axis': '(0)'}), '(Cloud_ElectricField, axis=0)\n', (141639, 141668), True, 'import numpy as np\n'), ((142709, 142731), 'numpy.min', 'np.min', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (142715, 142731), True, 'import numpy as np\n'), ((142733, 142755), 'numpy.max', 'np.max', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (142739, 142755), True, 'import numpy as np\n'), ((142772, 142794), 'numpy.min', 'np.min', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (142778, 142794), True, 'import numpy as np\n'), ((142796, 142818), 'numpy.max', 'np.max', (['Cloud_DateTime'], {}), '(Cloud_DateTime)\n', (142802, 142818), True, 'import numpy as np\n'), ((143149, 143171), 'matplotlib.dates.DateFormatter', 'DateFormatter', (['"""%H:%M"""'], {}), "('%H:%M')\n", (143162, 143171), False, 'from matplotlib.dates import DateFormatter, MinuteLocator, HourLocator, DayLocator\n'), ((143689, 143775), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running PointCharge from the DEV release"""'], {'type': '"""bold"""'}), "('[INFO] You are running PointCharge from the DEV release', type=\n 'bold')\n", (143698, 143775), True, 'import Gilly_Utilities as gu\n'), ((144451, 144461), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (144459, 144461), True, 'import Gilly_Utilities as gu\n'), ((144476, 144486), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (144484, 144486), True, 'import Gilly_Utilities as gu\n'), ((144503, 144513), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (144511, 144513), True, 'import Gilly_Utilities as gu\n'), ((144536, 144546), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (144544, 144546), True, 'import Gilly_Utilities as gu\n'), ((144568, 144578), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (144576, 144578), True, 'import Gilly_Utilities as gu\n'), ((144650, 144681), 'numpy.array', 'np.array', (["['3', '4', '9', '10']"], {}), "(['3', '4', '9', '10'])\n", (144658, 144681), True, 'import numpy as np\n'), ((147274, 147387), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IR', '(15)'], {'method': '"""unique"""', 'average': '"""mean"""', 'undersample': '(False)', 'slim': '(False)'}), "(Cloud_SpaceCharge, Cloud_IR, 15, method='unique', average=\n 'mean', undersample=False, slim=False)\n", (147285, 147387), True, 'import Gilly_Utilities as gu\n'), ((147418, 147525), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IR', '(15)'], {'method': '"""ma"""', 'average': '"""mean"""', 'undersample': '(True)', 'slim': '(False)'}), "(Cloud_SpaceCharge, Cloud_IR, 15, method='ma', average='mean',\n undersample=True, slim=False)\n", (147429, 147525), True, 'import Gilly_Utilities as gu\n'), ((147529, 147549), 'Gilly_Utilities.backend_changer', 'gu.backend_changer', ([], {}), '()\n', (147547, 147549), True, 'import Gilly_Utilities as gu\n'), ((147561, 147575), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (147573, 147575), True, 'import matplotlib.pyplot as plt\n'), ((148163, 148268), 'scipy.stats.linregress', 'sp.stats.linregress', (['Cloud_SpaceCharge_Ensemble_Unique[:, 0]', 'Cloud_SpaceCharge_Ensemble_Unique[:, 1]'], {}), '(Cloud_SpaceCharge_Ensemble_Unique[:, 0],\n Cloud_SpaceCharge_Ensemble_Unique[:, 1])\n', (148182, 148268), True, 'import scipy as sp\n'), ((148932, 148942), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (148940, 148942), True, 'import matplotlib.pyplot as plt\n'), ((148950, 148960), 'sys.exit', 'sys.exit', ([], {}), '()\n', (148958, 148960), False, 'import sys\n'), ((149983, 150083), 'Data_Output.SPEnsemble', 'SPEnsemble', (['Cloud_SpaceCharge', 'Cloud_IR', 'Cloud_SpaceCharge_Ensemble', 'filename'], {}), '(Cloud_SpaceCharge, Cloud_IR, Cloud_SpaceCharge_Ensemble,\n filename, **Ensemble_Kwargs)\n', (149993, 150083), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((150086, 150096), 'sys.exit', 'sys.exit', ([], {}), '()\n', (150094, 150096), False, 'import sys\n'), ((154065, 154122), 'Gilly_Utilities.HuberRegression', 'gu.HuberRegression', (['Cloud_SpaceCharge_Best', 'Cloud_IR_Best'], {}), '(Cloud_SpaceCharge_Best, Cloud_IR_Best)\n', (154083, 154122), True, 'import Gilly_Utilities as gu\n'), ((154422, 154432), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (154430, 154432), True, 'import Gilly_Utilities as gu\n'), ((154456, 154466), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (154464, 154466), True, 'import Gilly_Utilities as gu\n'), ((154483, 154493), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (154491, 154493), True, 'import Gilly_Utilities as gu\n'), ((157350, 157447), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_SLWC', '(50)'], {'method': '"""unique"""', 'undersample': '(True)', 'slim': '(True)'}), "(Cloud_SpaceCharge, Cloud_SLWC, 50, method='unique', undersample\n =True, slim=True)\n", (157361, 157447), True, 'import Gilly_Utilities as gu\n'), ((157605, 157913), 'Data_Output.CrossCorrelation_Scatter_Plot', 'CrossCorrelation_Scatter_Plot', (['Cloud_SpaceCharge2', 'Cloud_SLWC'], {'filename': 'filename', 'xlabel': '"""Space Charge (nC m$^{-3}$)"""', 'ylabel': '"""Liquid Water Sensor (g m$^{-1}$)"""', 'title': '"""Cross Correlation (Radiosonde No.3,4,5)"""', 'xlim': '"""auto"""', 'ylim': "[0, 'auto']", 'xscale': '"""linear"""', 'yscale': '"""linear"""', 'verbose': '(True)'}), "(Cloud_SpaceCharge2, Cloud_SLWC, filename=\n filename, xlabel='Space Charge (nC m$^{-3}$)', ylabel=\n 'Liquid Water Sensor (g m$^{-1}$)', title=\n 'Cross Correlation (Radiosonde No.3,4,5)', xlim='auto', ylim=[0, 'auto'\n ], xscale='linear', yscale='linear', verbose=True)\n", (157634, 157913), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((157950, 157983), 'Gilly_Utilities.stats', 'gu.stats', (['Cloud_Tdry'], {'output': '(True)'}), '(Cloud_Tdry, output=True)\n', (157958, 157983), True, 'import Gilly_Utilities as gu\n'), ((158276, 158553), 'Data_Output.CrossCorrelation_Scatter_Plot', 'CrossCorrelation_Scatter_Plot', (['Cloud_Tdry', 'Cloud_SLWC'], {'filename': 'filename', 'xlabel': '"""Temperature (C)"""', 'ylabel': '"""Liquid Water Sensor (g m$^{-1}$)"""', 'title': '"""Cross Correlation (Radiosonde No.3,4,5)"""', 'xlim': '"""auto"""', 'ylim': '"""auto"""', 'xscale': '"""linear"""', 'yscale': '"""linear"""', 'verbose': '(True)'}), "(Cloud_Tdry, Cloud_SLWC, filename=filename,\n xlabel='Temperature (C)', ylabel='Liquid Water Sensor (g m$^{-1}$)',\n title='Cross Correlation (Radiosonde No.3,4,5)', xlim='auto', ylim=\n 'auto', xscale='linear', yscale='linear', verbose=True)\n", (158305, 158553), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((158848, 158858), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (158856, 158858), True, 'import Gilly_Utilities as gu\n'), ((158886, 158896), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (158894, 158896), True, 'import Gilly_Utilities as gu\n'), ((158921, 158931), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (158929, 158931), True, 'import Gilly_Utilities as gu\n'), ((158957, 158967), 'Gilly_Utilities.array', 'gu.array', ([], {}), '()\n', (158965, 158967), True, 'import Gilly_Utilities as gu\n'), ((162803, 162867), 'scipy.stats.linregress', 'sp.stats.linregress', (['Cloud_SignChange_All', 'Cloud_SpaceCharge_All'], {}), '(Cloud_SignChange_All, Cloud_SpaceCharge_All)\n', (162822, 162867), True, 'import scipy as sp\n'), ((162880, 162940), 'scipy.stats.linregress', 'sp.stats.linregress', (['Air_SignChange_All', 'Air_SpaceCharge_All'], {}), '(Air_SignChange_All, Air_SpaceCharge_All)\n', (162899, 162940), True, 'import scipy as sp\n'), ((163549, 163558), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (163556, 163558), True, 'import matplotlib.pyplot as plt\n'), ((163562, 163573), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (163571, 163573), True, 'import matplotlib.pyplot as plt\n'), ((163585, 163603), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {}), '(1, 2)\n', (163597, 163603), True, 'import matplotlib.pyplot as plt\n'), ((164435, 164488), 'numpy.hstack', 'np.hstack', (['(Cloud_SignChange_All, Air_SignChange_All)'], {}), '((Cloud_SignChange_All, Air_SignChange_All))\n', (164444, 164488), True, 'import numpy as np\n'), ((164504, 164559), 'numpy.hstack', 'np.hstack', (['(Cloud_SpaceCharge_All, Air_SpaceCharge_All)'], {}), '((Cloud_SpaceCharge_All, Air_SpaceCharge_All))\n', (164513, 164559), True, 'import numpy as np\n'), ((164949, 165025), 'scipy.stats.linregress', 'sp.stats.linregress', (['Cloud_SignChange_All[mask]', 'Cloud_SpaceCharge_All[mask]'], {}), '(Cloud_SignChange_All[mask], Cloud_SpaceCharge_All[mask])\n', (164968, 165025), True, 'import scipy as sp\n'), ((165114, 165186), 'scipy.stats.linregress', 'sp.stats.linregress', (['Air_SignChange_All[mask]', 'Air_SpaceCharge_All[mask]'], {}), '(Air_SignChange_All[mask], Air_SpaceCharge_All[mask])\n', (165133, 165186), True, 'import scipy as sp\n'), ((166904, 166938), 'Gilly_Utilities.hide_axis', 'gu.hide_axis', ([], {'ax': 'ax[1]', 'x_or_y': '"""y"""'}), "(ax=ax[1], x_or_y='y')\n", (166916, 166938), True, 'import Gilly_Utilities as gu\n'), ((167230, 167297), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (167241, 167297), True, 'import matplotlib.pyplot as plt\n'), ((168816, 168904), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[INFO] You are running RH_Comparison from the DEV release"""'], {'type': '"""bold"""'}), "('[INFO] You are running RH_Comparison from the DEV release', type\n ='bold')\n", (168825, 168904), True, 'import Gilly_Utilities as gu\n'), ((171611, 171635), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""classic"""'], {}), "('classic')\n", (171624, 171635), True, 'import matplotlib.pyplot as plt\n'), ((171737, 171746), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (171744, 171746), True, 'import matplotlib.pyplot as plt\n'), ((171750, 171761), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (171759, 171761), True, 'import matplotlib.pyplot as plt\n'), ((171823, 171837), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (171835, 171837), True, 'import matplotlib.pyplot as plt\n'), ((173808, 173875), 'glob.glob', 'glob.glob', (["(self.Storage_Path + 'Plots/RH_Comparison/' + path + '/*')"], {}), "(self.Storage_Path + 'Plots/RH_Comparison/' + path + '/*')\n", (173817, 173875), False, 'import glob\n'), ((174615, 174687), 'matplotlib.pyplot.savefig', 'plt.savefig', (['Save_Location'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(Save_Location, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (174626, 174687), True, 'import matplotlib.pyplot as plt\n'), ((179109, 179220), 'sys.exit', 'sys.exit', (['"""[Error] You must specify either the Radiosonde_File location or the Sensor_Package number"""'], {}), "(\n '[Error] You must specify either the Radiosonde_File location or the Sensor_Package number'\n )\n", (179117, 179220), False, 'import sys\n'), ((179655, 179811), 'sys.exit', 'sys.exit', (["('[Error] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?'\n % Sensor_Package)"], {}), "(\n '[Error] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?'\n % Sensor_Package)\n", (179663, 179811), False, 'import sys\n'), ((180043, 180136), 'numpy.genfromtxt', 'np.genfromtxt', (['Radiosonde_File'], {'delimiter': 'None', 'skip_header': '(10)', 'dtype': 'float', 'comments': '"""#"""'}), "(Radiosonde_File, delimiter=None, skip_header=10, dtype=float,\n comments='#')\n", (180056, 180136), True, 'import numpy as np\n'), ((181862, 181973), 'sys.exit', 'sys.exit', (['"""[Error] You must specify either the Radiosonde_File location or the Sensor_Package number"""'], {}), "(\n '[Error] You must specify either the Radiosonde_File location or the Sensor_Package number'\n )\n", (181870, 181973), False, 'import sys\n'), ((182408, 182564), 'sys.exit', 'sys.exit', (["('[Error] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?'\n % Sensor_Package)"], {}), "(\n '[Error] Radiosonde package No.%s does not exist. Has the radiosonde been launched yet or has the data been misplaced?'\n % Sensor_Package)\n", (182416, 182564), False, 'import sys\n'), ((183036, 183129), 'numpy.genfromtxt', 'np.genfromtxt', (['Radiosonde_File'], {'delimiter': 'None', 'skip_header': '(10)', 'dtype': 'float', 'comments': '"""#"""'}), "(Radiosonde_File, delimiter=None, skip_header=10, dtype=float,\n comments='#')\n", (183049, 183129), True, 'import numpy as np\n'), ((184733, 184781), 'numpy.array', 'np.array', (['Launch_Datetime'], {'dtype': '"""datetime64[s]"""'}), "(Launch_Datetime, dtype='datetime64[s]')\n", (184741, 184781), True, 'import numpy as np\n'), ((186175, 186212), 'numpy.isnan', 'np.isnan', (['Radiosonde_Data_Error[:, 5]'], {}), '(Radiosonde_Data_Error[:, 5])\n', (186183, 186212), True, 'import numpy as np\n'), ((186434, 186482), 'numpy.array', 'np.array', (['Launch_Datetime'], {'dtype': '"""datetime64[s]"""'}), "(Launch_Datetime, dtype='datetime64[s]')\n", (186442, 186482), True, 'import numpy as np\n'), ((187157, 187166), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (187164, 187166), True, 'import matplotlib.pyplot as plt\n'), ((189276, 189306), 'os.path.dirname', 'os.path.dirname', (['Save_Location'], {}), '(Save_Location)\n', (189291, 189306), False, 'import os\n'), ((191195, 191215), 'numpy.arange', 'np.arange', (['(-15)', '(5)', '(1)'], {}), '(-15, 5, 1)\n', (191204, 191215), True, 'import numpy as np\n'), ((191295, 191316), 'numpy.arange', 'np.arange', (['(-50)', '(70)', '(1)'], {}), '(-50, 70, 1)\n', (191304, 191316), True, 'import numpy as np\n'), ((192857, 192874), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (192866, 192874), True, 'import numpy as np\n'), ((195308, 195338), 'os.path.dirname', 'os.path.dirname', (['Save_Location'], {}), '(Save_Location)\n', (195323, 195338), False, 'import os\n'), ((196632, 197456), 'pandas.read_csv', 'pd.read_csv', (['Linear_File'], {'sep': '""","""', 'header': 'None', 'engine': '"""python"""', 'names': "('Current_Sensor1', 'Current_Sensor2', 'Current_Sensor3+',\n 'Voltage_Sensor1', 'Voltage_Sensor2', 'Voltage_Sensor3',\n 'Voltage_Sensor4', 'Voltage_Sensor5', 'Voltage_Sensor6',\n 'Voltage_Sensor7', 'Voltage_Sensor8', 'Voltage_Sensor9', 'Voltage_Sensor10'\n )", 'dtype': "{'Current_Sensor1': np.float64, 'Current_Sensor2': np.float64,\n 'Current_Sensor3+': np.float64, 'Voltage_Sensor1': np.float64,\n 'Voltage_Sensor2': np.float64, 'Voltage_Sensor3': np.float64,\n 'Voltage_Sensor4': np.float64, 'Voltage_Sensor5': np.float64,\n 'Voltage_Sensor6': np.float64, 'Voltage_Sensor7': np.float64,\n 'Voltage_Sensor8': np.float64, 'Voltage_Sensor9': np.float64,\n 'Voltage_Sensor10': np.float64}", 'skiprows': '(2)', 'comment': '"""#"""', 'index_col': '(False)'}), "(Linear_File, sep=',', header=None, engine='python', names=(\n 'Current_Sensor1', 'Current_Sensor2', 'Current_Sensor3+',\n 'Voltage_Sensor1', 'Voltage_Sensor2', 'Voltage_Sensor3',\n 'Voltage_Sensor4', 'Voltage_Sensor5', 'Voltage_Sensor6',\n 'Voltage_Sensor7', 'Voltage_Sensor8', 'Voltage_Sensor9',\n 'Voltage_Sensor10'), dtype={'Current_Sensor1': np.float64,\n 'Current_Sensor2': np.float64, 'Current_Sensor3+': np.float64,\n 'Voltage_Sensor1': np.float64, 'Voltage_Sensor2': np.float64,\n 'Voltage_Sensor3': np.float64, 'Voltage_Sensor4': np.float64,\n 'Voltage_Sensor5': np.float64, 'Voltage_Sensor6': np.float64,\n 'Voltage_Sensor7': np.float64, 'Voltage_Sensor8': np.float64,\n 'Voltage_Sensor9': np.float64, 'Voltage_Sensor10': np.float64},\n skiprows=2, comment='#', index_col=False)\n", (196643, 197456), True, 'import pandas as pd\n'), ((197538, 198359), 'pandas.read_csv', 'pd.read_csv', (['Log_File'], {'sep': '""","""', 'header': 'None', 'engine': '"""python"""', 'names': "('Current_Sensor1', 'Current_Sensor2', 'Current_Sensor3+',\n 'Voltage_Sensor1', 'Voltage_Sensor2', 'Voltage_Sensor3',\n 'Voltage_Sensor4', 'Voltage_Sensor5', 'Voltage_Sensor6',\n 'Voltage_Sensor7', 'Voltage_Sensor8', 'Voltage_Sensor9', 'Voltage_Sensor10'\n )", 'dtype': "{'Current_Sensor1': np.float64, 'Current_Sensor2': np.float64,\n 'Current_Sensor3+': np.float64, 'Voltage_Sensor1': np.float64,\n 'Voltage_Sensor2': np.float64, 'Voltage_Sensor3': np.float64,\n 'Voltage_Sensor4': np.float64, 'Voltage_Sensor5': np.float64,\n 'Voltage_Sensor6': np.float64, 'Voltage_Sensor7': np.float64,\n 'Voltage_Sensor8': np.float64, 'Voltage_Sensor9': np.float64,\n 'Voltage_Sensor10': np.float64}", 'skiprows': '(2)', 'comment': '"""#"""', 'index_col': '(False)'}), "(Log_File, sep=',', header=None, engine='python', names=(\n 'Current_Sensor1', 'Current_Sensor2', 'Current_Sensor3+',\n 'Voltage_Sensor1', 'Voltage_Sensor2', 'Voltage_Sensor3',\n 'Voltage_Sensor4', 'Voltage_Sensor5', 'Voltage_Sensor6',\n 'Voltage_Sensor7', 'Voltage_Sensor8', 'Voltage_Sensor9',\n 'Voltage_Sensor10'), dtype={'Current_Sensor1': np.float64,\n 'Current_Sensor2': np.float64, 'Current_Sensor3+': np.float64,\n 'Voltage_Sensor1': np.float64, 'Voltage_Sensor2': np.float64,\n 'Voltage_Sensor3': np.float64, 'Voltage_Sensor4': np.float64,\n 'Voltage_Sensor5': np.float64, 'Voltage_Sensor6': np.float64,\n 'Voltage_Sensor7': np.float64, 'Voltage_Sensor8': np.float64,\n 'Voltage_Sensor9': np.float64, 'Voltage_Sensor10': np.float64},\n skiprows=2, comment='#', index_col=False)\n", (197549, 198359), True, 'import pandas as pd\n'), ((6633, 6651), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (6649, 6651), False, 'import sys\n'), ((15218, 15252), 'numpy.save', 'np.save', (['Save_Loc', 'Radiosonde_Data'], {}), '(Save_Loc, Radiosonde_Data)\n', (15225, 15252), True, 'import numpy as np\n'), ((22693, 22722), 'numpy.abs', 'np.abs', (['((x1 - x0) / (y1 - y0))'], {}), '((x1 - x0) / (y1 - y0))\n', (22699, 22722), True, 'import numpy as np\n'), ((24098, 24130), 'os.path.dirname', 'os.path.dirname', (['Radiosonde_File'], {}), '(Radiosonde_File)\n', (24113, 24130), False, 'import os\n'), ((31962, 32000), 'numpy.abs', 'np.abs', (['SpaceCharge[space[0]:space[1]]'], {}), '(SpaceCharge[space[0]:space[1]])\n', (31968, 32000), True, 'import numpy as np\n'), ((32976, 33011), 'numpy.nanmean', 'np.nanmean', (['Wind[space[0]:space[1]]'], {}), '(Wind[space[0]:space[1]])\n', (32986, 33011), True, 'import numpy as np\n'), ((38026, 38058), 'os.path.dirname', 'os.path.dirname', (['Radiosonde_File'], {}), '(Radiosonde_File)\n', (38041, 38058), False, 'import os\n'), ((41425, 41487), 'numpy.arctan2', 'np.arctan2', (["Radiosonde_Data['u'][1:]", "Radiosonde_Data['v'][1:]"], {}), "(Radiosonde_Data['u'][1:], Radiosonde_Data['v'][1:])\n", (41435, 41487), True, 'import numpy as np\n'), ((42070, 42120), 'numpy.array', 'np.array', (['[Pres_Plot[locator], Tdry_Plot[locator]]'], {}), '([Pres_Plot[locator], Tdry_Plot[locator]])\n', (42078, 42120), True, 'import numpy as np\n'), ((42202, 42245), 'numpy.array', 'np.array', (['[Pres_Plot, Tdry_Plot, Tdew_Plot]'], {}), '([Pres_Plot, Tdry_Plot, Tdew_Plot])\n', (42210, 42245), True, 'import numpy as np\n'), ((46840, 46870), 'os.path.dirname', 'os.path.dirname', (['Save_Location'], {}), '(Save_Location)\n', (46855, 46870), False, 'import os\n'), ((47773, 47814), 'numpy.sin', 'np.sin', (['(Wind_Dir[P_500] - Wind_Dir[P_850])'], {}), '(Wind_Dir[P_500] - Wind_Dir[P_850])\n', (47779, 47814), True, 'import numpy as np\n'), ((49200, 49242), 'numpy.exp', 'np.exp', (['(17.67 * (T - 273.15) / (T - 29.65))'], {}), '(17.67 * (T - 273.15) / (T - 29.65))\n', (49206, 49242), True, 'import numpy as np\n'), ((49948, 49972), 'numpy.arange', 'np.arange', (['Pqs_base.size'], {}), '(Pqs_base.size)\n', (49957, 49972), True, 'import numpy as np\n'), ((51614, 51634), 'numpy.arange', 'np.arange', (['Tdry.size'], {}), '(Tdry.size)\n', (51623, 51634), True, 'import numpy as np\n'), ((51683, 51703), 'numpy.arange', 'np.arange', (['Tdry.size'], {}), '(Tdry.size)\n', (51692, 51703), True, 'import numpy as np\n'), ((52486, 52506), 'numpy.arange', 'np.arange', (['Tdry.size'], {}), '(Tdry.size)\n', (52495, 52506), True, 'import numpy as np\n'), ((54681, 54717), 'numpy.datetime64', 'np.datetime64', (['"""2100-01-01 00:00:00"""'], {}), "('2100-01-01 00:00:00')\n", (54694, 54717), True, 'import numpy as np\n'), ((55567, 55606), 'numpy.zeros', 'np.zeros', (['Sensor_Package_TimeOrder.size'], {}), '(Sensor_Package_TimeOrder.size)\n', (55575, 55606), True, 'import numpy as np\n'), ((55719, 55752), 'Gilly_Utilities.isnat', 'gu.isnat', (['self.LaunchTime[sensor]'], {}), '(self.LaunchTime[sensor])\n', (55727, 55752), True, 'import Gilly_Utilities as gu\n'), ((59226, 59259), 'Gilly_Utilities.broadcast', 'gu.broadcast', (['which_ascents', '(2)', '(2)'], {}), '(which_ascents, 2, 2)\n', (59238, 59259), True, 'import Gilly_Utilities as gu\n'), ((59840, 59977), 'Data_Output.SPRadiosonde', 'SPRadiosonde', (['self.Radiosonde_Data'], {'numplots': '(7)', 'which_ascents': 'ascents', 'height_range': '[0, 12]', 'calibrate': '"""Units"""', 'plot_title': 'plot_title'}), "(self.Radiosonde_Data, numplots=7, which_ascents=ascents,\n height_range=[0, 12], calibrate='Units', plot_title=plot_title)\n", (59852, 59977), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((61510, 61531), 'Gilly_Utilities.isnat', 'gu.isnat', (['launch_time'], {}), '(launch_time)\n', (61518, 61531), True, 'import Gilly_Utilities as gu\n'), ((62217, 62278), 'numpy.array', 'np.array', (["Satellite_Passes['datetime']"], {'dtype': '"""datetime64[m]"""'}), "(Satellite_Passes['datetime'], dtype='datetime64[m]')\n", (62225, 62278), True, 'import numpy as np\n'), ((62314, 62352), 'numpy.array', 'np.array', (["Satellite_Passes['location']"], {}), "(Satellite_Passes['location'])\n", (62322, 62352), True, 'import numpy as np\n'), ((63241, 63290), 'Gilly_Utilities.urllib_authentication', 'gu.urllib_authentication', (['url', 'username', 'password'], {}), '(url, username, password)\n', (63265, 63290), True, 'import Gilly_Utilities as gu\n'), ((63318, 63338), 'urllib2.urlopen', 'urllib2.urlopen', (['url'], {}), '(url)\n', (63333, 63338), False, 'import urllib2\n'), ((63977, 64002), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (64000, 64002), False, 'import warnings\n'), ((64008, 64039), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (64029, 64039), False, 'import warnings\n'), ((68391, 68407), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (68400, 68407), True, 'import numpy as np\n'), ((69401, 69437), 'numpy.datetime64', 'np.datetime64', (['"""2100-01-01 00:00:00"""'], {}), "('2100-01-01 00:00:00')\n", (69414, 69437), True, 'import numpy as np\n'), ((70170, 70203), 'Gilly_Utilities.isnat', 'gu.isnat', (['self.LaunchTime[sensor]'], {}), '(self.LaunchTime[sensor])\n', (70178, 70203), True, 'import Gilly_Utilities as gu\n'), ((71011, 71020), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (71018, 71020), True, 'import matplotlib.pyplot as plt\n'), ((71025, 71036), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (71034, 71036), True, 'import matplotlib.pyplot as plt\n'), ((71054, 71068), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (71066, 71068), True, 'import matplotlib.pyplot as plt\n'), ((72355, 72413), 'Gilly_Utilities.fixed_aspect_ratio', 'gu.fixed_aspect_ratio', ([], {'ax': 'ax', 'ratio': '(1 / 4)', 'adjustable': 'None'}), '(ax=ax, ratio=1 / 4, adjustable=None)\n', (72376, 72413), True, 'import Gilly_Utilities as gu\n'), ((72487, 72505), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (72503, 72505), True, 'import matplotlib.pyplot as plt\n'), ((73382, 73449), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (73393, 73449), True, 'import matplotlib.pyplot as plt\n'), ((73870, 74017), 'Data_Output.SPRadiosonde', 'SPRadiosonde', (['self.Radiosonde_Data'], {'numplots': '(7)', 'which_ascents': 'sensor', 'height_range': '[0, 12]', 'calibrate': "('Basic', 'Units')", 'plot_title': 'plot_title'}), "(self.Radiosonde_Data, numplots=7, which_ascents=sensor,\n height_range=[0, 12], calibrate=('Basic', 'Units'), plot_title=plot_title)\n", (73882, 74017), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((75539, 75560), 'Gilly_Utilities.isnat', 'gu.isnat', (['launch_time'], {}), '(launch_time)\n', (75547, 75560), True, 'import Gilly_Utilities as gu\n'), ((76208, 76269), 'numpy.array', 'np.array', (["Satellite_Passes['datetime']"], {'dtype': '"""datetime64[m]"""'}), "(Satellite_Passes['datetime'], dtype='datetime64[m]')\n", (76216, 76269), True, 'import numpy as np\n'), ((76305, 76343), 'numpy.array', 'np.array', (["Satellite_Passes['location']"], {}), "(Satellite_Passes['location'])\n", (76313, 76343), True, 'import numpy as np\n'), ((77232, 77281), 'Gilly_Utilities.urllib_authentication', 'gu.urllib_authentication', (['url', 'username', 'password'], {}), '(url, username, password)\n', (77256, 77281), True, 'import Gilly_Utilities as gu\n'), ((77340, 77360), 'urllib2.urlopen', 'urllib2.urlopen', (['url'], {}), '(url)\n', (77355, 77360), False, 'import urllib2\n'), ((81892, 81913), 'Gilly_Utilities.isnat', 'gu.isnat', (['launch_time'], {}), '(launch_time)\n', (81900, 81913), True, 'import Gilly_Utilities as gu\n'), ((82496, 82548), 'urllib.urlretrieve', 'urllib.urlretrieve', (['filename_download', 'filename_save'], {}), '(filename_download, filename_save)\n', (82514, 82548), False, 'import urllib\n'), ((83311, 83330), 'Gilly_Utilities.argnear', 'gu.argnear', (['Tdry', '(0)'], {}), '(Tdry, 0)\n', (83321, 83330), True, 'import Gilly_Utilities as gu\n'), ((83778, 83800), 'numpy.all', 'np.all', (['(Cloud_Tdry < 0)'], {}), '(Cloud_Tdry < 0)\n', (83784, 83800), True, 'import numpy as np\n'), ((87617, 87633), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (87626, 87633), True, 'import numpy as np\n'), ((88969, 88999), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (['Height', 'cloud'], {}), '(Height, cloud)\n', (88984, 88999), True, 'import Gilly_Utilities as gu\n'), ((89539, 89562), 'numpy.all', 'np.all', (['(Tdry_Subset > 0)'], {}), '(Tdry_Subset > 0)\n', (89545, 89562), True, 'import numpy as np\n'), ((91949, 91977), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (['Height', 'air'], {}), '(Height, air)\n', (91964, 91977), True, 'import Gilly_Utilities as gu\n'), ((92482, 92505), 'numpy.all', 'np.all', (['(Tdry_Subset > 0)'], {}), '(Tdry_Subset > 0)\n', (92488, 92505), True, 'import numpy as np\n'), ((104297, 104382), 'Data_Output.Histogram_Back2Back', 'Histogram_Back2Back', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'None', 'xscale', 'yscale'], {}), '(data, filename, bins, ylabel, annotate, None, xscale,\n yscale)\n', (104316, 104382), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((105129, 105252), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'ylim', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)', 'fontsize': '(14)'}), '(data, filename, bins, ylabel, annotate, ylim, xscale,\n yscale, color, plot_stats=False, fontsize=14)\n', (105148, 105252), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((106123, 106246), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'ylim', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)', 'fontsize': '(14)'}), '(data, filename, bins, ylabel, annotate, ylim, xscale,\n yscale, color, plot_stats=False, fontsize=14)\n', (106142, 106246), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((106819, 106929), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'None', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)'}), '(data, filename, bins, ylabel, annotate, None, xscale,\n yscale, color, plot_stats=False)\n', (106838, 106929), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((107523, 107783), 'Data_Output.BoxPlots', 'BoxPlots', ([], {'plot_data': 'data', 'plot_filename': 'filename', 'plot_xlabel': 'xlabel', 'plot_xticklabel': 'xticklabel', 'plot_ylabel': 'ylabel', 'plot_ylim': 'None', 'plot_yscale': 'yscale', 'plot_group_color': 'colors', 'plot_indivdual_color': 'None', 'plot_positions': 'positions', 'plot_legend': 'None'}), '(plot_data=data, plot_filename=filename, plot_xlabel=xlabel,\n plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None,\n plot_yscale=yscale, plot_group_color=colors, plot_indivdual_color=None,\n plot_positions=positions, plot_legend=None)\n', (107531, 107783), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((108280, 108540), 'Data_Output.BoxPlots', 'BoxPlots', ([], {'plot_data': 'data', 'plot_filename': 'filename', 'plot_xlabel': 'xlabel', 'plot_xticklabel': 'xticklabel', 'plot_ylabel': 'ylabel', 'plot_ylim': 'None', 'plot_yscale': 'yscale', 'plot_group_color': 'colors', 'plot_indivdual_color': 'None', 'plot_positions': 'positions', 'plot_legend': 'None'}), '(plot_data=data, plot_filename=filename, plot_xlabel=xlabel,\n plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None,\n plot_yscale=yscale, plot_group_color=colors, plot_indivdual_color=None,\n plot_positions=positions, plot_legend=None)\n', (108288, 108540), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((109249, 109531), 'Data_Output.BoxPlots', 'BoxPlots', ([], {'plot_data': 'data', 'plot_filename': 'filename', 'plot_xlabel': 'xlabel', 'plot_xticklabel': 'xticklabel', 'plot_ylabel': 'ylabel', 'plot_ylim': 'None', 'plot_yscale': 'yscale', 'plot_group_color': 'group_colors', 'plot_indivdual_color': 'individual_colors', 'plot_positions': 'positions', 'plot_legend': 'legend'}), '(plot_data=data, plot_filename=filename, plot_xlabel=xlabel,\n plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None,\n plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color\n =individual_colors, plot_positions=positions, plot_legend=legend)\n', (109257, 109531), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((111292, 111415), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'ylim', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)', 'fontsize': '(14)'}), '(data, filename, bins, ylabel, annotate, ylim, xscale,\n yscale, color, plot_stats=False, fontsize=14)\n', (111311, 111415), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((114559, 114669), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'ylim', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)'}), '(data, filename, bins, ylabel, annotate, ylim, xscale,\n yscale, color, plot_stats=False)\n', (114578, 114669), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((115244, 115354), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'None', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)'}), '(data, filename, bins, ylabel, annotate, None, xscale,\n yscale, color, plot_stats=False)\n', (115263, 115354), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((116045, 116327), 'Data_Output.BoxPlots', 'BoxPlots', ([], {'plot_data': 'data', 'plot_filename': 'filename', 'plot_xlabel': 'xlabel', 'plot_xticklabel': 'xticklabel', 'plot_ylabel': 'ylabel', 'plot_ylim': 'None', 'plot_yscale': 'yscale', 'plot_group_color': 'group_colors', 'plot_indivdual_color': 'individual_colors', 'plot_positions': 'positions', 'plot_legend': 'legend'}), '(plot_data=data, plot_filename=filename, plot_xlabel=xlabel,\n plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None,\n plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color\n =individual_colors, plot_positions=positions, plot_legend=legend)\n', (116053, 116327), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((119554, 119664), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'ylim', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)'}), '(data, filename, bins, ylabel, annotate, ylim, xscale,\n yscale, color, plot_stats=False)\n', (119573, 119664), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((120249, 120359), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'None', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)'}), '(data, filename, bins, ylabel, annotate, None, xscale,\n yscale, color, plot_stats=False)\n', (120268, 120359), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((121062, 121344), 'Data_Output.BoxPlots', 'BoxPlots', ([], {'plot_data': 'data', 'plot_filename': 'filename', 'plot_xlabel': 'xlabel', 'plot_xticklabel': 'xticklabel', 'plot_ylabel': 'ylabel', 'plot_ylim': 'None', 'plot_yscale': 'yscale', 'plot_group_color': 'group_colors', 'plot_indivdual_color': 'individual_colors', 'plot_positions': 'positions', 'plot_legend': 'legend'}), '(plot_data=data, plot_filename=filename, plot_xlabel=xlabel,\n plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None,\n plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color\n =individual_colors, plot_positions=positions, plot_legend=legend)\n', (121070, 121344), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((124683, 124793), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'ylim', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)'}), '(data, filename, bins, ylabel, annotate, ylim, xscale,\n yscale, color, plot_stats=False)\n', (124702, 124793), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((125406, 125516), 'Data_Output.Histogram_Side2Side', 'Histogram_Side2Side', (['data', 'filename', 'bins', 'ylabel', 'annotate', 'None', 'xscale', 'yscale', 'color'], {'plot_stats': '(False)'}), '(data, filename, bins, ylabel, annotate, None, xscale,\n yscale, color, plot_stats=False)\n', (125425, 125516), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((126269, 126551), 'Data_Output.BoxPlots', 'BoxPlots', ([], {'plot_data': 'data', 'plot_filename': 'filename', 'plot_xlabel': 'xlabel', 'plot_xticklabel': 'xticklabel', 'plot_ylabel': 'ylabel', 'plot_ylim': 'None', 'plot_yscale': 'yscale', 'plot_group_color': 'group_colors', 'plot_indivdual_color': 'individual_colors', 'plot_positions': 'positions', 'plot_legend': 'legend'}), '(plot_data=data, plot_filename=filename, plot_xlabel=xlabel,\n plot_xticklabel=xticklabel, plot_ylabel=ylabel, plot_ylim=None,\n plot_yscale=yscale, plot_group_color=group_colors, plot_indivdual_color\n =individual_colors, plot_positions=positions, plot_legend=legend)\n', (126277, 126551), False, 'from Data_Output import SPRadiosonde, SPEnsemble, CrossCorrelation_Scatter_Plot, Histogram_Back2Back, Histogram_Side2Side, BoxPlots\n'), ((128375, 128384), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (128382, 128384), True, 'import matplotlib.pyplot as plt\n'), ((128389, 128400), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (128398, 128400), True, 'import matplotlib.pyplot as plt\n'), ((128418, 128446), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (128430, 128446), True, 'import matplotlib.pyplot as plt\n'), ((129402, 129431), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'labelsize': '(14)'}), '(labelsize=14)\n', (129417, 129431), True, 'import matplotlib.pyplot as plt\n'), ((130122, 130189), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (130133, 130189), True, 'import matplotlib.pyplot as plt\n'), ((137060, 137114), 'Gilly_Utilities.flatten', 'gu.flatten', (['[Cloud_ElectricField_Total, Field_Mill_PG]'], {}), '([Cloud_ElectricField_Total, Field_Mill_PG])\n', (137070, 137114), True, 'import Gilly_Utilities as gu\n'), ((137126, 137180), 'Gilly_Utilities.flatten', 'gu.flatten', (['[Cloud_ElectricField_Total, Field_Mill_PG]'], {}), '([Cloud_ElectricField_Total, Field_Mill_PG])\n', (137136, 137180), True, 'import Gilly_Utilities as gu\n'), ((137207, 137261), 'Gilly_Utilities.flatten', 'gu.flatten', (['[Cloud_ElectricField_Total, Field_Mill_PG]'], {}), '([Cloud_ElectricField_Total, Field_Mill_PG])\n', (137217, 137261), True, 'import Gilly_Utilities as gu\n'), ((137273, 137327), 'Gilly_Utilities.flatten', 'gu.flatten', (['[Cloud_ElectricField_Total, Field_Mill_PG]'], {}), '([Cloud_ElectricField_Total, Field_Mill_PG])\n', (137283, 137327), True, 'import Gilly_Utilities as gu\n'), ((140642, 140704), 'numpy.sqrt', 'np.sqrt', (["(Radiosonde_Data['u'] ** 2 + Radiosonde_Data['v'] ** 2)"], {}), "(Radiosonde_Data['u'] ** 2 + Radiosonde_Data['v'] ** 2)\n", (140649, 140704), True, 'import numpy as np\n'), ((149055, 149168), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IR', '(15)'], {'method': '"""unique"""', 'average': '"""mean"""', 'undersample': '(False)', 'slim': '(False)'}), "(Cloud_SpaceCharge, Cloud_IR, 15, method='unique', average=\n 'mean', undersample=False, slim=False)\n", (149066, 149168), True, 'import Gilly_Utilities as gu\n'), ((150828, 150925), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_Cyan', '(50)'], {'method': '"""unique"""', 'undersample': '(True)', 'slim': '(True)'}), "(Cloud_SpaceCharge, Cloud_Cyan, 50, method='unique', undersample\n =True, slim=True)\n", (150839, 150925), True, 'import Gilly_Utilities as gu\n'), ((151877, 151980), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IRdiffCyan', '(100)'], {'method': '"""unique"""', 'undersample': '(True)', 'slim': '(True)'}), "(Cloud_SpaceCharge, Cloud_IRdiffCyan, 100, method='unique',\n undersample=True, slim=True)\n", (151888, 151980), True, 'import Gilly_Utilities as gu\n'), ((152982, 153084), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IRdivCyan', '(100)'], {'method': '"""unique"""', 'undersample': '(True)', 'slim': '(True)'}), "(Cloud_SpaceCharge, Cloud_IRdivCyan, 100, method='unique',\n undersample=True, slim=True)\n", (152993, 153084), True, 'import Gilly_Utilities as gu\n'), ((155617, 155661), 'Gilly_Utilities.argcontiguous', 'gu.argcontiguous', (['LayerType[sensor]'], {'valid': '(0)'}), '(LayerType[sensor], valid=0)\n', (155633, 155661), True, 'import Gilly_Utilities as gu\n'), ((160263, 160436), 'Gilly_Utilities.antifinite', 'gu.antifinite', (["(Radiosonde_Data[sensor]['Units']['time'], Radiosonde_Data[sensor]['Units']\n ['height'], Radiosonde_Data[sensor]['Units']['SpaceCharge'])"], {'unpack': '(True)'}), "((Radiosonde_Data[sensor]['Units']['time'], Radiosonde_Data[\n sensor]['Units']['height'], Radiosonde_Data[sensor]['Units'][\n 'SpaceCharge']), unpack=True)\n", (160276, 160436), True, 'import Gilly_Utilities as gu\n'), ((162531, 162598), 'scipy.stats.anderson_ksamp', 'sp.stats.anderson_ksamp', (['(Cloud_SignChange_All, Air_SignChange_All)'], {}), '((Cloud_SignChange_All, Air_SignChange_All))\n', (162554, 162598), True, 'import scipy as sp\n'), ((162627, 162689), 'scipy.stats.pearsonr', 'sp.stats.pearsonr', (['Cloud_SignChange_All', 'Cloud_SpaceCharge_All'], {}), '(Cloud_SignChange_All, Cloud_SpaceCharge_All)\n', (162644, 162689), True, 'import scipy as sp\n'), ((162700, 162763), 'scipy.stats.spearmanr', 'sp.stats.spearmanr', (['Cloud_SignChange_All', 'Cloud_SpaceCharge_All'], {}), '(Cloud_SignChange_All, Cloud_SpaceCharge_All)\n', (162718, 162763), True, 'import scipy as sp\n'), ((162973, 163026), 'numpy.hstack', 'np.hstack', (['(Cloud_SignChange_All, Air_SignChange_All)'], {}), '((Cloud_SignChange_All, Air_SignChange_All))\n', (162982, 163026), True, 'import numpy as np\n'), ((163033, 163088), 'numpy.hstack', 'np.hstack', (['(Cloud_SpaceCharge_All, Air_SpaceCharge_All)'], {}), '((Cloud_SpaceCharge_All, Air_SpaceCharge_All))\n', (163042, 163088), True, 'import numpy as np\n'), ((164894, 164933), 'numpy.percentile', 'np.percentile', (['Cloud_SpaceCharge_All', '(0)'], {}), '(Cloud_SpaceCharge_All, 0)\n', (164907, 164933), True, 'import numpy as np\n'), ((165063, 165100), 'numpy.percentile', 'np.percentile', (['Air_SpaceCharge_All', '(0)'], {}), '(Air_SpaceCharge_All, 0)\n', (165076, 165100), True, 'import numpy as np\n'), ((165239, 165284), 'numpy.sort', 'np.sort', (['Air_SignChange_All'], {'kind': '"""mergesort"""'}), "(Air_SignChange_All, kind='mergesort')\n", (165246, 165284), True, 'import numpy as np\n'), ((165408, 165455), 'numpy.sort', 'np.sort', (['Cloud_SignChange_All'], {'kind': '"""mergesort"""'}), "(Cloud_SignChange_All, kind='mergesort')\n", (165415, 165455), True, 'import numpy as np\n'), ((167018, 167077), 'Gilly_Utilities.fixed_aspect_ratio', 'gu.fixed_aspect_ratio', ([], {'ax': 'subplot', 'ratio': '(1)', 'adjustable': 'None'}), '(ax=subplot, ratio=1, adjustable=None)\n', (167039, 167077), True, 'import Gilly_Utilities as gu\n'), ((167546, 167639), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_SignChange_All', 'Cloud_SignChange_All'], {'alternative': '"""two-sided"""'}), "(Air_SignChange_All, Cloud_SignChange_All, alternative\n ='two-sided')\n", (167567, 167639), True, 'import scipy as sp\n'), ((173294, 173317), 'numpy.any', 'np.any', (['(Temperature < 0)'], {}), '(Temperature < 0)\n', (173300, 173317), True, 'import numpy as np\n'), ((174580, 174610), 'os.path.dirname', 'os.path.dirname', (['Save_Location'], {}), '(Save_Location)\n', (174595, 174610), False, 'import os\n'), ((176496, 176520), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""classic"""'], {}), "('classic')\n", (176509, 176520), True, 'import matplotlib.pyplot as plt\n'), ((176622, 176631), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (176629, 176631), True, 'import matplotlib.pyplot as plt\n'), ((176635, 176646), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (176644, 176646), True, 'import matplotlib.pyplot as plt\n'), ((176708, 176722), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (176720, 176722), True, 'import matplotlib.pyplot as plt\n'), ((178087, 178154), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (178098, 178154), True, 'import matplotlib.pyplot as plt\n'), ((180473, 180486), 'numpy.isnan', 'np.isnan', (['PLL'], {}), '(PLL)\n', (180481, 180486), True, 'import numpy as np\n'), ((186379, 186399), 'numpy.diff', 'np.diff', (['Error_Index'], {}), '(Error_Index)\n', (186386, 186399), True, 'import numpy as np\n'), ((188463, 188495), 'os.path.dirname', 'os.path.dirname', (['Radiosonde_File'], {}), '(Radiosonde_File)\n', (188478, 188495), False, 'import os\n'), ((191824, 191834), 'numpy.size', 'np.size', (['x'], {}), '(x)\n', (191831, 191834), True, 'import numpy as np\n'), ((191842, 191975), 'matplotlib.pyplot.text', 'plt.text', (['x[lab]', 'y[lab]', 'label_txt[lab]'], {'color': '"""black"""', 'size': '(10)', 'horizontalalignment': '"""center"""', 'verticalalignment': '"""top"""', 'zorder': '(6)'}), "(x[lab], y[lab], label_txt[lab], color='black', size=10,\n horizontalalignment='center', verticalalignment='top', zorder=6)\n", (191850, 191975), True, 'import matplotlib.pyplot as plt\n'), ((194407, 194439), 'os.path.dirname', 'os.path.dirname', (['Radiosonde_File'], {}), '(Radiosonde_File)\n', (194422, 194439), False, 'import os\n'), ((209681, 209692), 'time.time', 'time.time', ([], {}), '()\n', (209690, 209692), False, 'import time\n'), ((7048, 7102), 'Gilly_Utilities.string_checker', 'gu.string_checker', (['file_check', 'tester'], {'condition': '"""all"""'}), "(file_check, tester, condition='all')\n", (7065, 7102), True, 'import Gilly_Utilities as gu\n'), ((10262, 10294), 'Gilly_Utilities.fix_recarray', 'gu.fix_recarray', (['Radiosonde_Data'], {}), '(Radiosonde_Data)\n', (10277, 10294), True, 'import Gilly_Utilities as gu\n'), ((10526, 10590), 'datetime.datetime.strptime', 'datetime.strptime', (['File_Comments[-2][18:37]', '"""%Y-%m-%dT%H:%M:%S"""'], {}), "(File_Comments[-2][18:37], '%Y-%m-%dT%H:%M:%S')\n", (10543, 10590), False, 'from datetime import datetime, timedelta\n'), ((12416, 12448), 'Gilly_Utilities.fix_recarray', 'gu.fix_recarray', (['Radiosonde_Data'], {}), '(Radiosonde_Data)\n', (12431, 12448), True, 'import Gilly_Utilities as gu\n'), ((12465, 12490), 'Gilly_Utilities.fix_recarray', 'gu.fix_recarray', (['GPS_Data'], {}), '(GPS_Data)\n', (12480, 12490), True, 'import Gilly_Utilities as gu\n'), ((15607, 15634), 'numpy.save', 'np.save', (['Save_Loc', 'GPS_Data'], {}), '(Save_Loc, GPS_Data)\n', (15614, 15634), True, 'import numpy as np\n'), ((18053, 18069), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (18062, 18069), True, 'import numpy as np\n'), ((24599, 24619), 'numpy.max', 'np.max', (['plot_version'], {}), '(plot_version)\n', (24605, 24619), True, 'import numpy as np\n'), ((30286, 30306), 'numpy.sign', 'np.sign', (['SpaceCharge'], {}), '(SpaceCharge)\n', (30293, 30306), True, 'import numpy as np\n'), ((31448, 31473), 'numpy.abs', 'np.abs', (['Local_SpaceCharge'], {}), '(Local_SpaceCharge)\n', (31454, 31473), True, 'import numpy as np\n'), ((33645, 33683), 'numpy.abs', 'np.abs', (['SpaceCharge[space[0]:space[1]]'], {}), '(SpaceCharge[space[0]:space[1]])\n', (33651, 33683), True, 'import numpy as np\n'), ((34484, 34542), 'Gilly_Utilities.cosarctan', 'gu.cosarctan', (['((Cloud_Time - time_diff) * velocity / height)'], {}), '((Cloud_Time - time_diff) * velocity / height)\n', (34496, 34542), True, 'import Gilly_Utilities as gu\n'), ((38531, 38551), 'numpy.max', 'np.max', (['plot_version'], {}), '(plot_version)\n', (38537, 38551), True, 'import numpy as np\n'), ((42024, 42051), 'numpy.array', 'np.array', (['self.height_range'], {}), '(self.height_range)\n', (42032, 42051), True, 'import numpy as np\n'), ((42912, 42972), 'glob.glob', 'glob.glob', (["(PhD_Global.Raw_Data_Path + 'Met_Data/ULS/03743/*')"], {}), "(PhD_Global.Raw_Data_Path + 'Met_Data/ULS/03743/*')\n", (42921, 42972), False, 'import glob\n'), ((43383, 43446), 'Gilly_Utilities.argnear', 'gu.argnear', (['ULS_Date', 'self.Launch_Datetime[self.sensor_package]'], {}), '(ULS_Date, self.Launch_Datetime[self.sensor_package])\n', (43393, 43446), True, 'import Gilly_Utilities as gu\n'), ((45099, 45187), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[WARNING] No Larkhill (03743) sounding data was found!"""'], {'type': '"""warning"""'}), "('[WARNING] No Larkhill (03743) sounding data was found!', type=\n 'warning')\n", (45108, 45187), True, 'import Gilly_Utilities as gu\n'), ((45894, 45926), 'os.path.dirname', 'os.path.dirname', (['Radiosonde_File'], {}), '(Radiosonde_File)\n', (45909, 45926), False, 'import os\n'), ((52207, 52236), 'numpy.log', 'np.log', (['(Pres[i] / Pres[i + 1])'], {}), '(Pres[i] / Pres[i + 1])\n', (52213, 52236), True, 'import numpy as np\n'), ((53077, 53088), 'time.time', 'time.time', ([], {}), '()\n', (53086, 53088), False, 'import time\n'), ((56837, 56959), 'Gilly_Utilities.time_axis', 'gu.time_axis', (['(PG_Data_All[i][0, 0], PG_Data_All[i][-1, 0])'], {'ax': 'ax[i]', 'xlabel': '"""Time (UTC)"""', 'format': '"""auto"""', 'rotation': '(45)'}), "((PG_Data_All[i][0, 0], PG_Data_All[i][-1, 0]), ax=ax[i],\n xlabel='Time (UTC)', format='auto', rotation=45)\n", (56849, 56959), True, 'import Gilly_Utilities as gu\n'), ((58173, 58206), 'Gilly_Utilities.isnat', 'gu.isnat', (['self.LaunchTime[sensor]'], {}), '(self.LaunchTime[sensor])\n', (58181, 58206), True, 'import Gilly_Utilities as gu\n'), ((62643, 62683), 'Gilly_Utilities.argnear', 'gu.argnear', (['Possible_Passes', 'launch_time'], {}), '(Possible_Passes, launch_time)\n', (62653, 62683), True, 'import Gilly_Utilities as gu\n'), ((64164, 64306), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""stere"""', 'lat_0': '(55)', 'lon_0': '(-5)', 'resolution': 'map_res', 'llcrnrlon': 'lonW', 'llcrnrlat': 'latS', 'urcrnrlon': 'lonE', 'urcrnrlat': 'latN', 'ax': 'ax'}), "(projection='stere', lat_0=55, lon_0=-5, resolution=map_res,\n llcrnrlon=lonW, llcrnrlat=latS, urcrnrlon=lonE, urcrnrlat=latN, ax=ax)\n", (64171, 64306), False, 'from mpl_toolkits.basemap import Basemap\n'), ((67834, 67845), 'time.time', 'time.time', ([], {}), '()\n', (67843, 67845), False, 'import time\n'), ((71323, 71427), 'Gilly_Utilities.time_axis', 'gu.time_axis', (['(PG_Data[0, 0], PG_Data[-1, 0])'], {'ax': 'ax', 'xlabel': '"""Time (UTC)"""', 'format': '"""auto"""', 'rotation': '(0)'}), "((PG_Data[0, 0], PG_Data[-1, 0]), ax=ax, xlabel='Time (UTC)',\n format='auto', rotation=0)\n", (71335, 71427), True, 'import Gilly_Utilities as gu\n'), ((72847, 72869), 'matplotlib.dates.DateFormatter', 'DateFormatter', (['"""%H:%M"""'], {}), "('%H:%M')\n", (72860, 72869), False, 'from matplotlib.dates import DateFormatter, MinuteLocator, HourLocator, DayLocator\n'), ((72946, 72979), 'Gilly_Utilities.isnat', 'gu.isnat', (['self.LaunchTime[sensor]'], {}), '(self.LaunchTime[sensor])\n', (72954, 72979), True, 'import Gilly_Utilities as gu\n'), ((76634, 76674), 'Gilly_Utilities.argnear', 'gu.argnear', (['Possible_Passes', 'launch_time'], {}), '(Possible_Passes, launch_time)\n', (76644, 76674), True, 'import Gilly_Utilities as gu\n'), ((77465, 77490), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (77488, 77490), False, 'import warnings\n'), ((77497, 77528), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (77518, 77528), False, 'import warnings\n'), ((77569, 77583), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (77581, 77583), True, 'import matplotlib.pyplot as plt\n'), ((77953, 78095), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""stere"""', 'lat_0': '(55)', 'lon_0': '(-5)', 'resolution': 'map_res', 'llcrnrlon': 'lonW', 'llcrnrlat': 'latS', 'urcrnrlon': 'lonE', 'urcrnrlat': 'latN', 'ax': 'ax'}), "(projection='stere', lat_0=55, lon_0=-5, resolution=map_res,\n llcrnrlon=lonW, llcrnrlat=latS, urcrnrlon=lonE, urcrnrlat=latN, ax=ax)\n", (77960, 78095), False, 'from mpl_toolkits.basemap import Basemap\n'), ((81293, 81360), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)', 'dpi': '(300)'}), "(filename, bbox_inches='tight', pad_inches=0.1, dpi=300)\n", (81304, 81360), True, 'import matplotlib.pyplot as plt\n'), ((82069, 82093), 'numpy.array', 'np.array', (['[0, 6, 12, 18]'], {}), '([0, 6, 12, 18])\n', (82077, 82093), True, 'import numpy as np\n'), ((82632, 82643), 'time.time', 'time.time', ([], {}), '()\n', (82641, 82643), False, 'import time\n'), ((88658, 88713), 'numpy.abs', 'np.abs', (["Radiosonde_Data[sensor]['Units']['SpaceCharge']"], {}), "(Radiosonde_Data[sensor]['Units']['SpaceCharge'])\n", (88664, 88713), True, 'import numpy as np\n'), ((89898, 89921), 'numpy.all', 'np.all', (['(Tdry_Subset < 0)'], {}), '(Tdry_Subset < 0)\n', (89904, 89921), True, 'import numpy as np\n'), ((91477, 91502), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (91500, 91502), False, 'import warnings\n'), ((91509, 91540), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (91530, 91540), False, 'import warnings\n'), ((92821, 92844), 'numpy.all', 'np.all', (['(Tdry_Subset < 0)'], {}), '(Tdry_Subset < 0)\n', (92827, 92844), True, 'import numpy as np\n'), ((94364, 94389), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (94387, 94389), False, 'import warnings\n'), ((94396, 94427), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (94417, 94427), False, 'import warnings\n'), ((95306, 95367), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IR_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IR_Liquid, type='ndarray', dtype=np.float64)\n", (95316, 95367), True, 'import Gilly_Utilities as gu\n'), ((95407, 95465), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IR_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IR_Ice, type='ndarray', dtype=np.float64)\n", (95417, 95465), True, 'import Gilly_Utilities as gu\n'), ((95507, 95567), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IR_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IR_Mixed, type='ndarray', dtype=np.float64)\n", (95517, 95567), True, 'import Gilly_Utilities as gu\n'), ((95613, 95677), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IR_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IR_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (95623, 95677), True, 'import Gilly_Utilities as gu\n'), ((95726, 95793), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IR_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IR_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (95736, 95793), True, 'import Gilly_Utilities as gu\n'), ((95841, 95904), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_Cyan_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_Cyan_Liquid, type='ndarray', dtype=np.float64)\n", (95851, 95904), True, 'import Gilly_Utilities as gu\n'), ((95946, 96006), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_Cyan_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_Cyan_Ice, type='ndarray', dtype=np.float64)\n", (95956, 96006), True, 'import Gilly_Utilities as gu\n'), ((96050, 96112), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_Cyan_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_Cyan_Mixed, type='ndarray', dtype=np.float64)\n", (96060, 96112), True, 'import Gilly_Utilities as gu\n'), ((96160, 96226), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_Cyan_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_Cyan_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (96170, 96226), True, 'import Gilly_Utilities as gu\n'), ((96277, 96346), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_Cyan_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_Cyan_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (96287, 96346), True, 'import Gilly_Utilities as gu\n'), ((96400, 96469), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdiffCyan_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdiffCyan_Liquid, type='ndarray', dtype=np.float64)\n", (96410, 96469), True, 'import Gilly_Utilities as gu\n'), ((96517, 96583), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdiffCyan_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdiffCyan_Ice, type='ndarray', dtype=np.float64)\n", (96527, 96583), True, 'import Gilly_Utilities as gu\n'), ((96633, 96701), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdiffCyan_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdiffCyan_Mixed, type='ndarray', dtype=np.float64)\n", (96643, 96701), True, 'import Gilly_Utilities as gu\n'), ((96755, 96827), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdiffCyan_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdiffCyan_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (96765, 96827), True, 'import Gilly_Utilities as gu\n'), ((96884, 96959), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdiffCyan_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdiffCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (96894, 96959), True, 'import Gilly_Utilities as gu\n'), ((97012, 97080), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdivCyan_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdivCyan_Liquid, type='ndarray', dtype=np.float64)\n", (97022, 97080), True, 'import Gilly_Utilities as gu\n'), ((97127, 97192), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdivCyan_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdivCyan_Ice, type='ndarray', dtype=np.float64)\n", (97137, 97192), True, 'import Gilly_Utilities as gu\n'), ((97241, 97308), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdivCyan_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdivCyan_Mixed, type='ndarray', dtype=np.float64)\n", (97251, 97308), True, 'import Gilly_Utilities as gu\n'), ((97361, 97432), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdivCyan_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdivCyan_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (97371, 97432), True, 'import Gilly_Utilities as gu\n'), ((97488, 97562), 'Gilly_Utilities.flatten', 'gu.flatten', (['Cloud_IRdivCyan_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Cloud_IRdivCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (97498, 97562), True, 'import Gilly_Utilities as gu\n'), ((98099, 98158), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IR_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IR_Liquid, type='ndarray', dtype=np.float64)\n", (98109, 98158), True, 'import Gilly_Utilities as gu\n'), ((98196, 98252), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IR_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IR_Ice, type='ndarray', dtype=np.float64)\n", (98206, 98252), True, 'import Gilly_Utilities as gu\n'), ((98292, 98350), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IR_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IR_Mixed, type='ndarray', dtype=np.float64)\n", (98302, 98350), True, 'import Gilly_Utilities as gu\n'), ((98394, 98456), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IR_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IR_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (98404, 98456), True, 'import Gilly_Utilities as gu\n'), ((98503, 98568), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IR_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IR_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (98513, 98568), True, 'import Gilly_Utilities as gu\n'), ((98614, 98675), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_Cyan_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_Cyan_Liquid, type='ndarray', dtype=np.float64)\n", (98624, 98675), True, 'import Gilly_Utilities as gu\n'), ((98715, 98773), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_Cyan_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_Cyan_Ice, type='ndarray', dtype=np.float64)\n", (98725, 98773), True, 'import Gilly_Utilities as gu\n'), ((98815, 98875), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_Cyan_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_Cyan_Mixed, type='ndarray', dtype=np.float64)\n", (98825, 98875), True, 'import Gilly_Utilities as gu\n'), ((98921, 98985), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_Cyan_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_Cyan_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (98931, 98985), True, 'import Gilly_Utilities as gu\n'), ((99034, 99101), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_Cyan_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_Cyan_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (99044, 99101), True, 'import Gilly_Utilities as gu\n'), ((99153, 99220), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdiffCyan_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdiffCyan_Liquid, type='ndarray', dtype=np.float64)\n", (99163, 99220), True, 'import Gilly_Utilities as gu\n'), ((99266, 99330), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdiffCyan_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdiffCyan_Ice, type='ndarray', dtype=np.float64)\n", (99276, 99330), True, 'import Gilly_Utilities as gu\n'), ((99378, 99444), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdiffCyan_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdiffCyan_Mixed, type='ndarray', dtype=np.float64)\n", (99388, 99444), True, 'import Gilly_Utilities as gu\n'), ((99496, 99566), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdiffCyan_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdiffCyan_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (99506, 99566), True, 'import Gilly_Utilities as gu\n'), ((99621, 99694), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdiffCyan_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdiffCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (99631, 99694), True, 'import Gilly_Utilities as gu\n'), ((99745, 99811), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdivCyan_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdivCyan_Liquid, type='ndarray', dtype=np.float64)\n", (99755, 99811), True, 'import Gilly_Utilities as gu\n'), ((99856, 99919), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdivCyan_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdivCyan_Ice, type='ndarray', dtype=np.float64)\n", (99866, 99919), True, 'import Gilly_Utilities as gu\n'), ((99966, 100031), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdivCyan_Mixed'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdivCyan_Mixed, type='ndarray', dtype=np.float64)\n", (99976, 100031), True, 'import Gilly_Utilities as gu\n'), ((100082, 100151), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdivCyan_Mixed_Ice'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdivCyan_Mixed_Ice, type='ndarray', dtype=np.float64)\n", (100092, 100151), True, 'import Gilly_Utilities as gu\n'), ((100205, 100277), 'Gilly_Utilities.flatten', 'gu.flatten', (['Air_IRdivCyan_Mixed_Liquid'], {'type': '"""ndarray"""', 'dtype': 'np.float64'}), "(Air_IRdivCyan_Mixed_Liquid, type='ndarray', dtype=np.float64)\n", (100215, 100277), True, 'import Gilly_Utilities as gu\n'), ((100735, 100834), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_SpaceCharge_Liquid', 'Cloud_SpaceCharge_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Ice,\n alternative='two-sided')\n", (100756, 100834), True, 'import scipy as sp\n'), ((101090, 101191), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_SpaceCharge_Liquid', 'Cloud_SpaceCharge_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Mixed,\n alternative='two-sided')\n", (101111, 101191), True, 'import scipy as sp\n'), ((101443, 101541), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_SpaceCharge_Ice', 'Cloud_SpaceCharge_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Mixed,\n alternative='two-sided')\n", (101464, 101541), True, 'import scipy as sp\n'), ((101825, 101936), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_SpaceCharge_Mixed_Liquid', 'Cloud_SpaceCharge_Mixed_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_SpaceCharge_Mixed_Liquid,\n Cloud_SpaceCharge_Mixed_Ice, alternative='two-sided')\n", (101846, 101936), True, 'import scipy as sp\n'), ((102233, 102333), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_SpaceCharge_Liquid', 'Cloud_SpaceCharge_Liquid'], {'alternative': '"""two-sided"""'}), "(Air_SpaceCharge_Liquid, Cloud_SpaceCharge_Liquid,\n alternative='two-sided')\n", (102254, 102333), True, 'import scipy as sp\n'), ((102605, 102699), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_SpaceCharge_Ice', 'Cloud_SpaceCharge_Ice'], {'alternative': '"""two-sided"""'}), "(Air_SpaceCharge_Ice, Cloud_SpaceCharge_Ice,\n alternative='two-sided')\n", (102626, 102699), True, 'import scipy as sp\n'), ((102967, 103065), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_SpaceCharge_Mixed', 'Cloud_SpaceCharge_Mixed'], {'alternative': '"""two-sided"""'}), "(Air_SpaceCharge_Mixed, Cloud_SpaceCharge_Mixed,\n alternative='two-sided')\n", (102988, 103065), True, 'import scipy as sp\n'), ((107281, 107303), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(210)', '(0)', '(46)'], {}), '(210, 0, 46)\n', (107291, 107303), True, 'import Gilly_Utilities as gu\n'), ((107303, 107326), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(0)', '(112)', '(192)'], {}), '(0, 112, 192)\n', (107313, 107326), True, 'import Gilly_Utilities as gu\n'), ((107326, 107350), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(146)', '(208)', '(80)'], {}), '(146, 208, 80)\n', (107336, 107350), True, 'import Gilly_Utilities as gu\n'), ((108068, 108090), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(210)', '(0)', '(46)'], {}), '(210, 0, 46)\n', (108078, 108090), True, 'import Gilly_Utilities as gu\n'), ((108090, 108113), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(0)', '(112)', '(192)'], {}), '(0, 112, 192)\n', (108100, 108113), True, 'import Gilly_Utilities as gu\n'), ((109920, 109975), 'Gilly_Utilities.flatten', 'gu.flatten', (['data'], {'type': '"""ndarray"""', 'dtype': 'float', 'level': '(-1)'}), "(data, type='ndarray', dtype=float, level=-1)\n", (109930, 109975), True, 'import Gilly_Utilities as gu\n'), ((111760, 111837), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_IR_Liquid', 'Cloud_IR_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_IR_Liquid, Cloud_IR_Ice, alternative='two-sided')\n", (111781, 111837), True, 'import scipy as sp\n'), ((112070, 112149), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_IR_Liquid', 'Cloud_IR_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_IR_Liquid, Cloud_IR_Mixed, alternative='two-sided')\n", (112091, 112149), True, 'import scipy as sp\n'), ((112378, 112454), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_IR_Ice', 'Cloud_IR_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_IR_Ice, Cloud_IR_Mixed, alternative='two-sided')\n", (112399, 112454), True, 'import scipy as sp\n'), ((112715, 112808), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_IR_Mixed_Liquid', 'Cloud_IR_Mixed_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_IR_Mixed_Liquid, Cloud_IR_Mixed_Ice,\n alternative='two-sided')\n", (112736, 112808), True, 'import scipy as sp\n'), ((113078, 113156), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_IR_Liquid', 'Cloud_IR_Liquid'], {'alternative': '"""two-sided"""'}), "(Air_IR_Liquid, Cloud_IR_Liquid, alternative='two-sided')\n", (113099, 113156), True, 'import scipy as sp\n'), ((113405, 113477), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_IR_Ice', 'Cloud_IR_Ice'], {'alternative': '"""two-sided"""'}), "(Air_IR_Ice, Cloud_IR_Ice, alternative='two-sided')\n", (113426, 113477), True, 'import scipy as sp\n'), ((113722, 113798), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_IR_Mixed', 'Cloud_IR_Mixed'], {'alternative': '"""two-sided"""'}), "(Air_IR_Mixed, Cloud_IR_Mixed, alternative='two-sided')\n", (113743, 113798), True, 'import scipy as sp\n'), ((116671, 116757), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_Cyan_Liquid', 'Cloud_Cyan_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_Cyan_Liquid, Cloud_Cyan_Ice, alternative=\n 'two-sided')\n", (116692, 116757), True, 'import scipy as sp\n'), ((116991, 117079), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_Cyan_Liquid', 'Cloud_Cyan_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_Cyan_Liquid, Cloud_Cyan_Mixed, alternative=\n 'two-sided')\n", (117012, 117079), True, 'import scipy as sp\n'), ((117309, 117394), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_Cyan_Ice', 'Cloud_Cyan_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_Cyan_Ice, Cloud_Cyan_Mixed, alternative='two-sided'\n )\n", (117330, 117394), True, 'import scipy as sp\n'), ((117656, 117753), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_Cyan_Mixed_Liquid', 'Cloud_Cyan_Mixed_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_Cyan_Mixed_Liquid, Cloud_Cyan_Mixed_Ice,\n alternative='two-sided')\n", (117677, 117753), True, 'import scipy as sp\n'), ((118029, 118116), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_Cyan_Liquid', 'Cloud_Cyan_Liquid'], {'alternative': '"""two-sided"""'}), "(Air_Cyan_Liquid, Cloud_Cyan_Liquid, alternative=\n 'two-sided')\n", (118050, 118116), True, 'import scipy as sp\n'), ((118366, 118442), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_Cyan_Ice', 'Cloud_Cyan_Ice'], {'alternative': '"""two-sided"""'}), "(Air_Cyan_Ice, Cloud_Cyan_Ice, alternative='two-sided')\n", (118387, 118442), True, 'import scipy as sp\n'), ((118693, 118778), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_Cyan_Mixed', 'Cloud_Cyan_Mixed'], {'alternative': '"""two-sided"""'}), "(Air_Cyan_Mixed, Cloud_Cyan_Mixed, alternative='two-sided'\n )\n", (118714, 118778), True, 'import scipy as sp\n'), ((121740, 121837), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_IRdiffCyan_Liquid', 'Cloud_IRdiffCyan_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_IRdiffCyan_Liquid, Cloud_IRdiffCyan_Ice,\n alternative='two-sided')\n", (121761, 121837), True, 'import scipy as sp\n'), ((122072, 122160), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_Cyan_Liquid', 'Cloud_Cyan_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_Cyan_Liquid, Cloud_Cyan_Mixed, alternative=\n 'two-sided')\n", (122093, 122160), True, 'import scipy as sp\n'), ((122390, 122475), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_Cyan_Ice', 'Cloud_Cyan_Mixed'], {'alternative': '"""two-sided"""'}), "(Cloud_Cyan_Ice, Cloud_Cyan_Mixed, alternative='two-sided'\n )\n", (122411, 122475), True, 'import scipy as sp\n'), ((122737, 122834), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Cloud_Cyan_Mixed_Liquid', 'Cloud_Cyan_Mixed_Ice'], {'alternative': '"""two-sided"""'}), "(Cloud_Cyan_Mixed_Liquid, Cloud_Cyan_Mixed_Ice,\n alternative='two-sided')\n", (122758, 122834), True, 'import scipy as sp\n'), ((123110, 123197), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_Cyan_Liquid', 'Cloud_Cyan_Liquid'], {'alternative': '"""two-sided"""'}), "(Air_Cyan_Liquid, Cloud_Cyan_Liquid, alternative=\n 'two-sided')\n", (123131, 123197), True, 'import scipy as sp\n'), ((123447, 123523), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_Cyan_Ice', 'Cloud_Cyan_Ice'], {'alternative': '"""two-sided"""'}), "(Air_Cyan_Ice, Cloud_Cyan_Ice, alternative='two-sided')\n", (123468, 123523), True, 'import scipy as sp\n'), ((123774, 123859), 'scipy.stats.mannwhitneyu', 'sp.stats.mannwhitneyu', (['Air_Cyan_Mixed', 'Cloud_Cyan_Mixed'], {'alternative': '"""two-sided"""'}), "(Air_Cyan_Mixed, Cloud_Cyan_Mixed, alternative='two-sided'\n )\n", (123795, 123859), True, 'import scipy as sp\n'), ((128297, 128319), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(210)', '(0)', '(46)'], {}), '(210, 0, 46)\n', (128307, 128319), True, 'import Gilly_Utilities as gu\n'), ((128319, 128342), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(0)', '(112)', '(192)'], {}), '(0, 112, 192)\n', (128329, 128342), True, 'import Gilly_Utilities as gu\n'), ((128342, 128366), 'Gilly_Utilities.rgb2hex', 'gu.rgb2hex', (['(146)', '(208)', '(80)'], {}), '(146, 208, 80)\n', (128352, 128366), True, 'import Gilly_Utilities as gu\n'), ((128792, 128817), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (128815, 128817), False, 'import warnings\n'), ((128824, 128855), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (128845, 128855), False, 'import warnings\n'), ((128881, 128984), 'scipy.stats.anderson_ksamp', 'sp.stats.anderson_ksamp', (['(Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Liquid, Cloud_SpaceCharge_Mixed)'], {}), '((Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Liquid,\n Cloud_SpaceCharge_Mixed))\n', (128904, 128984), True, 'import scipy as sp\n'), ((131890, 131901), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (131898, 131901), True, 'import numpy as np\n'), ((132060, 132086), 'scipy.stats.linregress', 'sp.stats.linregress', (['*data'], {}), '(*data)\n', (132079, 132086), True, 'import scipy as sp\n'), ((146016, 146046), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (['Height', 'cloud'], {}), '(Height, cloud)\n', (146031, 146046), True, 'import Gilly_Utilities as gu\n'), ((149320, 149427), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IR', '(15)'], {'method': '"""ma"""', 'average': '"""mean"""', 'undersample': '(True)', 'slim': '(False)'}), "(Cloud_SpaceCharge, Cloud_IR, 15, method='ma', average='mean',\n undersample=True, slim=False)\n", (149331, 149427), True, 'import Gilly_Utilities as gu\n'), ((151000, 151107), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_Cyan', '(2)'], {'method': '"""ma"""', 'average': '"""mean"""', 'undersample': '(True)', 'slim': '(True)'}), "(Cloud_SpaceCharge, Cloud_Cyan, 2, method='ma', average='mean',\n undersample=True, slim=True)\n", (151011, 151107), True, 'import Gilly_Utilities as gu\n'), ((152062, 152176), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IRdiffCyan', '(2)'], {'method': '"""ma"""', 'average': '"""mean"""', 'undersample': '(True)', 'slim': '(True)'}), "(Cloud_SpaceCharge, Cloud_IRdiffCyan, 2, method='ma', average=\n 'mean', undersample=True, slim=True)\n", (152073, 152176), True, 'import Gilly_Utilities as gu\n'), ((153165, 153278), 'Gilly_Utilities.ensemble', 'gu.ensemble', (['Cloud_SpaceCharge', 'Cloud_IRdivCyan', '(2)'], {'method': '"""ma"""', 'average': '"""mean"""', 'undersample': '(True)', 'slim': '(True)'}), "(Cloud_SpaceCharge, Cloud_IRdivCyan, 2, method='ma', average=\n 'mean', undersample=True, slim=True)\n", (153176, 153278), True, 'import Gilly_Utilities as gu\n'), ((154180, 154237), 'scipy.stats.spearmanr', 'sp.stats.spearmanr', (['Cloud_SpaceCharge_Best', 'Cloud_IR_Best'], {}), '(Cloud_SpaceCharge_Best, Cloud_IR_Best)\n', (154198, 154237), True, 'import scipy as sp\n'), ((154568, 154583), 'numpy.arange', 'np.arange', (['(3)', '(6)'], {}), '(3, 6)\n', (154577, 154583), True, 'import numpy as np\n'), ((156510, 156540), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (['Height', 'cloud'], {}), '(Height, cloud)\n', (156525, 156540), True, 'import Gilly_Utilities as gu\n'), ((159516, 159532), 'numpy.arange', 'np.arange', (['(3)', '(11)'], {}), '(3, 11)\n', (159525, 159532), True, 'import numpy as np\n'), ((160657, 160687), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (['Height', 'cloud'], {}), '(Height, cloud)\n', (160672, 160687), True, 'import Gilly_Utilities as gu\n'), ((160966, 161002), 'Gilly_Utilities.broadcast', 'gu.broadcast', (['Cloud_SignChange', '(2)', '(1)'], {}), '(Cloud_SignChange, 2, 1)\n', (160978, 161002), True, 'import Gilly_Utilities as gu\n'), ((161377, 161405), 'Gilly_Utilities.searchsorted', 'gu.searchsorted', (['Height', 'air'], {}), '(Height, air)\n', (161392, 161405), True, 'import Gilly_Utilities as gu\n'), ((161674, 161708), 'Gilly_Utilities.broadcast', 'gu.broadcast', (['Air_SignChange', '(2)', '(1)'], {}), '(Air_SignChange, 2, 1)\n', (161686, 161708), True, 'import Gilly_Utilities as gu\n'), ((163227, 163280), 'numpy.hstack', 'np.hstack', (['(Cloud_SignChange_All, Air_SignChange_All)'], {}), '((Cloud_SignChange_All, Air_SignChange_All))\n', (163236, 163280), True, 'import numpy as np\n'), ((164579, 164599), 'numpy.nanmin', 'np.nanmin', (['all_xdata'], {}), '(all_xdata)\n', (164588, 164599), True, 'import numpy as np\n'), ((164601, 164621), 'numpy.nanmax', 'np.nanmax', (['all_xdata'], {}), '(all_xdata)\n', (164610, 164621), True, 'import numpy as np\n'), ((164643, 164663), 'numpy.nanmin', 'np.nanmin', (['all_ydata'], {}), '(all_ydata)\n', (164652, 164663), True, 'import numpy as np\n'), ((164665, 164685), 'numpy.nanmax', 'np.nanmax', (['all_ydata'], {}), '(all_ydata)\n', (164674, 164685), True, 'import numpy as np\n'), ((164707, 164727), 'numpy.nanmin', 'np.nanmin', (['all_xdata'], {}), '(all_xdata)\n', (164716, 164727), True, 'import numpy as np\n'), ((164729, 164749), 'numpy.nanmax', 'np.nanmax', (['all_xdata'], {}), '(all_xdata)\n', (164738, 164749), True, 'import numpy as np\n'), ((164771, 164791), 'numpy.nanmin', 'np.nanmin', (['all_ydata'], {}), '(all_ydata)\n', (164780, 164791), True, 'import numpy as np\n'), ((164793, 164813), 'numpy.nanmax', 'np.nanmax', (['all_ydata'], {}), '(all_ydata)\n', (164802, 164813), True, 'import numpy as np\n'), ((167712, 167775), 'numpy.random.choice', 'np.random.choice', (['Cloud_SignChange_All', 'Air_SignChange_All.size'], {}), '(Cloud_SignChange_All, Air_SignChange_All.size)\n', (167728, 167775), True, 'import numpy as np\n'), ((172227, 172244), 'numpy.nanmin', 'np.nanmin', (['Height'], {}), '(Height)\n', (172236, 172244), True, 'import numpy as np\n'), ((172246, 172263), 'numpy.nanmax', 'np.nanmax', (['Height'], {}), '(Height)\n', (172255, 172263), True, 'import numpy as np\n'), ((173160, 173182), 'numpy.nanmin', 'np.nanmin', (['Temperature'], {}), '(Temperature)\n', (173169, 173182), True, 'import numpy as np\n'), ((173184, 173206), 'numpy.nanmax', 'np.nanmax', (['Temperature'], {}), '(Temperature)\n', (173193, 173206), True, 'import numpy as np\n'), ((173263, 173289), 'Gilly_Utilities.argnear', 'gu.argnear', (['Temperature', '(0)'], {}), '(Temperature, 0)\n', (173273, 173289), True, 'import Gilly_Utilities as gu\n'), ((173618, 173676), 'os.path.dirname', 'os.path.dirname', (['self.Radiosonde_File[self.sensor_package]'], {}), '(self.Radiosonde_File[self.sensor_package])\n', (173633, 173676), False, 'import os\n'), ((186249, 186279), 'Gilly_Utilities.bool2int', 'gu.bool2int', (['(Error_Mask == val)'], {}), '(Error_Mask == val)\n', (186260, 186279), True, 'import Gilly_Utilities as gu\n'), ((186335, 186356), 'numpy.unique', 'np.unique', (['Error_Mask'], {}), '(Error_Mask)\n', (186344, 186356), True, 'import numpy as np\n'), ((187460, 187489), 'numpy.nanmin', 'np.nanmin', (['Lightning_Distance'], {}), '(Lightning_Distance)\n', (187469, 187489), True, 'import numpy as np\n'), ((188945, 188965), 'numpy.max', 'np.max', (['plot_version'], {}), '(plot_version)\n', (188951, 188965), True, 'import numpy as np\n'), ((194991, 195011), 'numpy.max', 'np.max', (['plot_version'], {}), '(plot_version)\n', (194997, 195011), True, 'import numpy as np\n'), ((195705, 195716), 'time.time', 'time.time', ([], {}), '()\n', (195714, 195716), False, 'import time\n'), ((201973, 202014), 'Gilly_Utilities.antinan', 'gu.antinan', (["Linear_Cal['Voltage_Sensor3']"], {}), "(Linear_Cal['Voltage_Sensor3'])\n", (201983, 202014), True, 'import Gilly_Utilities as gu\n'), ((202016, 202070), 'Gilly_Utilities.antinan', 'gu.antinan', (["Linear_Cal['Voltage_Sensor4']"], {'unpack': '(True)'}), "(Linear_Cal['Voltage_Sensor4'], unpack=True)\n", (202026, 202070), True, 'import Gilly_Utilities as gu\n'), ((202084, 202122), 'Gilly_Utilities.antinan', 'gu.antinan', (["Log_Cal['Voltage_Sensor3']"], {}), "(Log_Cal['Voltage_Sensor3'])\n", (202094, 202122), True, 'import Gilly_Utilities as gu\n'), ((202124, 202175), 'Gilly_Utilities.antinan', 'gu.antinan', (["Log_Cal['Voltage_Sensor4']"], {'unpack': '(True)'}), "(Log_Cal['Voltage_Sensor4'], unpack=True)\n", (202134, 202175), True, 'import Gilly_Utilities as gu\n'), ((12660, 12719), 'Extras.WC3_Extras.GPS2UTC', 'GPS2UTC', (["GPS_Data['GPS_Week'][0]", "GPS_Data['GPS_Second'][0]"], {}), "(GPS_Data['GPS_Week'][0], GPS_Data['GPS_Second'][0])\n", (12667, 12719), False, 'from Extras.WC3_Extras import GPS2UTC, CloudDrift, Radiosonde_Launch\n'), ((31360, 31386), 'numpy.sign', 'np.sign', (['Local_SpaceCharge'], {}), '(Local_SpaceCharge)\n', (31367, 31386), True, 'import numpy as np\n'), ((39120, 39131), 'time.time', 'time.time', ([], {}), '()\n', (39129, 39131), False, 'import time\n'), ((44880, 45000), 'Gilly_Utilities.cprint', 'gu.cprint', (['"""[WARNING] No Larkhill (03743) sounding data was found within 24hrs of the ascent!"""'], {'type': '"""warning"""'}), "(\n '[WARNING] No Larkhill (03743) sounding data was found within 24hrs of the ascent!'\n , type='warning')\n", (44889, 45000), True, 'import Gilly_Utilities as gu\n'), ((46411, 46431), 'numpy.max', 'np.max', (['plot_version'], {}), '(plot_version)\n', (46417, 46431), True, 'import numpy as np\n'), ((52395, 52424), 'numpy.log', 'np.log', (['(Pres[i] / Pres[i + 1])'], {}), '(Pres[i] / Pres[i + 1])\n', (52401, 52424), True, 'import numpy as np\n'), ((52641, 52670), 'numpy.log', 'np.log', (['(Pres[i] / Pres[i + 1])'], {}), '(Pres[i] / Pres[i + 1])\n', (52647, 52670), True, 'import numpy as np\n'), ((56109, 56222), 'PG_Quickplotter.PG_Plotter', 'PG_Plotter', ([], {'Location': '"""RUAO"""', 'Date_Start': 'Date_Start', 'Date_End': 'Date_End', 'Print_Progress': '(False)', 'Return_Data': '(True)'}), "(Location='RUAO', Date_Start=Date_Start, Date_End=Date_End,\n Print_Progress=False, Return_Data=True)\n", (56119, 56222), False, 'from PG_Quickplotter import PG_Plotter\n'), ((57443, 57476), 'Gilly_Utilities.isnat', 'gu.isnat', (['self.LaunchTime[sensor]'], {}), '(self.LaunchTime[sensor])\n', (57451, 57476), True, 'import Gilly_Utilities as gu\n'), ((65135, 65170), 'matplotlib.pyplot.imread', 'plt.imread', (['Satellite_Imagery[i]', '(0)'], {}), '(Satellite_Imagery[i], 0)\n', (65145, 65170), True, 'import matplotlib.pyplot as plt\n'), ((70788, 70901), 'PG_Quickplotter.PG_Plotter', 'PG_Plotter', ([], {'Location': '"""RUAO"""', 'Date_Start': 'Date_Start', 'Date_End': 'Date_End', 'Print_Progress': '(False)', 'Return_Data': '(True)'}), "(Location='RUAO', Date_Start=Date_Start, Date_End=Date_End,\n Print_Progress=False, Return_Data=True)\n", (70798, 70901), False, 'from PG_Quickplotter import PG_Plotter\n'), ((71902, 71935), 'Gilly_Utilities.isnat', 'gu.isnat', (['self.LaunchTime[sensor]'], {}), '(self.LaunchTime[sensor])\n', (71910, 71935), True, 'import Gilly_Utilities as gu\n'), ((78225, 78246), 'numpy.arange', 'np.arange', (['(-50)', '(90)', '(5)'], {}), '(-50, 90, 5)\n', (78234, 78246), True, 'import numpy as np\n'), ((78329, 78350), 'numpy.arange', 'np.arange', (['(-50)', '(50)', '(5)'], {}), '(-50, 50, 5)\n', (78338, 78350), True, 'import numpy as np\n'), ((78582, 78614), 'matplotlib.pyplot.imread', 'plt.imread', (['Satellite_Imagery', '(0)'], {}), '(Satellite_Imagery, 0)\n', (78592, 78614), True, 'import matplotlib.pyplot as plt\n'), ((78629, 78645), 'numpy.flipud', 'np.flipud', (['image'], {}), '(image)\n', (78638, 78645), True, 'import numpy as np\n'), ((91577, 91617), 'numpy.nanpercentile', 'np.nanpercentile', (['SpaceCharge_Subset', '(95)'], {}), '(SpaceCharge_Subset, 95)\n', (91593, 91617), True, 'import numpy as np\n'), ((91640, 91671), 'numpy.nanpercentile', 'np.nanpercentile', (['IR_Subset', '(95)'], {}), '(IR_Subset, 95)\n', (91656, 91671), True, 'import numpy as np\n'), ((91696, 91729), 'numpy.nanpercentile', 'np.nanpercentile', (['Cyan_Subset', '(95)'], {}), '(Cyan_Subset, 95)\n', (91712, 91729), True, 'import numpy as np\n'), ((91760, 91799), 'numpy.nanpercentile', 'np.nanpercentile', (['IRdiffCyan_Subset', '(95)'], {}), '(IRdiffCyan_Subset, 95)\n', (91776, 91799), True, 'import numpy as np\n'), ((91829, 91868), 'numpy.nanpercentile', 'np.nanpercentile', (['IRdiffCyan_Subset', '(95)'], {}), '(IRdiffCyan_Subset, 95)\n', (91845, 91868), True, 'import numpy as np\n'), ((94461, 94501), 'numpy.nanpercentile', 'np.nanpercentile', (['SpaceCharge_Subset', '(95)'], {}), '(SpaceCharge_Subset, 95)\n', (94477, 94501), True, 'import numpy as np\n'), ((94522, 94553), 'numpy.nanpercentile', 'np.nanpercentile', (['IR_Subset', '(95)'], {}), '(IR_Subset, 95)\n', (94538, 94553), True, 'import numpy as np\n'), ((94576, 94609), 'numpy.nanpercentile', 'np.nanpercentile', (['Cyan_Subset', '(95)'], {}), '(Cyan_Subset, 95)\n', (94592, 94609), True, 'import numpy as np\n'), ((94638, 94677), 'numpy.nanpercentile', 'np.nanpercentile', (['IRdiffCyan_Subset', '(95)'], {}), '(IRdiffCyan_Subset, 95)\n', (94654, 94677), True, 'import numpy as np\n'), ((94705, 94743), 'numpy.nanpercentile', 'np.nanpercentile', (['IRdivCyan_Subset', '(95)'], {}), '(IRdivCyan_Subset, 95)\n', (94721, 94743), True, 'import numpy as np\n'), ((100915, 100985), 'numpy.random.choice', 'np.random.choice', (['Cloud_SpaceCharge_Ice', 'Cloud_SpaceCharge_Liquid.size'], {}), '(Cloud_SpaceCharge_Ice, Cloud_SpaceCharge_Liquid.size)\n', (100931, 100985), True, 'import numpy as np\n'), ((101272, 101344), 'numpy.random.choice', 'np.random.choice', (['Cloud_SpaceCharge_Mixed', 'Cloud_SpaceCharge_Liquid.size'], {}), '(Cloud_SpaceCharge_Mixed, Cloud_SpaceCharge_Liquid.size)\n', (101288, 101344), True, 'import numpy as np\n'), ((101619, 101688), 'numpy.random.choice', 'np.random.choice', (['Cloud_SpaceCharge_Mixed', 'Cloud_SpaceCharge_Ice.size'], {}), '(Cloud_SpaceCharge_Mixed, Cloud_SpaceCharge_Ice.size)\n', (101635, 101688), True, 'import numpy as np\n'), ((102023, 102109), 'numpy.random.choice', 'np.random.choice', (['Cloud_SpaceCharge_Mixed_Ice', 'Cloud_SpaceCharge_Mixed_Liquid.size'], {}), '(Cloud_SpaceCharge_Mixed_Ice,\n Cloud_SpaceCharge_Mixed_Liquid.size)\n', (102039, 102109), True, 'import numpy as np\n'), ((102412, 102483), 'numpy.random.choice', 'np.random.choice', (['Cloud_SpaceCharge_Liquid', 'Air_SpaceCharge_Liquid.size'], {}), '(Cloud_SpaceCharge_Liquid, Air_SpaceCharge_Liquid.size)\n', (102428, 102483), True, 'import numpy as np\n'), ((102775, 102840), 'numpy.random.choice', 'np.random.choice', (['Cloud_SpaceCharge_Ice', 'Air_SpaceCharge_Ice.size'], {}), '(Cloud_SpaceCharge_Ice, Air_SpaceCharge_Ice.size)\n', (102791, 102840), True, 'import numpy as np\n'), ((103143, 103212), 'numpy.random.choice', 'np.random.choice', (['Cloud_SpaceCharge_Mixed', 'Air_SpaceCharge_Mixed.size'], {}), '(Cloud_SpaceCharge_Mixed, Air_SpaceCharge_Mixed.size)\n', (103159, 103212), True, 'import numpy as np\n'), ((111913, 111965), 'numpy.random.choice', 'np.random.choice', (['Cloud_IR_Ice', 'Cloud_IR_Liquid.size'], {}), '(Cloud_IR_Ice, Cloud_IR_Liquid.size)\n', (111929, 111965), True, 'import numpy as np\n'), ((112225, 112279), 'numpy.random.choice', 'np.random.choice', (['Cloud_IR_Mixed', 'Cloud_IR_Liquid.size'], {}), '(Cloud_IR_Mixed, Cloud_IR_Liquid.size)\n', (112241, 112279), True, 'import numpy as np\n'), ((112527, 112578), 'numpy.random.choice', 'np.random.choice', (['Cloud_IR_Mixed', 'Cloud_IR_Ice.size'], {}), '(Cloud_IR_Mixed, Cloud_IR_Ice.size)\n', (112543, 112578), True, 'import numpy as np\n'), ((112886, 112950), 'numpy.random.choice', 'np.random.choice', (['Cloud_IR_Mixed_Ice', 'Cloud_IR_Mixed_Liquid.size'], {}), '(Cloud_IR_Mixed_Ice, Cloud_IR_Mixed_Liquid.size)\n', (112902, 112950), True, 'import numpy as np\n'), ((113230, 113283), 'numpy.random.choice', 'np.random.choice', (['Cloud_IR_Liquid', 'Air_IR_Liquid.size'], {}), '(Cloud_IR_Liquid, Air_IR_Liquid.size)\n', (113246, 113283), True, 'import numpy as np\n'), ((113548, 113595), 'numpy.random.choice', 'np.random.choice', (['Cloud_IR_Ice', 'Air_IR_Ice.size'], {}), '(Cloud_IR_Ice, Air_IR_Ice.size)\n', (113564, 113595), True, 'import numpy as np\n'), ((113871, 113922), 'numpy.random.choice', 'np.random.choice', (['Cloud_IR_Mixed', 'Air_IR_Mixed.size'], {}), '(Cloud_IR_Mixed, Air_IR_Mixed.size)\n', (113887, 113922), True, 'import numpy as np\n'), ((116830, 116886), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Ice', 'Cloud_Cyan_Liquid.size'], {}), '(Cloud_Cyan_Ice, Cloud_Cyan_Liquid.size)\n', (116846, 116886), True, 'import numpy as np\n'), ((117152, 117210), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed', 'Cloud_Cyan_Liquid.size'], {}), '(Cloud_Cyan_Mixed, Cloud_Cyan_Liquid.size)\n', (117168, 117210), True, 'import numpy as np\n'), ((117464, 117519), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed', 'Cloud_Cyan_Ice.size'], {}), '(Cloud_Cyan_Mixed, Cloud_Cyan_Ice.size)\n', (117480, 117519), True, 'import numpy as np\n'), ((117833, 117901), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed_Ice', 'Cloud_Cyan_Mixed_Liquid.size'], {}), '(Cloud_Cyan_Mixed_Ice, Cloud_Cyan_Mixed_Liquid.size)\n', (117849, 117901), True, 'import numpy as np\n'), ((118187, 118244), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Liquid', 'Air_Cyan_Liquid.size'], {}), '(Cloud_Cyan_Liquid, Air_Cyan_Liquid.size)\n', (118203, 118244), True, 'import numpy as np\n'), ((118515, 118566), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Ice', 'Air_Cyan_Ice.size'], {}), '(Cloud_Cyan_Ice, Air_Cyan_Ice.size)\n', (118531, 118566), True, 'import numpy as np\n'), ((118848, 118903), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed', 'Air_Cyan_Mixed.size'], {}), '(Cloud_Cyan_Mixed, Air_Cyan_Mixed.size)\n', (118864, 118903), True, 'import numpy as np\n'), ((121911, 121967), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Ice', 'Cloud_Cyan_Liquid.size'], {}), '(Cloud_Cyan_Ice, Cloud_Cyan_Liquid.size)\n', (121927, 121967), True, 'import numpy as np\n'), ((122233, 122291), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed', 'Cloud_Cyan_Liquid.size'], {}), '(Cloud_Cyan_Mixed, Cloud_Cyan_Liquid.size)\n', (122249, 122291), True, 'import numpy as np\n'), ((122545, 122600), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed', 'Cloud_Cyan_Ice.size'], {}), '(Cloud_Cyan_Mixed, Cloud_Cyan_Ice.size)\n', (122561, 122600), True, 'import numpy as np\n'), ((122914, 122982), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed_Ice', 'Cloud_Cyan_Mixed_Liquid.size'], {}), '(Cloud_Cyan_Mixed_Ice, Cloud_Cyan_Mixed_Liquid.size)\n', (122930, 122982), True, 'import numpy as np\n'), ((123268, 123325), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Liquid', 'Air_Cyan_Liquid.size'], {}), '(Cloud_Cyan_Liquid, Air_Cyan_Liquid.size)\n', (123284, 123325), True, 'import numpy as np\n'), ((123596, 123647), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Ice', 'Air_Cyan_Ice.size'], {}), '(Cloud_Cyan_Ice, Air_Cyan_Ice.size)\n', (123612, 123647), True, 'import numpy as np\n'), ((123929, 123984), 'numpy.random.choice', 'np.random.choice', (['Cloud_Cyan_Mixed', 'Air_Cyan_Mixed.size'], {}), '(Cloud_Cyan_Mixed, Air_Cyan_Mixed.size)\n', (123945, 123984), True, 'import numpy as np\n'), ((133495, 133536), 'Gilly_Utilities.hide_axis', 'gu.hide_axis', ([], {'ax': 'ax[row, col]', 'x_or_y': '"""x"""'}), "(ax=ax[row, col], x_or_y='x')\n", (133507, 133536), True, 'import Gilly_Utilities as gu\n'), ((141344, 141402), 'Gilly_Utilities.cosarctan', 'gu.cosarctan', (['((Cloud_Time + time_diff) * velocity / height)'], {}), '((Cloud_Time + time_diff) * velocity / height)\n', (141356, 141402), True, 'import Gilly_Utilities as gu\n'), ((148338, 148394), 'statsmodels.api.add_constant', 'sm.add_constant', (['Cloud_SpaceCharge_Ensemble_Unique[:, 0]'], {}), '(Cloud_SpaceCharge_Ensemble_Unique[:, 0])\n', (148353, 148394), True, 'import statsmodels.api as sm\n'), ((156295, 156350), 'numpy.abs', 'np.abs', (["Radiosonde_Data[sensor]['Units']['SpaceCharge']"], {}), "(Radiosonde_Data[sensor]['Units']['SpaceCharge'])\n", (156301, 156350), True, 'import numpy as np\n'), ((165286, 165331), 'numpy.sort', 'np.sort', (['Air_SignChange_All'], {'kind': '"""mergesort"""'}), "(Air_SignChange_All, kind='mergesort')\n", (165293, 165331), True, 'import numpy as np\n'), ((165457, 165504), 'numpy.sort', 'np.sort', (['Cloud_SignChange_All'], {'kind': '"""mergesort"""'}), "(Cloud_SignChange_All, kind='mergesort')\n", (165464, 165504), True, 'import numpy as np\n'), ((165655, 165684), 'numpy.size', 'np.size', (['Cloud_SignChange_All'], {}), '(Cloud_SignChange_All)\n', (165662, 165684), True, 'import numpy as np\n'), ((165904, 165931), 'numpy.size', 'np.size', (['Air_SignChange_All'], {}), '(Air_SignChange_All)\n', (165911, 165931), True, 'import numpy as np\n'), ((174156, 174176), 'numpy.max', 'np.max', (['plot_version'], {}), '(plot_version)\n', (174162, 174176), True, 'import numpy as np\n'), ((174861, 174895), 'numpy.linspace', 'np.linspace', (['(20)', '(-100)', 'data_points'], {}), '(20, -100, data_points)\n', (174872, 174895), True, 'import numpy as np\n'), ((174905, 174947), 'numpy.full', 'np.full', (['data_points', '(50)'], {'dtype': 'np.float64'}), '(data_points, 50, dtype=np.float64)\n', (174912, 174947), True, 'import numpy as np\n'), ((178252, 178263), 'time.time', 'time.time', ([], {}), '()\n', (178261, 178263), False, 'import time\n'), ((183283, 183313), 'Gilly_Utilities.toDateOnly', 'gu.toDateOnly', (['Launch_Datetime'], {}), '(Launch_Datetime)\n', (183296, 183313), True, 'import Gilly_Utilities as gu\n'), ((186284, 186314), 'Gilly_Utilities.bool2int', 'gu.bool2int', (['(Error_Mask == val)'], {}), '(Error_Mask == val)\n', (186295, 186314), True, 'import Gilly_Utilities as gu\n'), ((7316, 7370), 'Gilly_Utilities.string_checker', 'gu.string_checker', (['file_check', 'tester'], {'condition': '"""all"""'}), "(file_check, tester, condition='all')\n", (7333, 7370), True, 'import Gilly_Utilities as gu\n'), ((14426, 14456), 'numpy.datetime64', 'np.datetime64', (['Launch_Datetime'], {}), '(Launch_Datetime)\n', (14439, 14456), True, 'import numpy as np\n'), ((24459, 24482), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (24475, 24482), False, 'import os\n'), ((26407, 26427), 'numpy.unique', 'np.unique', (['Clouds_ID'], {}), '(Clouds_ID)\n', (26416, 26427), True, 'import numpy as np\n'), ((26766, 26785), 'numpy.unique', 'np.unique', (['Clear_ID'], {}), '(Clear_ID)\n', (26775, 26785), True, 'import numpy as np\n'), ((38391, 38414), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (38407, 38414), False, 'import os\n'), ((43563, 43627), 'numpy.abs', 'np.abs', (['(self.Launch_Datetime[self.sensor_package] - ULS_Date[ID])'], {}), '(self.Launch_Datetime[self.sensor_package] - ULS_Date[ID])\n', (43569, 43627), True, 'import numpy as np\n'), ((44041, 44081), 'Gilly_Utilities.argnear', 'gu.argnear', (['press_larkhill', 'Pres_Plot[0]'], {}), '(press_larkhill, Pres_Plot[0])\n', (44051, 44081), True, 'import Gilly_Utilities as gu\n'), ((44083, 44124), 'Gilly_Utilities.argnear', 'gu.argnear', (['press_larkhill', 'Pres_Plot[-1]'], {}), '(press_larkhill, Pres_Plot[-1])\n', (44093, 44124), True, 'import Gilly_Utilities as gu\n'), ((55912, 55934), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""h"""'], {}), "(1, 'h')\n", (55926, 55934), True, 'import numpy as np\n'), ((56004, 56026), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""h"""'], {}), "(1, 'h')\n", (56018, 56026), True, 'import numpy as np\n'), ((61994, 62048), 'datetime.datetime.strptime', 'datetime.strptime', (['bullet[:23]', '"""%d %b %Y at %H%M UTC"""'], {}), "(bullet[:23], '%d %b %Y at %H%M UTC')\n", (62011, 62048), False, 'from datetime import datetime, timedelta\n'), ((64475, 64496), 'numpy.arange', 'np.arange', (['(-50)', '(90)', '(5)'], {}), '(-50, 90, 5)\n', (64484, 64496), True, 'import numpy as np\n'), ((64610, 64631), 'numpy.arange', 'np.arange', (['(-50)', '(90)', '(5)'], {}), '(-50, 90, 5)\n', (64619, 64631), True, 'import numpy as np\n'), ((64747, 64769), 'numpy.arange', 'np.arange', (['(-50)', '(50)', '(10)'], {}), '(-50, 50, 10)\n', (64756, 64769), True, 'import numpy as np\n'), ((65188, 65204), 'numpy.flipud', 'np.flipud', (['image'], {}), '(image)\n', (65197, 65204), True, 'import numpy as np\n'), ((70336, 70359), 'numpy.timedelta64', 'np.timedelta64', (['(60)', '"""m"""'], {}), "(60, 'm')\n", (70350, 70359), True, 'import numpy as np\n'), ((70429, 70452), 'numpy.timedelta64', 'np.timedelta64', (['(60)', '"""m"""'], {}), "(60, 'm')\n", (70443, 70452), True, 'import numpy as np\n'), ((75985, 76039), 'datetime.datetime.strptime', 'datetime.strptime', (['bullet[:23]', '"""%d %b %Y at %H%M UTC"""'], {}), "(bullet[:23], '%d %b %Y at %H%M UTC')\n", (76002, 76039), False, 'from datetime import datetime, timedelta\n'), ((145389, 145444), 'numpy.abs', 'np.abs', (["Radiosonde_Data[sensor]['Units']['SpaceCharge']"], {}), "(Radiosonde_Data[sensor]['Units']['SpaceCharge'])\n", (145395, 145444), True, 'import numpy as np\n'), ((160518, 160538), 'numpy.sign', 'np.sign', (['SpaceCharge'], {}), '(SpaceCharge)\n', (160525, 160538), True, 'import numpy as np\n'), ((161182, 161207), 'numpy.diff', 'np.diff', (['Cloud_TimeChange'], {}), '(Cloud_TimeChange)\n', (161189, 161207), True, 'import numpy as np\n'), ((161884, 161907), 'numpy.diff', 'np.diff', (['Air_TimeChange'], {}), '(Air_TimeChange)\n', (161891, 161907), True, 'import numpy as np\n'), ((188805, 188828), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (188821, 188828), False, 'import os\n'), ((194851, 194874), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (194867, 194874), False, 'import os\n'), ((11964, 12232), 'pandas.read_csv', 'pd.read_csv', (['self.GPS_File[0]'], {'sep': '"""\t"""', 'skiprows': '(51)', 'header': 'None', 'usecols': '(1, 2, 4)', 'names': "('GPS_Week', 'GPS_Second', 'SondeX')", 'dtype': "{'GPS_Week': np.int32, 'GPS_Second': np.float64, 'SondeX': np.float64}", 'na_values': '(-32768)', 'comment': '"""#"""', 'index_col': '(False)'}), "(self.GPS_File[0], sep='\\t', skiprows=51, header=None, usecols=(\n 1, 2, 4), names=('GPS_Week', 'GPS_Second', 'SondeX'), dtype={'GPS_Week':\n np.int32, 'GPS_Second': np.float64, 'SondeX': np.float64}, na_values=-\n 32768, comment='#', index_col=False)\n", (11975, 12232), True, 'import pandas as pd\n'), ((12606, 12634), 'numpy.isnan', 'np.isnan', (["GPS_Data['SondeX']"], {}), "(GPS_Data['SondeX'])\n", (12614, 12634), True, 'import numpy as np\n'), ((24542, 24565), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (24558, 24565), False, 'import os\n'), ((26966, 26990), 'numpy.nanpercentile', 'np.nanpercentile', (['IR', '(80)'], {}), '(IR, 80)\n', (26982, 26990), True, 'import numpy as np\n'), ((27098, 27122), 'numpy.nanpercentile', 'np.nanpercentile', (['IR', '(20)'], {}), '(IR, 20)\n', (27114, 27122), True, 'import numpy as np\n'), ((27399, 27419), 'numpy.unique', 'np.unique', (['Clouds_ID'], {}), '(Clouds_ID)\n', (27408, 27419), True, 'import numpy as np\n'), ((27699, 27718), 'numpy.unique', 'np.unique', (['Clear_ID'], {}), '(Clear_ID)\n', (27708, 27718), True, 'import numpy as np\n'), ((38474, 38497), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (38490, 38497), False, 'import os\n'), ((43189, 43211), 'os.path.basename', 'os.path.basename', (['file'], {}), '(file)\n', (43205, 43211), False, 'import os\n'), ((43279, 43299), 'datetime.datetime', 'datetime', (['(1900)', '(1)', '(1)'], {}), '(1900, 1, 1)\n', (43287, 43299), False, 'from datetime import datetime, timedelta\n'), ((46267, 46290), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (46283, 46290), False, 'import os\n'), ((58372, 58391), 'numpy.array', 'np.array', (['labels[i]'], {}), '(labels[i])\n', (58380, 58391), True, 'import numpy as np\n'), ((64889, 64910), 'numpy.arange', 'np.arange', (['(-50)', '(50)', '(5)'], {}), '(-50, 50, 5)\n', (64898, 64910), True, 'import numpy as np\n'), ((73136, 73152), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (73144, 73152), True, 'import numpy as np\n'), ((155522, 155550), 'numpy.unique', 'np.unique', (['Clouds_ID[sensor]'], {}), '(Clouds_ID[sensor])\n', (155531, 155550), True, 'import numpy as np\n'), ((155925, 155944), 'numpy.unique', 'np.unique', (['Clear_ID'], {}), '(Clear_ID)\n', (155934, 155944), True, 'import numpy as np\n'), ((161053, 161091), 'numpy.abs', 'np.abs', (['SpaceCharge[space[0]:space[1]]'], {}), '(SpaceCharge[space[0]:space[1]])\n', (161059, 161091), True, 'import numpy as np\n'), ((161757, 161795), 'numpy.abs', 'np.abs', (['SpaceCharge[space[0]:space[1]]'], {}), '(SpaceCharge[space[0]:space[1]])\n', (161763, 161795), True, 'import numpy as np\n'), ((174012, 174035), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (174028, 174035), False, 'import os\n'), ((188888, 188911), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (188904, 188911), False, 'import os\n'), ((194934, 194957), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (194950, 194957), False, 'import os\n'), ((46352, 46375), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (46368, 46375), False, 'import os\n'), ((174097, 174120), 'os.path.basename', 'os.path.basename', (['plots'], {}), '(plots)\n', (174113, 174120), False, 'import os\n')]
import mmcv import numpy as np import pycocotools.mask as mask_util import torch import torch.nn as nn import torch.nn.functional as F from ..builder import build_loss from ..registry import HEADS from ..utils import ConvModule from mmdet.core import mask_target, force_fp32, auto_fp16 import matplotlib.pyplot as plt import kornia @HEADS.register_module class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, upsample_method='deconv', upsample_ratio=2, num_classes=81, class_agnostic=False, conv_cfg=None, norm_cfg=None, use_maskopt=False, generate_weight=False, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() if upsample_method not in [None, 'deconv', 'nearest', 'bilinear']: raise ValueError( 'Invalid upsample method {}, accepted methods ' 'are "deconv", "nearest", "bilinear"'.format(upsample_method)) self.generate_weight = generate_weight self.num_convs = num_convs self.roi_feat_size = roi_feat_size # WARN: not used and reserved self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = upsample_method self.upsample_ratio = upsample_ratio self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) # TODO: change here self.use_maskopt = use_maskopt # if use_maskopt: # self.edge_det = kornia.filters.Sobel() # upsample_in_channels = ( # self.conv_out_channels if self.num_convs > 0 else in_channels) # out_channels = 1 if self.class_agnostic else self.num_classes # self.convs = nn.ModuleList() # for i in range(self.num_convs): # in_channels = ( # self.in_channels if i == 0 else self.conv_out_channels) # padding = (self.conv_kernel_size - 1) // 2 # self.convs.append( # ConvModule( # in_channels, # self.conv_out_channels, # self.conv_kernel_size, # padding=padding, # conv_cfg=conv_cfg, # norm_cfg=norm_cfg)) # if self.upsample_method is None: # self.upsample = None # elif self.upsample_method == 'deconv': # self.upsample = nn.ConvTranspose2d( # upsample_in_channels, # self.conv_out_channels, # self.upsample_ratio, # stride=self.upsample_ratio) # else: # self.upsample = nn.Upsample( # scale_factor=self.upsample_ratio, mode=self.upsample_method) # logits_in_channel = ( # self.conv_out_channels # if self.upsample_method == 'deconv' else upsample_in_channels) # self.conv_logits = nn.Conv2d(logits_in_channel, out_channels+1, 1) # else: self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else in_channels) if self.upsample_method is None: self.upsample = None elif self.upsample_method == 'deconv': self.upsample = nn.ConvTranspose2d( upsample_in_channels, self.conv_out_channels, self.upsample_ratio, stride=self.upsample_ratio) else: self.upsample = nn.Upsample( scale_factor=self.upsample_ratio, mode=self.upsample_method) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = nn.Conv2d(logits_in_channel, out_channels, 1) # if self.generate_weight: # self.weights_predict = nn.Sequential( # nn.Linear(256 * 2, 1024), # nn.ReLU(True), # nn.Dropout(), # nn.Linear(1024, 1024), # nn.ReLU(True), # nn.Dropout(), # nn.Linear(1024, (self.conv_out_channels+1)*self.num_classes), # +1 for bias # ) # loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.1) # self.loss_cls = build_loss(loss_cls) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None self.ws = 3 def init_weights(self): for m in [self.upsample, self.conv_logits]: if m is None: continue nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x, query_feat=None, ref_feat=None, num_pos=None, num_cls_share=None): # if num_cls_share is None: # num_cls_share = len(self.convs) # for conv in self.convs[:num_cls_share]: # x = conv(x) # if self.generate_weight: # cls_feat = F.adaptive_avg_pool2d(x, 1) # cls_feat = cls_feat.view(cls_feat.size(0), 1, -1) # predicted = self.weights_predict(torch.cat([query_feat, ref_feat], 1)) # weight, bias = predicted.view(-1, self.num_classes, # self.conv_out_channels+1).split(self.conv_out_channels, 2) # cls_score = ((weight * cls_feat).sum(2, keepdim=True) + bias).view(-1, self.num_classes) # if num_pos is not None: # x = x[:num_pos] # for conv in self.convs[num_cls_share:]: # x = conv(x) for conv in self.convs: x = conv(x) if self.upsample is not None: x = self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) if self.use_maskopt: edge_pred, mask_pred = mask_pred.split(2, dim=1) return edge_pred, mask_pred if self.generate_weight: return cls_score, mask_pred return mask_pred def get_target(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels, num_pos=None): loss = dict() # if self.generate_weight: # cls_score, mask_pred = mask_pred # label_weights = torch.ones(len(cls_score)).to(labels.device) # avg_factor = max(torch.sum(label_weights > 0).float().item(), 1.) # loss['loss_cls_mask'] = self.loss_cls( # cls_score, # labels, # label_weights, # avg_factor=avg_factor, # reduction_override=None) # if num_pos is not None: # labels = labels[:num_pos] # if self.use_maskopt: # edge_pred, mask_pred = mask_pred # device = edge_pred.device # N, H, W = mask_targets.shape # with torch.no_grad(): # edges = self.edge_det(mask_targets.unsqueeze(0)).squeeze(0) # edges[:, 0, :] = torch.where(mask_targets[:, 0, :]==1, mask_targets[:, 0, :], edges[:, 0, :]) # edges[:, :, 0] = torch.where(mask_targets[:, :, 0]==1, mask_targets[:, :, 0], edges[:, :, 0]) # edges[:, H-1, :] = torch.where(mask_targets[:, H-1, :]==1, mask_targets[:, H-1, :], edges[:, H-1, :]) # edges[:, :, W-1] = torch.where(mask_targets[:, :, W-1]==1, mask_targets[:, :, W-1], edges[:, :, W-1]) # edge_targets = (edges > 0.25).long() # weight = torch.tensor([(edges==1).sum(), (edges==0).sum()]).float() / edges.numel() # edge_area = F.conv2d(edges.unsqueeze(1).float(), torch.ones(1, 1, self.ws, self.ws).to(device), # padding=self.ws//2) # loss_edge = F.cross_entropy(edge_pred, edge_targets, weight.to(device)) # loss['loss_edge'] = loss_edge # # loss_mask = F.binary_cross_entropy_with_logits(mask_pred[edge_area > 0], # # mask_targets.unsqueeze(1)[edge_area > 0].float()) # loss_mask = F.binary_cross_entropy_with_logits(mask_pred, # mask_targets.unsqueeze(1).float()) # else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, mask_feats, ref_feats, det_bboxes, det_labels, real_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale, gt_masks=None): """Get segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class+1, h, w). For single-scale testing, mask_pred is the direct output of model, whose type is Tensor, while for multi-scale testing, it will be converted to numpy array outside of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size Returns: list[list]: encoded masks """ if isinstance(mask_pred, tuple): edge_pred, mask_pred = mask_pred # if False: # edge_pred, mask_pred = mask_pred # edge_pred = edge_pred.argmax(1, keepdim=True).float() # device = mask_pred.device # # edge_area = F.conv2d(edge_pred, torch.ones(1, 1, self.ws, self.ws).to(device), padding=self.ws//2) # # a = torch.where(edge_area > 0, mask_pred.sigmoid() * 2 - 1, torch.zeros_like(mask_pred)) # # a = torch.where(edge_area > 0, mask_pred.tanh(), torch.zeros_like(mask_pred)) # a_0 = torch.where(mask_pred > 0, torch.ones_like(mask_pred), -torch.ones_like(mask_pred)) # can change to binary # a = torch.where(edge_pred > 0, a_0, torch.zeros_like(mask_pred)) # # b = F.cosine_similarity(mask_feats.unsqueeze(1), ref_feats, dim=2) # # b = F.interpolate(b, a.shape[-2:], mode='bilinear', align_corners=True) # alpha, beta, gamma, delta, lambd = 1, 1, 1, 1, 1e-1 # n_iters = 100 # # c = alpha * a + beta * b.mean(1, keepdim=True) # # f = torch.tensor([ [0, 1/4, 0], # # [1/4, 0, 1/4], # # [0, 1/4, 0]])[None, None, :, :].to(device) # f = torch.tensor([ [0, 1, 0], # [1, 0, 1], # [0, 1, 0]])[None, None, :, :].float().to(device) # H, W = a.shape[-2:] # divide = torch.ones(H, W) * 1/4 # divide[0, :] = 1/3 # divide[H-1, :] = 1/3 # divide[:, 0] = 1/3 # divide[:, W-1] = 1/3 # divide[0, 0] = 1/2 # divide[0, W-1] = 1/2 # divide[H-1, 0] = 1/2 # divide[H-1, W-1] = 1/2 # divide = divide[None, None, :, :].float().to(device) # # plt.matshow(edge_pred[0, 0].data.cpu().numpy()) # # plt.savefig('edge.jpg') # # plt.matshow(a_0[0, 0].data.cpu().numpy()) # # plt.savefig('qual1.jpg') # d = a_0 # for i in range(n_iters): # d_avg = F.conv2d(d, f, padding=1) * divide # # exp = alpha * a * torch.exp(-(a*d).sum(dim=[2,3], keepdim=True)) # sigmoid = torch.sigmoid(-(a*d).sum(dim=[2,3], keepdim=True)) # exp = alpha * a * sigmoid * (1 - sigmoid) # d = exp + d_avg # # print(d.min().item(), d.max().item()) # # plt.matshow(d[0, 0].data.cpu().numpy()) # # plt.savefig('qual_end.jpg') # # exit() # mask_pred = (d + 1) / 2 # # d_old = mask_pred # # for i in range(n_iters): # # d_g = (gamma + delta) * d # # d_g -= delta*F.conv2d(d, f, padding=1) # # d_g -= c * torch.exp(-(c * d).sum(dim=[0, 1, 2, 3], keepdim=True)) # # # d_g -= c * torch.exp(-(c * d)) # # # d_g -= alpha * a * torch.exp(-alpha * (a * d)) # # # d_g -= beta * b * torch.exp(-beta * (b * d)) # # d = d - lambd * d_g # # if torch.norm(d - d_old) < 0.01: # # break # # d_old = d # # mask_pred = d # else: mask_pred = mask_pred.sigmoid() if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.cpu().numpy() assert isinstance(mask_pred, np.ndarray) # when enabling mixed precision training, mask_pred may be float16 # numpy array mask_pred = mask_pred.astype(np.float32) cls_segms = [[] for _ in range(80)] bboxes = det_bboxes.cpu().numpy()[:, :4] labels = det_labels.cpu().numpy() + 1 real_labels = real_labels.cpu().numpy() if rescale: img_h, img_w = ori_shape[:2] else: img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) scale_factor = 1.0 for i in range(bboxes.shape[0]): bbox = (bboxes[i, :] / scale_factor).astype(np.int32) label = labels[i] real_label = real_labels[i] w = max(bbox[2] - bbox[0] + 1, 1) h = max(bbox[3] - bbox[1] + 1, 1) if not self.class_agnostic and not self.use_maskopt: mask_pred_ = mask_pred[i, label, :, :] else: mask_pred_ = mask_pred[i, 0, :, :] im_mask = np.zeros((img_h, img_w), dtype=np.uint8) if gt_masks is not None: bbox_mask = mmcv.imresize(gt_masks[i][0].cpu().numpy(), (w, h)) else: bbox_mask = mmcv.imresize(mask_pred_, (w, h)) bbox_mask = (bbox_mask > rcnn_test_cfg.mask_thr_binary).astype( np.uint8) im_mask[bbox[1]:bbox[1] + h, bbox[0]:bbox[0] + w] = bbox_mask rle = mask_util.encode( np.array(im_mask[:, :, np.newaxis], order='F'))[0] cls_segms[real_label].append(rle) return cls_segms, mask_pred[:, 0:1]
[ "torch.nn.ReLU", "torch.nn.init.constant_", "torch.nn.ModuleList", "numpy.round", "torch.nn.init.kaiming_normal_", "mmdet.core.auto_fp16", "torch.nn.Conv2d", "numpy.array", "numpy.zeros", "torch.nn.Upsample", "torch.zeros_like", "mmdet.core.mask_target", "torch.nn.ConvTranspose2d", "mmcv.i...
[((5944, 5955), 'mmdet.core.auto_fp16', 'auto_fp16', ([], {}), '()\n', (5953, 5955), False, 'from mmdet.core import mask_target, force_fp32, auto_fp16\n'), ((7749, 7784), 'mmdet.core.force_fp32', 'force_fp32', ([], {'apply_to': "('mask_pred',)"}), "(apply_to=('mask_pred',))\n", (7759, 7784), False, 'from mmdet.core import mask_target, force_fp32, auto_fp16\n'), ((3659, 3674), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (3672, 3674), True, 'import torch.nn as nn\n'), ((4971, 5016), 'torch.nn.Conv2d', 'nn.Conv2d', (['logits_in_channel', 'out_channels', '(1)'], {}), '(logits_in_channel, out_channels, 1)\n', (4980, 5016), True, 'import torch.nn as nn\n'), ((5592, 5613), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5599, 5613), True, 'import torch.nn as nn\n'), ((7605, 7679), 'mmdet.core.mask_target', 'mask_target', (['pos_proposals', 'pos_assigned_gt_inds', 'gt_masks', 'rcnn_train_cfg'], {}), '(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg)\n', (7616, 7679), False, 'from mmdet.core import mask_target, force_fp32, auto_fp16\n'), ((5809, 5879), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['m.weight'], {'mode': '"""fan_out"""', 'nonlinearity': '"""relu"""'}), "(m.weight, mode='fan_out', nonlinearity='relu')\n", (5832, 5879), True, 'import torch.nn as nn\n'), ((5909, 5937), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias', '(0)'], {}), '(m.bias, 0)\n', (5926, 5937), True, 'import torch.nn as nn\n'), ((15777, 15817), 'numpy.zeros', 'np.zeros', (['(img_h, img_w)'], {'dtype': 'np.uint8'}), '((img_h, img_w), dtype=np.uint8)\n', (15785, 15817), True, 'import numpy as np\n'), ((4422, 4540), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['upsample_in_channels', 'self.conv_out_channels', 'self.upsample_ratio'], {'stride': 'self.upsample_ratio'}), '(upsample_in_channels, self.conv_out_channels, self.\n upsample_ratio, stride=self.upsample_ratio)\n', (4440, 4540), True, 'import torch.nn as nn\n'), ((4643, 4715), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': 'self.upsample_ratio', 'mode': 'self.upsample_method'}), '(scale_factor=self.upsample_ratio, mode=self.upsample_method)\n', (4654, 4715), True, 'import torch.nn as nn\n'), ((10065, 10089), 'torch.zeros_like', 'torch.zeros_like', (['labels'], {}), '(labels)\n', (10081, 10089), False, 'import torch\n'), ((15982, 16015), 'mmcv.imresize', 'mmcv.imresize', (['mask_pred_', '(w, h)'], {}), '(mask_pred_, (w, h))\n', (15995, 16015), False, 'import mmcv\n'), ((15134, 15171), 'numpy.round', 'np.round', (['(ori_shape[0] * scale_factor)'], {}), '(ori_shape[0] * scale_factor)\n', (15142, 15171), True, 'import numpy as np\n'), ((15209, 15246), 'numpy.round', 'np.round', (['(ori_shape[1] * scale_factor)'], {}), '(ori_shape[1] * scale_factor)\n', (15217, 15246), True, 'import numpy as np\n'), ((16245, 16291), 'numpy.array', 'np.array', (['im_mask[:, :, np.newaxis]'], {'order': '"""F"""'}), "(im_mask[:, :, np.newaxis], order='F')\n", (16253, 16291), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import numpy as np import copy as cp from tqdm import tqdm import lib.metrics as metrics import sklearn.model_selection as sk_modsel import sklearn.metrics as sk_metrics import sklearn.utils as sk_utils def sk_learn_k_fold_cv(x, y, z, kf_reg, design_matrix, k_splits=4, test_percent=0.4, print_results=True): """Scikit Learn method for cross validation.""" x_train, x_test, y_train, y_test = sk_modsel.train_test_split( np.c_[x.ravel(), y.ravel()], z.ravel(), test_size=test_percent, shuffle=True) kf = sk_modsel.KFold(n_splits=k_splits) X_test = design_matrix(x_test) X_train = design_matrix(x_train) y_pred_list = [] beta_coefs = [] for train_index, test_index in tqdm(kf.split(X_train), desc="SciKit-Learn k-fold Cross Validation"): kX_train, kX_test = X_train[train_index], X_train[test_index] kY_train, kY_test = y_train[train_index], y_train[test_index] kf_reg.fit(kX_train, kY_train) y_pred_list.append(kf_reg.predict(X_test)) beta_coefs.append(kf_reg.coef_) y_pred_list = np.asarray(y_pred_list) # Mean Square Error, mean((y - y_approx)**2) _mse = (y_test - y_pred_list)**2 MSE = np.mean(np.mean(_mse, axis=0, keepdims=True)) # Bias, (y - mean(y_approx))^2 _mean_pred = np.mean(y_pred_list, axis=0, keepdims=True) bias = np.mean((y_test - _mean_pred)**2) # R^2 score, 1 - sum(y-y_approx)/sum(y-mean(y)) R2 = np.mean(metrics.R2(y_test, y_pred_list, axis=0)) # Variance, var(y_predictions) var = np.mean(np.var(y_pred_list, axis=0, keepdims=True)) beta_coefs_var = np.asarray(beta_coefs).var(axis=0) beta_coefs = np.asarray(beta_coefs).mean(axis=0) if print_results: print("R2: {:-20.16f}".format(R2)) print("MSE: {:-20.16f}".format(MSE)) print("Bias^2:{:-20.16f}".format(bias)) print("Var(y):{:-20.16f}".format(var)) print("Beta coefs: {}".format(beta_coefs)) print("Beta coefs variances: {}".format(beta_coefs_var)) print("Diff: {}".format(abs(MSE - bias - var))) results = { "y_pred": np.mean(y_pred_list, axis=0), "y_pred_var": np.var(y_pred_list, axis=0), "mse": MSE, "r2": R2, "var": var, "bias": bias, "beta_coefs": beta_coefs, "beta_coefs_var": beta_coefs_var, "beta_95c": np.sqrt(beta_coefs_var)*2, "diff": abs(MSE - bias - var), } return results def sk_learn_bootstrap(x, y, z, design_matrix, kf_reg, N_bs=100, test_percent=0.4, print_results=True): """Sci-kit learn bootstrap method.""" x_train, x_test, y_train, y_test = sk_modsel.train_test_split( np.c_[x.ravel(), y.ravel()], z.ravel(), test_size=test_percent, shuffle=False) # Ensures we are on axis shape (N_observations, N_predictors) y_test = y_test.reshape(-1, 1) y_train = y_train.reshape(-1, 1) y_pred = np.empty((y_test.shape[0], N_bs)) X_test = design_matrix(x_test) R2_ = np.empty(N_bs) mse_ = np.empty(N_bs) bias2_ = np.empty(N_bs) beta_coefs = [] X_train = design_matrix(x_train) for i_bs in tqdm(range(N_bs), desc="SciKit-Learn bootstrap"): x_boot, y_boot = sk_utils.resample(X_train, y_train) # x_boot, y_boot = sk_utils.resample(x_train, y_train) # X_boot = design_matrix(x_boot) kf_reg.fit(X_boot, y_boot) # y_pred[:, i_bs] = kf_reg.predict(cp.deepcopy(x_test)).ravel() y_predict = kf_reg.predict(X_test) # print(sk_metrics.r2_score(y_test.flatten(), y_pred[:,i_bs].flatten())) # R2_[i_bs] = sk_metrics.r2_score(y_test.flatten(), y_pred[:,i_bs].flatten()) # R2_[i_bs] = metrics.R2(y_test, y_predict) # mse_[i_bs] = metrics.mse(y_test.flatten(), y_pred[:, i_bs].flatten()) # bias2_[i_bs] = metrics.bias2( # y_test.flatten(), y_pred[:, i_bs].flatten()) y_pred[:, i_bs] = y_predict.ravel() beta_coefs.append(kf_reg.coef_) # R2 = np.mean(R2_) # # print("R2 from each bs step = ",R2) # # # MSE = mse_.mean() # # # bias = bias2_.mean() # # R2 = np.mean(R2_list) # # R2 = (1 - np.sum(np.average((y_test - y_pred)**2, axis=1)) / # # np.sum((y_test - np.average(y_test)**2))) # # print(R2) # print(y_test.shape, y_pred.shape) # s1 = np.sum((np.mean((y_test - y_pred)**2, axis=1))) # s2 = np.sum((y_test - np.mean(y_test))**2) # print ("R2=",1 - s1/s2) # R2 = (1 - np.sum(np.mean((y_test - y_pred)**2, axis=0, keepdims=True),keepdims=True) / # np.sum((y_test - np.mean(y_test, keepdims=True)**2,),keepdims=True)) # print(R2.mean()) # R2 = R2.mean() R2 = np.mean(metrics.R2(y_test, y_pred, axis=0)) # Mean Square Error, mean((y - y_approx)**2) _mse = ((y_test - y_pred))**2 MSE = np.mean(np.mean(_mse, axis=1, keepdims=True)) # Bias, (y - mean(y_approx))^2 _mean_pred = np.mean(y_pred, axis=1, keepdims=True) bias = np.mean((y_test - _mean_pred)**2) # Variance, var(y_predictions) var = np.mean(np.var(y_pred, axis=1, keepdims=True)) beta_coefs_var = np.asarray(beta_coefs).var(axis=0) beta_coefs = np.asarray(beta_coefs).mean(axis=0) # # R^2 score, 1 - sum((y-y_approx)**2)/sum((y-mean(y))**2) # y_pred_mean = np.mean(y_pred, axis=1) # _y_test = y_test.reshape(-1) # print ("R2:", metrics.R2(_y_test, y_pred_mean)) # _s1 = np.sum(((y_test - y_pred))**2, axis=1, keepdims=True) # _s2 = np.sum((y_test - np.mean(y_test))**2) # print (_s1.mean(), _s2) # R2 = 1 - _s1.mean()/_s2 # print(np.array([sk_metrics.r2_score(y_test, y_pred[:,i]) for i in range(N_bs)]).mean()) # R2 = metrics.R2(y_test, y_pred, axis=1) # R2 = np.mean(metrics.R2(y_test, y_pred, axis=1)) # print(np.mean(metrics.R2(y_test, y_pred, axis=1))) # R2 = R2.mean() # print(R2.mean()) if print_results: print("R2: {:-20.16f}".format(R2)) print("MSE: {:-20.16f}".format(MSE)) print("Bias^2:{:-20.16f}".format(bias)) print("Var(y):{:-20.16f}".format(var)) print("Beta coefs: {}".format(beta_coefs)) print("Beta coefs variances: {}".format(beta_coefs_var)) print("Diff: {}".format(abs(MSE - bias - var))) results = { "y_pred": np.mean(y_pred, axis=1), "y_pred_var": np.var(y_pred, axis=1), "mse": MSE, "r2": R2, "var": var, "bias": bias, "beta_coefs": beta_coefs, "beta_coefs_var": beta_coefs_var, "beta_95c": np.sqrt(beta_coefs_var)*2, "diff": abs(MSE - bias - var), } return results
[ "numpy.mean", "numpy.sqrt", "numpy.asarray", "sklearn.utils.resample", "lib.metrics.R2", "numpy.empty", "sklearn.model_selection.KFold", "numpy.var" ]
[((581, 615), 'sklearn.model_selection.KFold', 'sk_modsel.KFold', ([], {'n_splits': 'k_splits'}), '(n_splits=k_splits)\n', (596, 615), True, 'import sklearn.model_selection as sk_modsel\n'), ((1138, 1161), 'numpy.asarray', 'np.asarray', (['y_pred_list'], {}), '(y_pred_list)\n', (1148, 1161), True, 'import numpy as np\n'), ((1358, 1401), 'numpy.mean', 'np.mean', (['y_pred_list'], {'axis': '(0)', 'keepdims': '(True)'}), '(y_pred_list, axis=0, keepdims=True)\n', (1365, 1401), True, 'import numpy as np\n'), ((1413, 1448), 'numpy.mean', 'np.mean', (['((y_test - _mean_pred) ** 2)'], {}), '((y_test - _mean_pred) ** 2)\n', (1420, 1448), True, 'import numpy as np\n'), ((3064, 3097), 'numpy.empty', 'np.empty', (['(y_test.shape[0], N_bs)'], {}), '((y_test.shape[0], N_bs))\n', (3072, 3097), True, 'import numpy as np\n'), ((3145, 3159), 'numpy.empty', 'np.empty', (['N_bs'], {}), '(N_bs)\n', (3153, 3159), True, 'import numpy as np\n'), ((3171, 3185), 'numpy.empty', 'np.empty', (['N_bs'], {}), '(N_bs)\n', (3179, 3185), True, 'import numpy as np\n'), ((3199, 3213), 'numpy.empty', 'np.empty', (['N_bs'], {}), '(N_bs)\n', (3207, 3213), True, 'import numpy as np\n'), ((5086, 5124), 'numpy.mean', 'np.mean', (['y_pred'], {'axis': '(1)', 'keepdims': '(True)'}), '(y_pred, axis=1, keepdims=True)\n', (5093, 5124), True, 'import numpy as np\n'), ((5136, 5171), 'numpy.mean', 'np.mean', (['((y_test - _mean_pred) ** 2)'], {}), '((y_test - _mean_pred) ** 2)\n', (5143, 5171), True, 'import numpy as np\n'), ((1267, 1303), 'numpy.mean', 'np.mean', (['_mse'], {'axis': '(0)', 'keepdims': '(True)'}), '(_mse, axis=0, keepdims=True)\n', (1274, 1303), True, 'import numpy as np\n'), ((1517, 1556), 'lib.metrics.R2', 'metrics.R2', (['y_test', 'y_pred_list'], {'axis': '(0)'}), '(y_test, y_pred_list, axis=0)\n', (1527, 1556), True, 'import lib.metrics as metrics\n'), ((1612, 1654), 'numpy.var', 'np.var', (['y_pred_list'], {'axis': '(0)', 'keepdims': '(True)'}), '(y_pred_list, axis=0, keepdims=True)\n', (1618, 1654), True, 'import numpy as np\n'), ((2188, 2216), 'numpy.mean', 'np.mean', (['y_pred_list'], {'axis': '(0)'}), '(y_pred_list, axis=0)\n', (2195, 2216), True, 'import numpy as np\n'), ((2244, 2271), 'numpy.var', 'np.var', (['y_pred_list'], {'axis': '(0)'}), '(y_pred_list, axis=0)\n', (2250, 2271), True, 'import numpy as np\n'), ((3365, 3400), 'sklearn.utils.resample', 'sk_utils.resample', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (3382, 3400), True, 'import sklearn.utils as sk_utils\n'), ((4857, 4891), 'lib.metrics.R2', 'metrics.R2', (['y_test', 'y_pred'], {'axis': '(0)'}), '(y_test, y_pred, axis=0)\n', (4867, 4891), True, 'import lib.metrics as metrics\n'), ((4995, 5031), 'numpy.mean', 'np.mean', (['_mse'], {'axis': '(1)', 'keepdims': '(True)'}), '(_mse, axis=1, keepdims=True)\n', (5002, 5031), True, 'import numpy as np\n'), ((5224, 5261), 'numpy.var', 'np.var', (['y_pred'], {'axis': '(1)', 'keepdims': '(True)'}), '(y_pred, axis=1, keepdims=True)\n', (5230, 5261), True, 'import numpy as np\n'), ((6467, 6490), 'numpy.mean', 'np.mean', (['y_pred'], {'axis': '(1)'}), '(y_pred, axis=1)\n', (6474, 6490), True, 'import numpy as np\n'), ((6518, 6540), 'numpy.var', 'np.var', (['y_pred'], {'axis': '(1)'}), '(y_pred, axis=1)\n', (6524, 6540), True, 'import numpy as np\n'), ((1678, 1700), 'numpy.asarray', 'np.asarray', (['beta_coefs'], {}), '(beta_coefs)\n', (1688, 1700), True, 'import numpy as np\n'), ((1730, 1752), 'numpy.asarray', 'np.asarray', (['beta_coefs'], {}), '(beta_coefs)\n', (1740, 1752), True, 'import numpy as np\n'), ((2477, 2500), 'numpy.sqrt', 'np.sqrt', (['beta_coefs_var'], {}), '(beta_coefs_var)\n', (2484, 2500), True, 'import numpy as np\n'), ((5285, 5307), 'numpy.asarray', 'np.asarray', (['beta_coefs'], {}), '(beta_coefs)\n', (5295, 5307), True, 'import numpy as np\n'), ((5337, 5359), 'numpy.asarray', 'np.asarray', (['beta_coefs'], {}), '(beta_coefs)\n', (5347, 5359), True, 'import numpy as np\n'), ((6746, 6769), 'numpy.sqrt', 'np.sqrt', (['beta_coefs_var'], {}), '(beta_coefs_var)\n', (6753, 6769), True, 'import numpy as np\n')]
import impedance as imp import math from sympy.physics import units as u from sympy import sqrt, re, im, I from constants import constants as c import numpy as np import matplotlib.pyplot as plt from matplotlib import rc import matplotlib as mpl from helper_functions import indep_array rc('text', usetex=True) mpl.rcParams.update({'font.size': 18}) class byrn: d = .05 * u.m A = 9.6 * (u.cm)**2 mu = 1e-2 * (u.m)**2 / (u.V * u.s) m = 9.11e-31 * u.kg T_g = 300 * u.K alpha = 2.1e-29 * (u.m)**3 eps_r = 1. u.torr = u.mmHg def __init__(self, p): self.n_g = p * u.torr / (c.kB * self.T_g) self.nu_m = self.n_g * sqrt(math.pi * self.alpha * c.e**2 / (self.m * c.eps0)) class wtr: diff = 2e-9 * (u.m)**2 / u.s # reference Ranga T_l = 300 * u.K mu = diff * c.e / (c.kB * T_l) weight_Cl = 35.5 * u.g / u.mol m_Cl = weight_Cl / u.avogadro eps_r = 80. d = 1. * u.mm A = 9.6 * (u.cm)**2 def __init__(self, conducting_ion): if conducting_ion == "Cl": self.m = self.m_Cl self.nu_m = c.e / (self.m * self.mu) def impedance_arrays(dens_points, freq_points, params): Rp, Xp, Zp_mag = np.zeros((len(dens_points), len(freq_points))), np.zeros((len(dens_points), len(freq_points))), np.zeros((len(dens_points), len(freq_points))) for i in range(0, len(dens_points)): for j in range(0, len(freq_points)): eps, Yp, Zp = imp.impedance(freq_points[j] / u.s, params.m, dens_points[i] / (u.m)**3, params.A, params.d, params.eps_r, nu_m = params.nu_m) Rp[i][j] = re(Zp) / u.ohm Xp[i][j] = im(Zp) / u.ohm Zp_mag[i][j] = np.sqrt(Rp[i][j] ** 2 + Xp[i][j] ** 2) return Rp, Xp, Zp_mag def plasma_imp_vs_pg(pg_points, freq, dens): Rp, Xp = np.zeros(len(pg_points)), np.zeros(len(pg_points)) u.torr = u.mmHg for p,i in zip(pg_points, range(len(pg_points))): n_g = p * u.torr / (c.kB * byrn.T_g) nu_m = n_g * sqrt(math.pi * byrn.alpha * c.e**2 / (byrn.m * c.eps0)) eps, Yp, Zp = imp.impedance(freq / u.s, byrn.m, dens / u.m ** 3, byrn.A, byrn.d, byrn.eps_r, nu_m = nu_m) Rp[i] = re(Zp) / u.ohm Xp[i] = im(Zp) / u.ohm return Rp, Xp def imp_plot(indep_var, imp_var, imp_name, save_name, freq = True, labels = [''], styles = ['']): plt.close() for y_data, label, style in zip(imp_var, labels, styles): plt.plot(indep_var, y_data, label = label, linestyle = style, linewidth = 3) plt.yscale('log') plt.xscale('log') plt.ylabel(imp_name + ' ($\Omega$)') if freq is True: plt.xlabel('Frequency s$^{-1}$') else: plt.xlabel('Electron density (m$^{-3}$)') plt.legend(loc='best') plt.vlines(162e6, 0, 1e10, linestyle = '--') plt.savefig('/home/lindsayad/gdrive/Pictures/' + save_name + '.eps', format = 'eps') plt.show() # pstart, pend, psteps = 1e-3, 760, 50 # p_pts = indep_array(pstart, pend, psteps) # Rp, Xp = plasma_imp_vs_pg(p_pts, 162e6, 1e18) # plt.plot(p_pts, np.abs(Xp)) # plt.xscale('log') # plt.yscale('log') # plt.xlabel('Gas pressure (torr)') # plt.ylabel('Absolute value of the reactance ($\Omega$)') # # plt.savefig('Reactance_mag_vs_pressure.eps', format = 'eps') # plt.show() freq_start, freq_end, freq_steps = 1, 10e9, 50 freq_points = indep_array(freq_start, freq_end, freq_steps) atm_plas = byrn(760) Rp_gas, Xp_gas, Zp_mag_gas = impedance_arrays([1e18], freq_points, atm_plas) mass_conc_Cl = 13.3 * u.mg / u.l # reference Raleigh municipal plant n_Cl = mass_conc_Cl / wtr.weight_Cl * u.avogadro cl_soln = wtr("Cl") Rp_liq, Xp_liq, Zp_mag_liq = impedance_arrays([n_Cl * u.m ** 3], freq_points, cl_soln) # imp_plot(freq_points, Rp_gas[0,:], "resistance", "dummy") # imp_plot(freq_points, -Xp_gas[0,:], "reactance magnitude", "freq_vs_reactance_ne_1e18") # imp_plot(freq_points, Rp_liq[0,:], "Water resistance", "freq_vs_resistance_water") # imp_plot(freq_points, -Xp_liq[0,:], "Water reactance", "freq_vs_reactance_water") # imp_plot(freq_points, [Rp_gas[0,:], Rp_liq[0,:]], "Re(Z)", "Plasma_vs_water_resistance", labels = ['Plasma', 'Water'], styles = ['-', '--']) # imp_plot(freq_points, [-Xp_gas[0,:], -Xp_liq[0,:]], '$|$Im(Z)$|$', "Plasma_vs_water_reactance", labels = ['Plasma', 'Water'], styles = ['-', '--']) imp_plot(freq_points, [Zp_mag_gas[0,:], Zp_mag_liq[0,:]], '$|$Z$|$', "Plasma_vs_water_impedance_mag", labels = ['Plasma', 'Water'], styles = ['-', '--']) # RB = d * nu_em * m / (A * c.e**2 * n_0) # LB = RB / nu_em # CB = c.eps0 * A / d # ZRB = RB # ZLB = I * w * LB # ZCB = 1. / (I * w * CB) # Zp = 1. / (1. / ZCB + 1. / (ZRB + ZLB)) # Rp = re(Zp) / u.ohm # Xp = im(Zp) / u.ohm # print "Plasma resistance in Ohms from Brandon model is " + str(Rp) # print "Plasma reactance in Ohms from Brandon model is " + str(Xp)
[ "impedance.impedance", "helper_functions.indep_array", "matplotlib.pyplot.savefig", "matplotlib.rcParams.update", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.vlines", "matplotlib.pyplot.legend", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "sympy.sqrt", "numpy.sqrt", "sympy.re", ...
[((287, 310), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (289, 310), False, 'from matplotlib import rc\n'), ((311, 349), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (["{'font.size': 18}"], {}), "({'font.size': 18})\n", (330, 349), True, 'import matplotlib as mpl\n'), ((3328, 3373), 'helper_functions.indep_array', 'indep_array', (['freq_start', 'freq_end', 'freq_steps'], {}), '(freq_start, freq_end, freq_steps)\n', (3339, 3373), False, 'from helper_functions import indep_array\n'), ((2345, 2356), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2354, 2356), True, 'import matplotlib.pyplot as plt\n'), ((2508, 2525), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (2518, 2525), True, 'import matplotlib.pyplot as plt\n'), ((2530, 2547), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (2540, 2547), True, 'import matplotlib.pyplot as plt\n'), ((2552, 2589), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["(imp_name + ' ($\\\\Omega$)')"], {}), "(imp_name + ' ($\\\\Omega$)')\n", (2562, 2589), True, 'import matplotlib.pyplot as plt\n'), ((2715, 2737), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (2725, 2737), True, 'import matplotlib.pyplot as plt\n'), ((2742, 2799), 'matplotlib.pyplot.vlines', 'plt.vlines', (['(162000000.0)', '(0)', '(10000000000.0)'], {'linestyle': '"""--"""'}), "(162000000.0, 0, 10000000000.0, linestyle='--')\n", (2752, 2799), True, 'import matplotlib.pyplot as plt\n'), ((2791, 2878), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('/home/lindsayad/gdrive/Pictures/' + save_name + '.eps')"], {'format': '"""eps"""'}), "('/home/lindsayad/gdrive/Pictures/' + save_name + '.eps', format\n ='eps')\n", (2802, 2878), True, 'import matplotlib.pyplot as plt\n'), ((2880, 2890), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2888, 2890), True, 'import matplotlib.pyplot as plt\n'), ((2070, 2164), 'impedance.impedance', 'imp.impedance', (['(freq / u.s)', 'byrn.m', '(dens / u.m ** 3)', 'byrn.A', 'byrn.d', 'byrn.eps_r'], {'nu_m': 'nu_m'}), '(freq / u.s, byrn.m, dens / u.m ** 3, byrn.A, byrn.d, byrn.\n eps_r, nu_m=nu_m)\n', (2083, 2164), True, 'import impedance as imp\n'), ((2427, 2497), 'matplotlib.pyplot.plot', 'plt.plot', (['indep_var', 'y_data'], {'label': 'label', 'linestyle': 'style', 'linewidth': '(3)'}), '(indep_var, y_data, label=label, linestyle=style, linewidth=3)\n', (2435, 2497), True, 'import matplotlib.pyplot as plt\n'), ((2618, 2650), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency s$^{-1}$"""'], {}), "('Frequency s$^{-1}$')\n", (2628, 2650), True, 'import matplotlib.pyplot as plt\n'), ((2669, 2710), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Electron density (m$^{-3}$)"""'], {}), "('Electron density (m$^{-3}$)')\n", (2679, 2710), True, 'import matplotlib.pyplot as plt\n'), ((662, 719), 'sympy.sqrt', 'sqrt', (['(math.pi * self.alpha * c.e ** 2 / (self.m * c.eps0))'], {}), '(math.pi * self.alpha * c.e ** 2 / (self.m * c.eps0))\n', (666, 719), False, 'from sympy import sqrt, re, im, I\n'), ((1447, 1575), 'impedance.impedance', 'imp.impedance', (['(freq_points[j] / u.s)', 'params.m', '(dens_points[i] / u.m ** 3)', 'params.A', 'params.d', 'params.eps_r'], {'nu_m': 'params.nu_m'}), '(freq_points[j] / u.s, params.m, dens_points[i] / u.m ** 3,\n params.A, params.d, params.eps_r, nu_m=params.nu_m)\n', (1460, 1575), True, 'import impedance as imp\n'), ((1677, 1715), 'numpy.sqrt', 'np.sqrt', (['(Rp[i][j] ** 2 + Xp[i][j] ** 2)'], {}), '(Rp[i][j] ** 2 + Xp[i][j] ** 2)\n', (1684, 1715), True, 'import numpy as np\n'), ((1992, 2049), 'sympy.sqrt', 'sqrt', (['(math.pi * byrn.alpha * c.e ** 2 / (byrn.m * c.eps0))'], {}), '(math.pi * byrn.alpha * c.e ** 2 / (byrn.m * c.eps0))\n', (1996, 2049), False, 'from sympy import sqrt, re, im, I\n'), ((2178, 2184), 'sympy.re', 're', (['Zp'], {}), '(Zp)\n', (2180, 2184), False, 'from sympy import sqrt, re, im, I\n'), ((2209, 2215), 'sympy.im', 'im', (['Zp'], {}), '(Zp)\n', (2211, 2215), False, 'from sympy import sqrt, re, im, I\n'), ((1597, 1603), 'sympy.re', 're', (['Zp'], {}), '(Zp)\n', (1599, 1603), False, 'from sympy import sqrt, re, im, I\n'), ((1635, 1641), 'sympy.im', 'im', (['Zp'], {}), '(Zp)\n', (1637, 1641), False, 'from sympy import sqrt, re, im, I\n')]
import numpy as np def get_int_tuple_from_string_pair(pair): return tuple((int(x) for x in pair.split(','))) def get_zeroed_field(vectors): dimension_size = max(vectors.flat) + 1 return np.zeros((dimension_size, dimension_size), dtype=int) def get_overlaps_count_from_field(field): return len([x for x in field.flat if x > 1]) def filter_horizontal_and_vertical_lines(vector): return vector[0, 0] == vector[1, 0] or vector[0, 1] == vector[1, 1] def filter_diagonal_lines(vector): return vector[0, 0] != vector[1, 0] and vector[0, 1] != vector[1, 1] def get_lines_coordinates(vectors, predicate): return [(v[0, 0], v[1, 0], v[0, 1], v[1, 1]) for v in vectors if predicate(v)] def fill_field_by_horizontal_and_vertical_lines(vectors, field): lines = get_lines_coordinates(vectors, filter_horizontal_and_vertical_lines) for x1, x2, y1, y2 in lines: x1, x2 = min(x1, x2), max(x1, x2) y1, y2 = min(y1, y2), max(y1, y2) for y in range(y1, y2 + 1): for x in range(x1, x2 + 1): field[y][x] += 1 def fill_field_by_diagonal_lines(vectors, field): lines = get_lines_coordinates(vectors, filter_diagonal_lines) for x1, x2, y1, y2 in lines: xrange = range(x1, x2 + 1) if x1 < x2 else range(x1, x2 - 1, -1) yrange = range(y1, y2 + 1) if y1 < y2 else range(y1, y2 - 1, -1) for x, y in zip(xrange, yrange): field[y][x] += 1 def part_one(vectors, field): fill_field_by_horizontal_and_vertical_lines(vectors, field) return get_overlaps_count_from_field(field) def part_two(vectors, field): fill_field_by_horizontal_and_vertical_lines(vectors, field) fill_field_by_diagonal_lines(vectors, field) return get_overlaps_count_from_field(field) with open('input', 'r') as infile: vectors = [(get_int_tuple_from_string_pair(pair[0]), get_int_tuple_from_string_pair(pair[1])) for pair in (line.strip('\n').replace(' ', '').split('->') for line in infile.readlines())] vectors = np.array(vectors) print(part_one(vectors, get_zeroed_field(vectors))) print(part_two(vectors, get_zeroed_field(vectors)))
[ "numpy.array", "numpy.zeros" ]
[((2046, 2063), 'numpy.array', 'np.array', (['vectors'], {}), '(vectors)\n', (2054, 2063), True, 'import numpy as np\n'), ((202, 255), 'numpy.zeros', 'np.zeros', (['(dimension_size, dimension_size)'], {'dtype': 'int'}), '((dimension_size, dimension_size), dtype=int)\n', (210, 255), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Sun Dec 15 22:28:37 2019 @author: maheshsoundar """ import pandas as pd import random import numpy as np from sklearn.preprocessing import StandardScaler, MinMaxScaler #class to scale data. Provide chunksize and type of scaler. Use the object of created class to call scale method with dataframe as input. class MLScaler(): def __init__(self,scaler='minmax',chunk_size=1000,seed=5): if(scaler == 'std'): self.scaler = StandardScaler() else: self.scaler = MinMaxScaler() self.chunksize = chunk_size self.seed(seed) def seed(self,seed): np.random.seed(seed) random.seed(seed) def partial_fit(self,df): chunks = np.array_split(df,df.shape[0]/min(self.chunksize,df.shape[0])) for chunk in chunks: self.scaler.partial_fit(chunk) return self.scaler def transform(self,df): return np.array(self.scaler.transform(df)) def scale(self,df): self.partial_fit(df) return self.transform(df), self.scaler
[ "sklearn.preprocessing.StandardScaler", "sklearn.preprocessing.MinMaxScaler", "numpy.random.seed", "random.seed" ]
[((685, 705), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (699, 705), True, 'import numpy as np\n'), ((715, 732), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (726, 732), False, 'import random\n'), ((504, 520), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (518, 520), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n'), ((563, 577), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (575, 577), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n')]
import numpy as np import torchvision.transforms as T from labels import * import matplotlib.pyplot as plt import matplotlib.patches as patches import random def preprocess(images): images = [img.convert('RGB').resize([400, 600]) for img in images] return images def get_transform(normalize = False): custom_transforms = [] custom_transforms.append(T.ToTensor()) if normalize: custom_transforms.append(T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])) return T.Compose(custom_transforms) def expand(bbox, img): bbox = np.array(bbox, dtype=float) height, width, _ = np.array(img).shape if str(bbox) == 'nan': return None m = min(height,width)/30 x1, y1, x2, y2 = bbox bbox = [max(0, x1-m), max(0, y1-m), min(width, x2+m), min(height, y2+m)] return bbox def is_complete_overlap(box1, box2): # box1 > box2 check_x = box1[0] <= box2[0] and box1[2] >= box2[2] check_y = box1[1] <= box2[1] and box1[3] >= box2[3] return check_x and check_y def is_valid_overlap(box1, box2): # box1 > box2 check_1 = box1[0] <= box2[0] and box1[2] >= box2[2] check_2 = box1[0] >= box2[0] and box1[2] <= box2[2] check_3 = max(box1[1], box2[1]) <= min(box1[3], box2[3]) # condition of y overlap return (check_1 or check_2) and check_3 def get_valid_top_bottom(box1, box2, label1, label2): suplabel1, suplabel2 = cat_to_supercat(label1), cat_to_supercat(label2) if( box1[1] < box2[1] ): if suplabel1 != 'upper_body' and suplabel1 != 'outer': label1 = common_categories['upper_body'] if suplabel2 != 'lower_body': label2 = common_categories['lower_body'] return (box1, box2, label1, label2) else: if suplabel2 != 'upper_body' and suplabel2 != 'outer': label2 = common_categories['upper_body'] if suplabel1 != 'lower_body': label1 = common_categories['lower_body'] return (box2, box1, label2, label1) def get_desc(boxes, labels, probs): labels_sup = [id_to_supercat(l) for l in labels['cat']] desc = init_desc() if(len(boxes)==1): if(labels_sup[0] == 'full_body'): lbls = {k: labels[k][0] for k in labels.keys()} desc = init_desc(desc, boxes[0], lbls, 'full_body') conf = {k: [probs[k][0]] for k in probs.keys()} return desc, conf areas = [] for box in boxes: w = box[2] - box[0] h = box[3] - box[1] areas.append(w * h) areas = np.array(areas) top_areas = np.argsort(-areas) box1_i = 0 box1 = boxes[top_areas[box1_i]] i = 1 box2_i = i box2 = boxes[top_areas[i]] while(is_complete_overlap(box1, box2) and i < len(boxes)): box2_i = i box2 = boxes[top_areas[box2_i]] i+=1 if(labels_sup[top_areas[box1_i]] == 'full_body'): if(is_valid_overlap(box1, box2)): x1 = min(box1[0], box2[0]) x2 = max(box1[2], box2[2]) y1 = min(box1[1], box2[1]) y2 = max(box1[3], box2[3]) long_box = [x1, y1, x2, y2] else: long_box = box1 lbls = {k: labels[k][top_areas[box1_i]] for k in labels.keys()} desc = init_desc(desc, long_box, lbls, 'full_body') conf = {k: [probs[k][top_areas[box1_i]]] for k in probs.keys()} # return desc else: conf = {k: [0, 0] for k in probs.keys()} for a, idx in enumerate([top_areas[box1_i], top_areas[box2_i]]): supercat = labels_sup[idx] lbls = {k: labels[k][idx] for k in labels.keys()} desc = init_desc(desc, boxes[idx], lbls, supercat) for k in probs.keys(): if supercat == 'lower_body': conf[k][1] = probs[k][idx] else: conf[k][0] = probs[k][idx] return desc, conf def init_desc(desc=None, bbox=None, labels=None, supercat=None): if desc == None: desc = { 'full_body': 'nan', 'lower_body': 'nan', 'upper_body': 'nan', 'outerwear': 'nan', 'colour_bottom': 'nan', 'colour_top': 'nan', 'neckline': 'nan', 'upper_body_length': 'nan', 'lower_body_length': 'nan', 'closure_type': 'nan', 'sleeve_length': 'nan', 'full_body_bbox': 'nan', 'lower_body_bbox': 'nan', 'upper_body_bbox': 'nan' } if supercat == 'full_body': desc['full_body'] = id_to_cat(labels['cat']) desc['neckline'] = id_to_attr(labels['neck'], 'neckline') desc['upper_body_length'] = id_to_attr(labels['ubl'], 'upper_body_length') desc['closure_type'] = id_to_attr(labels['clos'], 'closure_type') desc['sleeve_length'] = id_to_attr(labels['slv'], 'sleeve_length') desc['full_body_bbox'] = bbox elif supercat == 'lower_body': desc['lower_body'] = id_to_cat(labels['cat']) desc['lower_body_length'] = id_to_attr(labels['lbl'], 'lower_body_length') desc['lower_body_bbox'] = bbox elif supercat == 'upper_body': desc['upper_body'] = id_to_cat(labels['cat']) desc['neckline'] = id_to_attr(labels['neck'], 'neckline') desc['upper_body_length'] = id_to_attr(labels['ubl'], 'upper_body_length') desc['closure_type'] = id_to_attr(labels['clos'], 'closure_type') desc['sleeve_length'] = id_to_attr(labels['slv'], 'sleeve_length') desc['upper_body_bbox'] = bbox elif supercat == 'outer': desc['outerwear'] = id_to_cat(labels['cat']) desc['neckline'] = id_to_attr(labels['neck'], 'neckline') desc['upper_body_length'] = id_to_attr(labels['ubl'], 'upper_body_length') desc['closure_type'] = id_to_attr(labels['clos'], 'closure_type') desc['sleeve_length'] = id_to_attr(labels['slv'], 'sleeve_length') desc['upper_body_bbox'] = bbox return desc def plot_annos(img, boxes, labels=None): cmap = plt.get_cmap("rainbow") plt.figure() fig, ax = plt.subplots(1, figsize=(10,8)) ax.imshow(img) colors = [cmap(i) for i in np.linspace(0, 1, 20)] i=0 for box in boxes: if str(box) != 'nan': x1 = box[0] y1 = box[1] x2 = box[2] y2 = box[3] color = colors[random.randint(0,19)] bbox = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=2, edgecolor=color, facecolor='none') ax.add_patch(bbox) if(labels != None): plt.text(x1, y1, s=labels[i], color='black', verticalalignment='top', bbox={'color': color, 'pad': 0}) i+=1 plt.axis('off') # save image # plt.savefig(img_path.replace(".jpg", "-det.jpg"), # bbox_inches='tight', pad_inches=0.0) plt.show()
[ "matplotlib.pyplot.text", "matplotlib.patches.Rectangle", "random.randint", "matplotlib.pyplot.show", "numpy.argsort", "numpy.array", "matplotlib.pyplot.figure", "numpy.linspace", "matplotlib.pyplot.subplots", "torchvision.transforms.Normalize", "matplotlib.pyplot.axis", "torchvision.transform...
[((518, 546), 'torchvision.transforms.Compose', 'T.Compose', (['custom_transforms'], {}), '(custom_transforms)\n', (527, 546), True, 'import torchvision.transforms as T\n'), ((585, 612), 'numpy.array', 'np.array', (['bbox'], {'dtype': 'float'}), '(bbox, dtype=float)\n', (593, 612), True, 'import numpy as np\n'), ((2624, 2639), 'numpy.array', 'np.array', (['areas'], {}), '(areas)\n', (2632, 2639), True, 'import numpy as np\n'), ((2657, 2675), 'numpy.argsort', 'np.argsort', (['(-areas)'], {}), '(-areas)\n', (2667, 2675), True, 'import numpy as np\n'), ((6263, 6286), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""rainbow"""'], {}), "('rainbow')\n", (6275, 6286), True, 'import matplotlib.pyplot as plt\n'), ((6292, 6304), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6302, 6304), True, 'import matplotlib.pyplot as plt\n'), ((6320, 6352), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {'figsize': '(10, 8)'}), '(1, figsize=(10, 8))\n', (6332, 6352), True, 'import matplotlib.pyplot as plt\n'), ((7022, 7037), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (7030, 7037), True, 'import matplotlib.pyplot as plt\n'), ((7188, 7198), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7196, 7198), True, 'import matplotlib.pyplot as plt\n'), ((380, 392), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (390, 392), True, 'import torchvision.transforms as T\n'), ((637, 650), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (645, 650), True, 'import numpy as np\n'), ((447, 504), 'torchvision.transforms.Normalize', 'T.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (458, 504), True, 'import torchvision.transforms as T\n'), ((6404, 6425), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(20)'], {}), '(0, 1, 20)\n', (6415, 6425), True, 'import numpy as np\n'), ((6660, 6757), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x1, y1)', '(x2 - x1)', '(y2 - y1)'], {'linewidth': '(2)', 'edgecolor': 'color', 'facecolor': '"""none"""'}), "((x1, y1), x2 - x1, y2 - y1, linewidth=2, edgecolor=color,\n facecolor='none')\n", (6677, 6757), True, 'import matplotlib.patches as patches\n'), ((6618, 6639), 'random.randint', 'random.randint', (['(0)', '(19)'], {}), '(0, 19)\n', (6632, 6639), False, 'import random\n'), ((6849, 6956), 'matplotlib.pyplot.text', 'plt.text', (['x1', 'y1'], {'s': 'labels[i]', 'color': '"""black"""', 'verticalalignment': '"""top"""', 'bbox': "{'color': color, 'pad': 0}"}), "(x1, y1, s=labels[i], color='black', verticalalignment='top', bbox=\n {'color': color, 'pad': 0})\n", (6857, 6956), True, 'import matplotlib.pyplot as plt\n')]
import numpy as np class NeuralNetwork: def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate, weights_input_to_hidden=None, weights_hidden_to_output=None): self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes # Initialize weights if type(weights_input_to_hidden).__name__ == 'NoneType' and type(weights_hidden_to_output).__name__ == 'NoneType': self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes**-0.5, (self.input_nodes, self.hidden_nodes)) self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes**-0.5, (self.hidden_nodes, self.output_nodes)) else: self.weights_input_to_hidden = weights_input_to_hidden self.weights_hidden_to_output = weights_hidden_to_output self.lr = learning_rate def sigmoid(x): return 1 / (1 + np.exp( -x )) def sigmoid_prime(x): return sigmoid(x) * (1 - sigmoid(x)) def linear(x): return x def linear_prime(x): return x ** 0 # Activation functions self.activation_function = sigmoid self.activation_function_prime = sigmoid_prime self.activation_function2 = linear self.activation_function_prime2 = linear_prime def train(self, features, targets): n_records = features.shape[0] delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape) delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape) for X, y in zip(features, targets): # Forward Pass hidden_inputs = np.dot(X, self.weights_input_to_hidden) hidden_outputs = self.activation_function(hidden_inputs) final_inputs = np.dot(hidden_outputs, self.weights_hidden_to_output) final_outputs = self.activation_function2(final_inputs) # Backward Pass error = y - final_outputs output_error_term = error * self.activation_function_prime2(final_inputs) hidden_error = np.dot(self.weights_hidden_to_output, error) hidden_error_term = hidden_error * self.activation_function_prime(hidden_inputs) # Weight steps delta_weights_i_h += hidden_error_term * X[:, None] delta_weights_h_o += output_error_term * hidden_outputs[:, None] # Weights update self.weights_hidden_to_output += self.lr * delta_weights_h_o / n_records self.weights_input_to_hidden += self.lr * delta_weights_i_h / n_records def run(self, features): hidden_inputs = np.dot(features, self.weights_input_to_hidden) hidden_outputs = self.activation_function(hidden_inputs) final_inputs = np.dot(hidden_outputs, self.weights_hidden_to_output) final_outputs = self.activation_function2(final_inputs) return final_outputs def get_weights(self): return self.weights_input_to_hidden, self.weights_hidden_to_output
[ "numpy.dot", "numpy.zeros", "numpy.exp", "numpy.random.normal" ]
[((1578, 1622), 'numpy.zeros', 'np.zeros', (['self.weights_input_to_hidden.shape'], {}), '(self.weights_input_to_hidden.shape)\n', (1586, 1622), True, 'import numpy as np\n'), ((1651, 1696), 'numpy.zeros', 'np.zeros', (['self.weights_hidden_to_output.shape'], {}), '(self.weights_hidden_to_output.shape)\n', (1659, 1696), True, 'import numpy as np\n'), ((2785, 2831), 'numpy.dot', 'np.dot', (['features', 'self.weights_input_to_hidden'], {}), '(features, self.weights_input_to_hidden)\n', (2791, 2831), True, 'import numpy as np\n'), ((2921, 2974), 'numpy.dot', 'np.dot', (['hidden_outputs', 'self.weights_hidden_to_output'], {}), '(hidden_outputs, self.weights_hidden_to_output)\n', (2927, 2974), True, 'import numpy as np\n'), ((511, 602), 'numpy.random.normal', 'np.random.normal', (['(0.0)', '(self.input_nodes ** -0.5)', '(self.input_nodes, self.hidden_nodes)'], {}), '(0.0, self.input_nodes ** -0.5, (self.input_nodes, self.\n hidden_nodes))\n', (527, 602), True, 'import numpy as np\n'), ((683, 776), 'numpy.random.normal', 'np.random.normal', (['(0.0)', '(self.hidden_nodes ** -0.5)', '(self.hidden_nodes, self.output_nodes)'], {}), '(0.0, self.hidden_nodes ** -0.5, (self.hidden_nodes, self.\n output_nodes))\n', (699, 776), True, 'import numpy as np\n'), ((1797, 1836), 'numpy.dot', 'np.dot', (['X', 'self.weights_input_to_hidden'], {}), '(X, self.weights_input_to_hidden)\n', (1803, 1836), True, 'import numpy as np\n'), ((1934, 1987), 'numpy.dot', 'np.dot', (['hidden_outputs', 'self.weights_hidden_to_output'], {}), '(hidden_outputs, self.weights_hidden_to_output)\n', (1940, 1987), True, 'import numpy as np\n'), ((2237, 2281), 'numpy.dot', 'np.dot', (['self.weights_hidden_to_output', 'error'], {}), '(self.weights_hidden_to_output, error)\n', (2243, 2281), True, 'import numpy as np\n'), ((1049, 1059), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (1055, 1059), True, 'import numpy as np\n')]
""" This module defines the chi-squared and related functions Module author: <NAME> Year: 2020 Email: <EMAIL> """ import numpy as np import model def chi2_no_soliton(c, Rs, ups_disk, ups_bulg, gal, DM_profile="NFW"): """chi2 for an NFW fit (c, Rs; ups_disk, ups_bulg). Runs over a single galaxy :param c: concentration param of the NFW profile, and delc for Burkert :param Rs: critical radius of the NFW profile :param ups_disk: disk surface brightness :param ups_bulg: bulge surface brightness :param gal: a Galaxy instance """ chi2 = 0 Vth2_arr = model.v2_rot(gal, c, Rs, ups_bulg, ups_disk, DM_profile) for i, r in enumerate(gal.R): # treat the i-th bin of the rot curve # # # TODO: move this part out to a dedicated function # # V thory due to DM # if DM_profile == "NFW": # M_enclosed = model.M_NFW(r, Rs, c) # elif DM_profile == "Burkert": # M_enclosed = model.M_Burkert( # r, delc=c, Rs=Rs) # else: # raise Exception( # "Only NFW and Burkert are implemented at the moment.") # VDM2 = model._G_Msun_over_kpc * model._c**2 * (M_enclosed/1.) * (1./r) # # combine DM with the baryon mass model (from SB data) # Vb2 = (ups_bulg*np.abs(gal.Vbul[i])*gal.Vbul[i] # + ups_disk*np.abs(gal.Vdisk[i])*gal.Vdisk[i] # + np.abs(gal.Vgas[i])*gal.Vgas[i] # ) # Vth2 = VDM2 + Vb2 # ODOT Vth2 = Vth2_arr[i] if Vth2 > 0: Vth = np.sqrt(Vth2) else: Vth = 0. Vobs = gal.Vobs[i] dVobs = gal.dVobs[i] # compute chi2 for this bin chi2 += (Vth - Vobs)**2/dVobs**2 # construct Vtot for visual/sanity checks # construct Vtot return chi2 def fit_rot_curve(gal, DM_profile='NFW', gridsize=50): """A quick fit with NFW/Burkert only """ rs_arr = np.linspace(1, 80, gridsize) c_arr = np.logspace(0, 1.5, gridsize) rs_mesh, c_mesh = np.meshgrid(rs_arr, c_arr, indexing='ij') rs_flat, c_flat = rs_mesh.reshape(-1), c_mesh.reshape(-1) chi2_flat = [] chi2_val_rec = 1e9 rec_idx = None for i in range(len(rs_flat)): rs = rs_flat[i] c = c_flat[i] chi2_val = chi2_no_soliton(c=c, Rs=rs, ups_disk=0.5, ups_bulg=0.5, gal=gal, DM_profile=DM_profile) chi2_flat.append(chi2_val) if chi2_val < chi2_val_rec: rec_idx = i chi2_val_rec = chi2_val # print(chi2_val) chi2_flat = np.array(chi2_flat) # best fit rs = rs_flat[rec_idx] c = c_flat[rec_idx] # output gal.rs = rs gal.c = c return (rs_mesh, c_mesh, chi2_flat) def chi2_single_gal(m, M, c, Rs, ups_disk, ups_bulg, gal, flg_Vtot=False, DM_profile="NFW", flg_overshoot=False, combine_mode=None): """chi2 for a fixed theory point (m, M, c, Rs; ups_disk, ups_bulg). Runs over a single galaxy, gal up :param m: scalar mass [eV] :param M: soliton mass [Msun] :param c: concentration param of the NFW profile, and delc for Burkert :param Rs: critical radius of the NFW profile :param ups_disk: disk surface brightness :param ups_bulg: bulge surface brightness :param gal: a Galaxy instance :param flg_Vtot: flg to signal returning of the total rot velocity defined as Vtot**2 = Vb**2 + VNFW**2 + Vsol**2 [km/s] :param DM_profile: flag to choose between NFW and Burkert. (Default: NFW) :returns: chi2 value """ chi2 = 0 if flg_Vtot: Vtot = np.array([]) Vth2_arr = model.v2_rot(gal, c, Rs, ups_bulg, ups_disk, DM_profile, m=m, M=M, combine_mode=combine_mode) for i, r in enumerate(gal.R): # treat the i-th bin of the rot curve # # # TODO: move this part out to a dedicated function # # V thory due to DM # if DM_profile == "NFW": # M_enclosed = model.M_NFW(r, Rs, c) + model.M_sol(r, m, M) # elif DM_profile == "Burkert": # M_enclosed = model.M_Burkert( # r, delc=c, Rs=Rs) + model.M_sol(r, m, M) # else: # raise Exception( # "Only NFW and Burkert are implemented at the moment.") # VDM2 = model._G_Msun_over_kpc * model._c**2 * (M_enclosed/1.) * (1./r) # # combine DM with the baryon mass model (from SB data) # Vb2 = (ups_bulg*np.abs(gal.Vbul[i])*gal.Vbul[i] # + ups_disk*np.abs(gal.Vdisk[i])*gal.Vdisk[i] # + np.abs(gal.Vgas[i])*gal.Vgas[i] # ) # Vth2 = VDM2 + Vb2 # ODOT Vth2 = Vth2_arr[i] if Vth2 > 0: Vth = np.sqrt(Vth2) else: Vth = 0. Vobs = gal.Vobs[i] dVobs = gal.dVobs[i] # compute chi2 for this bin if not flg_overshoot: chi2 += (Vth - Vobs)**2/dVobs**2 else: if Vth - Vobs > 0: chi2 += (Vth - Vobs)**2/dVobs**2 # construct Vtot for visual/sanity checks # construct Vtot if flg_Vtot: Vtot = np.append(Vtot, Vth) if flg_Vtot: return (chi2, Vtot) else: return chi2 def chi2_single_gal_overshooting(m, M, ups_disk, ups_bulg, gal, flg_Vtot=False): """chi2 for a fixed theory point (m, M; ups_disk, ups_bulg) run over a single galaxy, gal. It only has soliton core in it and only counts the overshooting of the data :param m: scalar mass [eV] :param M: soliton mass [Msun] :param ups_disk: disk surface brightness :param ups_bulg: bulge surface brightness :param gal: a Galaxy instance :param flg_Vtot: flg to signal returning of the total rot velocity defined as Vtot**2 = Vb**2 + VNFW**2 + Vsol**2 [km/s] :returns: chi2 value """ chi2 = 0 if flg_Vtot: Vtot = np.array([]) for i, r in enumerate(gal.R): # treat the i-th bin of the rot curve # # TODO: move this part out to a dedicated function # V thory due to DM M_enclosed = model.M_sol(r, m, M) # now only with soliton, no NFW VDM2 = model._G_Msun_over_kpc * model._c**2 * (M_enclosed/1.) * (1./r) # combine DM with the baryon mass model (from SB data) Vb2 = (ups_bulg*np.abs(gal.Vbul[i])*gal.Vbul[i] + ups_disk*np.abs(gal.Vdisk[i])*gal.Vdisk[i] + np.abs(gal.Vgas[i])*gal.Vgas[i] ) Vth2 = VDM2 + Vb2 if Vth2 > 0: Vth = np.sqrt(Vth2) else: Vth = 0. # ODOT Vobs = gal.Vobs[i] dVobs = gal.dVobs[i] # compute chi2 for this bin if Vth > Vobs: chi2 += (Vth - Vobs)**2/dVobs**2 # construct Vtot for visual/sanity checks # construct Vtot if flg_Vtot: Vtot = np.append(Vtot, Vth) if flg_Vtot: return (chi2, Vtot) else: return chi2 def chi2_gals(x, keys, keys_fixed, data, params, verbose=0): """This function mainly does the parsing of x from lnprob(x) and feeds each galaxy with parameters relevant to it. :param x: The theory point whose chi2 is being computed. n-tuple :param keys: The description of each entry of x. list of length n :param keys_fixed: The description of each fixed entry :param data: the galaxies to be run over :param params: param card :returns: chi2 value """ chi2_tot = 0 chi2_comp = [] # the list to save all the chi2 components for gal in data: # for each galaxy, we pack a dict param_for_gal = {} # deal with free params for i, key in enumerate(keys): words = key.split() if (len(words) == 2) and (words[1] == gal.name): # dealing with galaxy-specific variables param_for_gal[words[0]] = x[i] if len(words) == 1: # dealing with universal variables param_for_gal[words[0]] = x[i] # now deal with fixed params for i, key in enumerate(keys_fixed): param_for_gal[key] = params[key+' fixed'] # from now on only read param_for_gal param card m = 10**param_for_gal['logm'] # combining of DM components # catch the combine mode # try: # combine_mode = params['combine_mode'] # except KeyError: # combine_mode = 'matching' combine_mode = params['combine_mode'] # DM profile try: DM_profile = params['DM_profile'] except KeyError: if verbose > 0: print('chi2.py:DM_profile is not specified, default to NFW') DM_profile = "NFW" try: Rs = param_for_gal['Rs'] except Exception: if verbose > 5: print('-----param_for_gal= %s' % param_for_gal) print('-----Rs is not set, so soliton is the only component') if DM_profile != "Soliton": raise Exception( "You specify the DM profile to be either NFW or Burkert, but didn't supply Rs") flg_catch_c = False flg_catch_logc = False try: # in NFW use c for concentration c = param_for_gal['c'] flg_catch_c = True except: pass try: # in Burkert profile try to catch logc for log(del_c) c = 10**param_for_gal['logc'] flg_catch_logc = True except: pass # I'm being sloppy here by postponing the raise until here when it is actually used # let's call it a just-in-time warning :-) if flg_catch_c and flg_catch_logc: raise Exception('You gave both c and logc. Only one can be kept.') if (not flg_catch_c) and (not flg_catch_logc) and (DM_profile != "Soliton"): raise Exception( "You specify the DM profile to be either NFW or Burkert, but didn't supply c or logc") try: ups_disk = param_for_gal['ups_disk'] except KeyError: raise Exception('no ups_disk is specified.') try: ups_bulg = param_for_gal['ups_bulg'] except KeyError: raise Exception('no ups_bulg is specified') # try: # h = param_for_gal['h'] # except KeyError: # raise Exception('h is not specified.') # now deal with derived params, if any, such as M try: M = 10**param_for_gal['logM'] except KeyError: raise Exception('logM is not specified.') # sum over if (DM_profile == "NFW") or (DM_profile == "Burkert"): chi2_i = chi2_single_gal(m=m, M=M, c=c, Rs=Rs, ups_disk=ups_disk, ups_bulg=ups_bulg, gal=gal, DM_profile=DM_profile, combine_mode=combine_mode) elif DM_profile == "Soliton": chi2_i = chi2_single_gal_overshooting(m=m, M=M, ups_disk=ups_disk, ups_bulg=ups_bulg, gal=gal, flg_Vtot=False) chi2_tot += chi2_i # chi2_comp.append(chi2_i) chi2_comp.append(M) # use chi2_comp to contain M temporarily chi2_comp.insert(0, chi2_tot) if verbose > 5: print('-----chi2.py:chi2_comp=%s' % chi2_comp) # return chi2_tot return np.array(chi2_comp)
[ "numpy.abs", "numpy.sqrt", "model.M_sol", "numpy.append", "numpy.array", "model.v2_rot", "numpy.linspace", "numpy.meshgrid", "numpy.logspace" ]
[((591, 647), 'model.v2_rot', 'model.v2_rot', (['gal', 'c', 'Rs', 'ups_bulg', 'ups_disk', 'DM_profile'], {}), '(gal, c, Rs, ups_bulg, ups_disk, DM_profile)\n', (603, 647), False, 'import model\n'), ((1994, 2022), 'numpy.linspace', 'np.linspace', (['(1)', '(80)', 'gridsize'], {}), '(1, 80, gridsize)\n', (2005, 2022), True, 'import numpy as np\n'), ((2035, 2064), 'numpy.logspace', 'np.logspace', (['(0)', '(1.5)', 'gridsize'], {}), '(0, 1.5, gridsize)\n', (2046, 2064), True, 'import numpy as np\n'), ((2087, 2128), 'numpy.meshgrid', 'np.meshgrid', (['rs_arr', 'c_arr'], {'indexing': '"""ij"""'}), "(rs_arr, c_arr, indexing='ij')\n", (2098, 2128), True, 'import numpy as np\n'), ((2651, 2670), 'numpy.array', 'np.array', (['chi2_flat'], {}), '(chi2_flat)\n', (2659, 2670), True, 'import numpy as np\n'), ((3702, 3799), 'model.v2_rot', 'model.v2_rot', (['gal', 'c', 'Rs', 'ups_bulg', 'ups_disk', 'DM_profile'], {'m': 'm', 'M': 'M', 'combine_mode': 'combine_mode'}), '(gal, c, Rs, ups_bulg, ups_disk, DM_profile, m=m, M=M,\n combine_mode=combine_mode)\n', (3714, 3799), False, 'import model\n'), ((12069, 12088), 'numpy.array', 'np.array', (['chi2_comp'], {}), '(chi2_comp)\n', (12077, 12088), True, 'import numpy as np\n'), ((3674, 3686), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3682, 3686), True, 'import numpy as np\n'), ((6046, 6058), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6054, 6058), True, 'import numpy as np\n'), ((6257, 6277), 'model.M_sol', 'model.M_sol', (['r', 'm', 'M'], {}), '(r, m, M)\n', (6268, 6277), False, 'import model\n'), ((1598, 1611), 'numpy.sqrt', 'np.sqrt', (['Vth2'], {}), '(Vth2)\n', (1605, 1611), True, 'import numpy as np\n'), ((4848, 4861), 'numpy.sqrt', 'np.sqrt', (['Vth2'], {}), '(Vth2)\n', (4855, 4861), True, 'import numpy as np\n'), ((5276, 5296), 'numpy.append', 'np.append', (['Vtot', 'Vth'], {}), '(Vtot, Vth)\n', (5285, 5296), True, 'import numpy as np\n'), ((6700, 6713), 'numpy.sqrt', 'np.sqrt', (['Vth2'], {}), '(Vth2)\n', (6707, 6713), True, 'import numpy as np\n'), ((7042, 7062), 'numpy.append', 'np.append', (['Vtot', 'Vth'], {}), '(Vtot, Vth)\n', (7051, 7062), True, 'import numpy as np\n'), ((6586, 6605), 'numpy.abs', 'np.abs', (['gal.Vgas[i]'], {}), '(gal.Vgas[i])\n', (6592, 6605), True, 'import numpy as np\n'), ((6477, 6496), 'numpy.abs', 'np.abs', (['gal.Vbul[i]'], {}), '(gal.Vbul[i])\n', (6483, 6496), True, 'import numpy as np\n'), ((6535, 6555), 'numpy.abs', 'np.abs', (['gal.Vdisk[i]'], {}), '(gal.Vdisk[i])\n', (6541, 6555), True, 'import numpy as np\n')]
import hashlib import json import os from argparse import ArgumentParser, Namespace from collections import defaultdict from copy import deepcopy from functools import partial from typing import Dict, List, Optional, Type import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F import transformers from torch import Tensor from torch.utils.data import ConcatDataset, DataLoader, RandomSampler from transformers import AutoConfig, AutoModel, AutoTokenizer import constant import util from dataset.base import Dataset from enumeration import Schedule, Split, Task from metric import Metric from model.module import Identity, InputVariationalDropout, MeanPooling, Transformer class Model(pl.LightningModule): def __init__(self, hparams): super(Model, self).__init__() self.optimizer = None self.scheduler = None self._metric: Optional[Metric] = None self.metrics: Dict[str, Metric] = dict() self.trn_datasets: List[Dataset] = None self.val_datasets: List[Dataset] = None self.tst_datasets: List[Dataset] = None self.padding: Dict[str, int] = {} self.base_dir: str = "" self._batch_per_epoch: int = -1 self._comparsion: Optional[str] = None self._selection_criterion: Optional[str] = None if isinstance(hparams, dict): hparams = Namespace(**hparams) # self.hparams: Namespace = hparams self.save_hyperparameters(hparams) pl.seed_everything(hparams.seed) self.tokenizer = AutoTokenizer.from_pretrained(hparams.pretrain) self.model = self.build_model() self.freeze_layers() self.weight = nn.Parameter(torch.zeros(self.num_layers)) self.mapping = None if hparams.mapping: assert os.path.isfile(hparams.mapping) self.mapping = torch.load(hparams.mapping) util.freeze(self.mapping) self.projector = self.build_projector() self.dropout = InputVariationalDropout(hparams.input_dropout) def build_model(self): config = AutoConfig.from_pretrained( self.hparams.pretrain, output_hidden_states=True ) model = AutoModel.from_pretrained(self.hparams.pretrain, config=config) return model def freeze_layers(self): if self.hparams.freeze_layer == -1: return elif self.hparams.freeze_layer >= 0: for i in range(self.hparams.freeze_layer + 1): if i == 0: print("freeze embeddings") self.freeze_embeddings() else: print(f"freeze layer {i}") self.freeze_layer(i) def freeze_embeddings(self): if isinstance(self.model, transformers.BertModel) or isinstance( self.model, transformers.RobertaModel ): util.freeze(self.model.embeddings) elif isinstance(self.model, transformers.XLMModel): util.freeze(self.model.position_embeddings) if self.model.n_langs > 1 and self.model.use_lang_emb: util.freeze(self.model.lang_embeddings) util.freeze(self.model.embeddings) else: raise ValueError("Unsupported model") def freeze_layer(self, layer): if isinstance(self.model, transformers.BertModel) or isinstance( self.model, transformers.RobertaModel ): util.freeze(self.model.encoder.layer[layer - 1]) elif isinstance(self.model, transformers.XLMModel): util.freeze(self.model.attentions[layer - 1]) util.freeze(self.model.layer_norm1[layer - 1]) util.freeze(self.model.ffns[layer - 1]) util.freeze(self.model.layer_norm2[layer - 1]) else: raise ValueError("Unsupported model") @property def hidden_size(self): if isinstance(self.model, transformers.BertModel) or isinstance( self.model, transformers.RobertaModel ): return self.model.config.hidden_size elif isinstance(self.model, transformers.XLMModel): return self.model.dim else: raise ValueError("Unsupported model") @property def num_layers(self): if isinstance(self.model, transformers.BertModel) or isinstance( self.model, transformers.RobertaModel ): return self.model.config.num_hidden_layers + 1 elif isinstance(self.model, transformers.XLMModel): return self.model.n_layers + 1 else: raise ValueError("Unsupported model") @property def batch_per_epoch(self): if self.trn_datasets is None: self.trn_datasets = self.prepare_datasets(Split.train) if self._batch_per_epoch < 0: total_datasize = sum([len(d) for d in self.trn_datasets]) self._batch_per_epoch = np.ceil(total_datasize / self.hparams.batch_size) return self._batch_per_epoch @property def selection_criterion(self): assert self._selection_criterion is not None return self._selection_criterion @property def comparsion(self): assert self._comparsion is not None return self._comparsion def setup_metrics(self): assert self._metric is not None langs = self.hparams.trn_langs + self.hparams.val_langs + self.hparams.tst_langs langs = sorted(list(set(langs))) for lang in langs: self.metrics[lang] = deepcopy(self._metric) self.reset_metrics() def reset_metrics(self): for metric in self.metrics.values(): metric.reset() def build_projector(self): hparams = self.hparams if hparams.projector == "id": return Identity() elif hparams.projector == "meanpool": return MeanPooling() elif hparams.projector == "transformer": return Transformer( input_dim=self.hidden_size, hidden_dim=hparams.projector_trm_hidden_size, num_heads=hparams.projector_trm_num_heads, dropout=hparams.projector_dropout, num_layers=hparams.projector_trm_num_layers, ) else: raise ValueError(hparams.projector) def get_mask(self, sent: Tensor): mask = (sent != self.tokenizer.pad_token_id).long() return mask def encode_sent( self, sent: Tensor, langs: Optional[List[str]] = None, segment: Optional[Tensor] = None, model: Optional[transformers.PreTrainedModel] = None, return_raw_hidden_states: bool = False, ): if model is None: model = self.model mask = self.get_mask(sent) if isinstance(model, transformers.BertModel) or isinstance( self.model, transformers.RobertaModel ): output = model(input_ids=sent, attention_mask=mask, token_type_ids=segment) elif isinstance(model, transformers.XLMModel): lang_ids: Optional[torch.Tensor] if langs is not None: try: batch_size, seq_len = sent.shape lang_ids = torch.tensor( [self.tokenizer.lang2id[lang] for lang in langs], dtype=torch.long, device=sent.device, ) lang_ids = lang_ids.unsqueeze(1).expand(batch_size, seq_len) except KeyError as e: print(f"KeyError with missing language {e}") lang_ids = None output = model( input_ids=sent, attention_mask=mask, langs=lang_ids, token_type_ids=segment, ) else: raise ValueError("Unsupported model") if return_raw_hidden_states: return output["hidden_states"] hs = self.map_feature(output["hidden_states"], langs) hs = self.process_feature(hs) hs = self.dropout(hs) hs = self.projector(hs, mask) return hs def map_feature(self, hidden_states: List[Tensor], langs): if self.mapping is None: return hidden_states assert len(set(langs)) == 1, "a batch should contain only one language" lang = langs[0] lang = constant.LANGUAGE_TO_ISO639.get(lang, lang) if lang not in self.mapping: return hidden_states hs = [] for h, m in zip(hidden_states, self.mapping[lang]): hs.append(m(h)) return hs def process_feature(self, hidden_states: List[Tensor]): if self.hparams.weighted_feature: hs: Tensor = torch.stack(hidden_states) weight = F.softmax(self.weight, dim=0).view(-1, 1, 1, 1) hs = hs * weight hs = hs.sum(dim=0) else: hs = hidden_states[self.hparams.feature_layer] return hs def evaluation_step_helper(self, batch, prefix) -> Dict[str, Tensor]: raise NotImplementedError def validation_step(self, batch, batch_idx, dataloader_idx=0): return self.evaluation_step_helper(batch, "val") def test_step(self, batch, batch_idx, dataloader_idx=0): return self.evaluation_step_helper(batch, "tst") def training_epoch_end(self, outputs): return def aggregate_outputs( self, outputs: List[List[Dict[str, Tensor]]], langs: List[str], prefix: str ): assert prefix in ["val", "tst"] aver_result = defaultdict(list) for lang, output in zip(langs, outputs): for key in output[0]: mean_val = torch.stack([x[key] for x in output]).mean() self.log(key, mean_val) raw_key = key.replace(f"{lang}_", "") aver_result[raw_key].append(mean_val) for key, vals in aver_result.items(): self.log(key, torch.stack(vals).mean()) def aggregate_metrics(self, langs: List[str], prefix: str): aver_metric = defaultdict(list) for lang in langs: metric = self.metrics[lang] for key, val in metric.get_metric().items(): self.log(f"{prefix}_{lang}_{key}", val) aver_metric[key].append(val) for key, vals in aver_metric.items(): self.log(f"{prefix}_{key}", torch.stack(vals).mean()) def validation_epoch_end(self, outputs): if len(self.hparams.val_langs) == 1: outputs = [outputs] self.aggregate_outputs(outputs, self.hparams.val_langs, "val") self.aggregate_metrics(self.hparams.val_langs, "val") return def test_epoch_end(self, outputs): if len(self.hparams.tst_langs) == 1: outputs = [outputs] self.aggregate_outputs(outputs, self.hparams.tst_langs, "tst") self.aggregate_metrics(self.hparams.tst_langs, "tst") return def get_warmup_and_total_steps(self): if self.hparams.max_steps is not None: max_steps = self.hparams.max_steps else: max_steps = self.hparams.max_epochs * self.batch_per_epoch assert not ( self.hparams.warmup_steps != -1 and self.hparams.warmup_portion != -1 ) if self.hparams.warmup_steps != -1: assert self.hparams.warmup_steps > 0 warmup_steps = self.hparams.warmup_steps elif self.hparams.warmup_portion != -1: assert 0 < self.hparams.warmup_portion < 1 warmup_steps = int(max_steps * self.hparams.warmup_portion) else: warmup_steps = 1 return warmup_steps, max_steps def configure_optimizers(self): no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [] optimizer_grouped_parameters.append( { "params": [ p for n, p in self.named_parameters() if not any(nd in n for nd in no_decay) ], "weight_decay": self.hparams.weight_decay, } ) optimizer_grouped_parameters.append( { "params": [ p for n, p in self.named_parameters() if any(nd in n for nd in no_decay) ], "weight_decay": 0.0, } ) optimizer = torch.optim.AdamW( optimizer_grouped_parameters, lr=self.hparams.learning_rate, betas=(0.9, self.hparams.adam_beta2), eps=self.hparams.adam_eps, ) warmup_steps, max_steps = self.get_warmup_and_total_steps() if self.hparams.schedule == Schedule.invsqroot: scheduler = util.get_inverse_square_root_schedule_with_warmup( optimizer, warmup_steps ) interval = "step" elif self.hparams.schedule == Schedule.linear: scheduler = util.get_linear_schedule_with_warmup( optimizer, warmup_steps, max_steps ) interval = "step" elif self.hparams.schedule == Schedule.reduceOnPlateau: scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, factor=0.5, patience=0, min_lr=1e-6, mode="min" ) interval = "epoch" else: raise ValueError(self.hparams.schedule) self.optimizer = optimizer self.scheduler = scheduler scheduler_dict = {"scheduler": scheduler, "interval": interval} if self.hparams.schedule == Schedule.reduceOnPlateau: scheduler_dict["monitor"] = "val_loss" return [optimizer], [scheduler_dict] def _get_signature(self, params: Dict): def md5_helper(obj): return hashlib.md5(str(obj).encode()).hexdigest() signature = dict() for key, val in params.items(): if key == "tokenizer" and isinstance(val, transformers.PreTrainedTokenizer): signature[key] = md5_helper(list(val.get_vocab().items())) else: signature[key] = str(val) md5 = md5_helper(list(signature.items())) return md5, signature def prepare_datasets(self, split: str) -> List[Dataset]: raise NotImplementedError def prepare_datasets_helper( self, data_class: Type[Dataset], langs: List[str], split: str, max_len: int, **kwargs, ): datasets = [] for lang in langs: filepath = data_class.get_file(self.hparams.data_dir, lang, split) if filepath is None: print(f"skipping {split} language: {lang}") continue params = {} params["task"] = self.hparams.task params["tokenizer"] = self.tokenizer params["filepath"] = filepath params["lang"] = lang params["split"] = split params["max_len"] = max_len if split == Split.train: params["subset_ratio"] = self.hparams.subset_ratio params["subset_count"] = self.hparams.subset_count params["subset_seed"] = self.hparams.subset_seed params.update(kwargs) md5, signature = self._get_signature(params) del params["task"] cache_file = f"{self.hparams.cache_path}/{md5}" if self.hparams.cache_dataset and os.path.isfile(cache_file): print(f"load from cache {filepath} with {self.hparams.pretrain}") dataset = torch.load(cache_file) else: dataset = data_class(**params) if self.hparams.cache_dataset: print(f"save to cache {filepath} with {self.hparams.pretrain}") torch.save(dataset, cache_file) with open(f"{cache_file}.json", "w") as fp: json.dump(signature, fp) datasets.append(dataset) return datasets def train_dataloader(self): if self.trn_datasets is None: self.trn_datasets = self.prepare_datasets(Split.train) collate = partial(util.default_collate, padding=self.padding) if len(self.trn_datasets) == 1: dataset = self.trn_datasets[0] sampler = RandomSampler(dataset) else: dataset = ConcatDataset(self.trn_datasets) if self.hparams.mix_sampling: sampler = RandomSampler(dataset) else: sampler = util.ConcatSampler(dataset, self.hparams.batch_size) return DataLoader( dataset, batch_size=self.hparams.batch_size, sampler=sampler, pin_memory=True, drop_last=False, collate_fn=collate, num_workers=1, ) def val_dataloader(self): if self.val_datasets is None: self.val_datasets = self.prepare_datasets(Split.dev) collate = partial(util.default_collate, padding=self.padding) return [ DataLoader( val_dataset, batch_size=self.hparams.eval_batch_size, shuffle=False, pin_memory=True, drop_last=False, collate_fn=collate, num_workers=1, ) for val_dataset in self.val_datasets ] def test_dataloader(self): if self.tst_datasets is None: self.tst_datasets = self.prepare_datasets(Split.test) collate = partial(util.default_collate, padding=self.padding) return [ DataLoader( tst_dataset, batch_size=self.hparams.eval_batch_size, shuffle=False, pin_memory=True, drop_last=False, collate_fn=collate, num_workers=1, ) for tst_dataset in self.tst_datasets ] @classmethod def add_model_specific_args(cls, parent_parser): parser = ArgumentParser(parents=[parent_parser], add_help=False) # fmt: off # shared parser.add_argument("--task", required=True, choices=Task().choices(), type=str) parser.add_argument("--data_dir", required=True, type=str) parser.add_argument("--trn_langs", required=True, nargs="+", type=str) parser.add_argument("--val_langs", required=True, nargs="+", type=str) parser.add_argument("--tst_langs", default=[], nargs="*", type=str) parser.add_argument("--max_trn_len", default=128, type=int) parser.add_argument("--max_tst_len", default=128, type=int) parser.add_argument("--subset_ratio", default=1.0, type=float) parser.add_argument("--subset_count", default=-1, type=int) parser.add_argument("--subset_seed", default=42, type=int) parser.add_argument("--mix_sampling", default=False, type=util.str2bool) # encoder parser.add_argument("--pretrain", required=True, type=str) parser.add_argument("--freeze_layer", default=-1, type=int) parser.add_argument("--feature_layer", default=-1, type=int) parser.add_argument("--weighted_feature", default=False, type=util.str2bool) parser.add_argument("--projector", default="id", choices=["id", "meanpool", "transformer"], type=str) parser.add_argument("--projector_trm_hidden_size", default=3072, type=int) parser.add_argument("--projector_trm_num_heads", default=12, type=int) parser.add_argument("--projector_trm_num_layers", default=4, type=int) parser.add_argument("--projector_dropout", default=0.2, type=float) parser.add_argument("--input_dropout", default=0.2, type=float) parser.add_argument("--mapping", default="", type=str) # misc parser.add_argument("--seed", default=42, type=int) parser.add_argument("--learning_rate", default=5e-5, type=float) parser.add_argument("--adam_beta2", default=0.99, type=float) parser.add_argument("--adam_eps", default=1e-8, type=float) parser.add_argument("--weight_decay", default=0.0, type=float) parser.add_argument("--batch_size", default=32, type=int) parser.add_argument("--eval_batch_size", default=32, type=int) parser.add_argument("--schedule", default=Schedule.linear, choices=Schedule().choices(), type=str) parser.add_argument("--warmup_steps", default=-1, type=int) parser.add_argument("--warmup_portion", default=-1, type=float) # fmt: on return parser
[ "torch.utils.data.ConcatDataset", "model.module.InputVariationalDropout", "argparse.Namespace", "constant.LANGUAGE_TO_ISO639.get", "transformers.AutoTokenizer.from_pretrained", "copy.deepcopy", "torch.nn.functional.softmax", "transformers.AutoModel.from_pretrained", "argparse.ArgumentParser", "jso...
[((1536, 1568), 'pytorch_lightning.seed_everything', 'pl.seed_everything', (['hparams.seed'], {}), '(hparams.seed)\n', (1554, 1568), True, 'import pytorch_lightning as pl\n'), ((1595, 1642), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['hparams.pretrain'], {}), '(hparams.pretrain)\n', (1624, 1642), False, 'from transformers import AutoConfig, AutoModel, AutoTokenizer\n'), ((2050, 2096), 'model.module.InputVariationalDropout', 'InputVariationalDropout', (['hparams.input_dropout'], {}), '(hparams.input_dropout)\n', (2073, 2096), False, 'from model.module import Identity, InputVariationalDropout, MeanPooling, Transformer\n'), ((2142, 2218), 'transformers.AutoConfig.from_pretrained', 'AutoConfig.from_pretrained', (['self.hparams.pretrain'], {'output_hidden_states': '(True)'}), '(self.hparams.pretrain, output_hidden_states=True)\n', (2168, 2218), False, 'from transformers import AutoConfig, AutoModel, AutoTokenizer\n'), ((2257, 2320), 'transformers.AutoModel.from_pretrained', 'AutoModel.from_pretrained', (['self.hparams.pretrain'], {'config': 'config'}), '(self.hparams.pretrain, config=config)\n', (2282, 2320), False, 'from transformers import AutoConfig, AutoModel, AutoTokenizer\n'), ((8511, 8554), 'constant.LANGUAGE_TO_ISO639.get', 'constant.LANGUAGE_TO_ISO639.get', (['lang', 'lang'], {}), '(lang, lang)\n', (8542, 8554), False, 'import constant\n'), ((9716, 9733), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (9727, 9733), False, 'from collections import defaultdict\n'), ((10224, 10241), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (10235, 10241), False, 'from collections import defaultdict\n'), ((12629, 12782), 'torch.optim.AdamW', 'torch.optim.AdamW', (['optimizer_grouped_parameters'], {'lr': 'self.hparams.learning_rate', 'betas': '(0.9, self.hparams.adam_beta2)', 'eps': 'self.hparams.adam_eps'}), '(optimizer_grouped_parameters, lr=self.hparams.\n learning_rate, betas=(0.9, self.hparams.adam_beta2), eps=self.hparams.\n adam_eps)\n', (12646, 12782), False, 'import torch\n'), ((16448, 16499), 'functools.partial', 'partial', (['util.default_collate'], {'padding': 'self.padding'}), '(util.default_collate, padding=self.padding)\n', (16455, 16499), False, 'from functools import partial\n'), ((16901, 17046), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'self.hparams.batch_size', 'sampler': 'sampler', 'pin_memory': '(True)', 'drop_last': '(False)', 'collate_fn': 'collate', 'num_workers': '(1)'}), '(dataset, batch_size=self.hparams.batch_size, sampler=sampler,\n pin_memory=True, drop_last=False, collate_fn=collate, num_workers=1)\n', (16911, 17046), False, 'from torch.utils.data import ConcatDataset, DataLoader, RandomSampler\n'), ((17291, 17342), 'functools.partial', 'partial', (['util.default_collate'], {'padding': 'self.padding'}), '(util.default_collate, padding=self.padding)\n', (17298, 17342), False, 'from functools import partial\n'), ((17862, 17913), 'functools.partial', 'partial', (['util.default_collate'], {'padding': 'self.padding'}), '(util.default_collate, padding=self.padding)\n', (17869, 17913), False, 'from functools import partial\n'), ((18366, 18421), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'parents': '[parent_parser]', 'add_help': '(False)'}), '(parents=[parent_parser], add_help=False)\n', (18380, 18421), False, 'from argparse import ArgumentParser, Namespace\n'), ((1420, 1440), 'argparse.Namespace', 'Namespace', ([], {}), '(**hparams)\n', (1429, 1440), False, 'from argparse import ArgumentParser, Namespace\n'), ((1748, 1776), 'torch.zeros', 'torch.zeros', (['self.num_layers'], {}), '(self.num_layers)\n', (1759, 1776), False, 'import torch\n'), ((1853, 1884), 'os.path.isfile', 'os.path.isfile', (['hparams.mapping'], {}), '(hparams.mapping)\n', (1867, 1884), False, 'import os\n'), ((1912, 1939), 'torch.load', 'torch.load', (['hparams.mapping'], {}), '(hparams.mapping)\n', (1922, 1939), False, 'import torch\n'), ((1952, 1977), 'util.freeze', 'util.freeze', (['self.mapping'], {}), '(self.mapping)\n', (1963, 1977), False, 'import util\n'), ((2948, 2982), 'util.freeze', 'util.freeze', (['self.model.embeddings'], {}), '(self.model.embeddings)\n', (2959, 2982), False, 'import util\n'), ((3515, 3563), 'util.freeze', 'util.freeze', (['self.model.encoder.layer[layer - 1]'], {}), '(self.model.encoder.layer[layer - 1])\n', (3526, 3563), False, 'import util\n'), ((4996, 5045), 'numpy.ceil', 'np.ceil', (['(total_datasize / self.hparams.batch_size)'], {}), '(total_datasize / self.hparams.batch_size)\n', (5003, 5045), True, 'import numpy as np\n'), ((5605, 5627), 'copy.deepcopy', 'deepcopy', (['self._metric'], {}), '(self._metric)\n', (5613, 5627), False, 'from copy import deepcopy\n'), ((5879, 5889), 'model.module.Identity', 'Identity', ([], {}), '()\n', (5887, 5889), False, 'from model.module import Identity, InputVariationalDropout, MeanPooling, Transformer\n'), ((8876, 8902), 'torch.stack', 'torch.stack', (['hidden_states'], {}), '(hidden_states)\n', (8887, 8902), False, 'import torch\n'), ((12981, 13055), 'util.get_inverse_square_root_schedule_with_warmup', 'util.get_inverse_square_root_schedule_with_warmup', (['optimizer', 'warmup_steps'], {}), '(optimizer, warmup_steps)\n', (13030, 13055), False, 'import util\n'), ((16605, 16627), 'torch.utils.data.RandomSampler', 'RandomSampler', (['dataset'], {}), '(dataset)\n', (16618, 16627), False, 'from torch.utils.data import ConcatDataset, DataLoader, RandomSampler\n'), ((16664, 16696), 'torch.utils.data.ConcatDataset', 'ConcatDataset', (['self.trn_datasets'], {}), '(self.trn_datasets)\n', (16677, 16696), False, 'from torch.utils.data import ConcatDataset, DataLoader, RandomSampler\n'), ((17372, 17525), 'torch.utils.data.DataLoader', 'DataLoader', (['val_dataset'], {'batch_size': 'self.hparams.eval_batch_size', 'shuffle': '(False)', 'pin_memory': '(True)', 'drop_last': '(False)', 'collate_fn': 'collate', 'num_workers': '(1)'}), '(val_dataset, batch_size=self.hparams.eval_batch_size, shuffle=\n False, pin_memory=True, drop_last=False, collate_fn=collate, num_workers=1)\n', (17382, 17525), False, 'from torch.utils.data import ConcatDataset, DataLoader, RandomSampler\n'), ((17943, 18096), 'torch.utils.data.DataLoader', 'DataLoader', (['tst_dataset'], {'batch_size': 'self.hparams.eval_batch_size', 'shuffle': '(False)', 'pin_memory': '(True)', 'drop_last': '(False)', 'collate_fn': 'collate', 'num_workers': '(1)'}), '(tst_dataset, batch_size=self.hparams.eval_batch_size, shuffle=\n False, pin_memory=True, drop_last=False, collate_fn=collate, num_workers=1)\n', (17953, 18096), False, 'from torch.utils.data import ConcatDataset, DataLoader, RandomSampler\n'), ((3055, 3098), 'util.freeze', 'util.freeze', (['self.model.position_embeddings'], {}), '(self.model.position_embeddings)\n', (3066, 3098), False, 'import util\n'), ((3234, 3268), 'util.freeze', 'util.freeze', (['self.model.embeddings'], {}), '(self.model.embeddings)\n', (3245, 3268), False, 'import util\n'), ((3636, 3681), 'util.freeze', 'util.freeze', (['self.model.attentions[layer - 1]'], {}), '(self.model.attentions[layer - 1])\n', (3647, 3681), False, 'import util\n'), ((3694, 3740), 'util.freeze', 'util.freeze', (['self.model.layer_norm1[layer - 1]'], {}), '(self.model.layer_norm1[layer - 1])\n', (3705, 3740), False, 'import util\n'), ((3753, 3792), 'util.freeze', 'util.freeze', (['self.model.ffns[layer - 1]'], {}), '(self.model.ffns[layer - 1])\n', (3764, 3792), False, 'import util\n'), ((3805, 3851), 'util.freeze', 'util.freeze', (['self.model.layer_norm2[layer - 1]'], {}), '(self.model.layer_norm2[layer - 1])\n', (3816, 3851), False, 'import util\n'), ((5955, 5968), 'model.module.MeanPooling', 'MeanPooling', ([], {}), '()\n', (5966, 5968), False, 'from model.module import Identity, InputVariationalDropout, MeanPooling, Transformer\n'), ((13195, 13267), 'util.get_linear_schedule_with_warmup', 'util.get_linear_schedule_with_warmup', (['optimizer', 'warmup_steps', 'max_steps'], {}), '(optimizer, warmup_steps, max_steps)\n', (13231, 13267), False, 'import util\n'), ((15710, 15736), 'os.path.isfile', 'os.path.isfile', (['cache_file'], {}), '(cache_file)\n', (15724, 15736), False, 'import os\n'), ((15846, 15868), 'torch.load', 'torch.load', (['cache_file'], {}), '(cache_file)\n', (15856, 15868), False, 'import torch\n'), ((16765, 16787), 'torch.utils.data.RandomSampler', 'RandomSampler', (['dataset'], {}), '(dataset)\n', (16778, 16787), False, 'from torch.utils.data import ConcatDataset, DataLoader, RandomSampler\n'), ((16832, 16884), 'util.ConcatSampler', 'util.ConcatSampler', (['dataset', 'self.hparams.batch_size'], {}), '(dataset, self.hparams.batch_size)\n', (16850, 16884), False, 'import util\n'), ((3182, 3221), 'util.freeze', 'util.freeze', (['self.model.lang_embeddings'], {}), '(self.model.lang_embeddings)\n', (3193, 3221), False, 'import util\n'), ((6037, 6259), 'model.module.Transformer', 'Transformer', ([], {'input_dim': 'self.hidden_size', 'hidden_dim': 'hparams.projector_trm_hidden_size', 'num_heads': 'hparams.projector_trm_num_heads', 'dropout': 'hparams.projector_dropout', 'num_layers': 'hparams.projector_trm_num_layers'}), '(input_dim=self.hidden_size, hidden_dim=hparams.\n projector_trm_hidden_size, num_heads=hparams.projector_trm_num_heads,\n dropout=hparams.projector_dropout, num_layers=hparams.\n projector_trm_num_layers)\n', (6048, 6259), False, 'from model.module import Identity, InputVariationalDropout, MeanPooling, Transformer\n'), ((8924, 8953), 'torch.nn.functional.softmax', 'F.softmax', (['self.weight'], {'dim': '(0)'}), '(self.weight, dim=0)\n', (8933, 8953), True, 'import torch.nn.functional as F\n'), ((13416, 13524), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'torch.optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'factor': '(0.5)', 'patience': '(0)', 'min_lr': '(1e-06)', 'mode': '"""min"""'}), "(optimizer, factor=0.5, patience=\n 0, min_lr=1e-06, mode='min')\n", (13458, 13524), False, 'import torch\n'), ((16085, 16116), 'torch.save', 'torch.save', (['dataset', 'cache_file'], {}), '(dataset, cache_file)\n', (16095, 16116), False, 'import torch\n'), ((7330, 7435), 'torch.tensor', 'torch.tensor', (['[self.tokenizer.lang2id[lang] for lang in langs]'], {'dtype': 'torch.long', 'device': 'sent.device'}), '([self.tokenizer.lang2id[lang] for lang in langs], dtype=torch.\n long, device=sent.device)\n', (7342, 7435), False, 'import torch\n'), ((9844, 9881), 'torch.stack', 'torch.stack', (['[x[key] for x in output]'], {}), '([x[key] for x in output])\n', (9855, 9881), False, 'import torch\n'), ((10111, 10128), 'torch.stack', 'torch.stack', (['vals'], {}), '(vals)\n', (10122, 10128), False, 'import torch\n'), ((10555, 10572), 'torch.stack', 'torch.stack', (['vals'], {}), '(vals)\n', (10566, 10572), False, 'import torch\n'), ((16205, 16229), 'json.dump', 'json.dump', (['signature', 'fp'], {}), '(signature, fp)\n', (16214, 16229), False, 'import json\n'), ((18519, 18525), 'enumeration.Task', 'Task', ([], {}), '()\n', (18523, 18525), False, 'from enumeration import Schedule, Split, Task\n'), ((20709, 20719), 'enumeration.Schedule', 'Schedule', ([], {}), '()\n', (20717, 20719), False, 'from enumeration import Schedule, Split, Task\n')]
import numpy as np from matplotlib import pyplot as plt from math import * from scipy.integrate import quad from scipy.integrate import dblquad from scipy import integrate from scipy import special from numpy import median from numpy import linspace from copy import deepcopy def catoni(w, X, Y, delta, alpha, valpha): """ Catoni estimator of the gradient Parameters ---------- w : d-array, candidate X : d-n array, sample Y : n-array, sample delta : float, a parameter that determines the precision of the gradient estimates alpha : float, quantile level valpha : float, value-at-risk Returns ------- theta : d-array, gradient estimates """ d = len(w) n = len(Y) ll = stagewise_grad(w, X, Y, alpha, valpha) variance = [np.var(ll[k]) for k in range(d)] s = [sqrt(variance[k] * n / log(2 / delta)) for k in range(d)] for i in range(d): if s[i] == 0: s[i] = 0.00001 theta = np.zeros(d) for i in range(5): xx = [(ll[k] - theta[k]) / s[k] for k in range(d)] xx = [np.where(xx[k] >= 0, np.log(1 + xx[k] + xx[k] * xx[k]), -np.log(1 - xx[k] + xx[k] * xx[k])) for k in range(d)] theta = [theta[k] + (s[k] / n) * sum(xx[k]) for k in range(d)] return theta def rgd(initial_w, X1, Y1, X2, Y2, alpha, delta, eta, max_iterations, max_gradient_descents): """ A stage-wise robust gradient descent (uses the catoni estimator for the gradient) Parameters ---------- initial_w : d-array, initial value of w X1 : d-n array, first half of the x-sample X2 : d-n array, second half of the x-sample used to compute the value at risk Y1 : n array, first half of the y-sample Y2 : n-array, second half of the y-sample used to compute the value-at-risk alpha : float, quantile level delta : float, a parameter that determines the precision of the gradient estimates eta : float, stepsize for each gradient descent max_iterations : int, maximum number of iterations for each gradient descent max_gradient_descents : int, maximum number of gradient descents Returns ------- ws : d-array, estimate of the optimal candidate """ d = len(initial_w) n = len(Y1) ws = initial_w w_history = [] S = max_gradient_descents T = max_iterations for s in range(S): X1_s = X1[:, s * int(n / S):(s + 1) * int(n / S)] Y1_s = Y1[s * int(n / S): (s + 1) * int(n / S)] X2_s = X2[:, s * int(n / S): (s + 1) * int(n / S)] Y2_s = Y2[s * int(n / S): (s + 1) * int(n / S)] w_0 = ws valpha = value_at_risk(loss_function(ws, X2_s, Y2_s), alpha) wt = w_0 for t in range(T): gradient = catoni(wt, X1_s, Y1_s, delta, alpha, valpha) print(gradient) wt = [wt[i] - eta * gradient[i] for i in range(d)] w_history += [wt] print(wt) ws = wt return ws
[ "numpy.zeros", "numpy.log", "numpy.var" ]
[((1040, 1051), 'numpy.zeros', 'np.zeros', (['d'], {}), '(d)\n', (1048, 1051), True, 'import numpy as np\n'), ((856, 869), 'numpy.var', 'np.var', (['ll[k]'], {}), '(ll[k])\n', (862, 869), True, 'import numpy as np\n'), ((1169, 1202), 'numpy.log', 'np.log', (['(1 + xx[k] + xx[k] * xx[k])'], {}), '(1 + xx[k] + xx[k] * xx[k])\n', (1175, 1202), True, 'import numpy as np\n'), ((1205, 1238), 'numpy.log', 'np.log', (['(1 - xx[k] + xx[k] * xx[k])'], {}), '(1 - xx[k] + xx[k] * xx[k])\n', (1211, 1238), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import cv2 import numpy as np import os from pathlib import Path from tqdm import tqdm import settings cwd = Path(os.path.dirname(__file__)) rollouts = cwd/'rollouts' def make_csv(): files = [] for i in sorted(rollouts.iterdir()): trajectory = Path(i) for file in sorted(trajectory.iterdir()): # TODO: Abstract this path = ('car_racing'/file).as_posix() if path.endswith('.png'): files.append(path) np.random.shuffle(files) split = int(settings.train_test_split*len(files)) train_files = files[:split] test_files = files[split:] with open('train_images.txt', 'w') as f: f.write('\n'.join(train_files)) with open('test_images.txt', 'w') as f: f.write('\n'.join(test_files)) #TODO: refactor redundant parts in these two calls def make_seq_csv(): dirs = [] for _dir in sorted(rollouts.iterdir()): dirs.append(('car_racing'/_dir).as_posix()) np.random.shuffle(dirs) split = len(dirs) - 5 train_dirs = dirs[:split] test_dirs = dirs[split:] with open('train_seq_dirs.txt', 'w') as f: f.write('\n'.join(train_dirs)) with open('test_seq_dirs.txt', 'w') as f: f.write('\n'.join(test_dirs)) def main(): make_csv() make_seq_csv() if __name__ == '__main__': main()
[ "os.path.dirname", "pathlib.Path", "numpy.random.shuffle" ]
[((141, 166), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (156, 166), False, 'import os\n'), ((508, 532), 'numpy.random.shuffle', 'np.random.shuffle', (['files'], {}), '(files)\n', (525, 532), True, 'import numpy as np\n'), ((1005, 1028), 'numpy.random.shuffle', 'np.random.shuffle', (['dirs'], {}), '(dirs)\n', (1022, 1028), True, 'import numpy as np\n'), ((289, 296), 'pathlib.Path', 'Path', (['i'], {}), '(i)\n', (293, 296), False, 'from pathlib import Path\n')]
import numpy as np import pytest import psyneulink.core.components.functions.nonstateful.selectionfunctions as Functions import psyneulink.core.globals.keywords as kw import psyneulink.core.llvm as pnlvm from psyneulink.core.globals.utilities import _SeededPhilox np.random.seed(0) SIZE=10 test_var = np.random.rand(SIZE) * 2.0 - 1.0 # the sum of probs should be 1.0 test_prob = np.random.rand(SIZE) test_prob /= sum(test_prob) test_philox = np.random.rand(SIZE) test_philox /= sum(test_philox) test_data = [ (Functions.OneHot, test_var, {'mode':kw.MAX_VAL}, [0., 0., 0., 0., 0., 0., 0., 0., 0.92732552, 0.]), (Functions.OneHot, test_var, {'mode':kw.MAX_ABS_VAL}, [0., 0., 0., 0., 0., 0., 0., 0., 0.92732552, 0.]), (Functions.OneHot, test_var, {'mode':kw.MAX_INDICATOR}, [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.]), (Functions.OneHot, test_var, {'mode':kw.MAX_ABS_INDICATOR}, [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.]), (Functions.OneHot, test_var, {'mode':kw.MIN_VAL}, [0., 0., 0., 0., 0., 0., 0., 0., 0., -0.23311696]), (Functions.OneHot, test_var, {'mode':kw.MIN_ABS_VAL}, [0., 0., 0., 0.08976637, 0., 0., 0., 0., 0., 0.]), (Functions.OneHot, test_var, {'mode':kw.MIN_INDICATOR}, [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]), (Functions.OneHot, test_var, {'mode':kw.MIN_ABS_INDICATOR}, [0., 0., 0., 1.,0., 0., 0., 0., 0., 0.]), (Functions.OneHot, [test_var, test_prob], {'mode':kw.PROB}, [0., 0., 0., 0.08976636599379373, 0., 0., 0., 0., 0., 0.]), (Functions.OneHot, [test_var, test_prob], {'mode':kw.PROB_INDICATOR}, [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.]), (Functions.OneHot, [test_var, test_philox], {'mode':kw.PROB}, [0., 0.43037873274483895, 0., 0., 0., 0., 0., 0., 0., 0.]), (Functions.OneHot, [test_var, test_philox], {'mode':kw.PROB_INDICATOR}, [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]), ] # use list, naming function produces ugly names names = [ "OneHot MAX_VAL", "OneHot MAX_ABS_VAL", "OneHot MAX_INDICATOR", "OneHot MAX_ABS_INDICATOR", "OneHot MIN_VAL", "OneHot MIN_ABS_VAL", "OneHot MIN_INDICATOR", "OneHot MIN_ABS_INDICATOR", "OneHot PROB", "OneHot PROB_INDICATOR", "OneHot PROB PHILOX", "OneHot PROB_INDICATOR PHILOX", ] GROUP_PREFIX="SelectionFunction " @pytest.mark.function @pytest.mark.integrator_function @pytest.mark.benchmark @pytest.mark.parametrize("func, variable, params, expected", test_data, ids=names) def test_basic(func, variable, params, expected, benchmark, func_mode): benchmark.group = GROUP_PREFIX + func.componentName + params['mode'] f = func(default_variable=variable, **params) if len(variable) == 2 and variable[1] is test_philox: f.parameters.random_state.set(_SeededPhilox([0])) EX = pytest.helpers.get_func_execution(f, func_mode) EX(variable) res = EX(variable) assert np.allclose(res, expected) if benchmark.enabled: benchmark(EX, variable)
[ "numpy.allclose", "psyneulink.core.globals.utilities._SeededPhilox", "numpy.random.rand", "pytest.helpers.get_func_execution", "pytest.mark.parametrize", "numpy.random.seed" ]
[((266, 283), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (280, 283), True, 'import numpy as np\n'), ((382, 402), 'numpy.random.rand', 'np.random.rand', (['SIZE'], {}), '(SIZE)\n', (396, 402), True, 'import numpy as np\n'), ((445, 465), 'numpy.random.rand', 'np.random.rand', (['SIZE'], {}), '(SIZE)\n', (459, 465), True, 'import numpy as np\n'), ((2351, 2437), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""func, variable, params, expected"""', 'test_data'], {'ids': 'names'}), "('func, variable, params, expected', test_data, ids=\n names)\n", (2374, 2437), False, 'import pytest\n'), ((2755, 2802), 'pytest.helpers.get_func_execution', 'pytest.helpers.get_func_execution', (['f', 'func_mode'], {}), '(f, func_mode)\n', (2788, 2802), False, 'import pytest\n'), ((2855, 2881), 'numpy.allclose', 'np.allclose', (['res', 'expected'], {}), '(res, expected)\n', (2866, 2881), True, 'import numpy as np\n'), ((303, 323), 'numpy.random.rand', 'np.random.rand', (['SIZE'], {}), '(SIZE)\n', (317, 323), True, 'import numpy as np\n'), ((2725, 2743), 'psyneulink.core.globals.utilities._SeededPhilox', '_SeededPhilox', (['[0]'], {}), '([0])\n', (2738, 2743), False, 'from psyneulink.core.globals.utilities import _SeededPhilox\n')]
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from numpy.testing import assert_allclose try: import matplotlib.pyplot as plt HAS_PLT = True except ImportError: HAS_PLT = False try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False from ...tests.helper import pytest import numpy as np from .. import hist from ...stats import histogram @pytest.mark.skipif('not HAS_PLT') def test_hist_basic(rseed=0): rng = np.random.RandomState(rseed) x = rng.randn(100) for range in [None, (-2, 2)]: n1, bins1, patches1 = plt.hist(x, 10, range=range) n2, bins2, patches2 = hist(x, 10, range=range) assert_allclose(n1, n2) assert_allclose(bins1, bins2) @pytest.mark.skipif('not HAS_PLT') def test_hist_specify_ax(rseed=0): rng = np.random.RandomState(rseed) x = rng.randn(100) fig, ax = plt.subplots(2) n1, bins1, patches1 = hist(x, 10, ax=ax[0]) assert patches1[0].axes is ax[0] n2, bins2, patches2 = hist(x, 10, ax=ax[1]) assert patches2[0].axes is ax[1] @pytest.mark.skipif('not HAS_PLT') def test_hist_autobin(rseed=0): rng = np.random.RandomState(rseed) x = rng.randn(100) # 'knuth' bintype depends on scipy that is optional dependency if HAS_SCIPY: bintypes = [10, np.arange(-3, 3, 10), 'knuth', 'scott', 'freedman', 'blocks'] else: bintypes = [10, np.arange(-3, 3, 10), 'scott', 'freedman', 'blocks'] for bintype in bintypes: for range in [None, (-3, 3)]: n1, bins1 = histogram(x, bintype, range=range) n2, bins2, patches = hist(x, bintype, range=range) assert_allclose(n1, n2) assert_allclose(bins1, bins2)
[ "matplotlib.pyplot.hist", "numpy.arange", "numpy.testing.assert_allclose", "matplotlib.pyplot.subplots", "numpy.random.RandomState" ]
[((588, 616), 'numpy.random.RandomState', 'np.random.RandomState', (['rseed'], {}), '(rseed)\n', (609, 616), True, 'import numpy as np\n'), ((942, 970), 'numpy.random.RandomState', 'np.random.RandomState', (['rseed'], {}), '(rseed)\n', (963, 970), True, 'import numpy as np\n'), ((1009, 1024), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (1021, 1024), True, 'import matplotlib.pyplot as plt\n'), ((1275, 1303), 'numpy.random.RandomState', 'np.random.RandomState', (['rseed'], {}), '(rseed)\n', (1296, 1303), True, 'import numpy as np\n'), ((705, 733), 'matplotlib.pyplot.hist', 'plt.hist', (['x', '(10)'], {'range': 'range'}), '(x, 10, range=range)\n', (713, 733), True, 'import matplotlib.pyplot as plt\n'), ((798, 821), 'numpy.testing.assert_allclose', 'assert_allclose', (['n1', 'n2'], {}), '(n1, n2)\n', (813, 821), False, 'from numpy.testing import assert_allclose\n'), ((830, 859), 'numpy.testing.assert_allclose', 'assert_allclose', (['bins1', 'bins2'], {}), '(bins1, bins2)\n', (845, 859), False, 'from numpy.testing import assert_allclose\n'), ((1437, 1457), 'numpy.arange', 'np.arange', (['(-3)', '(3)', '(10)'], {}), '(-3, 3, 10)\n', (1446, 1457), True, 'import numpy as np\n'), ((1553, 1573), 'numpy.arange', 'np.arange', (['(-3)', '(3)', '(10)'], {}), '(-3, 3, 10)\n', (1562, 1573), True, 'import numpy as np\n'), ((1828, 1851), 'numpy.testing.assert_allclose', 'assert_allclose', (['n1', 'n2'], {}), '(n1, n2)\n', (1843, 1851), False, 'from numpy.testing import assert_allclose\n'), ((1864, 1893), 'numpy.testing.assert_allclose', 'assert_allclose', (['bins1', 'bins2'], {}), '(bins1, bins2)\n', (1879, 1893), False, 'from numpy.testing import assert_allclose\n')]
import numpy as np import numba as nb from pymcx import MCX def create_props(spec, wavelen): layers = spec['layers'] lprops = spec['layer_properties'] ext_coeff = {k: np.interp(wavelen, *itr) for k, itr in spec['extinction_coeffs'].items()} media = np.empty((1+len(layers), 4), np.float32) media[0] = 0, 0, 1, spec.get('n_external', 1) for i, l in enumerate(layers): lp = lprops[l] g = lp['g'] mua = sum(ext_coeff[k] * lp['components'][k] for k in ext_coeff) mus = lp['Scatter A'] * wavelen ** -lp['Scatter b'] / (1 - g) media[1+i] = mua, mus, g, lp['n'] return media, np.stack(lprops[l]['BFi'] for l in layers) @nb.jit(nopython=True, nogil=True, parallel=False) def analysis(detp, prop, tof_domain, tau, wavelength, BFi, freq, ndet, ntof, nmedia, pcounts, paths, phiTD, phiFD, g1_top, phiDist): c = 2.998e+11 # speed of light in mm / s detBins = detp[0].astype(np.intc) - 1 tofBins = np.minimum(np.digitize(prop[1:, 3] @ detp[2:(2+nmedia)], c * tof_domain), ntof) - 1 distBins = np.minimum(np.digitize(prop[1:, 3] * detp[2:(2+nmedia)].T, c * tof_domain), ntof) - 1 path = -prop[1:, 0] @ detp[2:(2+nmedia)] phis = np.exp(path) fds = np.exp((-prop[1:, 0] + 2j * np.pi * freq * prop[1:, 3] / c).astype(np.complex64) @ detp[2:(2+nmedia)].astype(np.complex64)) prep = (-2*(2*np.pi*prop[1:, 3]/(wavelength*1e-6))**2*BFi).astype(np.float32) @ detp[(2+nmedia):(2+2*nmedia)] for i in range(len(detBins)): pcounts[detBins[i], tofBins[i]] += 1 paths[detBins[i], tofBins[i]] += detp[2:(2+nmedia), i] phiTD[detBins[i], tofBins[i]] += phis[i] phiFD[detBins[i]] += fds[i] for l in range(nmedia): phiDist[detBins[i], distBins[i, l], l] += phis[i] for j in range(len(tau)): g1_top[detBins[i], j] += np.exp(prep[i] * tau[j] + path[i]) def simulate(spec, wavelength): cfg = spec['mcx'] cfg.ismomentum = True cfg.prop, BFi = create_props(spec, wavelength) run_count = spec.get('run_count', 1) seeds = np.asarray(spec.get('seeds', np.random.randint(0xFFFF, size=run_count))) tof_domain = spec.get('tof_domain', np.append(np.arange(cfg.tstart, cfg.tend, cfg.tstep), cfg.tend)) tau = spec.get('tau', np.logspace(-8, -2)) freq = spec.get('frequency', 110e6) ndet, ntof, nmedia = len(cfg.detpos), len(tof_domain) - 1, len(cfg.prop) - 1 phiTD = np.zeros((ndet, ntof), np.float64) phiFD = np.zeros(ndet, np.complex128) paths = np.zeros((ndet, ntof, nmedia), np.float64) pcounts = np.zeros((ndet, ntof), np.int64) g1_top = np.zeros((ndet, len(tau)), np.float64) phiDist = np.zeros((ndet, ntof, nmedia), np.float64) fslice = 0 for seed in seeds: cfg.seed = int(seed) result = cfg.run(2) detp = result["detphoton"] if detp.shape[1] >= cfg.maxdetphoton: raise Exception("Too many photons detected: {}".format(detp.shape[1])) analysis(detp, cfg.prop, tof_domain, tau, wavelength, BFi, freq, ndet, ntof, nmedia, pcounts, paths, phiTD, phiFD, g1_top, phiDist) fslice += result["fluence"][spec['slice']] del detp del result fslice /= run_count paths /= pcounts[:, :, np.newaxis] g1 = g1_top / np.sum(phiTD, axis=1)[:, np.newaxis] phiDist /= np.sum(phiTD, axis=1)[:, np.newaxis, np.newaxis] return {'Photons': pcounts, 'Paths': paths, 'PhiTD': phiTD, 'PhiFD': phiFD, 'PhiDist': phiDist, 'Seeds': seeds, 'Slice': fslice, 'g1': g1}
[ "numpy.digitize", "numpy.exp", "numpy.stack", "numpy.zeros", "numba.jit", "numpy.sum", "numpy.random.randint", "numpy.interp", "numpy.logspace", "numpy.arange" ]
[((685, 734), 'numba.jit', 'nb.jit', ([], {'nopython': '(True)', 'nogil': '(True)', 'parallel': '(False)'}), '(nopython=True, nogil=True, parallel=False)\n', (691, 734), True, 'import numba as nb\n'), ((1210, 1222), 'numpy.exp', 'np.exp', (['path'], {}), '(path)\n', (1216, 1222), True, 'import numpy as np\n'), ((2442, 2476), 'numpy.zeros', 'np.zeros', (['(ndet, ntof)', 'np.float64'], {}), '((ndet, ntof), np.float64)\n', (2450, 2476), True, 'import numpy as np\n'), ((2489, 2518), 'numpy.zeros', 'np.zeros', (['ndet', 'np.complex128'], {}), '(ndet, np.complex128)\n', (2497, 2518), True, 'import numpy as np\n'), ((2531, 2573), 'numpy.zeros', 'np.zeros', (['(ndet, ntof, nmedia)', 'np.float64'], {}), '((ndet, ntof, nmedia), np.float64)\n', (2539, 2573), True, 'import numpy as np\n'), ((2588, 2620), 'numpy.zeros', 'np.zeros', (['(ndet, ntof)', 'np.int64'], {}), '((ndet, ntof), np.int64)\n', (2596, 2620), True, 'import numpy as np\n'), ((2687, 2729), 'numpy.zeros', 'np.zeros', (['(ndet, ntof, nmedia)', 'np.float64'], {}), '((ndet, ntof, nmedia), np.float64)\n', (2695, 2729), True, 'import numpy as np\n'), ((181, 205), 'numpy.interp', 'np.interp', (['wavelen', '*itr'], {}), '(wavelen, *itr)\n', (190, 205), True, 'import numpy as np\n'), ((639, 681), 'numpy.stack', 'np.stack', (["(lprops[l]['BFi'] for l in layers)"], {}), "(lprops[l]['BFi'] for l in layers)\n", (647, 681), True, 'import numpy as np\n'), ((2288, 2307), 'numpy.logspace', 'np.logspace', (['(-8)', '(-2)'], {}), '(-8, -2)\n', (2299, 2307), True, 'import numpy as np\n'), ((3349, 3370), 'numpy.sum', 'np.sum', (['phiTD'], {'axis': '(1)'}), '(phiTD, axis=1)\n', (3355, 3370), True, 'import numpy as np\n'), ((980, 1041), 'numpy.digitize', 'np.digitize', (['(prop[1:, 3] @ detp[2:2 + nmedia])', '(c * tof_domain)'], {}), '(prop[1:, 3] @ detp[2:2 + nmedia], c * tof_domain)\n', (991, 1041), True, 'import numpy as np\n'), ((1079, 1142), 'numpy.digitize', 'np.digitize', (['(prop[1:, 3] * detp[2:2 + nmedia].T)', '(c * tof_domain)'], {}), '(prop[1:, 3] * detp[2:2 + nmedia].T, c * tof_domain)\n', (1090, 1142), True, 'import numpy as np\n'), ((1863, 1897), 'numpy.exp', 'np.exp', (['(prep[i] * tau[j] + path[i])'], {}), '(prep[i] * tau[j] + path[i])\n', (1869, 1897), True, 'import numpy as np\n'), ((2113, 2153), 'numpy.random.randint', 'np.random.randint', (['(65535)'], {'size': 'run_count'}), '(65535, size=run_count)\n', (2130, 2153), True, 'import numpy as np\n'), ((2207, 2249), 'numpy.arange', 'np.arange', (['cfg.tstart', 'cfg.tend', 'cfg.tstep'], {}), '(cfg.tstart, cfg.tend, cfg.tstep)\n', (2216, 2249), True, 'import numpy as np\n'), ((3297, 3318), 'numpy.sum', 'np.sum', (['phiTD'], {'axis': '(1)'}), '(phiTD, axis=1)\n', (3303, 3318), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding:utf8 import lasagne import numpy as np import multiverso as mv class MVNetParamManager(object): ''' MVNetParamManager is manager to make managing and synchronizing the variables in lasagne more easily ''' def __init__(self, network): ''' The constructor of MVNetParamManager The constructor will associate the parameter with multiverso array table. The initial value of ArrayTableHandler will be same as the parameters of network. If different parameters are used in different processes, the average of them will be used as the initial value ''' self.shapes = [] self.dtypes = [] self.sizes = [] self.all_param_list = [] self.network = network for arr in lasagne.layers.get_all_param_values(self.network): self.shapes.append(arr.shape) # TODO: Now only float32 is supported in multiverso. So I store all # the parameters in a float32 array. This place need modification # after other types are supported assert(np.dtype("float32") == arr.dtype) self.dtypes.append(arr.dtype) self.sizes.append(arr.size) self.all_param_list.extend([i for i in np.nditer(arr)]) self.all_param_list = np.array(self.all_param_list) self.tbh = mv.ArrayTableHandler(len(self.all_param_list), init_value=self.all_param_list) mv.barrier() # add barrier to make sure the initial values have token effect self.all_param_list = self.tbh.get() self._set_all_param_to_net() def _set_all_param_to_net(self): n = 0 params = [] for i, size in enumerate(self.sizes): params.append(self.all_param_list[n:n + size].reshape(self.shapes[i])) n += size lasagne.layers.set_all_param_values(self.network, params) def sync_all_param(self): '''sync all parameters with multiverso server This function will 1) calc all the delta of params in the network and add the delta to multiverso server 2) get the latest value from the multiverso server ''' cur_network_params = np.concatenate([ arr.reshape(-1) for arr in lasagne.layers.get_all_param_values(self.network)]) params_delta = cur_network_params - self.all_param_list self.tbh.add(params_delta) self.all_param_list = self.tbh.get() self._set_all_param_to_net()
[ "multiverso.barrier", "numpy.nditer", "numpy.array", "lasagne.layers.get_all_param_values", "numpy.dtype", "lasagne.layers.set_all_param_values" ]
[((807, 856), 'lasagne.layers.get_all_param_values', 'lasagne.layers.get_all_param_values', (['self.network'], {}), '(self.network)\n', (842, 856), False, 'import lasagne\n'), ((1337, 1366), 'numpy.array', 'np.array', (['self.all_param_list'], {}), '(self.all_param_list)\n', (1345, 1366), True, 'import numpy as np\n'), ((1474, 1486), 'multiverso.barrier', 'mv.barrier', ([], {}), '()\n', (1484, 1486), True, 'import multiverso as mv\n'), ((1865, 1922), 'lasagne.layers.set_all_param_values', 'lasagne.layers.set_all_param_values', (['self.network', 'params'], {}), '(self.network, params)\n', (1900, 1922), False, 'import lasagne\n'), ((1123, 1142), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (1131, 1142), True, 'import numpy as np\n'), ((2286, 2335), 'lasagne.layers.get_all_param_values', 'lasagne.layers.get_all_param_values', (['self.network'], {}), '(self.network)\n', (2321, 2335), False, 'import lasagne\n'), ((1290, 1304), 'numpy.nditer', 'np.nditer', (['arr'], {}), '(arr)\n', (1299, 1304), True, 'import numpy as np\n')]
"""GaussianMLPMultitaskPolicy.""" import akro import numpy as np import tensorflow as tf from metarl.tf.models import GaussianMLPModel from metarl.tf.policies.multitask_policy import StochasticMultitaskPolicy class GaussianMLPMultitaskPolicy(StochasticMultitaskPolicy): """GaussianMLPMultitaskPolicy. Args: env_spec (metarl.envs.env_spec.EnvSpec): Environment specification. embedding (metarl.tf.embeddings.Embedding): Embedding network. task_space (akro.Box): Space of the task. name (str): Model name, also the variable scope. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a tf.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a tf.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a tf.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a tf.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a tf.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a tf.Tensor. learn_std (bool): Is std trainable. adaptive_std (bool): Is std a neural network. If False, it will be a parameter. std_share_network (bool): Boolean for whether mean and std share the same network. init_std (float): Initial value for std. std_hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for std. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues. max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues. std_hidden_nonlinearity (callable): Nonlinearity for each hidden layer in the std network. It should return a tf.Tensor. Set it to None to maintain a linear activation. std_output_nonlinearity (callable): Nonlinearity for output layer in the std network. It should return a tf.Tensor. Set it to None to maintain a linear activation. std_parameterization (str): How the std should be parametrized. There are a few options: - exp: the logarithm of the std will be stored, and applied a exponential transformation - softplus: the std will be computed as log(1+exp(x)) layer_normalization (bool): Bool for using layer normalization or not. """ def __init__(self, env_spec, embedding, task_space, name='GaussianMLPMultitaskPolicy', hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.glorot_uniform_initializer(), hidden_b_init=tf.zeros_initializer(), output_nonlinearity=None, output_w_init=tf.glorot_uniform_initializer(), output_b_init=tf.zeros_initializer(), learn_std=True, adaptive_std=False, std_share_network=False, init_std=1.0, min_std=1e-6, max_std=None, std_hidden_sizes=(32, 32), std_hidden_nonlinearity=tf.nn.tanh, std_output_nonlinearity=None, std_parameterization='exp', layer_normalization=False): assert isinstance(env_spec.action_space, akro.Box) super().__init__(env_spec, embedding, task_space, name) self.obs_dim = env_spec.observation_space.flat_dim self.action_dim = env_spec.action_space.flat_dim self.model = GaussianMLPModel( output_dim=self.action_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, adaptive_std=adaptive_std, std_share_network=std_share_network, init_std=init_std, min_std=min_std, max_std=max_std, std_hidden_sizes=std_hidden_sizes, std_hidden_nonlinearity=std_hidden_nonlinearity, std_output_nonlinearity=std_output_nonlinearity, std_parameterization=std_parameterization, layer_normalization=layer_normalization, name='GaussianMLPModel') self._initialize() def _initialize(self): state_input = tf.compat.v1.placeholder(tf.float32, shape=(None, self.obs_dim)) task_input = self._embedding.input latent_input = tf.compat.v1.placeholder( tf.float32, shape=(None, self._embedding.latent_dim)) with tf.compat.v1.variable_scope(self.name) as vs: self._variable_scope = vs with tf.variable_scope('concat_latent_obs'): latent_state_input = tf.concat( [latent_input, state_input], axis=-1) self.model.build(latent_state_input, name='from_latent') # Connect with embedding network's latent output with tf.variable_scope('concat_embed_obs'): latent_dist_info_sym = self._embedding.dist_info_sym( task_input, name='dist_info_sym') latent_var = self._embedding.distribution.sample_sym( latent_dist_info_sym) embed_state_input = tf.concat( [latent_var, state_input], axis=-1) self.model.build(embed_state_input, name='default') self._f_dist_latent_obs = tf.compat.v1.get_default_session().make_callable( [ self.model.networks['from_latent'].mean, self.model.networks['from_latent'].log_std ], feed_list=[latent_input, state_input]) self._f_dist_task_obs = tf.compat.v1.get_default_session().make_callable( [ self.model.networks['default'].mean, self.model.networks['default'].log_std, self._embedding.latent_mean, self._embedding.latent_std_param, ], feed_list=[task_input, state_input]) def get_action(self, observation): """Get action sampled from the policy. Args: observation (np.ndarray): Observation from the environment. Returns: (np.ndarray): Action sampled from the policy. """ flat_task_obs = self.task_observation_space.flatten(observation) flat_task, flat_obs = self.split_observation(flat_task_obs) (action_mean, action_log_std, latent_mean, latent_log_std) = self._f_dist_task_obs([flat_task], [flat_obs]) rnd = np.random.normal(size=action_mean.shape) action_sample = rnd * np.exp(action_log_std) + action_mean action_sample = self.action_space.unflatten(action_sample[0]) action_mean = self.action_space.unflatten(action_mean[0]) action_log_std = self.action_space.unflatten(action_log_std[0]) mean = self._embedding.latent_space.unflatten(latent_mean[0]) log_std = self._embedding.latent_space.unflatten(latent_log_std[0]) latent_info = dict(mean=latent_mean, log_std=latent_log_std) return action, dict(mean=action_mean, log_std=action_log_std, latent_info=latent_info) def get_action_from_latent(self, latent, observation): """Get action sampled from the latent and observation. Args: latent (np.ndarray): Latent var from the policy. observation (np.ndarray): Observation from the environment. Returns: (np.ndarray): Action sampled from the policy. """ flat_obs = self.observation_space.flatten(observation) flat_latent = self.latent_space.flatten(latent) mean, log_std = self._f_dist_latent_obs([flat_latent], [flat_obs]) rnd = np.random.normal(size=mean.shape) sample = rnd * np.exp(log_std) + mean sample = self.action_space.unflatten(sample[0]) mean = self.action_space.unflatten(mean[0]) log_std = self.action_space.unflatten(log_std[0]) return sample, dict(mean=mean, log_std=log_std) def dist_info_sym(self, task_var, obs_var, state_info_vars=None, name='default'): """Build a symbolic graph of the distribution parameters. Args: task_var (tf.Tensor): Tensor input for symbolic graph. obs_var (tf.Tensor): Tensor input for symbolic graph. state_info_vars (dict): Extra state information, e.g. previous action. name (str): Name for symbolic graph. Returns: dict[tf.Tensor]: Outputs of the symbolic graph of distribution parameters. """ with tf.compat.v1.variable_scope(self._variable_scope): latent_dist_info_sym = self._embedding.dist_info_sym( task_var, name=name) latent = self._embedding.distribution.sample_sym( latent_dist_info_sym) embed_state_input = tf.concat( [latent, obs_var], axis=-1) mean_var, log_std_var, _, _ = self.model.build(embed_state_input, name=name) return dict(mean=mean_var, log_std=log_std_var) def dist_info_sym_from_latent(self, latent_var, obs_var, state_info_vars=None, name='from_latent'): """Build a symbolic graph of the distribution parameters from latent. Args: latent_var (tf.Tensor): Tensor input for symbolic graph. obs_var (tf.Tensor): Tensor input for symbolic graph. state_info_vars (dict): Extra state information, e.g. previous action. name (str): Name for symbolic graph. Returns: dict[tf.Tensor]: Outputs of the symbolic graph of distribution parameters. """ with tf.compat.v1.variable_scope(self._variable_scope): embed_state_input = tf.concat([latent_var, obs_var], axis=-1) mean_var, log_std_var, _, _ = self.model.build(embed_state_input, name=name) return dict(mean=mean_var, log_std=log_std_var) @property def distribution(self): """Policy distribution. Returns: metarl.tf.distributions.DiagonalGaussian: Policy distribution. """ return self.model.networks['default'].dist def get_action_from_onehot(self, observation, onehot): """Get action sampled from the policy based on onehot index. Args: observation (np.ndarray): Observation from the environment. onehot (np.ndarray): One hot task index. Returns: (np.ndarray): Action sampled from the policy. """ raise NotImplementedError def get_actions_from_onehots(self, observations, onehots): """Get actions sampled from the policy based on onehot indices. Args: observations (np.ndarray): Observations from the environment. onehots (np.ndarray): One hot task indices. Returns: (np.ndarray): Action sampled from the policy. """ raise NotImplementedError def get_actions_from_latents(self, observations, latents): """Get actions sampled from the policy. Args: observations (np.ndarray): Observations from the environment. latents (np.ndarray): Latent. Returns: (np.ndarray): Actions sampled from the policy. """ raise NotImplementedError def get_actions(self, observations): """Get action sampled from the policy. Args: observations (list[np.ndarray]): Observations from the environment. Returns: (np.ndarray): Actions sampled from the policy. """ raise NotImplementedError def __getstate__(self): """Object.__getstate__. Returns: dict: the state to be pickled for the instance. """ new_dict = super().__getstate__() del new_dict['_f_dist_latent_obs'] del new_dict['_f_dist_task_obs'] return new_dict def __setstate__(self, state): """Object.__setstate__. Args: state (dict): Unpickled state. """ super().__setstate__(state) self._initialize()
[ "tensorflow.glorot_uniform_initializer", "tensorflow.compat.v1.placeholder", "numpy.random.normal", "tensorflow.compat.v1.variable_scope", "tensorflow.variable_scope", "tensorflow.compat.v1.get_default_session", "numpy.exp", "tensorflow.concat", "tensorflow.zeros_initializer", "metarl.tf.models.Ga...
[((3612, 3643), 'tensorflow.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (3641, 3643), True, 'import tensorflow as tf\n'), ((3676, 3698), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (3696, 3698), True, 'import tensorflow as tf\n'), ((3774, 3805), 'tensorflow.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (3803, 3805), True, 'import tensorflow as tf\n'), ((3838, 3860), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (3858, 3860), True, 'import tensorflow as tf\n'), ((4562, 5251), 'metarl.tf.models.GaussianMLPModel', 'GaussianMLPModel', ([], {'output_dim': 'self.action_dim', 'hidden_sizes': 'hidden_sizes', 'hidden_nonlinearity': 'hidden_nonlinearity', 'hidden_w_init': 'hidden_w_init', 'hidden_b_init': 'hidden_b_init', 'output_nonlinearity': 'output_nonlinearity', 'output_w_init': 'output_w_init', 'output_b_init': 'output_b_init', 'learn_std': 'learn_std', 'adaptive_std': 'adaptive_std', 'std_share_network': 'std_share_network', 'init_std': 'init_std', 'min_std': 'min_std', 'max_std': 'max_std', 'std_hidden_sizes': 'std_hidden_sizes', 'std_hidden_nonlinearity': 'std_hidden_nonlinearity', 'std_output_nonlinearity': 'std_output_nonlinearity', 'std_parameterization': 'std_parameterization', 'layer_normalization': 'layer_normalization', 'name': '"""GaussianMLPModel"""'}), "(output_dim=self.action_dim, hidden_sizes=hidden_sizes,\n hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init,\n hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity,\n output_w_init=output_w_init, output_b_init=output_b_init, learn_std=\n learn_std, adaptive_std=adaptive_std, std_share_network=\n std_share_network, init_std=init_std, min_std=min_std, max_std=max_std,\n std_hidden_sizes=std_hidden_sizes, std_hidden_nonlinearity=\n std_hidden_nonlinearity, std_output_nonlinearity=\n std_output_nonlinearity, std_parameterization=std_parameterization,\n layer_normalization=layer_normalization, name='GaussianMLPModel')\n", (4578, 5251), False, 'from metarl.tf.models import GaussianMLPModel\n'), ((5531, 5595), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32'], {'shape': '(None, self.obs_dim)'}), '(tf.float32, shape=(None, self.obs_dim))\n', (5555, 5595), True, 'import tensorflow as tf\n'), ((5709, 5787), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32'], {'shape': '(None, self._embedding.latent_dim)'}), '(tf.float32, shape=(None, self._embedding.latent_dim))\n', (5733, 5787), True, 'import tensorflow as tf\n'), ((7836, 7876), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'action_mean.shape'}), '(size=action_mean.shape)\n', (7852, 7876), True, 'import numpy as np\n'), ((9032, 9065), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'mean.shape'}), '(size=mean.shape)\n', (9048, 9065), True, 'import numpy as np\n'), ((5815, 5853), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['self.name'], {}), '(self.name)\n', (5842, 5853), True, 'import tensorflow as tf\n'), ((9930, 9979), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['self._variable_scope'], {}), '(self._variable_scope)\n', (9957, 9979), True, 'import tensorflow as tf\n'), ((10216, 10253), 'tensorflow.concat', 'tf.concat', (['[latent, obs_var]'], {'axis': '(-1)'}), '([latent, obs_var], axis=-1)\n', (10225, 10253), True, 'import tensorflow as tf\n'), ((11078, 11127), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['self._variable_scope'], {}), '(self._variable_scope)\n', (11105, 11127), True, 'import tensorflow as tf\n'), ((11161, 11202), 'tensorflow.concat', 'tf.concat', (['[latent_var, obs_var]'], {'axis': '(-1)'}), '([latent_var, obs_var], axis=-1)\n', (11170, 11202), True, 'import tensorflow as tf\n'), ((5917, 5955), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""concat_latent_obs"""'], {}), "('concat_latent_obs')\n", (5934, 5955), True, 'import tensorflow as tf\n'), ((5994, 6041), 'tensorflow.concat', 'tf.concat', (['[latent_input, state_input]'], {'axis': '(-1)'}), '([latent_input, state_input], axis=-1)\n', (6003, 6041), True, 'import tensorflow as tf\n'), ((6211, 6248), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""concat_embed_obs"""'], {}), "('concat_embed_obs')\n", (6228, 6248), True, 'import tensorflow as tf\n'), ((6523, 6568), 'tensorflow.concat', 'tf.concat', (['[latent_var, state_input]'], {'axis': '(-1)'}), '([latent_var, state_input], axis=-1)\n', (6532, 6568), True, 'import tensorflow as tf\n'), ((6689, 6723), 'tensorflow.compat.v1.get_default_session', 'tf.compat.v1.get_default_session', ([], {}), '()\n', (6721, 6723), True, 'import tensorflow as tf\n'), ((6968, 7002), 'tensorflow.compat.v1.get_default_session', 'tf.compat.v1.get_default_session', ([], {}), '()\n', (7000, 7002), True, 'import tensorflow as tf\n'), ((7907, 7929), 'numpy.exp', 'np.exp', (['action_log_std'], {}), '(action_log_std)\n', (7913, 7929), True, 'import numpy as np\n'), ((9089, 9104), 'numpy.exp', 'np.exp', (['log_std'], {}), '(log_std)\n', (9095, 9104), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pylab as plt import cv2 from numpy.lib.npyio import save from skimage.metrics import structural_similarity as ssim from skimage.metrics import peak_signal_noise_ratio as psnr import os from os.path import join as opj from os.path import exists as ope from os.path import dirname as opd from tqdm import tqdm def plot(img,title="",savename="",savedir=None): # plot a figure plt.figure() plt.title(title) plt.imshow(img,vmax=img.max(),vmin=0) if savedir!=None: if not ope(savedir): os.makedirs(savedir) plt.savefig(opj(savedir,savename+'.png'),dpi=200) else: plt.show() plt.close() def plot12(img1,img2,title1="",title2="",title="",savename="",savedir=None): fig = plt.figure() fig.suptitle(title) plt.subplot(121) plt.title(title1) plt.imshow(img1,vmax=img1.max(),vmin=0) plt.subplot(122) plt.title(title2) plt.imshow(img2,vmax=img2.max(),vmin=0) if savedir!=None: plt.savefig(opj(savedir,savename+'.png'),dpi=200) else: plt.show() plt.close() def plot_multi(imgs, title="", titles=None, col_num=4, fig_sz=None, savename="", savedir=None): # plot multiple figures fig = plt.figure() fig.suptitle(title) num_img = imgs.shape[-1] for nt in range(num_img): plt.subplot(np.ceil(num_img/col_num), col_num, nt+1) plt.imshow(imgs[...,nt], cmap=plt.cm.gray, vmin=0, vmax=imgs.max()) plt.axis('off') if titles is not None: if isinstance(titles[0],str): # titles are strings plt.title('#{0:d}: '.format(nt+1) + titles[nt], fontsize=12) else: # titles are values plt.title('#{0:d}: {1:.2f}'.format(nt+1, titles[nt]), fontsize=12) plt.subplots_adjust(wspace=0.02, hspace=0.02, bottom=0, top=1, left=0, right=1) if savedir is not None: if not ope(savedir): os.makedirs(savedir) plt.savefig('{}{}.png'.format(savedir,savename),dpi=200) else: plt.show() plt.close() def plot_hist(array,bins=None,title='',savename="",savedir=None): plt.figure() plt.title(title) if bins!=None: plt.hist(array,bins=bins) else: plt.hist(array) if savedir!=None: if not ope(savedir): os.makedirs(savedir) plt.savefig(opj(savedir,savename+'.png'),dpi=200) else: plt.show() plt.close() def plot_matrix(matrix,cmap='viridis_r',vmin=None,vmax=None,text=False,title='',savename="",savedir=None): plt.figure(figsize=(20,20)) plt.title(title) if vmin!=None and vmax!=None: plt.imshow(matrix,cmap=cmap,vmin=vmin,vmax=vmax) else: plt.imshow(matrix,cmap=cmap) plt.colorbar(shrink=0.8) if text: for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): plt.text(j, i, "{:.2f}".format(matrix[i, j]), ha="center", va="center", color="w",size=8) if savedir!=None: if not ope(savedir): os.makedirs(savedir) plt.savefig(opj(savedir,savename+'.png'),dpi=200) else: plt.show() plt.close() def plot_boxplot(array,showfliers=True,whis=1.5,flierprops=None,title='',savename="",savedir=None): plt.figure() plt.title(title) plt.boxplot(array,showfliers=showfliers,whis=whis,flierprops=flierprops) if savedir!=None: if not ope(savedir): os.makedirs(savedir) plt.savefig(opj(savedir,savename+'.png'),dpi=200) else: plt.show() plt.close() def plot12_boxplot(array1,array2,showfliers=True,whis=1.5,flierprops=None, title1="",title2="",title="",savename="",savedir=None): fig = plt.figure() fig.suptitle(title) plt.subplot(121) plt.title(title1) plt.boxplot(array1,showfliers=showfliers,whis=whis,flierprops=flierprops) plt.subplot(122) plt.title(title2) plt.boxplot(array2,showfliers=showfliers,whis=whis,flierprops=flierprops) if savedir!=None: if not ope(savedir): os.makedirs(savedir) plt.savefig(opj(savedir,savename+'.png'),dpi=200) else: plt.show() plt.close()
[ "os.path.exists", "matplotlib.pylab.axis", "numpy.ceil", "os.makedirs", "matplotlib.pylab.figure", "matplotlib.pylab.boxplot", "matplotlib.pylab.title", "os.path.join", "matplotlib.pylab.colorbar", "matplotlib.pylab.hist", "matplotlib.pylab.imshow", "matplotlib.pylab.show", "matplotlib.pylab...
[((422, 434), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (432, 434), True, 'import matplotlib.pylab as plt\n'), ((439, 455), 'matplotlib.pylab.title', 'plt.title', (['title'], {}), '(title)\n', (448, 455), True, 'import matplotlib.pylab as plt\n'), ((681, 692), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (690, 692), True, 'import matplotlib.pylab as plt\n'), ((785, 797), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (795, 797), True, 'import matplotlib.pylab as plt\n'), ((826, 842), 'matplotlib.pylab.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (837, 842), True, 'import matplotlib.pylab as plt\n'), ((847, 864), 'matplotlib.pylab.title', 'plt.title', (['title1'], {}), '(title1)\n', (856, 864), True, 'import matplotlib.pylab as plt\n'), ((913, 929), 'matplotlib.pylab.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (924, 929), True, 'import matplotlib.pylab as plt\n'), ((934, 951), 'matplotlib.pylab.title', 'plt.title', (['title2'], {}), '(title2)\n', (943, 951), True, 'import matplotlib.pylab as plt\n'), ((1109, 1120), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (1118, 1120), True, 'import matplotlib.pylab as plt\n'), ((1260, 1272), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (1270, 1272), True, 'import matplotlib.pylab as plt\n'), ((1852, 1931), 'matplotlib.pylab.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.02)', 'hspace': '(0.02)', 'bottom': '(0)', 'top': '(1)', 'left': '(0)', 'right': '(1)'}), '(wspace=0.02, hspace=0.02, bottom=0, top=1, left=0, right=1)\n', (1871, 1931), True, 'import matplotlib.pylab as plt\n'), ((2126, 2137), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (2135, 2137), True, 'import matplotlib.pylab as plt\n'), ((2209, 2221), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (2219, 2221), True, 'import matplotlib.pylab as plt\n'), ((2226, 2242), 'matplotlib.pylab.title', 'plt.title', (['title'], {}), '(title)\n', (2235, 2242), True, 'import matplotlib.pylab as plt\n'), ((2513, 2524), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (2522, 2524), True, 'import matplotlib.pylab as plt\n'), ((2636, 2664), 'matplotlib.pylab.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (2646, 2664), True, 'import matplotlib.pylab as plt\n'), ((2668, 2684), 'matplotlib.pylab.title', 'plt.title', (['title'], {}), '(title)\n', (2677, 2684), True, 'import matplotlib.pylab as plt\n'), ((2827, 2851), 'matplotlib.pylab.colorbar', 'plt.colorbar', ([], {'shrink': '(0.8)'}), '(shrink=0.8)\n', (2839, 2851), True, 'import matplotlib.pylab as plt\n'), ((3260, 3271), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (3269, 3271), True, 'import matplotlib.pylab as plt\n'), ((3376, 3388), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (3386, 3388), True, 'import matplotlib.pylab as plt\n'), ((3393, 3409), 'matplotlib.pylab.title', 'plt.title', (['title'], {}), '(title)\n', (3402, 3409), True, 'import matplotlib.pylab as plt\n'), ((3414, 3489), 'matplotlib.pylab.boxplot', 'plt.boxplot', (['array'], {'showfliers': 'showfliers', 'whis': 'whis', 'flierprops': 'flierprops'}), '(array, showfliers=showfliers, whis=whis, flierprops=flierprops)\n', (3425, 3489), True, 'import matplotlib.pylab as plt\n'), ((3662, 3673), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (3671, 3673), True, 'import matplotlib.pylab as plt\n'), ((3836, 3848), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (3846, 3848), True, 'import matplotlib.pylab as plt\n'), ((3877, 3893), 'matplotlib.pylab.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (3888, 3893), True, 'import matplotlib.pylab as plt\n'), ((3898, 3915), 'matplotlib.pylab.title', 'plt.title', (['title1'], {}), '(title1)\n', (3907, 3915), True, 'import matplotlib.pylab as plt\n'), ((3920, 3996), 'matplotlib.pylab.boxplot', 'plt.boxplot', (['array1'], {'showfliers': 'showfliers', 'whis': 'whis', 'flierprops': 'flierprops'}), '(array1, showfliers=showfliers, whis=whis, flierprops=flierprops)\n', (3931, 3996), True, 'import matplotlib.pylab as plt\n'), ((3998, 4014), 'matplotlib.pylab.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (4009, 4014), True, 'import matplotlib.pylab as plt\n'), ((4019, 4036), 'matplotlib.pylab.title', 'plt.title', (['title2'], {}), '(title2)\n', (4028, 4036), True, 'import matplotlib.pylab as plt\n'), ((4041, 4117), 'matplotlib.pylab.boxplot', 'plt.boxplot', (['array2'], {'showfliers': 'showfliers', 'whis': 'whis', 'flierprops': 'flierprops'}), '(array2, showfliers=showfliers, whis=whis, flierprops=flierprops)\n', (4052, 4117), True, 'import matplotlib.pylab as plt\n'), ((4290, 4301), 'matplotlib.pylab.close', 'plt.close', ([], {}), '()\n', (4299, 4301), True, 'import matplotlib.pylab as plt\n'), ((666, 676), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (674, 676), True, 'import matplotlib.pylab as plt\n'), ((1094, 1104), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (1102, 1104), True, 'import matplotlib.pylab as plt\n'), ((1507, 1522), 'matplotlib.pylab.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1515, 1522), True, 'import matplotlib.pylab as plt\n'), ((2111, 2121), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (2119, 2121), True, 'import matplotlib.pylab as plt\n'), ((2270, 2296), 'matplotlib.pylab.hist', 'plt.hist', (['array'], {'bins': 'bins'}), '(array, bins=bins)\n', (2278, 2296), True, 'import matplotlib.pylab as plt\n'), ((2314, 2329), 'matplotlib.pylab.hist', 'plt.hist', (['array'], {}), '(array)\n', (2322, 2329), True, 'import matplotlib.pylab as plt\n'), ((2498, 2508), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (2506, 2508), True, 'import matplotlib.pylab as plt\n'), ((2727, 2778), 'matplotlib.pylab.imshow', 'plt.imshow', (['matrix'], {'cmap': 'cmap', 'vmin': 'vmin', 'vmax': 'vmax'}), '(matrix, cmap=cmap, vmin=vmin, vmax=vmax)\n', (2737, 2778), True, 'import matplotlib.pylab as plt\n'), ((2794, 2823), 'matplotlib.pylab.imshow', 'plt.imshow', (['matrix'], {'cmap': 'cmap'}), '(matrix, cmap=cmap)\n', (2804, 2823), True, 'import matplotlib.pylab as plt\n'), ((3245, 3255), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (3253, 3255), True, 'import matplotlib.pylab as plt\n'), ((3647, 3657), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (3655, 3657), True, 'import matplotlib.pylab as plt\n'), ((4275, 4285), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (4283, 4285), True, 'import matplotlib.pylab as plt\n'), ((535, 547), 'os.path.exists', 'ope', (['savedir'], {}), '(savedir)\n', (538, 547), True, 'from os.path import exists as ope\n'), ((561, 581), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (572, 581), False, 'import os\n'), ((610, 641), 'os.path.join', 'opj', (['savedir', "(savename + '.png')"], {}), "(savedir, savename + '.png')\n", (613, 641), True, 'from os.path import join as opj\n'), ((1038, 1069), 'os.path.join', 'opj', (['savedir', "(savename + '.png')"], {}), "(savedir, savename + '.png')\n", (1041, 1069), True, 'from os.path import join as opj\n'), ((1382, 1408), 'numpy.ceil', 'np.ceil', (['(num_img / col_num)'], {}), '(num_img / col_num)\n', (1389, 1408), True, 'import numpy as np\n'), ((1980, 1992), 'os.path.exists', 'ope', (['savedir'], {}), '(savedir)\n', (1983, 1992), True, 'from os.path import exists as ope\n'), ((2006, 2026), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (2017, 2026), False, 'import os\n'), ((2367, 2379), 'os.path.exists', 'ope', (['savedir'], {}), '(savedir)\n', (2370, 2379), True, 'from os.path import exists as ope\n'), ((2393, 2413), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (2404, 2413), False, 'import os\n'), ((2442, 2473), 'os.path.join', 'opj', (['savedir', "(savename + '.png')"], {}), "(savedir, savename + '.png')\n", (2445, 2473), True, 'from os.path import join as opj\n'), ((3122, 3134), 'os.path.exists', 'ope', (['savedir'], {}), '(savedir)\n', (3125, 3134), True, 'from os.path import exists as ope\n'), ((3148, 3168), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (3159, 3168), False, 'import os\n'), ((3189, 3220), 'os.path.join', 'opj', (['savedir', "(savename + '.png')"], {}), "(savedir, savename + '.png')\n", (3192, 3220), True, 'from os.path import join as opj\n'), ((3524, 3536), 'os.path.exists', 'ope', (['savedir'], {}), '(savedir)\n', (3527, 3536), True, 'from os.path import exists as ope\n'), ((3550, 3570), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (3561, 3570), False, 'import os\n'), ((3591, 3622), 'os.path.join', 'opj', (['savedir', "(savename + '.png')"], {}), "(savedir, savename + '.png')\n", (3594, 3622), True, 'from os.path import join as opj\n'), ((4152, 4164), 'os.path.exists', 'ope', (['savedir'], {}), '(savedir)\n', (4155, 4164), True, 'from os.path import exists as ope\n'), ((4178, 4198), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (4189, 4198), False, 'import os\n'), ((4219, 4250), 'os.path.join', 'opj', (['savedir', "(savename + '.png')"], {}), "(savedir, savename + '.png')\n", (4222, 4250), True, 'from os.path import join as opj\n')]
""" Defines JSON-format encoding and decoding functions """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # 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 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** # XXX this module should certainly be rewritten as a custom `json.JSONEncoder` import types as _types import importlib as _importlib import base64 as _base64 import numpy as _np import uuid as _uuid import collections as _collections import pygsti.objects def class_hasattr(instance, attr): """Helper function for checking if `instance.__class__` has an attribute""" return hasattr(instance.__class__, attr) def encode_obj(py_obj, binary): """ Returns JSON-compatible version of `py_obj`. Constructs in-memory a JSON-format-compatible copy of the Python object `py_obj`, handling pyGSTi objects appropriately. When `binary=False`, the output must contain only ASCII-compatible strings (no 'bytes'), otherwise the output is allowed to contain non-ASCII string values (OK for binary formats like MSGPACK and BSON). Parameters ---------- py_obj : object The object to encode. binary : bool Whether the output is allowed to have binary-mode strings or not. Returns ------- object A JSON-format compatible object. Usually a dict, list, or string. """ #print("ENCODING ", str(type(py_obj))) is_pygsti_obj = hasattr(py_obj, '__class__') and \ hasattr(py_obj.__class__, '__module__') and \ py_obj.__class__.__module__.startswith('pygsti') is_pygsti_class = isinstance(py_obj, type) and hasattr(py_obj, '__module__') \ and py_obj.__module__.startswith('pygsti') is_plotly_fig = hasattr(py_obj, '__class__') and \ hasattr(py_obj.__class__, '__module__') and \ py_obj.__class__.__module__ == 'plotly.graph_objs._figure' and \ py_obj.__class__.__name__ == "Figure" # just needed for v3 plotly where figures aren't dicts... # Pygsti class encoding if is_pygsti_class: # or class_hasattr(py_obj, '__pygsti_getstate__') return {'__pygsticlass__': (py_obj.__module__, py_obj.__name__)} # Pygsti object encoding elif is_pygsti_obj: # or class_hasattr(py_obj, '__pygsti_getstate__') #Get State (and/or init args) if class_hasattr(py_obj, '__pygsti_reduce__'): red = py_obj.__pygsti_reduce__() # returns class, construtor_args, state assert(red[0] is py_obj.__class__), "No support for weird reducing!" init_args = red[1] if len(red) > 1 else [] state = red[2] if len(red) > 2 else {} if state is None: state = {} state.update({'__init_args__': init_args}) elif class_hasattr(py_obj, '__pygsti_getstate__'): state = py_obj.__pygsti_getstate__() # must return a dict elif class_hasattr(py_obj, '__getstate__'): state = py_obj.__getstate__() elif hasattr(py_obj, '__dict__'): state = py_obj.__dict__ # take __dict__ as state elif class_hasattr(py_obj, '__reduce__'): red = py_obj.__reduce__() # returns class, construtor_args, state if red[0] is not py_obj.__class__: state = None # weird reducing can happen, for instance, for namedtuples - just punt else: init_args = red[1] if len(red) > 1 else [] state = red[2] if len(red) > 2 else {} if state is None: state = {} state.update({'__init_args__': init_args}) else: state = None if state is None: # Note: __dict__ and __getstate__ may *return* None (python 2.7) if hasattr(py_obj, '_asdict'): # named tuples state = {'__init_args__': list(py_obj._asdict().values())} # values will be ordered as per __init__ so no need for keys else: raise ValueError("Can't get state of %s object" % type(py_obj)) d = {k: encode_obj(v, binary) for k, v in state.items()} #DEBUG (instead of above line) #import json as _json #d = {} #print("DB: Encoding state for pyGSTi %s object:" % type(py_obj)) #for k,v in state.items(): # print(">>> Encoding key: ",k) # d[k] = encode_obj(v,binary) # print("<<< Done encoding key ",k) # try: _json.dumps(d[k]) # except Exception as e: # print("Cannot JSON %s key: " % k, d[k]) # raise e d.update({'__pygstiobj__': (py_obj.__class__.__module__, py_obj.__class__.__name__)}) #Currently, don't add standard-base-class state #if we know how to __init__, since we'll assume this # should initialize the entire (base class included) instance encode_std_base = bool('__init_args__' not in d) if encode_std_base: std_encode = encode_std_obj(py_obj, binary) if std_encode is not py_obj: # if there's something to encode # this pygsti object is also a standard-object instance assert(isinstance(std_encode, dict)) d['__std_base__'] = std_encode #try: # _json.dumps(d) #except Exception as e: # print("Cannot JSON ",type(py_obj)) # raise e return d #Special case: a plotly Figure object - these need special help being serialized elif is_plotly_fig and hasattr(py_obj, 'to_dict'): return {'__plotlyfig__': encode_std_obj(py_obj.to_dict(), binary)} else: return encode_std_obj(py_obj, binary) def encode_std_obj(py_obj, binary): """ Helper to :func:`encode_obj` that encodes only "standard" (non-pyGSTi) types """ # Other builtin or standard object encoding #print("Encoding std type: ",str(type(py_obj))) if isinstance(py_obj, tuple): return {'__tuple__': [encode_obj(v, binary) for v in py_obj]} elif isinstance(py_obj, list): return {'__list__': [encode_obj(v, binary) for v in py_obj]} elif isinstance(py_obj, set): return {'__set__': [encode_obj(v, binary) for v in py_obj]} elif isinstance(py_obj, slice): return {'__slice__': [encode_obj(py_obj.start, binary), encode_obj(py_obj.stop, binary), encode_obj(py_obj.step, binary)]} elif isinstance(py_obj, range): return {'__range__': (py_obj.start, py_obj.stop, py_obj.step)} elif isinstance(py_obj, _collections.OrderedDict): return {'__odict__': [(encode_obj(k, binary), encode_obj(v, binary)) for k, v in py_obj.items()]} elif isinstance(py_obj, _collections.Counter): return {'__counter__': [(encode_obj(k, binary), encode_obj(v, binary)) for k, v in dict(py_obj).items()]} elif isinstance(py_obj, dict): return {'__ndict__': [(encode_obj(k, binary), encode_obj(v, binary)) for k, v in py_obj.items()]} elif isinstance(py_obj, _uuid.UUID): return {'__uuid__': str(py_obj.hex)} elif isinstance(py_obj, complex): rep = py_obj.__repr__() # a string data = tobin(rep) if binary else rep # binary if need be return {'__complex__': data} elif not binary and isinstance(py_obj, bytes): return {'__bytes__': tostr(_base64.b64encode(py_obj))} elif binary and isinstance(py_obj, str): return {'__string__': tobin(py_obj)} #Numpy encoding elif isinstance(py_obj, _np.ndarray): # If the dtype is structured, store the interface description; # otherwise, store the corresponding array protocol type string: if py_obj.dtype.kind == 'V': kind = 'V' descr = tobin(py_obj.dtype.descr) if binary else tostr(py_obj.dtype.descr) else: kind = '' descr = tobin(py_obj.dtype.str) if binary else tostr(py_obj.dtype.str) data = py_obj.tobytes() if binary else tostr(_base64.b64encode(py_obj.tobytes())) if(py_obj.dtype == _np.object): raise TypeError("Cannot serialize object ndarrays!") return {'__ndarray__': data, 'dtype': descr, 'kind': kind, 'shape': py_obj.shape} elif isinstance(py_obj, (_np.bool_, _np.number)): data = py_obj.tobytes() if binary else tostr(_base64.b64encode(py_obj.tobytes())) return {'__npgeneric__': data, 'dtype': tostr(py_obj.dtype.str)} elif isinstance(py_obj, _types.FunctionType): # functions # OLD: elif callable(py_obj): #incorrectly includes pygsti classes w/__call__ (e.g. AutoGator) return {'__function__': (py_obj.__module__, py_obj.__name__)} return py_obj # assume the bare py_obj is json-able def decode_obj(json_obj, binary): """ Inverse of :func:`encode_obj` that decodes the JSON-compatible `json_obj` object into the original Python object that was encoded. Parameters ---------- json_obj : object The JSON-compabtible object to decode. Note that this is NOT a JSON string, but rather the object that would be decoded from such a string (by `json.loads`, for instance). binary : bool Whether `json_obj` is a binary format or not. If so, then the decoding expects all strings to be binary strings i.e. `b'name'` instead of just `'name'`. The value of this argument should match that used in the original call to :func:`encode_obj`. Returns ------- object A Python object. """ B = tobin if binary else _ident if isinstance(json_obj, dict): if B('__pygsticlass__') in json_obj: modname, clsname = json_obj[B('__pygsticlass__')] module = _importlib.import_module(tostr(modname)) class_ = getattr(module, tostr(clsname)) return class_ elif B('__pygstiobj__') in json_obj: #DEBUG #print("DB: creating %s" % str(json_obj['__pygstiobj__'])) #print("DB: json_obj is type %s with keyvals:" % type(json_obj)) #for k,v in json_obj.items(): # print("%s (%s): %s (%s)" % (k,type(k),v,type(v))) modname, clsname = json_obj[B('__pygstiobj__')] module = _importlib.import_module(tostr(modname)) class_ = getattr(module, tostr(clsname)) if B('__init_args__') in json_obj: # construct via __init__ args = decode_obj(json_obj[B('__init_args__')], binary) instance = class_(*args) else: # init via __new__ and set state instance = class_.__new__(class_) #Create state dict state_dict = {} for k, v in json_obj.items(): if k in (B('__pygstiobj__'), B('__init_args__'), B('__std_base__')): continue state_dict[tostr(k)] = decode_obj(v, binary) #Set state if class_hasattr(instance, '__pygsti_setstate__'): instance.__pygsti_setstate__(state_dict) elif class_hasattr(instance, '__setstate__'): instance.__setstate__(state_dict) elif hasattr(instance, '__dict__'): # just update __dict__ instance.__dict__.update(state_dict) elif len(state_dict) > 0: raise ValueError("Cannot set nontrivial state of %s object" % type(instance)) #update instance with std-object info if needed (only if __init__ not called) if B('__std_base__') in json_obj: decode_std_base(json_obj[B('__std_base__')], instance, binary) return instance elif B('__plotlyfig__') in json_obj: import plotly.graph_objs as go return go.Figure(decode_obj(json_obj[B('__plotlyfig__')], binary)) else: return decode_std_obj(json_obj, binary) else: return json_obj def decode_std_base(json_obj, start, binary): """ Helper to :func:`decode_obj` for decoding pyGSTi objects that are also derived from a standard type. """ B = tobin if binary else _ident if B('__tuple__') in json_obj: #OK if __init_args since this means we knew how to construct it (e.g. namedtuples) assert(B('__init_args') in json_obj), "No support for sub-classing tuple" elif B('__list__') in json_obj: for v in json_obj[B('__list__')]: start.append(decode_obj(v, binary)) elif B('__set__') in json_obj: for v in json_obj[B('__set__')]: start.add(decode_obj(v, binary)) elif B('__ndict__') in json_obj: for k, v in json_obj[B('__ndict__')]: start[decode_obj(k, binary)] = decode_obj(v, binary) elif B('__odict__') in json_obj: for k, v in json_obj[B('__odict__')]: start[decode_obj(k, binary)] = decode_obj(v, binary) elif B('__uuid__') in json_obj: assert(False), "No support for sub-classing UUID" elif B('__ndarray__') in json_obj: assert(False), "No support for sub-classing ndarray" elif B('__npgeneric__') in json_obj: assert(False), "No support for sub-classing numpy generics" elif B('__complex__') in json_obj: assert(False), "No support for sub-classing complex" elif B('__counter__') in json_obj: assert(False), "No support for sub-classing Counter" elif B('__slice__') in json_obj: assert(False), "No support for sub-classing slice" def decode_std_obj(json_obj, binary): """ Helper to :func:`decode_obj` that decodes standard (non-pyGSTi) types. """ B = tobin if binary else _ident if B('__tuple__') in json_obj: return tuple([decode_obj(v, binary) for v in json_obj[B('__tuple__')]]) elif B('__list__') in json_obj: return list([decode_obj(v, binary) for v in json_obj[B('__list__')]]) elif B('__set__') in json_obj: return set([decode_obj(v, binary) for v in json_obj[B('__set__')]]) elif B('__slice__') in json_obj: v = json_obj[B('__slice__')] return slice(decode_obj(v[0], binary), decode_obj(v[1], binary), decode_obj(v[2], binary)) elif B('__range__') in json_obj: start, stop, step = json_obj[B('__range__')] return range(start, stop, step) elif B('__ndict__') in json_obj: return dict([(decode_obj(k, binary), decode_obj(v, binary)) for k, v in json_obj[B('__ndict__')]]) elif B('__odict__') in json_obj: return _collections.OrderedDict( [(decode_obj(k, binary), decode_obj(v, binary)) for k, v in json_obj[B('__odict__')]]) elif B('__counter__') in json_obj: return _collections.Counter( {decode_obj(k, binary): decode_obj(v, binary) for k, v in json_obj[B('__counter__')]}) elif B('__uuid__') in json_obj: return _uuid.UUID(hex=tostr(json_obj[B('__uuid__')])) elif B('__bytes__') in json_obj: return json_obj[B('__bytes__')] if binary else \ _base64.b64decode(json_obj[B('__bytes__')]) elif B('__string__') in json_obj: return tostr(json_obj[B('__string__')]) if binary else \ json_obj[B('__string__')] # check for numpy elif B('__ndarray__') in json_obj: # Check if 'kind' is in json_obj to enable decoding of data # serialized with older versions: if json_obj[B('kind')] == 'V': descr = [tuple(tostr(t) if isinstance(t, bytes) else t for t in d) for d in json_obj[B('dtype')]] else: descr = json_obj[B('dtype')] data = json_obj[B('__ndarray__')] if binary else \ _base64.b64decode(json_obj[B('__ndarray__')]) return _np.fromstring(data, dtype=_np.dtype(descr)).reshape(json_obj[B('shape')]) elif B('__npgeneric__') in json_obj: data = json_obj[B('__npgeneric__')] if binary else \ _base64.b64decode(json_obj[B('__npgeneric__')]) return _np.fromstring( data, dtype=_np.dtype(json_obj[B('dtype')]) )[0] elif B('__complex__') in json_obj: return complex(tostr(json_obj[B('__complex__')])) elif B('__function__') in json_obj: modname, fnname = json_obj[B('__function__')] module = _importlib.import_module(tostr(modname)) return getattr(module, tostr(fnname)) def tostr(x): """ Convert a value to the native string format. """ if isinstance(x, bytes): return x.decode() else: return str(x) def tobin(x): """ Serialize strings to UTF8 """ if isinstance(x, str): return bytes(x, 'utf-8') else: return x def _ident(x): return x
[ "numpy.dtype", "base64.b64encode" ]
[((8039, 8064), 'base64.b64encode', '_base64.b64encode', (['py_obj'], {}), '(py_obj)\n', (8056, 8064), True, 'import base64 as _base64\n'), ((16524, 16540), 'numpy.dtype', '_np.dtype', (['descr'], {}), '(descr)\n', (16533, 16540), True, 'import numpy as _np\n')]
import os import time import numpy as np import argparse import functools from PIL import Image from PIL import ImageDraw import paddle import paddle.fluid as fluid import reader from mobilenet_ssd import mobile_net from utility import add_arguments, print_arguments parser = argparse.ArgumentParser(description=__doc__) add_arg = functools.partial(add_arguments, argparser=parser) # yapf: disable add_arg('dataset', str, 'pascalvoc', "coco and pascalvoc.") add_arg('use_gpu', bool, True, "Whether use GPU.") add_arg('image_path', str, '', "The image used to inference and visualize.") add_arg('model_dir', str, '', "The model path.") add_arg('nms_threshold', float, 0.45, "NMS threshold.") add_arg('confs_threshold', float, 0.2, "Confidence threshold to draw bbox.") add_arg('resize_h', int, 300, "The resized image height.") add_arg('resize_w', int, 300, "The resized image height.") add_arg('mean_value_B', float, 127.5, "Mean value for B channel which will be subtracted.") #123.68 add_arg('mean_value_G', float, 127.5, "Mean value for G channel which will be subtracted.") #116.78 add_arg('mean_value_R', float, 127.5, "Mean value for R channel which will be subtracted.") #103.94 # yapf: enable def infer(args, data_args, image_path, model_dir): image_shape = [3, data_args.resize_h, data_args.resize_w] if 'coco' in data_args.dataset: num_classes = 91 elif 'pascalvoc' in data_args.dataset: num_classes = 21 image = fluid.layers.data(name='image', shape=image_shape, dtype='float32') locs, confs, box, box_var = mobile_net(num_classes, image, image_shape) nmsed_out = fluid.layers.detection_output( locs, confs, box, box_var, nms_threshold=args.nms_threshold) place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace() exe = fluid.Executor(place) # yapf: disable if model_dir: def if_exist(var): return os.path.exists(os.path.join(model_dir, var.name)) fluid.io.load_vars(exe, model_dir, predicate=if_exist) # yapf: enable infer_reader = reader.infer(data_args, image_path) feeder = fluid.DataFeeder(place=place, feed_list=[image]) def infer(): data = infer_reader() nmsed_out_v = exe.run(fluid.default_main_program(), feed=feeder.feed([[data]]), fetch_list=[nmsed_out], return_numpy=False) nmsed_out_v = np.array(nmsed_out_v[0]) draw_bounding_box_on_image(image_path, nmsed_out_v, args.confs_threshold) for dt in nmsed_out_v: category_id, score, xmin, ymin, xmax, ymax = dt.tolist() infer() def draw_bounding_box_on_image(image_path, nms_out, confs_threshold): image = Image.open(image_path) draw = ImageDraw.Draw(image) im_width, im_height = image.size for dt in nms_out: category_id, score, xmin, ymin, xmax, ymax = dt.tolist() if score < confs_threshold: continue bbox = dt[2:] xmin, ymin, xmax, ymax = bbox (left, right, top, bottom) = (xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height) draw.line( [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], width=4, fill='red') image_name = image_path.split('/')[-1] print("image with bbox drawed saved as {}".format(image_name)) image.save(image_name) if __name__ == '__main__': args = parser.parse_args() print_arguments(args) data_args = reader.Settings( dataset=args.dataset, data_dir='', label_file='', resize_h=args.resize_h, resize_w=args.resize_w, mean_value=[args.mean_value_B, args.mean_value_G, args.mean_value_R], apply_distort=False, apply_expand=False, ap_version='', toy=0) infer( args, data_args=data_args, image_path=args.image_path, model_dir=args.model_dir)
[ "paddle.fluid.DataFeeder", "reader.infer", "PIL.Image.open", "argparse.ArgumentParser", "reader.Settings", "paddle.fluid.layers.data", "paddle.fluid.CPUPlace", "os.path.join", "numpy.array", "PIL.ImageDraw.Draw", "paddle.fluid.Executor", "functools.partial", "paddle.fluid.io.load_vars", "p...
[((278, 322), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (301, 322), False, 'import argparse\n'), ((333, 383), 'functools.partial', 'functools.partial', (['add_arguments'], {'argparser': 'parser'}), '(add_arguments, argparser=parser)\n', (350, 383), False, 'import functools\n'), ((1570, 1637), 'paddle.fluid.layers.data', 'fluid.layers.data', ([], {'name': '"""image"""', 'shape': 'image_shape', 'dtype': '"""float32"""'}), "(name='image', shape=image_shape, dtype='float32')\n", (1587, 1637), True, 'import paddle.fluid as fluid\n'), ((1670, 1713), 'mobilenet_ssd.mobile_net', 'mobile_net', (['num_classes', 'image', 'image_shape'], {}), '(num_classes, image, image_shape)\n', (1680, 1713), False, 'from mobilenet_ssd import mobile_net\n'), ((1730, 1825), 'paddle.fluid.layers.detection_output', 'fluid.layers.detection_output', (['locs', 'confs', 'box', 'box_var'], {'nms_threshold': 'args.nms_threshold'}), '(locs, confs, box, box_var, nms_threshold=args\n .nms_threshold)\n', (1759, 1825), True, 'import paddle.fluid as fluid\n'), ((1910, 1931), 'paddle.fluid.Executor', 'fluid.Executor', (['place'], {}), '(place)\n', (1924, 1931), True, 'import paddle.fluid as fluid\n'), ((2167, 2202), 'reader.infer', 'reader.infer', (['data_args', 'image_path'], {}), '(data_args, image_path)\n', (2179, 2202), False, 'import reader\n'), ((2216, 2264), 'paddle.fluid.DataFeeder', 'fluid.DataFeeder', ([], {'place': 'place', 'feed_list': '[image]'}), '(place=place, feed_list=[image])\n', (2232, 2264), True, 'import paddle.fluid as fluid\n'), ((2896, 2918), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (2906, 2918), False, 'from PIL import Image\n'), ((2930, 2951), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['image'], {}), '(image)\n', (2944, 2951), False, 'from PIL import ImageDraw\n'), ((3706, 3727), 'utility.print_arguments', 'print_arguments', (['args'], {}), '(args)\n', (3721, 3727), False, 'from utility import add_arguments, print_arguments\n'), ((3745, 4004), 'reader.Settings', 'reader.Settings', ([], {'dataset': 'args.dataset', 'data_dir': '""""""', 'label_file': '""""""', 'resize_h': 'args.resize_h', 'resize_w': 'args.resize_w', 'mean_value': '[args.mean_value_B, args.mean_value_G, args.mean_value_R]', 'apply_distort': '(False)', 'apply_expand': '(False)', 'ap_version': '""""""', 'toy': '(0)'}), "(dataset=args.dataset, data_dir='', label_file='', resize_h=\n args.resize_h, resize_w=args.resize_w, mean_value=[args.mean_value_B,\n args.mean_value_G, args.mean_value_R], apply_distort=False,\n apply_expand=False, ap_version='', toy=0)\n", (3760, 4004), False, 'import reader\n'), ((1843, 1861), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (1858, 1861), True, 'import paddle.fluid as fluid\n'), ((1883, 1899), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (1897, 1899), True, 'import paddle.fluid as fluid\n'), ((2074, 2128), 'paddle.fluid.io.load_vars', 'fluid.io.load_vars', (['exe', 'model_dir'], {'predicate': 'if_exist'}), '(exe, model_dir, predicate=if_exist)\n', (2092, 2128), True, 'import paddle.fluid as fluid\n'), ((2557, 2581), 'numpy.array', 'np.array', (['nmsed_out_v[0]'], {}), '(nmsed_out_v[0])\n', (2565, 2581), True, 'import numpy as np\n'), ((2343, 2371), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (2369, 2371), True, 'import paddle.fluid as fluid\n'), ((2031, 2064), 'os.path.join', 'os.path.join', (['model_dir', 'var.name'], {}), '(model_dir, var.name)\n', (2043, 2064), False, 'import os\n')]
import logging from metadrive.component.road_network.node_road_network import NodeRoadNetwork import numpy as np from panda3d.core import TransparencyAttrib, LineSegs, NodePath from metadrive.component.lane.circular_lane import CircularLane from metadrive.component.map.base_map import BaseMap from metadrive.component.pgblock.first_block import FirstPGBlock from metadrive.component.road_network import Road from metadrive.constants import RENDER_MODE_ONSCREEN, CamMask from metadrive.engine.asset_loader import AssetLoader from metadrive.utils import clip, norm, get_np_random from metadrive.utils.coordinates_shift import panda_position from metadrive.utils.scene_utils import ray_localization from metadrive.utils.space import Parameter, BlockParameterSpace class BaseNavigation: navigation_info_dim = 10 NAVI_POINT_DIST = 50 PRE_NOTIFY_DIST = 40 MIN_ALPHA = 0.15 CKPT_UPDATE_RANGE = 5 FORCE_CALCULATE = False LINE_TO_DEST_HEIGHT = 0.6 def __init__( self, engine, show_navi_mark: bool = False, random_navi_mark_color=False, show_dest_mark=False, show_line_to_dest=False ): """ This class define a helper for localizing vehicles and retrieving navigation information. It now only support from first block start to the end node, but can be extended easily. """ self.map = None self.checkpoints = None self._target_checkpoints_index = None self.current_ref_lanes = None self.next_ref_lanes = None self.final_lane = None self.current_lane = None self._navi_info = np.zeros((self.navigation_info_dim, ), dtype=np.float32) # navi information res # Vis self._show_navi_info = (engine.mode == RENDER_MODE_ONSCREEN and not engine.global_config["debug_physics_world"]) self.origin = NodePath("navigation_sign") if self._show_navi_info else None self.navi_mark_color = (0.6, 0.8, 0.5) if not random_navi_mark_color else get_np_random().rand(3) self.navi_arrow_dir = [0, 0] self._dest_node_path = None self._goal_node_path = None self._line_to_dest = None self._show_line_to_dest = show_line_to_dest if self._show_navi_info: # nodepath self._line_to_dest = self.origin.attachNewNode("line") self._goal_node_path = self.origin.attachNewNode("target") self._dest_node_path = self.origin.attachNewNode("dest") if show_navi_mark: navi_point_model = AssetLoader.loader.loadModel(AssetLoader.file_path("models", "box.bam")) navi_point_model.reparentTo(self._goal_node_path) if show_dest_mark: dest_point_model = AssetLoader.loader.loadModel(AssetLoader.file_path("models", "box.bam")) dest_point_model.reparentTo(self._dest_node_path) if show_line_to_dest: line_seg = LineSegs("line_to_dest") line_seg.setColor(self.navi_mark_color[0], self.navi_mark_color[1], self.navi_mark_color[2], 0.7) line_seg.setThickness(2) self._dynamic_line_np = NodePath(line_seg.create(True)) self._dynamic_line_np.reparentTo(self.origin) self._line_to_dest = line_seg self._goal_node_path.setTransparency(TransparencyAttrib.M_alpha) self._dest_node_path.setTransparency(TransparencyAttrib.M_alpha) self._goal_node_path.setColor( self.navi_mark_color[0], self.navi_mark_color[1], self.navi_mark_color[2], 0.7 ) self._dest_node_path.setColor( self.navi_mark_color[0], self.navi_mark_color[1], self.navi_mark_color[2], 0.7 ) self._goal_node_path.hide(CamMask.AllOn) self._dest_node_path.hide(CamMask.AllOn) self._goal_node_path.show(CamMask.MainCam) self._dest_node_path.show(CamMask.MainCam) logging.debug("Load Vehicle Module: {}".format(self.__class__.__name__)) def reset(self, map: BaseMap, current_lane): self.map = map self.current_lane = current_lane def set_route(self, current_lane_index: str, destination: str): """ Find a shortest path from start road to end road :param current_lane_index: start road node :param destination: end road node or end lane index :return: None """ raise NotImplementedError def update_localization(self, ego_vehicle): """ It is called every step """ raise NotImplementedError def _get_info_for_checkpoint(self, lanes_id, ref_lane, ego_vehicle): navi_information = [] # Project the checkpoint position into the target vehicle's coordination, where # +x is the heading and +y is the right hand side. later_middle = (float(self.get_current_lane_num()) / 2 - 0.5) * self.get_current_lane_width() check_point = ref_lane.position(ref_lane.length, later_middle) dir_vec = check_point - ego_vehicle.position # get the vector from center of vehicle to checkpoint dir_norm = norm(dir_vec[0], dir_vec[1]) if dir_norm > self.NAVI_POINT_DIST: # if the checkpoint is too far then crop the direction vector dir_vec = dir_vec / dir_norm * self.NAVI_POINT_DIST ckpt_in_heading, ckpt_in_rhs = ego_vehicle.projection(dir_vec) # project to ego vehicle's coordination # Dim 1: the relative position of the checkpoint in the target vehicle's heading direction. navi_information.append(clip((ckpt_in_heading / self.NAVI_POINT_DIST + 1) / 2, 0.0, 1.0)) # Dim 2: the relative position of the checkpoint in the target vehicle's right hand side direction. navi_information.append(clip((ckpt_in_rhs / self.NAVI_POINT_DIST + 1) / 2, 0.0, 1.0)) if lanes_id == 0: lanes_heading = ref_lane.heading_theta_at(ref_lane.local_coordinates(ego_vehicle.position)[0]) else: lanes_heading = ref_lane.heading_theta_at(min(self.PRE_NOTIFY_DIST, ref_lane.length)) # Try to include the current lane's information into the navigation information bendradius = 0.0 dir = 0.0 angle = 0.0 if isinstance(ref_lane, CircularLane): bendradius = ref_lane.radius / ( BlockParameterSpace.CURVE[Parameter.radius].max + self.get_current_lane_num() * self.get_current_lane_width() ) dir = ref_lane.direction if dir == 1: angle = ref_lane.end_phase - ref_lane.start_phase elif dir == -1: angle = ref_lane.start_phase - ref_lane.end_phase # Dim 3: The bending radius of current lane navi_information.append(clip(bendradius, 0.0, 1.0)) # Dim 4: The bending direction of current lane (+1 for clockwise, -1 for counterclockwise) navi_information.append(clip((dir + 1) / 2, 0.0, 1.0)) # Dim 5: The angular difference between the heading in lane ending position and # the heading in lane starting position navi_information.append( clip((np.rad2deg(angle) / BlockParameterSpace.CURVE[Parameter.angle].max + 1) / 2, 0.0, 1.0) ) return navi_information, lanes_heading, check_point def _update_target_checkpoints(self, ego_lane_index, ego_lane_longitude): raise NotImplementedError def get_navi_info(self): return self._navi_info def destroy(self): if self._show_navi_info: try: self._line_to_dest.removeNode() except AttributeError: pass self._dest_node_path.removeNode() self._goal_node_path.removeNode() self.next_ref_lanes = None self.current_ref_lanes = None def set_force_calculate_lane_index(self, force: bool): self.FORCE_CALCULATE = force def __del__(self): logging.debug("{} is destroyed".format(self.__class__.__name__)) def get_current_lateral_range(self, current_position, engine) -> float: raise NotImplementedError def get_current_lane_width(self) -> float: return self.current_lane.width def get_current_lane_num(self) -> float: return len(self.current_ref_lanes) def _get_current_lane(self, ego_vehicle): """ Called in update_localization to find current lane information """ possible_lanes = ray_localization( ego_vehicle.heading, ego_vehicle.position, ego_vehicle.engine, return_all_result=True ) for lane, index, l_1_dist in possible_lanes: if lane in self.current_ref_lanes: return lane, index nx_ckpt = self._target_checkpoints_index[-1] if nx_ckpt == self.checkpoints[-1] or self.next_ref_lanes is None: return possible_lanes[0][:-1] if len(possible_lanes) > 0 else (None, None) if self.map.road_network_type == NodeRoadNetwork: nx_nx_ckpt = nx_ckpt + 1 next_ref_lanes = self.map.road_network.graph[self.checkpoints[nx_ckpt]][self.checkpoints[nx_nx_ckpt]] else: next_ref_lanes = self.next_ref_lanes for lane, index, l_1_dist in possible_lanes: if lane in next_ref_lanes: return lane, index return possible_lanes[0][:-1] if len(possible_lanes) > 0 else (None, None) def _update_current_lane(self, ego_vehicle): lane, lane_index = self._get_current_lane(ego_vehicle) if lane is None: lane, lane_index = ego_vehicle.lane, ego_vehicle.lane_index ego_vehicle.on_lane = False if self.FORCE_CALCULATE: lane_index, _ = self.map.road_network.get_closest_lane_index(ego_vehicle.position) lane = self.map.road_network.get_lane(lane_index) self.current_lane = lane assert lane_index == lane.index, "lane index mismatch!" return lane, lane_index def _ray_lateral_range(self, engine, start_position, dir, length=50): """ It is used to measure the lateral range of special blocks :param start_position: start_point :param dir: ray direction :param length: length of ray :return: lateral range [m] """ end_position = start_position[0] + dir[0] * length, start_position[1] + dir[1] * length start_position = panda_position(start_position, z=0.15) end_position = panda_position(end_position, z=0.15) mask = FirstPGBlock.CONTINUOUS_COLLISION_MASK res = engine.physics_world.static_world.rayTestClosest(start_position, end_position, mask=mask) if not res.hasHit(): return length else: return res.getHitFraction() * length def _draw_line_to_dest(self, start_position, end_position): if not self._show_line_to_dest: return line_seg = self._line_to_dest line_seg.moveTo(panda_position(start_position, self.LINE_TO_DEST_HEIGHT)) line_seg.drawTo(panda_position(end_position, self.LINE_TO_DEST_HEIGHT)) self._dynamic_line_np.removeNode() self._dynamic_line_np = NodePath(line_seg.create(False)) self._dynamic_line_np.hide(CamMask.Shadow | CamMask.RgbCam) self._dynamic_line_np.reparentTo(self.origin) def detach_from_world(self): if isinstance(self.origin, NodePath): self.origin.detachNode() def attach_to_world(self, engine): if isinstance(self.origin, NodePath): self.origin.reparentTo(engine.render)
[ "metadrive.engine.asset_loader.AssetLoader.file_path", "panda3d.core.NodePath", "panda3d.core.LineSegs", "metadrive.utils.get_np_random", "metadrive.utils.coordinates_shift.panda_position", "metadrive.utils.norm", "metadrive.utils.clip", "numpy.zeros", "metadrive.utils.scene_utils.ray_localization",...
[((1649, 1704), 'numpy.zeros', 'np.zeros', (['(self.navigation_info_dim,)'], {'dtype': 'np.float32'}), '((self.navigation_info_dim,), dtype=np.float32)\n', (1657, 1704), True, 'import numpy as np\n'), ((5226, 5254), 'metadrive.utils.norm', 'norm', (['dir_vec[0]', 'dir_vec[1]'], {}), '(dir_vec[0], dir_vec[1])\n', (5230, 5254), False, 'from metadrive.utils import clip, norm, get_np_random\n'), ((8594, 8702), 'metadrive.utils.scene_utils.ray_localization', 'ray_localization', (['ego_vehicle.heading', 'ego_vehicle.position', 'ego_vehicle.engine'], {'return_all_result': '(True)'}), '(ego_vehicle.heading, ego_vehicle.position, ego_vehicle.\n engine, return_all_result=True)\n', (8610, 8702), False, 'from metadrive.utils.scene_utils import ray_localization\n'), ((10569, 10607), 'metadrive.utils.coordinates_shift.panda_position', 'panda_position', (['start_position'], {'z': '(0.15)'}), '(start_position, z=0.15)\n', (10583, 10607), False, 'from metadrive.utils.coordinates_shift import panda_position\n'), ((10631, 10667), 'metadrive.utils.coordinates_shift.panda_position', 'panda_position', (['end_position'], {'z': '(0.15)'}), '(end_position, z=0.15)\n', (10645, 10667), False, 'from metadrive.utils.coordinates_shift import panda_position\n'), ((1888, 1915), 'panda3d.core.NodePath', 'NodePath', (['"""navigation_sign"""'], {}), "('navigation_sign')\n", (1896, 1915), False, 'from panda3d.core import TransparencyAttrib, LineSegs, NodePath\n'), ((5671, 5735), 'metadrive.utils.clip', 'clip', (['((ckpt_in_heading / self.NAVI_POINT_DIST + 1) / 2)', '(0.0)', '(1.0)'], {}), '((ckpt_in_heading / self.NAVI_POINT_DIST + 1) / 2, 0.0, 1.0)\n', (5675, 5735), False, 'from metadrive.utils import clip, norm, get_np_random\n'), ((5878, 5938), 'metadrive.utils.clip', 'clip', (['((ckpt_in_rhs / self.NAVI_POINT_DIST + 1) / 2)', '(0.0)', '(1.0)'], {}), '((ckpt_in_rhs / self.NAVI_POINT_DIST + 1) / 2, 0.0, 1.0)\n', (5882, 5938), False, 'from metadrive.utils import clip, norm, get_np_random\n'), ((6893, 6919), 'metadrive.utils.clip', 'clip', (['bendradius', '(0.0)', '(1.0)'], {}), '(bendradius, 0.0, 1.0)\n', (6897, 6919), False, 'from metadrive.utils import clip, norm, get_np_random\n'), ((7053, 7082), 'metadrive.utils.clip', 'clip', (['((dir + 1) / 2)', '(0.0)', '(1.0)'], {}), '((dir + 1) / 2, 0.0, 1.0)\n', (7057, 7082), False, 'from metadrive.utils import clip, norm, get_np_random\n'), ((11130, 11186), 'metadrive.utils.coordinates_shift.panda_position', 'panda_position', (['start_position', 'self.LINE_TO_DEST_HEIGHT'], {}), '(start_position, self.LINE_TO_DEST_HEIGHT)\n', (11144, 11186), False, 'from metadrive.utils.coordinates_shift import panda_position\n'), ((11212, 11266), 'metadrive.utils.coordinates_shift.panda_position', 'panda_position', (['end_position', 'self.LINE_TO_DEST_HEIGHT'], {}), '(end_position, self.LINE_TO_DEST_HEIGHT)\n', (11226, 11266), False, 'from metadrive.utils.coordinates_shift import panda_position\n'), ((2987, 3011), 'panda3d.core.LineSegs', 'LineSegs', (['"""line_to_dest"""'], {}), "('line_to_dest')\n", (2995, 3011), False, 'from panda3d.core import TransparencyAttrib, LineSegs, NodePath\n'), ((2032, 2047), 'metadrive.utils.get_np_random', 'get_np_random', ([], {}), '()\n', (2045, 2047), False, 'from metadrive.utils import clip, norm, get_np_random\n'), ((2611, 2653), 'metadrive.engine.asset_loader.AssetLoader.file_path', 'AssetLoader.file_path', (['"""models"""', '"""box.bam"""'], {}), "('models', 'box.bam')\n", (2632, 2653), False, 'from metadrive.engine.asset_loader import AssetLoader\n'), ((2816, 2858), 'metadrive.engine.asset_loader.AssetLoader.file_path', 'AssetLoader.file_path', (['"""models"""', '"""box.bam"""'], {}), "('models', 'box.bam')\n", (2837, 2858), False, 'from metadrive.engine.asset_loader import AssetLoader\n'), ((7272, 7289), 'numpy.rad2deg', 'np.rad2deg', (['angle'], {}), '(angle)\n', (7282, 7289), True, 'import numpy as np\n')]
'''stride''' # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ import numpy as np from mindspore import nn from mindspore.ops import operations as P from mindspore.common import dtype as mstype class _stride_unfold_(nn.Cell): '''stride''' def __init__(self, kernel_size, stride=-1): super(_stride_unfold_, self).__init__() if stride == -1: self.stride = kernel_size else: self.stride = stride self.kernel_size = kernel_size self.reshape = P.Reshape() self.transpose = P.Transpose() self.unfold = _unfold_(kernel_size) def construct(self, x): """stride""" N, C, H, W = x.shape leftup_idx_x = [] leftup_idx_y = [] nh = int(H / self.stride) nw = int(W / self.stride) for i in range(nh): leftup_idx_x.append(i * self.stride) for i in range(nw): leftup_idx_y.append(i * self.stride) NumBlock_x = len(leftup_idx_x) NumBlock_y = len(leftup_idx_y) zeroslike = P.ZerosLike() cc_2 = P.Concat(axis=2) cc_3 = P.Concat(axis=3) unf_x = P.Zeros()((N, C, NumBlock_x * self.kernel_size, NumBlock_y * self.kernel_size), mstype.float32) N, C, H, W = unf_x.shape for i in range(NumBlock_x): for j in range(NumBlock_y): unf_i = i * self.kernel_size unf_j = j * self.kernel_size org_i = leftup_idx_x[i] org_j = leftup_idx_y[j] fills = x[:, :, org_i:org_i + self.kernel_size, org_j:org_j + self.kernel_size] unf_x += cc_3((cc_3((zeroslike(unf_x[:, :, :, :unf_j]), cc_2((cc_2( (zeroslike(unf_x[:, :, :unf_i, unf_j:unf_j + self.kernel_size]), fills)), zeroslike( unf_x[:, :, unf_i + self.kernel_size:, unf_j:unf_j + self.kernel_size]))))), zeroslike(unf_x[:, :, :, unf_j + self.kernel_size:]))) y = self.unfold(unf_x) return y class _stride_fold_(nn.Cell): '''stride''' def __init__(self, kernel_size, output_shape=(-1, -1), stride=-1): super(_stride_fold_, self).__init__() if isinstance(kernel_size, (list, tuple)): self.kernel_size = kernel_size else: self.kernel_size = [kernel_size, kernel_size] if stride == -1: self.stride = kernel_size[0] else: self.stride = stride self.output_shape = output_shape self.reshape = P.Reshape() self.transpose = P.Transpose() self.fold = _fold_(kernel_size) def construct(self, x): '''stride''' if self.output_shape[0] == -1: large_x = self.fold(x) N, C, H, _ = large_x.shape leftup_idx = [] for i in range(0, H, self.kernel_size[0]): leftup_idx.append(i) NumBlock = len(leftup_idx) fold_x = P.Zeros()((N, C, (NumBlock - 1) * self.stride + self.kernel_size[0], (NumBlock - 1) * self.stride + self.kernel_size[0]), mstype.float32) for i in range(NumBlock): for j in range(NumBlock): fold_i = i * self.stride fold_j = j * self.stride org_i = leftup_idx[i] org_j = leftup_idx[j] fills = x[:, :, org_i:org_i + self.kernel_size[0], org_j:org_j + self.kernel_size[1]] fold_x += cc_3((cc_3((zeroslike(fold_x[:, :, :, :fold_j]), cc_2((cc_2( (zeroslike(fold_x[:, :, :fold_i, fold_j:fold_j + self.kernel_size[1]]), fills)), zeroslike( fold_x[:, :, fold_i + self.kernel_size[0]:, fold_j:fold_j + self.kernel_size[1]]))))), zeroslike(fold_x[:, :, :, fold_j + self.kernel_size[1]:]))) y = fold_x else: NumBlock_x = int( (self.output_shape[0] - self.kernel_size[0]) / self.stride + 1) NumBlock_y = int( (self.output_shape[1] - self.kernel_size[1]) / self.stride + 1) large_shape = [NumBlock_x * self.kernel_size[0], NumBlock_y * self.kernel_size[1]] self.fold = _fold_(self.kernel_size, large_shape) large_x = self.fold(x) N, C, H, _ = large_x.shape leftup_idx_x = [] leftup_idx_y = [] for i in range(NumBlock_x): leftup_idx_x.append(i * self.kernel_size[0]) for i in range(NumBlock_y): leftup_idx_y.append(i * self.kernel_size[1]) fold_x = P.Zeros()((N, C, (NumBlock_x - 1) * self.stride + self.kernel_size[0], (NumBlock_y - 1) * self.stride + self.kernel_size[1]), mstype.float32) for i in range(NumBlock_x): for j in range(NumBlock_y): fold_i = i * self.stride fold_j = j * self.stride org_i = leftup_idx_x[i] org_j = leftup_idx_y[j] fills = x[:, :, org_i:org_i + self.kernel_size[0], org_j:org_j + self.kernel_size[1]] fold_x += cc_3((cc_3((zeroslike(fold_x[:, :, :, :fold_j]), cc_2((cc_2( (zeroslike(fold_x[:, :, :fold_i, fold_j:fold_j + self.kernel_size[1]]), fills)), zeroslike( fold_x[:, :, fold_i + self.kernel_size[0]:, fold_j:fold_j + self.kernel_size[1]]))))), zeroslike(fold_x[:, :, :, fold_j + self.kernel_size[1]:]))) y = fold_x return y class _unfold_(nn.Cell): '''stride''' def __init__(self, kernel_size, stride=-1): super(_unfold_, self).__init__() if stride == -1: self.stride = kernel_size self.kernel_size = kernel_size self.reshape = P.Reshape() self.transpose = P.Transpose() def construct(self, x): '''stride''' N, C, H, W = x.shape numH = int(H / self.kernel_size) numW = int(W / self.kernel_size) if numH * self.kernel_size != H or numW * self.kernel_size != W: x = x[:, :, :numH * self.kernel_size, :, numW * self.kernel_size] output_img = self.reshape(x, (N, C, numH, self.kernel_size, W)) output_img = self.transpose(output_img, (0, 1, 2, 4, 3)) output_img = self.reshape(output_img, (N, C, int( numH * numW), self.kernel_size, self.kernel_size)) output_img = self.transpose(output_img, (0, 2, 1, 4, 3)) output_img = self.reshape(output_img, (N, int(numH * numW), -1)) return output_img class _fold_(nn.Cell): '''stride''' def __init__(self, kernel_size, output_shape=(-1, -1), stride=-1): super(_fold_, self).__init__() if isinstance(kernel_size, (list, tuple)): self.kernel_size = kernel_size else: self.kernel_size = [kernel_size, kernel_size] if stride == -1: self.stride = kernel_size[0] self.output_shape = output_shape self.reshape = P.Reshape() self.transpose = P.Transpose() def construct(self, x): '''stride''' N, C, L = x.shape org_C = int(L / self.kernel_size[0] / self.kernel_size[1]) if self.output_shape[0] == -1: numH = int(np.sqrt(C)) numW = int(np.sqrt(C)) org_H = int(numH * self.kernel_size[0]) org_W = org_H else: org_H = int(self.output_shape[0]) org_W = int(self.output_shape[1]) numH = int(org_H / self.kernel_size[0]) numW = int(org_W / self.kernel_size[1]) output_img = self.reshape( x, (N, C, org_C, self.kernel_size[0], self.kernel_size[1])) output_img = self.transpose(output_img, (0, 2, 1, 3, 4)) output_img = self.reshape( output_img, (N, org_C, numH, numW, self.kernel_size[0], self.kernel_size[1])) output_img = self.transpose(output_img, (0, 1, 2, 4, 3, 5)) output_img = self.reshape(output_img, (N, org_C, org_H, org_W)) return output_img
[ "numpy.sqrt", "mindspore.ops.operations.Zeros", "mindspore.ops.operations.Transpose", "mindspore.ops.operations.Concat", "mindspore.ops.operations.Reshape", "mindspore.ops.operations.ZerosLike" ]
[((1167, 1178), 'mindspore.ops.operations.Reshape', 'P.Reshape', ([], {}), '()\n', (1176, 1178), True, 'from mindspore.ops import operations as P\n'), ((1204, 1217), 'mindspore.ops.operations.Transpose', 'P.Transpose', ([], {}), '()\n', (1215, 1217), True, 'from mindspore.ops import operations as P\n'), ((1713, 1726), 'mindspore.ops.operations.ZerosLike', 'P.ZerosLike', ([], {}), '()\n', (1724, 1726), True, 'from mindspore.ops import operations as P\n'), ((1742, 1758), 'mindspore.ops.operations.Concat', 'P.Concat', ([], {'axis': '(2)'}), '(axis=2)\n', (1750, 1758), True, 'from mindspore.ops import operations as P\n'), ((1774, 1790), 'mindspore.ops.operations.Concat', 'P.Concat', ([], {'axis': '(3)'}), '(axis=3)\n', (1782, 1790), True, 'from mindspore.ops import operations as P\n'), ((3320, 3331), 'mindspore.ops.operations.Reshape', 'P.Reshape', ([], {}), '()\n', (3329, 3331), True, 'from mindspore.ops import operations as P\n'), ((3357, 3370), 'mindspore.ops.operations.Transpose', 'P.Transpose', ([], {}), '()\n', (3368, 3370), True, 'from mindspore.ops import operations as P\n'), ((6856, 6867), 'mindspore.ops.operations.Reshape', 'P.Reshape', ([], {}), '()\n', (6865, 6867), True, 'from mindspore.ops import operations as P\n'), ((6893, 6906), 'mindspore.ops.operations.Transpose', 'P.Transpose', ([], {}), '()\n', (6904, 6906), True, 'from mindspore.ops import operations as P\n'), ((8149, 8160), 'mindspore.ops.operations.Reshape', 'P.Reshape', ([], {}), '()\n', (8158, 8160), True, 'from mindspore.ops import operations as P\n'), ((8186, 8199), 'mindspore.ops.operations.Transpose', 'P.Transpose', ([], {}), '()\n', (8197, 8199), True, 'from mindspore.ops import operations as P\n'), ((1807, 1816), 'mindspore.ops.operations.Zeros', 'P.Zeros', ([], {}), '()\n', (1814, 1816), True, 'from mindspore.ops import operations as P\n'), ((3754, 3763), 'mindspore.ops.operations.Zeros', 'P.Zeros', ([], {}), '()\n', (3761, 3763), True, 'from mindspore.ops import operations as P\n'), ((5531, 5540), 'mindspore.ops.operations.Zeros', 'P.Zeros', ([], {}), '()\n', (5538, 5540), True, 'from mindspore.ops import operations as P\n'), ((8405, 8415), 'numpy.sqrt', 'np.sqrt', (['C'], {}), '(C)\n', (8412, 8415), True, 'import numpy as np\n'), ((8440, 8450), 'numpy.sqrt', 'np.sqrt', (['C'], {}), '(C)\n', (8447, 8450), True, 'import numpy as np\n')]
from typing import List import numpy as np class Board: """ Represents the state of the game, and says which moves are available. """ def __init__(self, grid: np.ndarray, available): self.grid = np.copy(grid) self.available = available def clone(self): return Board(self.grid, self.available) def available_moves(self) -> List[int]: return self.available(self.grid) def apply_move(self, pos: int, token: int): """ Apply a players move. """ self.grid.flat[pos] = token def __str__(self) -> str: return f"{self.grid}"
[ "numpy.copy" ]
[((233, 246), 'numpy.copy', 'np.copy', (['grid'], {}), '(grid)\n', (240, 246), True, 'import numpy as np\n')]
from collections import OrderedDict import json import xml.etree.ElementTree as ET import mmcv import os import numpy as np from PIL import Image from .pipelines import Compose from mmcv.utils import print_log from mmdet.core import eval_map, eval_recalls from .builder import DATASETS from .xml_style import XMLDataset from .custom import CustomDataset @DATASETS.register_module() class SemiVOCDataset(CustomDataset): CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') def __init__(self, ann_file, pipeline, classes=None, data_root=None, img_prefix='', seg_prefix=None, proposal_file=None, test_mode=False, filter_empty_gt=True, ann_path='', labelmapper='', thres=None,): self.ann_file = ann_file self.ann_path = ann_path self.labelmapper = json.load(open(labelmapper,'r')) self.thres=thres self.default_thres = [0.1, 0.3] self.thres_list_by_class = {} self.data_root = data_root self.img_prefix = img_prefix self.seg_prefix = seg_prefix self.proposal_file = proposal_file self.test_mode = test_mode self.filter_empty_gt = filter_empty_gt self.CLASSES = self.get_classes(classes) self.cat2label = {cat: i for i, cat in enumerate(self.CLASSES)} self.data_infos = self.load_annotations(self.ann_file) if not test_mode: valid_inds = self._filter_imgs() self.data_infos = [self.data_infos[i] for i in valid_inds] # set group flag for the sampler self._set_group_flag() self.pipeline = Compose(pipeline) self.proposals = None self.year=2007 self.min_size = None def load_annotations(self, ann_file): """Load annotation from json ann_file. Args: ann_file (str): Path of XML file. Returns: list[dict]: Annotation info from XML file. """ data_infos = [] with open(ann_file,'r') as f: lines=f.readlines() for line in lines: filename = line.strip() img = Image.open(os.path.join(self.img_prefix, filename)) width, height = img.size data_infos.append( dict(id=filename.replace('.jpg',''), filename=filename, width=width, height=height)) return data_infos def get_cat_ids(self, idx): img_id = self.data_infos[idx]['id'] gt_labels = [] img_info = self.data_infos[idx] name = img_info['filename']+'.json' with open(os.path.join(self.ann_path, name),'r') as f: data = json.load(f) for i in range(int(data['targetNum'])): x1,y1,x2,y2 = data['rects'][i] inter_w = max(0, min(x2, img_info['width']) - max(x1, 0)) inter_h = max(0, min(y2, img_info['height']) - max(y1, 0)) if inter_w * inter_h == 0: continue if x2-x1<1 or y2-y1<1: continue bbox = [x1,y1,x2,y2] if 'scores' in data.keys() and self.thres is not None: if isinstance(self.thres, str): if not os.path.exists(self.thres): if data['scores'][i] < float(self.default_thres[1]) and data['scores'][i]>= float(self.default_thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: with open(self.thres, 'r') as f: self.thres_list_by_class = json.load(f)["thres"] if data['tags'][i] not in self.thres_list_by_class.keys(): if data['scores'][i] < float(self.default_thres[1]) and data['scores'][i]>= float(self.default_thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: if data['scores'][i] < float(self.thres_list_by_class[data['tags'][i]]) and data['scores'][i]>= float(self.default_thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: if data['scores'][i] < float(self.thres[1]) and data['scores'][i]>= float(self.thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) return gt_labels def _filter_imgs(self, min_size=32): """Filter images too small or without annotation.""" valid_inds = [] for i, img_info in enumerate(self.data_infos): name = img_info['filename']+'.json' with open(os.path.join(self.ann_path, name),'r') as f: data = json.load(f) if min(img_info['width'], img_info['height']) < min_size or data['targetNum']==0: continue valid_inds.append(i) return valid_inds def get_ann_info(self, idx): """Get annotation from XML file by index. Args: idx (int): Index of data. Returns: dict: Annotation info of specified index. """ img_id = self.data_infos[idx]['id'] gt_bboxes = [] gt_labels = [] gt_bboxes_ignore = [] gt_masks_ann = [] img_info = self.data_infos[idx] name = img_info['filename']+'.json' with open(os.path.join(self.ann_path, name),'r') as f: data = json.load(f) for i in range(int(data['targetNum'])): x1,y1,x2,y2 = data['rects'][i] inter_w = max(0, min(x2, img_info['width']) - max(x1, 0)) inter_h = max(0, min(y2, img_info['height']) - max(y1, 0)) if inter_w * inter_h == 0: continue if x2-x1<1 or y2-y1<1: continue bbox = [x1,y1,x2,y2] if 'scores' in data.keys() and self.thres is not None: if isinstance(self.thres, str): if not os.path.exists(self.thres): if data['scores'][i] < float(self.default_thres[1]) and data['scores'][i]>= float(self.default_thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: with open(self.thres, 'r') as f: self.thres_list_by_class = json.load(f)["thres"] if data['tags'][i] not in self.thres_list_by_class.keys(): if data['scores'][i] < float(self.default_thres[1]) and data['scores'][i]>= float(self.default_thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: if data['scores'][i] < float(self.thres_list_by_class[data['tags'][i]]) and data['scores'][i]>= float(self.default_thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: if data['scores'][i] < float(self.thres[1]) and data['scores'][i]>= float(self.thres[0]): gt_bboxes_ignore.append(bbox) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) else: gt_bboxes.append(bbox) gt_labels.append(int(self.labelmapper['cat2id'][data['tags'][i]])) gt_masks_ann.append(None) if gt_bboxes: gt_bboxes = np.array(gt_bboxes, dtype=np.float32) gt_labels = np.array(gt_labels, dtype=np.int64) else: gt_bboxes = np.zeros((0, 4), dtype=np.float32) gt_labels = np.array([], dtype=np.int64) if gt_bboxes_ignore: gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32) else: gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32) seg_map = img_info['filename'].replace('jpg', 'png') ann = dict( bboxes=gt_bboxes, labels=gt_labels, bboxes_ignore=gt_bboxes_ignore, ) return ann def evaluate(self, results, metric='mAP', logger=None, proposal_nums=(100, 300, 1000), iou_thr=0.5, scale_ranges=None): """Evaluate in VOC protocol. Args: results (list[list | tuple]): Testing results of the dataset. metric (str | list[str]): Metrics to be evaluated. Options are 'mAP', 'recall'. logger (logging.Logger | str, optional): Logger used for printing related information during evaluation. Default: None. proposal_nums (Sequence[int]): Proposal number used for evaluating recalls, such as recall@100, recall@1000. Default: (100, 300, 1000). iou_thr (float | list[float]): IoU threshold. Default: 0.5. scale_ranges (list[tuple], optional): Scale ranges for evaluating mAP. If not specified, all bounding boxes would be included in evaluation. Default: None. Returns: dict[str, float]: AP/recall metrics. """ if not isinstance(metric, str): assert len(metric) == 1 metric = metric[0] allowed_metrics = ['mAP', 'recall'] if metric not in allowed_metrics: raise KeyError(f'metric {metric} is not supported') annotations = [self.get_ann_info(i) for i in range(len(self))] eval_results = OrderedDict() iou_thrs = [iou_thr] if isinstance(iou_thr, float) else iou_thr if metric == 'mAP': assert isinstance(iou_thrs, list) if self.year == 2007: ds_name = 'voc07' else: ds_name = self.CLASSES mean_aps = [] for iou_thr in iou_thrs: print_log(f'\n{"-" * 15}iou_thr: {iou_thr}{"-" * 15}') mean_ap, _ = eval_map( results, annotations, scale_ranges=None, iou_thr=iou_thr, dataset=ds_name, logger=logger) mean_aps.append(mean_ap) eval_results[f'AP{int(iou_thr * 100):02d}'] = round(mean_ap, 3) eval_results['mAP'] = sum(mean_aps) / len(mean_aps) elif metric == 'recall': gt_bboxes = [ann['bboxes'] for ann in annotations] recalls = eval_recalls( gt_bboxes, results, proposal_nums, iou_thrs, logger=logger) for i, num in enumerate(proposal_nums): for j, iou_thr in enumerate(iou_thrs): eval_results[f'recall@{num}@{iou_thr}'] = recalls[i, j] if recalls.shape[1] > 1: ar = recalls.mean(axis=1) for i, num in enumerate(proposal_nums): eval_results[f'AR@{num}'] = ar[i] return eval_results
[ "os.path.exists", "collections.OrderedDict", "mmcv.utils.print_log", "os.path.join", "numpy.array", "numpy.zeros", "mmdet.core.eval_map", "mmdet.core.eval_recalls", "json.load" ]
[((12242, 12255), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (12253, 12255), False, 'from collections import OrderedDict\n'), ((3045, 3057), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3054, 3057), False, 'import json\n'), ((7056, 7068), 'json.load', 'json.load', (['f'], {}), '(f)\n', (7065, 7068), False, 'import json\n'), ((10120, 10157), 'numpy.array', 'np.array', (['gt_bboxes'], {'dtype': 'np.float32'}), '(gt_bboxes, dtype=np.float32)\n', (10128, 10157), True, 'import numpy as np\n'), ((10182, 10217), 'numpy.array', 'np.array', (['gt_labels'], {'dtype': 'np.int64'}), '(gt_labels, dtype=np.int64)\n', (10190, 10217), True, 'import numpy as np\n'), ((10256, 10290), 'numpy.zeros', 'np.zeros', (['(0, 4)'], {'dtype': 'np.float32'}), '((0, 4), dtype=np.float32)\n', (10264, 10290), True, 'import numpy as np\n'), ((10315, 10343), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.int64'}), '([], dtype=np.int64)\n', (10323, 10343), True, 'import numpy as np\n'), ((10405, 10449), 'numpy.array', 'np.array', (['gt_bboxes_ignore'], {'dtype': 'np.float32'}), '(gt_bboxes_ignore, dtype=np.float32)\n', (10413, 10449), True, 'import numpy as np\n'), ((10495, 10529), 'numpy.zeros', 'np.zeros', (['(0, 4)'], {'dtype': 'np.float32'}), '((0, 4), dtype=np.float32)\n', (10503, 10529), True, 'import numpy as np\n'), ((2981, 3014), 'os.path.join', 'os.path.join', (['self.ann_path', 'name'], {}), '(self.ann_path, name)\n', (2993, 3014), False, 'import os\n'), ((6319, 6331), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6328, 6331), False, 'import json\n'), ((6992, 7025), 'os.path.join', 'os.path.join', (['self.ann_path', 'name'], {}), '(self.ann_path, name)\n', (7004, 7025), False, 'import os\n'), ((12606, 12663), 'mmcv.utils.print_log', 'print_log', (['f"""\n{\'-\' * 15}iou_thr: {iou_thr}{\'-\' * 15}"""'], {}), '(f"""\n{\'-\' * 15}iou_thr: {iou_thr}{\'-\' * 15}""")\n', (12615, 12663), False, 'from mmcv.utils import print_log\n'), ((12690, 12793), 'mmdet.core.eval_map', 'eval_map', (['results', 'annotations'], {'scale_ranges': 'None', 'iou_thr': 'iou_thr', 'dataset': 'ds_name', 'logger': 'logger'}), '(results, annotations, scale_ranges=None, iou_thr=iou_thr, dataset=\n ds_name, logger=logger)\n', (12698, 12793), False, 'from mmdet.core import eval_map, eval_recalls\n'), ((13213, 13285), 'mmdet.core.eval_recalls', 'eval_recalls', (['gt_bboxes', 'results', 'proposal_nums', 'iou_thrs'], {'logger': 'logger'}), '(gt_bboxes, results, proposal_nums, iou_thrs, logger=logger)\n', (13225, 13285), False, 'from mmdet.core import eval_map, eval_recalls\n'), ((2519, 2558), 'os.path.join', 'os.path.join', (['self.img_prefix', 'filename'], {}), '(self.img_prefix, filename)\n', (2531, 2558), False, 'import os\n'), ((6251, 6284), 'os.path.join', 'os.path.join', (['self.ann_path', 'name'], {}), '(self.ann_path, name)\n', (6263, 6284), False, 'import os\n'), ((3637, 3663), 'os.path.exists', 'os.path.exists', (['self.thres'], {}), '(self.thres)\n', (3651, 3663), False, 'import os\n'), ((7648, 7674), 'os.path.exists', 'os.path.exists', (['self.thres'], {}), '(self.thres)\n', (7662, 7674), False, 'import os\n'), ((4257, 4269), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4266, 4269), False, 'import json\n'), ((8268, 8280), 'json.load', 'json.load', (['f'], {}), '(f)\n', (8277, 8280), False, 'import json\n')]
import numpy as np import torch import torchvision.utils as vutils import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt #import pandas as pd import seaborn as sns sns.set() sns.set_style('whitegrid') sns.set_palette('colorblind') def convert_npimage_torchimage(image): return 255*torch.transpose(torch.transpose(torch.from_numpy(image), 0, 2), 1, 2) def get_scatter_plot(data, labels=None, n_classes=None, num_samples=1000, xlim=None, ylim=None): ''' data : 2d points, batch_size x data_dim (numpy array) labels : labels, batch_size (numpy array) ''' batch_size, data_dim = data.shape num_samples = min(num_samples, batch_size) if labels is None: labels = np.zeros(batch_size, dtype=np.int) if n_classes is None: n_classes = len(np.unique(labels)) # sub-samples if num_samples != batch_size: indices = np.random.permutation(batch_size) data = data[indices[:num_samples]] labels = labels[indices[:num_samples]] # init config palette = sns.color_palette(n_colors=n_classes) palette = [palette[i] for i in np.unique(labels)] # plot fig, ax = plt.subplots(figsize=(5, 5)) data = {'x': data[:, 0], 'y': data[:, 1], 'class': labels} sns.scatterplot(x='x', y='y', hue='class', data=data, palette=palette) # set config if xlim is not None: plt.xlim((-xlim, xlim)) if ylim is not None: plt.ylim((-ylim, ylim)) # draw to canvas fig.canvas.draw() # draw the canvas, cache the renderer image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) # close figure plt.close() return image def get_data_for_quiver_plot(val, num): _x = np.linspace(-val, val, num) _y = np.linspace(-val, val, num) _u, _v = np.meshgrid(_x, _y) _vis_data = np.stack([_u.reshape(num**2), _v.reshape(num**2)], axis=1) vis_data = torch.from_numpy(_vis_data).float() return vis_data, _x, _y def get_quiver_plot(vec, x_pos, y_pos, xlim=None, ylim=None, scale=None): ''' vec : 2d points, batch_size x data_dim (numpy array) pos : 2d points, batch_size x data_dim (numpy array) ''' grid_size = x_pos.shape[0] batch_size = vec.shape[0] assert batch_size == grid_size**2 assert y_pos.shape[0] == grid_size # get x, y, u, v X = x_pos #np.arange(-10, 10, 1) Y = y_pos #np.arange(-10, 10, 1) #U, V = np.meshgrid(X, Y) U = vec[:, 0].reshape(grid_size, grid_size) V = vec[:, 1].reshape(grid_size, grid_size) # plot fig, ax = plt.subplots(figsize=(5, 5)) q = ax.quiver(X, Y, U, V, pivot='mid', scale=scale) #ax.quiverkey(q, X=0.3, Y=1.1, U=10, # label='Quiver key, length = 10', labelpos='E') # set config if xlim is not None: plt.xlim((-xlim, xlim)) if ylim is not None: plt.ylim((-ylim, ylim)) # tight plt.tight_layout() # draw to canvas fig.canvas.draw() # draw the canvas, cache the renderer image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) # close figure plt.close() return image def get_data_for_heatmap(val=4, num=256): _x = np.linspace(-val, val, num) _y = np.linspace(-val, val, num) _u, _v = np.meshgrid(_x, _y) _data = np.stack([_u.reshape(num**2), _v.reshape(num**2)], axis=1) return _data, _x, _y def energy_to_unnormalized_prob(energy): prob = torch.exp(-energy) # unnormalized prob return prob def get_prob_from_energy_func_for_vis(energy_func, val=4, num=256): # get grid _z, _, _ = get_data_for_heatmap(val=val, num=num) z = torch.from_numpy(_z).float() # run energy func energy = energy_func(z) prob = energy_to_unnormalized_prob(energy) # convert to numpy array _prob = prob.cpu().float().numpy() _prob = _prob.reshape(num, num) return _prob def get_imshow_plot(prob, val=4, use_grid=True): # plot fig, ax = plt.subplots(figsize=(5, 5)) im = ax.imshow(prob, cmap='jet', extent=[-val, val, -val, val]) ax.grid(False) if use_grid: plt.xticks(np.arange(-val, val+1, step=1)) plt.yticks(np.arange(-val, val+1, step=1)) else: plt.xticks([]) plt.yticks([]) # tight plt.tight_layout() # draw to canvas fig.canvas.draw() # draw the canvas, cache the renderer image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) # close figure plt.close() return image def get_1d_histogram_plot(data, val=4, num=256, use_grid=True): xmin = 0 xmax = val # get data x = data # get histogram hist, xedges = np.histogram(x, range=[xmin, xmax], bins=num) # plot heatmap fig, ax = plt.subplots(figsize=(5, 5)) im = ax.bar(xedges[:-1], hist, width=0.5)#, color='#0504aa',alpha=0.7) ax.grid(False) if use_grid: plt.xticks(np.arange(0, val+1, step=1)) else: plt.xticks([]) # tight plt.tight_layout() # draw to canvas fig.canvas.draw() # draw the canvas, cache the renderer image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) # close figure plt.close() return image def get_2d_histogram_plot(data, val=4, num=256, use_grid=True): xmin = -val xmax = val ymin = -val ymax = val # get data x = data[:, 0] y = data[:, 1] # get histogram heatmap, xedges, yedges = np.histogram2d(x, y, range=[[xmin, xmax], [ymin, ymax]], bins=num) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] # plot heatmap fig, ax = plt.subplots(figsize=(5, 5)) im = ax.imshow(heatmap.T, extent=extent, cmap='jet') ax.grid(False) if use_grid: plt.xticks(np.arange(-val, val+1, step=1)) plt.yticks(np.arange(-val, val+1, step=1)) else: plt.xticks([]) plt.yticks([]) # tight plt.tight_layout() # draw to canvas fig.canvas.draw() # draw the canvas, cache the renderer image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) # close figure plt.close() return image def get_grid_image(input, batch_size, nchannels, nheight, nwidth=None, ncol=8, pad_value=0, do_square=True): ''' input : b x c x h x w (where h = w) ''' if batch_size > ncol**2 and do_square: input = input[:ncol**2, :, :, :] batch_size = ncol**2 nwidth = nwidth if nwidth is not None else nheight input = input.detach() output = input.view(batch_size, nchannels, nheight, nwidth).clone().cpu() output = vutils.make_grid(output, nrow=ncol, normalize=True, scale_each=True, pad_value=pad_value) #output = vutils.make_grid(output, normalize=False, scale_each=False) return output #def get_canvas(fig): # fig.canvas.draw() # draw the canvas, cache the renderer # image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') # image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,)) # return image # # close figure # plt.close() # #def get_contour_with_batch_size(model, batch_size=128, vmin=-10.0, vmax=10.0, title=None): # model.eval() # matplotlib.rcParams['xtick.direction'] = 'out' # matplotlib.rcParams['ytick.direction'] = 'out' # matplotlib.rcParams['contour.negative_linestyle'] = 'solid' # # # tmp # weight = next(model.parameters()) # # # gen grid⋅ # delta = 0.1 # xv, yv = torch.meshgrid([torch.arange(vmin, vmax, delta), torch.arange(vmin, vmax, delta)]) # h = yv.size(0) # w = xv.size(0) # yv = yv.contiguous().view(-1) # xv = xv.contiguous().view(-1) # input = torch.cat([xv.unsqueeze(1), yv.unsqueeze(1)], dim=1).to(weight.device) # # # forward # prob = model.prob(input, batch_size=batch_size) # # # convert torch variable to numpy array # xv = xv.cpu().numpy().reshape(h, w) # yv = yv.cpu().numpy().reshape(h, w) # zv = prob.detach().cpu().numpy().reshape(h, w) # # # plot and save⋅ # fig = plt.figure() # CS1 = plt.contourf(xv, yv, zv) # CS2 = plt.contour(xv, yv, zv, alpha=.7, colors='k') # plt.clabel(CS2, inline=1, fontsize=10, colors='k') # #plt.title('Simplest default with labels') # if title is not None: # plt.title(title) # #plt.savefig(filename) # #plt.close() # image = get_canvas(fig) # plt.close() # # return image # ##def get_contour_with_data(model, data, vmin=-10.0, vmax=10.0, title=None): ## model.eval() ## matplotlib.rcParams['xtick.direction'] = 'out' ## matplotlib.rcParams['ytick.direction'] = 'out' ## matplotlib.rcParams['contour.negative_linestyle'] = 'solid' ## ## # gen grid⋅ ## delta = 0.1 ## xv, yv = torch.meshgrid([torch.arange(vmin, vmax, delta), torch.arange(vmin, vmax, delta)]) ## h = yv.size(0) ## w = xv.size(0) ## yv = yv.contiguous().view(-1) ## xv = xv.contiguous().view(-1) ## input = torch.cat([xv.unsqueeze(1), yv.unsqueeze(1)], dim=1).to(data.device) ## ## # forward ## prob = model.prob(input, data) ## ## # convert torch variable to numpy array ## xv = xv.cpu().numpy().reshape(h, w) ## yv = yv.cpu().numpy().reshape(h, w) ## zv = prob.detach().cpu().numpy().reshape(h, w) ## ## # plot and save⋅ ## fig = plt.figure() ## CS1 = plt.contourf(xv, yv, zv) ## CS2 = plt.contour(xv, yv, zv, alpha=.7, colors='k') ## plt.clabel(CS2, inline=1, fontsize=10, colors='k') ## #plt.title('Simplest default with labels') ## if title is not None: ## plt.title(title) ## #plt.savefig(filename) ## #plt.close() ## image = get_canvas(fig) ## plt.close() ## ## return image # #def get_contour_with_z(model, z, vmin=-10.0, vmax=10.0, title=None): # model.eval() # matplotlib.rcParams['xtick.direction'] = 'out' # matplotlib.rcParams['ytick.direction'] = 'out' # matplotlib.rcParams['contour.negative_linestyle'] = 'solid' # # # gen grid⋅ # delta = 0.1 # xv, yv = torch.meshgrid([torch.arange(vmin, vmax, delta), torch.arange(vmin, vmax, delta)]) # h = yv.size(0) # w = xv.size(0) # yv = yv.contiguous().view(-1) # xv = xv.contiguous().view(-1) # input = torch.cat([xv.unsqueeze(1), yv.unsqueeze(1)], dim=1).to(z.device) # # # forward # prob = model.prob(input, z=z) # # # convert torch variable to numpy array # xv = xv.cpu().numpy().reshape(h, w) # yv = yv.cpu().numpy().reshape(h, w) # zv = prob.detach().cpu().numpy().reshape(h, w) # # # plot and save⋅ # fig = plt.figure() # CS1 = plt.contourf(xv, yv, zv) # CS2 = plt.contour(xv, yv, zv, alpha=.7, colors='k') # plt.clabel(CS2, inline=1, fontsize=10, colors='k') # #plt.title('Simplest default with labels') # if title is not None: # plt.title(title) # #plt.savefig(filename) # #plt.close() # image = get_canvas(fig) # plt.close() # # return image
[ "torch.exp", "torch.from_numpy", "seaborn.set_style", "seaborn.scatterplot", "torchvision.utils.make_grid", "numpy.arange", "seaborn.set", "numpy.histogram", "seaborn.color_palette", "matplotlib.pyplot.close", "numpy.linspace", "matplotlib.pyplot.yticks", "numpy.histogram2d", "numpy.meshgr...
[((87, 108), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (101, 108), False, 'import matplotlib\n'), ((184, 193), 'seaborn.set', 'sns.set', ([], {}), '()\n', (191, 193), True, 'import seaborn as sns\n'), ((194, 220), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (207, 220), True, 'import seaborn as sns\n'), ((221, 250), 'seaborn.set_palette', 'sns.set_palette', (['"""colorblind"""'], {}), "('colorblind')\n", (236, 250), True, 'import seaborn as sns\n'), ((1054, 1091), 'seaborn.color_palette', 'sns.color_palette', ([], {'n_colors': 'n_classes'}), '(n_colors=n_classes)\n', (1071, 1091), True, 'import seaborn as sns\n'), ((1172, 1200), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (1184, 1200), True, 'import matplotlib.pyplot as plt\n'), ((1292, 1362), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'hue': '"""class"""', 'data': 'data', 'palette': 'palette'}), "(x='x', y='y', hue='class', data=data, palette=palette)\n", (1307, 1362), True, 'import seaborn as sns\n'), ((1749, 1760), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1758, 1760), True, 'import matplotlib.pyplot as plt\n'), ((1828, 1855), 'numpy.linspace', 'np.linspace', (['(-val)', 'val', 'num'], {}), '(-val, val, num)\n', (1839, 1855), True, 'import numpy as np\n'), ((1865, 1892), 'numpy.linspace', 'np.linspace', (['(-val)', 'val', 'num'], {}), '(-val, val, num)\n', (1876, 1892), True, 'import numpy as np\n'), ((1906, 1925), 'numpy.meshgrid', 'np.meshgrid', (['_x', '_y'], {}), '(_x, _y)\n', (1917, 1925), True, 'import numpy as np\n'), ((2676, 2704), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (2688, 2704), True, 'import matplotlib.pyplot as plt\n'), ((3024, 3042), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3040, 3042), True, 'import matplotlib.pyplot as plt\n'), ((3297, 3308), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3306, 3308), True, 'import matplotlib.pyplot as plt\n'), ((3378, 3405), 'numpy.linspace', 'np.linspace', (['(-val)', 'val', 'num'], {}), '(-val, val, num)\n', (3389, 3405), True, 'import numpy as np\n'), ((3415, 3442), 'numpy.linspace', 'np.linspace', (['(-val)', 'val', 'num'], {}), '(-val, val, num)\n', (3426, 3442), True, 'import numpy as np\n'), ((3456, 3475), 'numpy.meshgrid', 'np.meshgrid', (['_x', '_y'], {}), '(_x, _y)\n', (3467, 3475), True, 'import numpy as np\n'), ((3625, 3643), 'torch.exp', 'torch.exp', (['(-energy)'], {}), '(-energy)\n', (3634, 3643), False, 'import torch\n'), ((4150, 4178), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (4162, 4178), True, 'import matplotlib.pyplot as plt\n'), ((4458, 4476), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4474, 4476), True, 'import matplotlib.pyplot as plt\n'), ((4731, 4742), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4740, 4742), True, 'import matplotlib.pyplot as plt\n'), ((4922, 4967), 'numpy.histogram', 'np.histogram', (['x'], {'range': '[xmin, xmax]', 'bins': 'num'}), '(x, range=[xmin, xmax], bins=num)\n', (4934, 4967), True, 'import numpy as np\n'), ((5002, 5030), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (5014, 5030), True, 'import matplotlib.pyplot as plt\n'), ((5241, 5259), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5257, 5259), True, 'import matplotlib.pyplot as plt\n'), ((5514, 5525), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5523, 5525), True, 'import matplotlib.pyplot as plt\n'), ((5775, 5841), 'numpy.histogram2d', 'np.histogram2d', (['x', 'y'], {'range': '[[xmin, xmax], [ymin, ymax]]', 'bins': 'num'}), '(x, y, range=[[xmin, xmax], [ymin, ymax]], bins=num)\n', (5789, 5841), True, 'import numpy as np\n'), ((5936, 5964), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (5948, 5964), True, 'import matplotlib.pyplot as plt\n'), ((6233, 6251), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6249, 6251), True, 'import matplotlib.pyplot as plt\n'), ((6506, 6517), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6515, 6517), True, 'import matplotlib.pyplot as plt\n'), ((6987, 7080), 'torchvision.utils.make_grid', 'vutils.make_grid', (['output'], {'nrow': 'ncol', 'normalize': '(True)', 'scale_each': '(True)', 'pad_value': 'pad_value'}), '(output, nrow=ncol, normalize=True, scale_each=True,\n pad_value=pad_value)\n', (7003, 7080), True, 'import torchvision.utils as vutils\n'), ((722, 756), 'numpy.zeros', 'np.zeros', (['batch_size'], {'dtype': 'np.int'}), '(batch_size, dtype=np.int)\n', (730, 756), True, 'import numpy as np\n'), ((897, 930), 'numpy.random.permutation', 'np.random.permutation', (['batch_size'], {}), '(batch_size)\n', (918, 930), True, 'import numpy as np\n'), ((1414, 1437), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-xlim, xlim)'], {}), '((-xlim, xlim))\n', (1422, 1437), True, 'import matplotlib.pyplot as plt\n'), ((1471, 1494), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-ylim, ylim)'], {}), '((-ylim, ylim))\n', (1479, 1494), True, 'import matplotlib.pyplot as plt\n'), ((2926, 2949), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-xlim, xlim)'], {}), '((-xlim, xlim))\n', (2934, 2949), True, 'import matplotlib.pyplot as plt\n'), ((2983, 3006), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-ylim, ylim)'], {}), '((-ylim, ylim))\n', (2991, 3006), True, 'import matplotlib.pyplot as plt\n'), ((4403, 4417), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (4413, 4417), True, 'import matplotlib.pyplot as plt\n'), ((4426, 4440), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (4436, 4440), True, 'import matplotlib.pyplot as plt\n'), ((5209, 5223), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (5219, 5223), True, 'import matplotlib.pyplot as plt\n'), ((6178, 6192), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (6188, 6192), True, 'import matplotlib.pyplot as plt\n'), ((6201, 6215), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (6211, 6215), True, 'import matplotlib.pyplot as plt\n'), ((807, 824), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (816, 824), True, 'import numpy as np\n'), ((1127, 1144), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (1136, 1144), True, 'import numpy as np\n'), ((2016, 2043), 'torch.from_numpy', 'torch.from_numpy', (['_vis_data'], {}), '(_vis_data)\n', (2032, 2043), False, 'import torch\n'), ((3826, 3846), 'torch.from_numpy', 'torch.from_numpy', (['_z'], {}), '(_z)\n', (3842, 3846), False, 'import torch\n'), ((4302, 4334), 'numpy.arange', 'np.arange', (['(-val)', '(val + 1)'], {'step': '(1)'}), '(-val, val + 1, step=1)\n', (4311, 4334), True, 'import numpy as np\n'), ((4353, 4385), 'numpy.arange', 'np.arange', (['(-val)', '(val + 1)'], {'step': '(1)'}), '(-val, val + 1, step=1)\n', (4362, 4385), True, 'import numpy as np\n'), ((5162, 5191), 'numpy.arange', 'np.arange', (['(0)', '(val + 1)'], {'step': '(1)'}), '(0, val + 1, step=1)\n', (5171, 5191), True, 'import numpy as np\n'), ((6077, 6109), 'numpy.arange', 'np.arange', (['(-val)', '(val + 1)'], {'step': '(1)'}), '(-val, val + 1, step=1)\n', (6086, 6109), True, 'import numpy as np\n'), ((6128, 6160), 'numpy.arange', 'np.arange', (['(-val)', '(val + 1)'], {'step': '(1)'}), '(-val, val + 1, step=1)\n', (6137, 6160), True, 'import numpy as np\n'), ((339, 362), 'torch.from_numpy', 'torch.from_numpy', (['image'], {}), '(image)\n', (355, 362), False, 'import torch\n')]
import torch import numpy as np class FFNet(torch.nn.Module): """Simple class to implement a feed-forward neural network in PyTorch. Attributes: layers: list of torch.nn.Linear layers to be applied in forward pass. activation: activation function to be applied between layers. """ def __init__(self,shape,activation=None): """Constructor for FFNet. Arguments: shape: list of ints describing network shape, including input & output size. activation: a torch.nn function specifying the network activation. """ super(FFNet, self).__init__() self.shape = shape self.layers = [] self.activation = activation ##TODO(pculbertson): make it possible use >1 activation... maybe? who cares for ii in range(0,len(shape)-1): self.layers.append(torch.nn.Linear(shape[ii],shape[ii+1])) self.layers = torch.nn.ModuleList(self.layers) def forward(self, x): "Performs a forward pass on x, a numpy array of size (-1,shape[0])" for ii in range(0,len(self.layers)-1): x = self.layers[ii](x) if self.activation: x = self.activation(x) return self.layers[-1](x) class CNNet(torch.nn.Module): """PyTorch Module which implements a combined CNN-feedforward network for node classification. Attributes: conv_layers: ModuleList of Conv2d layers for CNN forward pass. ff_layers: ModuleList of Linear layers for feedforward pass. pool_layers: ModuleList of MaxPool2d layers for CNN forward pass. Contains Nones if no pooling. kernel: list of kernel sizes for CNN layers. stride: list of strides for CNN layers. padding: list of paddings for CNN layers. conv_activation: activation function to be applied between CNN layers ff_activation: activation function to be applied between feedforward layers. """ def __init__(self,num_features,channels,ff_shape, input_size, kernel=2,stride=2, padding=0, conv_activation=None,ff_activation=None,pool=None): """Constructor for CNNet. Arguments: num_features: length of node feature vector. channels: vector of length N+1 specifying # of channels for each convolutional layer, where N is number of conv layers. channels[0] should be the size of the input image. ff_shape: vector specifying shape of feedforward network. ff_shape[0] should be the size of the first hidden layer; constructor does the math to determine ff input size. input_size: tuple of input image size, (W1, H1) kernel: vector (or scalar) of kernel sizes for each conv layer. if scalar, each layer uses the same kernel. stride: vector (or scalar) of strides for each conv layer. uniform stride if scalar. padding: vector (or scalar) of paddings for each conv layer. uniform if scalar. conv_activation: nonlinear activation to be used after each conv layer ff_activation: nonlinear activation to be used after each ff layer pool: pooling to be added after each layer. if None, no pooling. if scalar, same pooling for each layer. """ super(CNNet, self).__init__() N = len(channels)-1 #number of conv layers if type(kernel) is int: self.kernel = [kernel]*N if type(stride) is int: self.stride = [stride]*N if type(padding) is int: self.padding = [padding]*N if not pool or len(pool)==1: self.pool = [pool]*N self.conv_activation = conv_activation self.ff_activation = ff_activation self.conv_layers = [] self.pool_layers = [] self.ff_layers = [] W, H = input_size for ii in range(0,len(channels)-1): self.conv_layers.append(torch.nn.Conv2d(channels[ii],channels[ii+1],self.kernel[ii], stride=self.stride[ii],padding=self.padding[ii])) W = int(1+(W-self.kernel[ii]+2*self.padding[ii])/self.stride[ii]) H = int(1+(H-self.kernel[ii]+2*self.padding[ii])/self.stride[ii]) if self.pool[ii]: if W % self.pool[ii] != 0 or H % self.pool[ii] != 0: raise ValueError('trying to pool by non-factor') W, H = W/self.pool[ii], H/self.pool[ii] self.pool_layers.append(torch.nn.MaxPool2d(self.pool[ii])) else: self.pool_layers.append(None) cnn_output_size = W*H*channels[-1]+num_features shape = np.concatenate(([cnn_output_size], ff_shape)) for ii in range(0,len(shape)-1): self.ff_layers.append(torch.nn.Linear(shape[ii],shape[ii+1])) self.conv_layers = torch.nn.ModuleList(self.conv_layers) self.ff_layers = torch.nn.ModuleList(self.ff_layers) if pool: self.pool_layers = torch.nn.ModuleList(self.pool_layers) def forward(self, image_batch, feature_batch): """Performs a network forward pass on images/features. Images go through CNN, these features are concatenated with the real-valued features, and passed through feed-forward network. Arguments: image_batch: batch of images (as a torch.Tensor of floats) to be passed through, of size [B,W1,H1,C1], where B is the batch_size, (W1,H1) and C1 are the input_size and channels[0] passed during initialization. feature_batch: batch of real-valued features (torch.Tensor of floats), of size [B,N], where N is the num_features passed during initialization. Usage: cnn = CNNet(...); outs = cnn(images_in,features_in) """ x = image_batch for ii in range(0,len(self.conv_layers)): x = self.conv_layers[ii](x) if self.conv_activation: x = self.conv_activation(x) if self.pool_layers[ii]: x = self.pool_layers[ii](x) x = torch.flatten(x,start_dim=1) x = torch.cat((x,feature_batch),dim=1) for ii in range(0,len(self.ff_layers)-1): x = self.ff_layers[ii](x) if self.ff_activation: x = self.ff_activation(x) return self.ff_layers[-1](x)
[ "torch.nn.ModuleList", "torch.flatten", "torch.nn.Conv2d", "torch.nn.MaxPool2d", "torch.nn.Linear", "numpy.concatenate", "torch.cat" ]
[((946, 978), 'torch.nn.ModuleList', 'torch.nn.ModuleList', (['self.layers'], {}), '(self.layers)\n', (965, 978), False, 'import torch\n'), ((4672, 4717), 'numpy.concatenate', 'np.concatenate', (['([cnn_output_size], ff_shape)'], {}), '(([cnn_output_size], ff_shape))\n', (4686, 4717), True, 'import numpy as np\n'), ((4861, 4898), 'torch.nn.ModuleList', 'torch.nn.ModuleList', (['self.conv_layers'], {}), '(self.conv_layers)\n', (4880, 4898), False, 'import torch\n'), ((4924, 4959), 'torch.nn.ModuleList', 'torch.nn.ModuleList', (['self.ff_layers'], {}), '(self.ff_layers)\n', (4943, 4959), False, 'import torch\n'), ((6107, 6136), 'torch.flatten', 'torch.flatten', (['x'], {'start_dim': '(1)'}), '(x, start_dim=1)\n', (6120, 6136), False, 'import torch\n'), ((6148, 6184), 'torch.cat', 'torch.cat', (['(x, feature_batch)'], {'dim': '(1)'}), '((x, feature_batch), dim=1)\n', (6157, 6184), False, 'import torch\n'), ((5008, 5045), 'torch.nn.ModuleList', 'torch.nn.ModuleList', (['self.pool_layers'], {}), '(self.pool_layers)\n', (5027, 5045), False, 'import torch\n'), ((883, 924), 'torch.nn.Linear', 'torch.nn.Linear', (['shape[ii]', 'shape[ii + 1]'], {}), '(shape[ii], shape[ii + 1])\n', (898, 924), False, 'import torch\n'), ((3953, 4072), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['channels[ii]', 'channels[ii + 1]', 'self.kernel[ii]'], {'stride': 'self.stride[ii]', 'padding': 'self.padding[ii]'}), '(channels[ii], channels[ii + 1], self.kernel[ii], stride=\n self.stride[ii], padding=self.padding[ii])\n', (3968, 4072), False, 'import torch\n'), ((4793, 4834), 'torch.nn.Linear', 'torch.nn.Linear', (['shape[ii]', 'shape[ii + 1]'], {}), '(shape[ii], shape[ii + 1])\n', (4808, 4834), False, 'import torch\n'), ((4500, 4533), 'torch.nn.MaxPool2d', 'torch.nn.MaxPool2d', (['self.pool[ii]'], {}), '(self.pool[ii])\n', (4518, 4533), False, 'import torch\n')]
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import unittest import numpy as np import paddle import paddle.fluid as fluid from paddle.fluid.data_feeder import convert_dtype import paddle.fluid.core as core from paddle.static import program_guard, Program class TestEmptyLikeAPICommon(unittest.TestCase): def __check_out__(self, out): data_type = convert_dtype(out.dtype) self.assertEqual(data_type, self.dst_dtype, 'dtype should be %s, but get %s' % (self.dst_dtype, data_type)) shape = out.shape self.assertTupleEqual(shape, self.dst_shape, 'shape should be %s, but get %s' % (self.dst_shape, shape)) if data_type in ['float32', 'float64', 'int32', 'int64']: max_value = np.nanmax(out) min_value = np.nanmin(out) always_non_full_zero = max_value >= min_value always_full_zero = max_value == 0.0 and min_value == 0.0 self.assertTrue(always_full_zero or always_non_full_zero, 'always_full_zero or always_non_full_zero.') elif data_type in ['bool']: total_num = out.size true_num = np.sum(out == True) false_num = np.sum(out == False) self.assertTrue(total_num == true_num + false_num, 'The value should always be True or False.') else: self.assertTrue(False, 'invalid data type') class TestEmptyLikeAPI(TestEmptyLikeAPICommon): def setUp(self): self.init_config() def test_dygraph_api_out(self): paddle.disable_static() out = paddle.empty_like(self.x, self.dtype) self.__check_out__(out.numpy()) paddle.enable_static() def init_config(self): self.x = np.random.random((200, 3)).astype("float32") self.dtype = self.x.dtype self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI2(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("float64") self.dtype = self.x.dtype self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI3(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("int") self.dtype = self.x.dtype self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI4(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("int64") self.dtype = self.x.dtype self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI5(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("bool") self.dtype = self.x.dtype self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI6(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("float64") self.dtype = "float32" self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI7(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("int") self.dtype = "float32" self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI8(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("int64") self.dtype = "float32" self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI9(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("bool") self.dtype = "float32" self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI10(TestEmptyLikeAPI): def init_config(self): self.x = np.random.random((200, 3)).astype("float32") self.dtype = "bool" self.dst_shape = self.x.shape self.dst_dtype = self.dtype class TestEmptyLikeAPI_Static(TestEmptyLikeAPICommon): def setUp(self): self.init_config() def test_static_graph(self): paddle.enable_static() dtype = 'float32' train_program = Program() startup_program = Program() with program_guard(train_program, startup_program): x = np.random.random(self.x_shape).astype(dtype) data_x = paddle.static.data( 'x', shape=self.data_x_shape, dtype=dtype) out = paddle.empty_like(data_x) place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda( ) else paddle.CPUPlace() exe = paddle.static.Executor(place) res = exe.run(train_program, feed={'x': x}, fetch_list=[out]) self.dst_dtype = dtype self.dst_shape = x.shape self.__check_out__(res[0]) paddle.disable_static() def init_config(self): self.x_shape = (200, 3) self.data_x_shape = [200, 3] class TestEmptyLikeAPI_Static2(TestEmptyLikeAPI_Static): def init_config(self): self.x_shape = (3, 200, 3) self.data_x_shape = [-1, 200, 3] class TestEmptyError(unittest.TestCase): def test_attr(self): def test_dtype(): x = np.random.random((200, 3)).astype("float64") dtype = 'uint8' result = paddle.empty_like(x, dtype=dtype) self.assertRaises(TypeError, test_dtype) if __name__ == '__main__': unittest.main()
[ "paddle.static.Executor", "paddle.CPUPlace", "numpy.random.random", "paddle.CUDAPlace", "paddle.enable_static", "paddle.fluid.data_feeder.convert_dtype", "paddle.empty_like", "paddle.disable_static", "paddle.static.program_guard", "numpy.nanmax", "paddle.static.data", "numpy.sum", "unittest....
[((6230, 6245), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6243, 6245), False, 'import unittest\n'), ((967, 991), 'paddle.fluid.data_feeder.convert_dtype', 'convert_dtype', (['out.dtype'], {}), '(out.dtype)\n', (980, 991), False, 'from paddle.fluid.data_feeder import convert_dtype\n'), ((2279, 2302), 'paddle.disable_static', 'paddle.disable_static', ([], {}), '()\n', (2300, 2302), False, 'import paddle\n'), ((2317, 2354), 'paddle.empty_like', 'paddle.empty_like', (['self.x', 'self.dtype'], {}), '(self.x, self.dtype)\n', (2334, 2354), False, 'import paddle\n'), ((2403, 2425), 'paddle.enable_static', 'paddle.enable_static', ([], {}), '()\n', (2423, 2425), False, 'import paddle\n'), ((4914, 4936), 'paddle.enable_static', 'paddle.enable_static', ([], {}), '()\n', (4934, 4936), False, 'import paddle\n'), ((4989, 4998), 'paddle.static.Program', 'Program', ([], {}), '()\n', (4996, 4998), False, 'from paddle.static import program_guard, Program\n'), ((5025, 5034), 'paddle.static.Program', 'Program', ([], {}), '()\n', (5032, 5034), False, 'from paddle.static import program_guard, Program\n'), ((5417, 5446), 'paddle.static.Executor', 'paddle.static.Executor', (['place'], {}), '(place)\n', (5439, 5446), False, 'import paddle\n'), ((5626, 5649), 'paddle.disable_static', 'paddle.disable_static', ([], {}), '()\n', (5647, 5649), False, 'import paddle\n'), ((1449, 1463), 'numpy.nanmax', 'np.nanmax', (['out'], {}), '(out)\n', (1458, 1463), True, 'import numpy as np\n'), ((1488, 1502), 'numpy.nanmin', 'np.nanmin', (['out'], {}), '(out)\n', (1497, 1502), True, 'import numpy as np\n'), ((5049, 5094), 'paddle.static.program_guard', 'program_guard', (['train_program', 'startup_program'], {}), '(train_program, startup_program)\n', (5062, 5094), False, 'from paddle.static import program_guard, Program\n'), ((5178, 5239), 'paddle.static.data', 'paddle.static.data', (['"""x"""'], {'shape': 'self.data_x_shape', 'dtype': 'dtype'}), "('x', shape=self.data_x_shape, dtype=dtype)\n", (5196, 5239), False, 'import paddle\n'), ((5276, 5301), 'paddle.empty_like', 'paddle.empty_like', (['data_x'], {}), '(data_x)\n', (5293, 5301), False, 'import paddle\n'), ((5342, 5370), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (5368, 5370), True, 'import paddle.fluid.core as core\n'), ((5319, 5338), 'paddle.CUDAPlace', 'paddle.CUDAPlace', (['(0)'], {}), '(0)\n', (5335, 5338), False, 'import paddle\n'), ((5385, 5402), 'paddle.CPUPlace', 'paddle.CPUPlace', ([], {}), '()\n', (5400, 5402), False, 'import paddle\n'), ((6113, 6146), 'paddle.empty_like', 'paddle.empty_like', (['x'], {'dtype': 'dtype'}), '(x, dtype=dtype)\n', (6130, 6146), False, 'import paddle\n'), ((1865, 1884), 'numpy.sum', 'np.sum', (['(out == True)'], {}), '(out == True)\n', (1871, 1884), True, 'import numpy as np\n'), ((1909, 1929), 'numpy.sum', 'np.sum', (['(out == False)'], {}), '(out == False)\n', (1915, 1929), True, 'import numpy as np\n'), ((2471, 2497), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (2487, 2497), True, 'import numpy as np\n'), ((2713, 2739), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (2729, 2739), True, 'import numpy as np\n'), ((2955, 2981), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (2971, 2981), True, 'import numpy as np\n'), ((3193, 3219), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (3209, 3219), True, 'import numpy as np\n'), ((3433, 3459), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (3449, 3459), True, 'import numpy as np\n'), ((3672, 3698), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (3688, 3698), True, 'import numpy as np\n'), ((3911, 3937), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (3927, 3937), True, 'import numpy as np\n'), ((4146, 4172), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (4162, 4172), True, 'import numpy as np\n'), ((4383, 4409), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (4399, 4409), True, 'import numpy as np\n'), ((4620, 4646), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (4636, 4646), True, 'import numpy as np\n'), ((5112, 5142), 'numpy.random.random', 'np.random.random', (['self.x_shape'], {}), '(self.x_shape)\n', (5128, 5142), True, 'import numpy as np\n'), ((6019, 6045), 'numpy.random.random', 'np.random.random', (['(200, 3)'], {}), '((200, 3))\n', (6035, 6045), True, 'import numpy as np\n')]
import numpy as np import spenc as spenc import pysal as ps import geopandas as gpd import os SEED = 1901 dir_self = os.path.dirname(__file__) datadir = os.path.join(dir_self, 'spenc/tests/data') if __name__ == "__main__": nat = gpd.read_file(ps.examples.get_path("NAT.shp")) natR = ps.weights.Rook.from_dataframe(nat) names = nat.filter(like='90').columns.tolist() + nat.filter(like='89').columns.tolist() X = nat[names].values X = (X - X.mean(axis=0))/X.var(axis=0) print('(1 of 5) doing 10k nodata') np.random.seed(SEED) labels = spenc.SPENC(n_clusters=10, random_state=SEED).fit(None, natR.sparse).labels_ labels.dump(os.path.join(datadir, 'nat_10k_nodata.ary')) print('(2 of 5) doing 30k sampling') np.random.seed(SEED) labels = spenc.SPENC(n_clusters=30, random_state=SEED).sample(natR.sparse, n_samples=3) labels.dump(os.path.join(datadir, 'nat_30k_randoms.ary')) print('(3 of 5) doing 30k withdata') np.random.seed(SEED) labels = spenc.SPENC(n_clusters=30, gamma=.001, random_state=SEED).fit(X, natR.sparse).labels_ labels.dump(os.path.join(datadir, 'nat_30k_discovered.ary')) print('(4 of 5) doing infk sampling') np.random.seed(SEED) labels = spenc.SPENC(n_clusters=np.inf, random_state=SEED).sample(natR.sparse, floor=20) labels.dump(os.path.join(datadir, 'nat_infk_randoms.ary')) print('(5 of 5) doing infk withdata') np.random.seed(SEED) labels = spenc.SPENC(n_clusters=np.inf, gamma=.001, random_state=SEED).fit(X, natR.sparse, floor=20).labels_ labels.dump(os.path.join(datadir, 'nat_infk_discovered.ary')) print('done!')
[ "spenc.SPENC", "os.path.join", "os.path.dirname", "pysal.weights.Rook.from_dataframe", "numpy.random.seed", "pysal.examples.get_path" ]
[((117, 142), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (132, 142), False, 'import os\n'), ((153, 195), 'os.path.join', 'os.path.join', (['dir_self', '"""spenc/tests/data"""'], {}), "(dir_self, 'spenc/tests/data')\n", (165, 195), False, 'import os\n'), ((292, 327), 'pysal.weights.Rook.from_dataframe', 'ps.weights.Rook.from_dataframe', (['nat'], {}), '(nat)\n', (322, 327), True, 'import pysal as ps\n'), ((533, 553), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (547, 553), True, 'import numpy as np\n'), ((751, 771), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (765, 771), True, 'import numpy as np\n'), ((972, 992), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (986, 992), True, 'import numpy as np\n'), ((1204, 1224), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (1218, 1224), True, 'import numpy as np\n'), ((1428, 1448), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (1442, 1448), True, 'import numpy as np\n'), ((248, 279), 'pysal.examples.get_path', 'ps.examples.get_path', (['"""NAT.shp"""'], {}), "('NAT.shp')\n", (268, 279), True, 'import pysal as ps\n'), ((660, 703), 'os.path.join', 'os.path.join', (['datadir', '"""nat_10k_nodata.ary"""'], {}), "(datadir, 'nat_10k_nodata.ary')\n", (672, 703), False, 'import os\n'), ((880, 924), 'os.path.join', 'os.path.join', (['datadir', '"""nat_30k_randoms.ary"""'], {}), "(datadir, 'nat_30k_randoms.ary')\n", (892, 924), False, 'import os\n'), ((1108, 1155), 'os.path.join', 'os.path.join', (['datadir', '"""nat_30k_discovered.ary"""'], {}), "(datadir, 'nat_30k_discovered.ary')\n", (1120, 1155), False, 'import os\n'), ((1334, 1379), 'os.path.join', 'os.path.join', (['datadir', '"""nat_infk_randoms.ary"""'], {}), "(datadir, 'nat_infk_randoms.ary')\n", (1346, 1379), False, 'import os\n'), ((1578, 1626), 'os.path.join', 'os.path.join', (['datadir', '"""nat_infk_discovered.ary"""'], {}), "(datadir, 'nat_infk_discovered.ary')\n", (1590, 1626), False, 'import os\n'), ((785, 830), 'spenc.SPENC', 'spenc.SPENC', ([], {'n_clusters': '(30)', 'random_state': 'SEED'}), '(n_clusters=30, random_state=SEED)\n', (796, 830), True, 'import spenc as spenc\n'), ((1238, 1287), 'spenc.SPENC', 'spenc.SPENC', ([], {'n_clusters': 'np.inf', 'random_state': 'SEED'}), '(n_clusters=np.inf, random_state=SEED)\n', (1249, 1287), True, 'import spenc as spenc\n'), ((567, 612), 'spenc.SPENC', 'spenc.SPENC', ([], {'n_clusters': '(10)', 'random_state': 'SEED'}), '(n_clusters=10, random_state=SEED)\n', (578, 612), True, 'import spenc as spenc\n'), ((1006, 1064), 'spenc.SPENC', 'spenc.SPENC', ([], {'n_clusters': '(30)', 'gamma': '(0.001)', 'random_state': 'SEED'}), '(n_clusters=30, gamma=0.001, random_state=SEED)\n', (1017, 1064), True, 'import spenc as spenc\n'), ((1462, 1524), 'spenc.SPENC', 'spenc.SPENC', ([], {'n_clusters': 'np.inf', 'gamma': '(0.001)', 'random_state': 'SEED'}), '(n_clusters=np.inf, gamma=0.001, random_state=SEED)\n', (1473, 1524), True, 'import spenc as spenc\n')]
import os import time import gym from gym.spaces import Discrete import haiku as hk import jax import jax.numpy as jnp import jax.random as random from jax.experimental.optimizers import adam import numpy as np from rlax import huber_loss from jax_baselines import logger from jax_baselines.common.critic import DiscreteActionCritic from jax_baselines.common.learner import ActionCriticLearner from jax_baselines.common.scheduler import LinearDecay from jax_baselines.common.util import make_preprocessor from jax_baselines.dqn.replay import ReplayBuffer, PrioritizedReplayBuffer from jax_baselines.save import load_from_zip, save_to_zip def learn(rng, env_fn, net_fn, gamma=0.99, lr=5e-4, steps=1e6, batch_size=100, epsilon=0.1, epsilon_scheduler=None, warmup=1000, train_freq=1, buffer_size=50000, eval_freq=1e4, eval_episodes=10, double_q=False, prioritized_replay=False, alpha=0.6, beta=0.4, beta_scheduler=None, save_dir='./experiments/dqn', save_freq=1e4, logger_format_strs=None): """ """ # configure logger logger.configure(dir=save_dir, format_strs=logger_format_strs) logger.set_level(logger.INFO) # get observation preprocessor preprocess = make_preprocessor() # get schedulers if epsilon_scheduler is None: epsilon_scheduler = lambda i: epsilon if beta_scheduler is None: beta_scheduler = lambda i: beta # make sure there are sufficient examples for a batch after warmup warmup = max(warmup, batch_size) # initialize environment and buffer env = env_fn() action_space = env.action_space if not isinstance(action_space, Discrete): raise ValueError('Environment action space must be discrete.') # initialize replay buffer dummy_obs = preprocess(env.observation_space.sample()) dummy_act = env.action_space.sample() if prioritized_replay: buffer = PrioritizedReplayBuffer(buffer_size, dummy_obs, dummy_act, alpha=alpha) else: buffer = ReplayBuffer(buffer_size, dummy_obs, dummy_act) # create action critic def loss_fn(target, q_val): return huber_loss(target - q_val).mean() critic = ActionCriticLearner( DiscreteActionCritic(net_fn, action_space.n), adam(lr), loss_fn, target_train_steps=1000, double_q=double_q, ) # initialize state rng, init_rng = random.split(rng) state = critic.init_state(init_rng, dummy_obs) # training loop start_time = time.time() losses = [] obs = preprocess(env.reset()) for i in range(int(steps)): rng, step_rng = random.split(rng) # take action (epsilon-greedy approach) epsilon = epsilon_scheduler(i) if random.uniform(step_rng) < epsilon: act = action_space.sample() else: q_vals = critic.action_values(state, obs) act = jnp.argmax(q_vals).item() new_obs, rew, done, _ = env.step(act) new_obs = preprocess(new_obs) # store transition and update obs buffer.store(obs, act, rew, new_obs) obs = new_obs # start new episode if finished if done: buffer.store(obs, act, 0, new_obs, is_terminal=True) obs = preprocess(env.reset()) # update the network if i >= warmup and (i - warmup) % train_freq == 0: j = (i - warmup) // train_freq # update step batch = buffer.sample(batch_size) # update paramaters state = critic.update(j, state, batch) # get loss loss = critic.loss(state, batch) losses.append(loss) # run evaluation if i % eval_freq == 0 and i > 0: ep_lens, ep_rets = [], [] qs = [] # store the chosen action q value eval_env = env_fn() for _ in range(eval_episodes): ep_ret, ep_len = 0, 0 done = False obs = preprocess(eval_env.reset()) while not done: q_vals = critic.action_values(state, obs, train=False) qs.append(jnp.max(q_vals).item()) act = jnp.argmax(q_vals).item() obs, rew, done, _ = eval_env.step(act) obs = preprocess(obs) ep_len += 1 ep_ret += rew ep_lens.append(ep_len) ep_rets.append(ep_ret) # log results ep_lens, ep_rets = np.array(ep_lens), np.array(ep_rets) logger.info('evaluation at step {:}'.format(i)) logger.info('elapsed time {:}'.format(time.time() - start_time)) logger.logkv('loss_mean', sum(losses) / len(losses)) logger.logkv('ep_len_mean', ep_lens.mean()) logger.logkv('ep_len_std', ep_lens.std()) logger.logkv('ep_ret_mean', ep_rets.mean()) logger.logkv('ep_ret_std', ep_rets.std()) logger.logkv('q_mean', sum(q_vals) / len(q_vals)) logger.dumpkvs() # reset loss buffer losses = [] # save model if i % save_freq == 0: params = critic.get_params(state) save_to_zip(save_dir, dict(params=params)) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('--env', type=str, default='CartPole-v0', help='Environment id.') parser.add_argument('--gamma', type=float, default=0.99, help='Discount parameter.') parser.add_argument('--lr', type=float, default=5e-4, help='Learning rate.') parser.add_argument('--initial-epsilon', type=float, default=0.1, help='Initial value for epsilon.') parser.add_argument('--final-epsilon', type=float, default=0.01, help='Final value of epsilon.') parser.add_argument('--decay-proportion', type=float, default=0.2, help='Proportion of the training in which epsilon is annealed.') parser.add_argument('--seed', '-s', type=int, default=0, help='Seed for the random number generator.') parser.add_argument('--steps', type=int, default=1e6, help='Number of training timesteps.') parser.add_argument('--eval-freq', type=int, default=1e4, help='Number of timesteps between evaluations.') parser.add_argument('--warmup', type=int, default=1000, help='Number of timesteps before learning.') parser.add_argument('--exp-name', type=str, default='dqn', help='Experiment name for saving.') args = parser.parse_args() # Path where all experiment data and saves will be dumped save_dir = os.path.join('./experiments', args.exp_name) # Define Q-network (without output layer) net_fn = lambda obs: hk.nets.MLP(output_sizes=[32, 32])(obs) # Create learning rate scheduler epsilon_scheduler = LinearDecay( args.initial_epsilon, args.final_epsilon, args.decay_proportion * args.steps) # Run experiment key = random.PRNGKey(args.seed) learn(key, lambda: gym.make(args.env), net_fn, gamma=args.gamma, lr=args.lr, steps=args.steps, eval_freq=args.eval_freq, warmup=args.warmup, epsilon_scheduler=epsilon_scheduler, save_dir=save_dir)
[ "jax_baselines.common.util.make_preprocessor", "jax_baselines.logger.dumpkvs", "jax_baselines.common.critic.DiscreteActionCritic", "jax.numpy.max", "numpy.array", "gym.make", "jax.random.split", "jax_baselines.dqn.replay.PrioritizedReplayBuffer", "jax.random.PRNGKey", "argparse.ArgumentParser", ...
[((1106, 1168), 'jax_baselines.logger.configure', 'logger.configure', ([], {'dir': 'save_dir', 'format_strs': 'logger_format_strs'}), '(dir=save_dir, format_strs=logger_format_strs)\n', (1122, 1168), False, 'from jax_baselines import logger\n'), ((1173, 1202), 'jax_baselines.logger.set_level', 'logger.set_level', (['logger.INFO'], {}), '(logger.INFO)\n', (1189, 1202), False, 'from jax_baselines import logger\n'), ((1256, 1275), 'jax_baselines.common.util.make_preprocessor', 'make_preprocessor', ([], {}), '()\n', (1273, 1275), False, 'from jax_baselines.common.util import make_preprocessor\n'), ((2451, 2468), 'jax.random.split', 'random.split', (['rng'], {}), '(rng)\n', (2463, 2468), True, 'import jax.random as random\n'), ((2558, 2569), 'time.time', 'time.time', ([], {}), '()\n', (2567, 2569), False, 'import time\n'), ((5411, 5436), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5434, 5436), False, 'import argparse\n'), ((6930, 6974), 'os.path.join', 'os.path.join', (['"""./experiments"""', 'args.exp_name'], {}), "('./experiments', args.exp_name)\n", (6942, 6974), False, 'import os\n'), ((7149, 7242), 'jax_baselines.common.scheduler.LinearDecay', 'LinearDecay', (['args.initial_epsilon', 'args.final_epsilon', '(args.decay_proportion * args.steps)'], {}), '(args.initial_epsilon, args.final_epsilon, args.decay_proportion *\n args.steps)\n', (7160, 7242), False, 'from jax_baselines.common.scheduler import LinearDecay\n'), ((7280, 7305), 'jax.random.PRNGKey', 'random.PRNGKey', (['args.seed'], {}), '(args.seed)\n', (7294, 7305), True, 'import jax.random as random\n'), ((1949, 2020), 'jax_baselines.dqn.replay.PrioritizedReplayBuffer', 'PrioritizedReplayBuffer', (['buffer_size', 'dummy_obs', 'dummy_act'], {'alpha': 'alpha'}), '(buffer_size, dummy_obs, dummy_act, alpha=alpha)\n', (1972, 2020), False, 'from jax_baselines.dqn.replay import ReplayBuffer, PrioritizedReplayBuffer\n'), ((2060, 2107), 'jax_baselines.dqn.replay.ReplayBuffer', 'ReplayBuffer', (['buffer_size', 'dummy_obs', 'dummy_act'], {}), '(buffer_size, dummy_obs, dummy_act)\n', (2072, 2107), False, 'from jax_baselines.dqn.replay import ReplayBuffer, PrioritizedReplayBuffer\n'), ((2260, 2304), 'jax_baselines.common.critic.DiscreteActionCritic', 'DiscreteActionCritic', (['net_fn', 'action_space.n'], {}), '(net_fn, action_space.n)\n', (2280, 2304), False, 'from jax_baselines.common.critic import DiscreteActionCritic\n'), ((2314, 2322), 'jax.experimental.optimizers.adam', 'adam', (['lr'], {}), '(lr)\n', (2318, 2322), False, 'from jax.experimental.optimizers import adam\n'), ((2676, 2693), 'jax.random.split', 'random.split', (['rng'], {}), '(rng)\n', (2688, 2693), True, 'import jax.random as random\n'), ((2793, 2817), 'jax.random.uniform', 'random.uniform', (['step_rng'], {}), '(step_rng)\n', (2807, 2817), True, 'import jax.random as random\n'), ((5120, 5136), 'jax_baselines.logger.dumpkvs', 'logger.dumpkvs', ([], {}), '()\n', (5134, 5136), False, 'from jax_baselines import logger\n'), ((7047, 7081), 'haiku.nets.MLP', 'hk.nets.MLP', ([], {'output_sizes': '[32, 32]'}), '(output_sizes=[32, 32])\n', (7058, 7081), True, 'import haiku as hk\n'), ((7329, 7347), 'gym.make', 'gym.make', (['args.env'], {}), '(args.env)\n', (7337, 7347), False, 'import gym\n'), ((2183, 2209), 'rlax.huber_loss', 'huber_loss', (['(target - q_val)'], {}), '(target - q_val)\n', (2193, 2209), False, 'from rlax import huber_loss\n'), ((4587, 4604), 'numpy.array', 'np.array', (['ep_lens'], {}), '(ep_lens)\n', (4595, 4604), True, 'import numpy as np\n'), ((4606, 4623), 'numpy.array', 'np.array', (['ep_rets'], {}), '(ep_rets)\n', (4614, 4623), True, 'import numpy as np\n'), ((2955, 2973), 'jax.numpy.argmax', 'jnp.argmax', (['q_vals'], {}), '(q_vals)\n', (2965, 2973), True, 'import jax.numpy as jnp\n'), ((4734, 4745), 'time.time', 'time.time', ([], {}), '()\n', (4743, 4745), False, 'import time\n'), ((4258, 4276), 'jax.numpy.argmax', 'jnp.argmax', (['q_vals'], {}), '(q_vals)\n', (4268, 4276), True, 'import jax.numpy as jnp\n'), ((4208, 4223), 'jax.numpy.max', 'jnp.max', (['q_vals'], {}), '(q_vals)\n', (4215, 4223), True, 'import jax.numpy as jnp\n')]
import pandas as pd from nltk.corpus import stopwords import numpy as np import nltk import re from bs4 import BeautifulSoup from nltk.corpus import stopwords import pprint train = pd.read_csv("labeledTweet.csv",header=0,\ delimiter="\t", quoting=3) test = pd.read_csv("testTweet.csv",header=0,\ delimiter="\t", quoting=3) # print(test) # print(train) def review_wordlist(review , remove_stopwords=False): review_text = BeautifulSoup(review).get_text() review_text = re.sub("[^a-zA-Z]"," ",review_text) words = review_text.lower().split() if remove_stopwords: stops = set(stopwords.words("english")) words = [w for w in words if not w in stops] return(words) def review_sentences(review, tokenizer, remove_stopwords=False): raw_sentences = tokenizer.tokenize(review.strip()) sentences = [] for raw_sentence in raw_sentences: if len(raw_sentence)>0: sentences.append(review_wordlist(raw_sentence,remove_stopwords)) return sentences sentences = [] tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') print("parsing sentences from training set") for review in train["review"]: sentences += review_sentences(review,tokenizer) # Importing the built-in logging module import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # Creating the model and setting values for the various parameters num_features = 500 # Word vector dimensionality min_word_count = 40 # Minimum word count num_workers = 4 # Number of parallel threads context = 10 # Context window size downsampling = 1e-3 # (0.001) Downsample setting for frequent words # # Initializing the train model from gensim.models import word2vec # print("Training model....") # model = word2vec.Word2Vec(sentences,\ # workers=num_workers,\ # size=num_features,\ # min_count=min_word_count,\ # window=context, # sample=downsampling) # # To make the model memory efficient # model.init_sims(replace=True) # Saving the model for later use. Can be loaded using Word2Vec.load() model_name = "300features_40minwords_10context" model = word2vec.Word2VecKeyedVectors.load(model_name) # print(model["man"]) # Function to average all word vectors in a paragraph def featureVecMethod(words, model, num_features): # intializing new zero vector featureVec = np.zeros(num_features,dtype = 'float32') nwords = 0 #Converting Index2Word which is a list of words only to a set for better speed in the execution. index2word_set = set(model.wv.index2word) for word in words: if word in index2word_set: nwords = nwords + 1 featureVec = np.add(featureVec,model[word]) featureVec = np.divide(featureVec,nwords) return featureVec # Function for calculating the average feature vector def getAvgFeatureVec(reviews, model,num_features): counter = 0 reviewFeatureVecs = np.zeros((len(reviews),num_features),dtype = 'float32') for review in reviews: # Printing a status message every 1000th review if counter%100 == 0: print("Review %d of %d"%(counter,len(reviews))) reviewFeatureVecs[counter] = featureVecMethod(review,model,num_features) counter = counter+1 return reviewFeatureVecs # Calculating average feature vector for training set clean_train_reviews = [] for review in train['review']: clean_train_reviews.append(review_wordlist(review, remove_stopwords=True)) trainDataVecs = getAvgFeatureVec(clean_train_reviews, model, num_features) # Calculating average feature vactors for test set clean_test_reviews = [] for review in test["review"]: clean_test_reviews.append(review_wordlist(review,remove_stopwords=True)) testDataVecs = getAvgFeatureVec(clean_test_reviews, model, num_features) from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(n_estimators = 100) print("Fitting random forest to training data....") forest = forest.fit(trainDataVecs, train["sentiment"]) print("Predicting the test data") result = forest.predict(testDataVecs) output = pd.DataFrame(data={"sentiment":result}) print('Parameters currently in use:\n') pprint.pprint(forest.get_params()) # test_labels = test["sentiment"] # errors = abs(result - test_labels) # mape = 100 * np.mean(errors / test_labels) # accuracy = 100 - mape # print('Model Performance') # print('Average Error: {:0.4f} degrees.'.format(np.mean(errors))) # print('Accuracy = {:0.2f}%.'.format(accuracy)) output.to_csv( "output.csv", index=False, quoting=3 ) counter = 0 # finalResult = pd.read_csv("output.csv",header=0,\ # delimiter="\t", quoting=3)
[ "logging.basicConfig", "nltk.corpus.stopwords.words", "pandas.read_csv", "numpy.add", "gensim.models.word2vec.Word2VecKeyedVectors.load", "sklearn.ensemble.RandomForestClassifier", "bs4.BeautifulSoup", "numpy.zeros", "nltk.data.load", "pandas.DataFrame", "re.sub", "numpy.divide" ]
[((183, 251), 'pandas.read_csv', 'pd.read_csv', (['"""labeledTweet.csv"""'], {'header': '(0)', 'delimiter': '"""\t"""', 'quoting': '(3)'}), "('labeledTweet.csv', header=0, delimiter='\\t', quoting=3)\n", (194, 251), True, 'import pandas as pd\n'), ((280, 345), 'pandas.read_csv', 'pd.read_csv', (['"""testTweet.csv"""'], {'header': '(0)', 'delimiter': '"""\t"""', 'quoting': '(3)'}), "('testTweet.csv', header=0, delimiter='\\t', quoting=3)\n", (291, 345), True, 'import pandas as pd\n'), ((1100, 1149), 'nltk.data.load', 'nltk.data.load', (['"""tokenizers/punkt/english.pickle"""'], {}), "('tokenizers/punkt/english.pickle')\n", (1114, 1149), False, 'import nltk\n'), ((1339, 1434), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (1358, 1434), False, 'import logging\n'), ((2335, 2381), 'gensim.models.word2vec.Word2VecKeyedVectors.load', 'word2vec.Word2VecKeyedVectors.load', (['model_name'], {}), '(model_name)\n', (2369, 2381), False, 'from gensim.models import word2vec\n'), ((4091, 4131), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)'}), '(n_estimators=100)\n', (4113, 4131), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((4332, 4372), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'sentiment': result}"}), "(data={'sentiment': result})\n", (4344, 4372), True, 'import pandas as pd\n'), ((525, 562), 're.sub', 're.sub', (['"""[^a-zA-Z]"""', '""" """', 'review_text'], {}), "('[^a-zA-Z]', ' ', review_text)\n", (531, 562), False, 'import re\n'), ((2561, 2600), 'numpy.zeros', 'np.zeros', (['num_features'], {'dtype': '"""float32"""'}), "(num_features, dtype='float32')\n", (2569, 2600), True, 'import numpy as np\n'), ((2926, 2955), 'numpy.divide', 'np.divide', (['featureVec', 'nwords'], {}), '(featureVec, nwords)\n', (2935, 2955), True, 'import numpy as np\n'), ((473, 494), 'bs4.BeautifulSoup', 'BeautifulSoup', (['review'], {}), '(review)\n', (486, 494), False, 'from bs4 import BeautifulSoup\n'), ((647, 673), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (662, 673), False, 'from nltk.corpus import stopwords\n'), ((2877, 2908), 'numpy.add', 'np.add', (['featureVec', 'model[word]'], {}), '(featureVec, model[word])\n', (2883, 2908), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Fri Jul 2 12:09:14 2021 @author: vohuynhq """ import numpy as np import pandas as pd from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp def example(A): A_true = np.array([[3, 4, 5], [3, 4, 5]]) np.testing.assert_equal(A, A_true) return None def derivative(eval_1,eval_2,eval_3,eval_4,*args): init_printing(use_unicode= True) x = symbols('x') f_1 = x **(3/2) + pi * x ** 2 + sqrt(2) diff_1 = diff(f_1,x) eval_1_true = diff_1.subs(x,2) f_2 = sin(x)*exp(cos(x)) diff_2 = diff(f_2,x) eval_2_true= diff_2.subs(x,pi) f_3 = exp((x + 1) ** 2) diff_3 = diff(f_3,x) eval_3_true = diff_3.subs(x,1) f_4 = x ** 2 * (cos(x) ** 3) diff_4 = diff(f_4,x) eval_4_true = diff_4.subs(x,pi) assert eval_1 == eval_1_true, "Wrong answer!" assert eval_2 == eval_2_true, "Wrong answer!" assert eval_3 == eval_3_true, "Wrong answer!" assert eval_4 == eval_4_true, "Wrong answer!" return None def jacobians_hessians(eval_1,eval_2,eval_3,eval_4): init_printing(use_unicode= True) x, y, z = symbols('x y z') f_1 = x ** 2 * cos(y) + exp(z)*sin(y) J_1 = [diff(f_1,x), diff(f_1,y), diff(f_1,z)] eval_1_true = [J_1[0].subs([(x,pi), (y,pi),(z,1)]), J_1[1].subs([(x,pi), (y,pi),(z,1)]), J_1[2].subs([(x,pi), (y,pi),(z,1)])] u = x ** 2 *y - cos(x) * sin(y) v = exp(x + y) J_u = [diff(u,x), diff(u,y)] J_v = [diff(v,x), diff(v,y)] eval_u = [J_u[0].subs([(x,0),(y,pi)]), J_u[1].subs([(x,0),(y,pi)])] eval_v = [J_v[0].subs([(x,0),(y,pi)]), J_v[1].subs([(x,0),(y,pi)])] eval_2_true = [eval_u,eval_v] f_3 = x ** 3 * cos(y) - x * sin(y) H_3 = [[diff(diff(f_3,x),x), diff(diff(f_3,x),y)], [diff(diff(f_3,y),x), diff(diff(f_3,y),y)]] eval_3_true = [[H_3[0][0].subs([(x,pi), (y,pi)]), H_3[0][1].subs([(x,pi),(y,pi)])], [H_3[1][0].subs([(x,pi), (y,pi)]), H_3[1][1].subs([(x,pi),(y,pi)])]] f_4 = x * y * cos(z) - sin(x) * exp(y) * z**3 H_4 = [[diff(diff(f_4,x),x), diff(diff(f_4,x),y), diff(diff(f_4,x),z)], [diff(diff(f_4,y),x), diff(diff(f_4,y),y), diff(diff(f_4,y),z)], [diff(diff(f_4,z),x), diff(diff(f_4,z),y), diff(diff(f_4,z),z)]] eval_4_true = [ [H_4[0][0].subs([(x,pi),(y,pi),(z,pi)]), H_4[0][1].subs([(x,pi),(y,pi),(z,pi)]), H_4[0][2].subs([(x,pi),(y,pi),(z,pi)])], [H_4[1][0].subs([(x,pi),(y,pi),(z,pi)]), H_4[1][1].subs([(x,pi),(y,pi),(z,pi)]), H_4[1][2].subs([(x,pi),(y,pi),(z,pi)])], [H_4[2][0].subs([(x,pi),(y,pi),(z,pi)]), H_4[2][1].subs([(x,pi),(y,pi),(z,pi)]), H_4[2][2].subs([(x,pi),(y,pi),(z,pi)])] ] assert set(eval_1) == set(eval_1_true), 'Wrong answer!' assert set(eval_2) == set(eval_2_true), 'Wrong answer!' assert set(eval_3) == set(eval_3_true), 'Wrong answer!' assert set(eval_4) == set(eval_4_true), 'Wrong answer!' return None def question1(m,b,X,y,*args): ## # Load dataset: # data = pd.read_csv("./dataset/Xy_dataset.csv") X = np.array(data['X']) y = np.array(data['y']) X = X.reshape(X.shape[0],1) y = y.reshape(y.shape[0],1) ## # Step 1: Initialize m and b: # m_true = 0 b_true = 0 for i in range(50): ## # Step 2: Find y_pred = mx + b: # y_pred = m*X + b ## # Step 3: Update m and b using the Gradient Descent algorithm: # dm = np.mean((y_pred - y) * X) db = np.mean(y_pred - y) m_true = m_true - 0.1*dm b_true = b_true - 0.1*db np.testing.assert_equal(m,m_true) np.testing.assert_equal(b,b_true) return None def question2(m,b,X,y,*args): ## # Step 1: Initialize m and b: # m_true = 0 b_true = 0 for i in range(50): ## # Step 2: Find y_pred = mx + b: # y_pred = m*X + b ## # Step 3: Update m and b using the Gradient Descent algorithm: # dm = np.mean((y_pred - y) * X) db = np.mean(y_pred - y) m_true = m_true - 0.1*dm b_true = b_true - 0.1*db np.testing.assert_equal(m,m_true) np.testing.assert_equal(b,b_true) return None def question3(m,b,X,y,*args): ## # Step 1: Initialize m and b: # m_true = 0 b_true = 0 for i in range(50): ## # Step 2: Find y_pred = mx + b: # y_pred = m*X + b ## # Step 3: Update m and b using the Gradient Descent algorithm: # dm = np.mean((y_pred - y) * X) db = np.mean(y_pred - y) m_true = m_true - 0.2*dm b_true = b_true - 0.2*db np.testing.assert_equal(m,m_true) np.testing.assert_equal(b,b_true) return None def question4(m,b,X,y,*args): ## # Step 1: Initialize m and b: # m_true = 0 b_true = 0 for i in range(100): ## # Step 2: Find y_pred = mx + b: # y_pred = m*X + b ## # Step 3: Update m and b using the Gradient Descent algorithm: # dm = np.mean((y_pred - y) * X) db = np.mean(y_pred - y) m_true = m_true - 0.1*dm b_true = b_true - 0.1*db np.testing.assert_equal(m,m_true) np.testing.assert_equal(b,b_true) return None
[ "sympy.sin", "numpy.mean", "sympy.cos", "numpy.testing.assert_equal", "pandas.read_csv", "sympy.sqrt", "sympy.init_printing", "sympy.symbols", "numpy.array", "sympy.diff", "sympy.exp" ]
[((241, 273), 'numpy.array', 'np.array', (['[[3, 4, 5], [3, 4, 5]]'], {}), '([[3, 4, 5], [3, 4, 5]])\n', (249, 273), True, 'import numpy as np\n'), ((279, 313), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['A', 'A_true'], {}), '(A, A_true)\n', (302, 313), True, 'import numpy as np\n'), ((390, 421), 'sympy.init_printing', 'init_printing', ([], {'use_unicode': '(True)'}), '(use_unicode=True)\n', (403, 421), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((432, 444), 'sympy.symbols', 'symbols', (['"""x"""'], {}), "('x')\n", (439, 444), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((510, 522), 'sympy.diff', 'diff', (['f_1', 'x'], {}), '(f_1, x)\n', (514, 522), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((608, 620), 'sympy.diff', 'diff', (['f_2', 'x'], {}), '(f_2, x)\n', (612, 620), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((669, 686), 'sympy.exp', 'exp', (['((x + 1) ** 2)'], {}), '((x + 1) ** 2)\n', (672, 686), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((701, 713), 'sympy.diff', 'diff', (['f_3', 'x'], {}), '(f_3, x)\n', (705, 713), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((799, 811), 'sympy.diff', 'diff', (['f_4', 'x'], {}), '(f_4, x)\n', (803, 811), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1142, 1173), 'sympy.init_printing', 'init_printing', ([], {'use_unicode': '(True)'}), '(use_unicode=True)\n', (1155, 1173), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1190, 1206), 'sympy.symbols', 'symbols', (['"""x y z"""'], {}), "('x y z')\n", (1197, 1206), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1522, 1532), 'sympy.exp', 'exp', (['(x + y)'], {}), '(x + y)\n', (1525, 1532), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((3229, 3268), 'pandas.read_csv', 'pd.read_csv', (['"""./dataset/Xy_dataset.csv"""'], {}), "('./dataset/Xy_dataset.csv')\n", (3240, 3268), True, 'import pandas as pd\n'), ((3278, 3297), 'numpy.array', 'np.array', (["data['X']"], {}), "(data['X'])\n", (3286, 3297), True, 'import numpy as np\n'), ((3307, 3326), 'numpy.array', 'np.array', (["data['y']"], {}), "(data['y'])\n", (3315, 3326), True, 'import numpy as np\n'), ((3868, 3902), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['m', 'm_true'], {}), '(m, m_true)\n', (3891, 3902), True, 'import numpy as np\n'), ((3907, 3941), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['b', 'b_true'], {}), '(b, b_true)\n', (3930, 3941), True, 'import numpy as np\n'), ((4470, 4504), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['m', 'm_true'], {}), '(m, m_true)\n', (4493, 4504), True, 'import numpy as np\n'), ((4509, 4543), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['b', 'b_true'], {}), '(b, b_true)\n', (4532, 4543), True, 'import numpy as np\n'), ((5070, 5104), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['m', 'm_true'], {}), '(m, m_true)\n', (5093, 5104), True, 'import numpy as np\n'), ((5109, 5143), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['b', 'b_true'], {}), '(b, b_true)\n', (5132, 5143), True, 'import numpy as np\n'), ((5673, 5707), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['m', 'm_true'], {}), '(m, m_true)\n', (5696, 5707), True, 'import numpy as np\n'), ((5712, 5746), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['b', 'b_true'], {}), '(b, b_true)\n', (5735, 5746), True, 'import numpy as np\n'), ((488, 495), 'sympy.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (492, 495), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((575, 581), 'sympy.sin', 'sin', (['x'], {}), '(x)\n', (578, 581), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1268, 1280), 'sympy.diff', 'diff', (['f_1', 'x'], {}), '(f_1, x)\n', (1272, 1280), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1281, 1293), 'sympy.diff', 'diff', (['f_1', 'y'], {}), '(f_1, y)\n', (1285, 1293), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1294, 1306), 'sympy.diff', 'diff', (['f_1', 'z'], {}), '(f_1, z)\n', (1298, 1306), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1545, 1555), 'sympy.diff', 'diff', (['u', 'x'], {}), '(u, x)\n', (1549, 1555), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1556, 1566), 'sympy.diff', 'diff', (['u', 'y'], {}), '(u, y)\n', (1560, 1566), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1579, 1589), 'sympy.diff', 'diff', (['v', 'x'], {}), '(v, x)\n', (1583, 1589), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1590, 1600), 'sympy.diff', 'diff', (['v', 'y'], {}), '(v, y)\n', (1594, 1600), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((3726, 3751), 'numpy.mean', 'np.mean', (['((y_pred - y) * X)'], {}), '((y_pred - y) * X)\n', (3733, 3751), True, 'import numpy as np\n'), ((3766, 3785), 'numpy.mean', 'np.mean', (['(y_pred - y)'], {}), '(y_pred - y)\n', (3773, 3785), True, 'import numpy as np\n'), ((4328, 4353), 'numpy.mean', 'np.mean', (['((y_pred - y) * X)'], {}), '((y_pred - y) * X)\n', (4335, 4353), True, 'import numpy as np\n'), ((4368, 4387), 'numpy.mean', 'np.mean', (['(y_pred - y)'], {}), '(y_pred - y)\n', (4375, 4387), True, 'import numpy as np\n'), ((4928, 4953), 'numpy.mean', 'np.mean', (['((y_pred - y) * X)'], {}), '((y_pred - y) * X)\n', (4935, 4953), True, 'import numpy as np\n'), ((4968, 4987), 'numpy.mean', 'np.mean', (['(y_pred - y)'], {}), '(y_pred - y)\n', (4975, 4987), True, 'import numpy as np\n'), ((5531, 5556), 'numpy.mean', 'np.mean', (['((y_pred - y) * X)'], {}), '((y_pred - y) * X)\n', (5538, 5556), True, 'import numpy as np\n'), ((5571, 5590), 'numpy.mean', 'np.mean', (['(y_pred - y)'], {}), '(y_pred - y)\n', (5578, 5590), True, 'import numpy as np\n'), ((586, 592), 'sympy.cos', 'cos', (['x'], {}), '(x)\n', (589, 592), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((772, 778), 'sympy.cos', 'cos', (['x'], {}), '(x)\n', (775, 778), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1233, 1239), 'sympy.cos', 'cos', (['y'], {}), '(y)\n', (1236, 1239), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1242, 1248), 'sympy.exp', 'exp', (['z'], {}), '(z)\n', (1245, 1248), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1249, 1255), 'sympy.sin', 'sin', (['y'], {}), '(y)\n', (1252, 1255), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1497, 1503), 'sympy.cos', 'cos', (['x'], {}), '(x)\n', (1500, 1503), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1506, 1512), 'sympy.sin', 'sin', (['y'], {}), '(y)\n', (1509, 1512), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1840, 1846), 'sympy.cos', 'cos', (['y'], {}), '(y)\n', (1843, 1846), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1853, 1859), 'sympy.sin', 'sin', (['y'], {}), '(y)\n', (1856, 1859), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2175, 2181), 'sympy.cos', 'cos', (['z'], {}), '(z)\n', (2178, 2181), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1878, 1890), 'sympy.diff', 'diff', (['f_3', 'x'], {}), '(f_3, x)\n', (1882, 1890), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1899, 1911), 'sympy.diff', 'diff', (['f_3', 'x'], {}), '(f_3, x)\n', (1903, 1911), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1934, 1946), 'sympy.diff', 'diff', (['f_3', 'y'], {}), '(f_3, y)\n', (1938, 1946), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((1955, 1967), 'sympy.diff', 'diff', (['f_3', 'y'], {}), '(f_3, y)\n', (1959, 1967), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2184, 2190), 'sympy.sin', 'sin', (['x'], {}), '(x)\n', (2187, 2190), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2193, 2199), 'sympy.exp', 'exp', (['y'], {}), '(y)\n', (2196, 2199), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2225, 2237), 'sympy.diff', 'diff', (['f_4', 'x'], {}), '(f_4, x)\n', (2229, 2237), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2246, 2258), 'sympy.diff', 'diff', (['f_4', 'x'], {}), '(f_4, x)\n', (2250, 2258), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2267, 2279), 'sympy.diff', 'diff', (['f_4', 'x'], {}), '(f_4, x)\n', (2271, 2279), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2302, 2314), 'sympy.diff', 'diff', (['f_4', 'y'], {}), '(f_4, y)\n', (2306, 2314), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2323, 2335), 'sympy.diff', 'diff', (['f_4', 'y'], {}), '(f_4, y)\n', (2327, 2335), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2344, 2356), 'sympy.diff', 'diff', (['f_4', 'y'], {}), '(f_4, y)\n', (2348, 2356), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2379, 2391), 'sympy.diff', 'diff', (['f_4', 'z'], {}), '(f_4, z)\n', (2383, 2391), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2400, 2412), 'sympy.diff', 'diff', (['f_4', 'z'], {}), '(f_4, z)\n', (2404, 2412), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n'), ((2421, 2433), 'sympy.diff', 'diff', (['f_4', 'z'], {}), '(f_4, z)\n', (2425, 2433), False, 'from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp\n')]
"""Validation function""" import time import logging import numpy as np import torch from torch import nn from helpers.miou_utils import compute_iu, compute_ius_accs, fast_cm from helpers.utils import ctime, try_except import pdb import matplotlib.pyplot as plt logger = logging.getLogger(__name__) import pylab cmap = np.load('./utils/cmap.npy') @try_except def validate(segmenter, val_loader, epoch, epoch2, num_classes=-1, print_every=10): """Validate segmenter Args: segmenter (nn.Module) : segmentation network val_loader (DataLoader) : training data iterator epoch (int) : current search epoch epoch2 (int) : current segm. training epoch num_classes (int) : number of segmentation classes print_every (int) : how often to print out information Returns: Reward (float) """ try: val_loader.dataset.set_stage('val') except AttributeError: val_loader.dataset.dataset.set_stage('val') # for subset segmenter.eval() cm = np.zeros((num_classes, num_classes), dtype=int) idx=1 with torch.no_grad(): for i, sample in enumerate(val_loader): image = sample['image'] target = sample['mask'] #plt.imshow(target) #plt.show() input_var = torch.autograd.Variable(image).float().cuda() # Compute output # output, _ = segmenter(input_var) output = segmenter(input_var) output = nn.Upsample(size=target.size()[1:], mode='bilinear', align_corners=False)(output) # Compute IoU output = output.data.cpu().numpy().argmax(axis=1).astype(np.uint8) gt = target.data.cpu().numpy().astype(np.uint8) # for i in range(4): # output_cmap=cmap[output[i]] # gt_cmap = cmap[gt[i]] # plt.subplot(4, 2, idx) # plt.imshow(output_cmap) # idx+=1 # plt.subplot(4, 2, idx) # plt.imshow(gt_cmap) # idx+=1 # plt.show() # Ignore every class index larger than the number of classes gt_idx = gt < num_classes cm += fast_cm(output[gt_idx], gt[gt_idx], num_classes) if i % print_every == 0: logger.info(' [{}] Val epoch: {} [{}/{}]\t' 'Mean IoU: {:.3f}'.format( ctime(), epoch, i, len(val_loader), compute_iu(cm).mean() )) ious, n_pixels, accs = compute_ius_accs(cm) logger.info(" IoUs: {}, accs: {}".format(ious, accs)) # IoU by default is 1, so we ignore all the unchanged classes # +1 - since we ignore background present_ind = np.array( [idx + 1 for idx, iu in enumerate(ious[1:]) if iu != 1.]) present_ious = ious[present_ind] present_pixels = n_pixels[present_ind] miou = np.mean(present_ious) macc = np.mean(accs[present_ind]) mfwiou = np.sum(present_ious * present_pixels) / np.sum(present_pixels) metrics = [miou, macc, mfwiou] reward = np.prod(metrics) ** (1. / len(metrics)) info = (' [{}] Val epoch: {}/{}\tMean IoU: {:.3f}\tMean FW-IoU: {:.3f}\t' 'Mean Acc: {:.3f}\tReward: {:.3f}').format( ctime(), epoch, epoch2, miou, mfwiou, macc, reward) logger.info(info) # if(reward > 0.2): # # for i in range(4): # output_cmap=cmap[output[i]] # gt_cmap = cmap[gt[i]] # plt.subplot(4, 2, idx) # plt.imshow(output_cmap) # #pylab.rcParams['figure.figsize'] = (8.0, 10.0) # # idx+=1 # plt.subplot(4, 2, idx) # plt.imshow(gt_cmap) # #pylab.rcParams['figure.figsize'] = (8.0, 10.0) # idx+=1 # plt.show() # if (reward>0): # fig, axes = plt.subplots(4, 2, figsize=(10, 10)) # ax= axes.ravel() # for i in range(4): #sample 4 image to show # output_cmap=cmap[output[i]] # gt_cmap = cmap[gt[i]] # ax[i*2].imshow(output_cmap) # ax[i*2].set_title("ouput image") # ax[i*2+1].imshow(gt_cmap) # ax[i*2+1].set_title("gt image") return miou #reward #, miou
[ "logging.getLogger", "numpy.mean", "numpy.prod", "torch.autograd.Variable", "helpers.utils.ctime", "helpers.miou_utils.compute_iu", "numpy.sum", "numpy.zeros", "helpers.miou_utils.compute_ius_accs", "torch.no_grad", "numpy.load", "helpers.miou_utils.fast_cm" ]
[((274, 301), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (291, 301), False, 'import logging\n'), ((324, 351), 'numpy.load', 'np.load', (['"""./utils/cmap.npy"""'], {}), "('./utils/cmap.npy')\n", (331, 351), True, 'import numpy as np\n'), ((1022, 1069), 'numpy.zeros', 'np.zeros', (['(num_classes, num_classes)'], {'dtype': 'int'}), '((num_classes, num_classes), dtype=int)\n', (1030, 1069), True, 'import numpy as np\n'), ((2670, 2690), 'helpers.miou_utils.compute_ius_accs', 'compute_ius_accs', (['cm'], {}), '(cm)\n', (2686, 2690), False, 'from helpers.miou_utils import compute_iu, compute_ius_accs, fast_cm\n'), ((3038, 3059), 'numpy.mean', 'np.mean', (['present_ious'], {}), '(present_ious)\n', (3045, 3059), True, 'import numpy as np\n'), ((3071, 3097), 'numpy.mean', 'np.mean', (['accs[present_ind]'], {}), '(accs[present_ind])\n', (3078, 3097), True, 'import numpy as np\n'), ((1089, 1104), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1102, 1104), False, 'import torch\n'), ((3111, 3148), 'numpy.sum', 'np.sum', (['(present_ious * present_pixels)'], {}), '(present_ious * present_pixels)\n', (3117, 3148), True, 'import numpy as np\n'), ((3151, 3173), 'numpy.sum', 'np.sum', (['present_pixels'], {}), '(present_pixels)\n', (3157, 3173), True, 'import numpy as np\n'), ((3222, 3238), 'numpy.prod', 'np.prod', (['metrics'], {}), '(metrics)\n', (3229, 3238), True, 'import numpy as np\n'), ((3412, 3419), 'helpers.utils.ctime', 'ctime', ([], {}), '()\n', (3417, 3419), False, 'from helpers.utils import ctime, try_except\n'), ((2256, 2304), 'helpers.miou_utils.fast_cm', 'fast_cm', (['output[gt_idx]', 'gt[gt_idx]', 'num_classes'], {}), '(output[gt_idx], gt[gt_idx], num_classes)\n', (2263, 2304), False, 'from helpers.miou_utils import compute_iu, compute_ius_accs, fast_cm\n'), ((2490, 2497), 'helpers.utils.ctime', 'ctime', ([], {}), '()\n', (2495, 2497), False, 'from helpers.utils import ctime, try_except\n'), ((1306, 1336), 'torch.autograd.Variable', 'torch.autograd.Variable', (['image'], {}), '(image)\n', (1329, 1336), False, 'import torch\n'), ((2590, 2604), 'helpers.miou_utils.compute_iu', 'compute_iu', (['cm'], {}), '(cm)\n', (2600, 2604), False, 'from helpers.miou_utils import compute_iu, compute_ius_accs, fast_cm\n')]
# tests/test_rms.py import numpy as np from kallisto.rmsd import rmsd from tests.store import propanolIntermediate, propanolLowest def test_rms(): mol1 = propanolLowest() nat1 = mol1.get_number_of_atoms() coord1 = mol1.get_positions() mol2 = propanolIntermediate() coord2 = mol2.get_positions() _, u = rmsd(nat1, coord1, coord2) assert np.isclose(u[0, 0], 0.98139458) assert np.isclose(u[0, 1], -0.04965545) assert np.isclose(u[0, 2], -0.18546973) assert np.isclose(u[1, 0], 0.06170977) assert np.isclose(u[1, 1], 0.9963015) assert np.isclose(u[1, 2], 0.05979323) assert np.isclose(u[2, 0], 0.18181471) assert np.isclose(u[2, 1], -0.07012604) assert np.isclose(u[2, 2], 0.98082911)
[ "tests.store.propanolLowest", "numpy.isclose", "tests.store.propanolIntermediate", "kallisto.rmsd.rmsd" ]
[((162, 178), 'tests.store.propanolLowest', 'propanolLowest', ([], {}), '()\n', (176, 178), False, 'from tests.store import propanolIntermediate, propanolLowest\n'), ((262, 284), 'tests.store.propanolIntermediate', 'propanolIntermediate', ([], {}), '()\n', (282, 284), False, 'from tests.store import propanolIntermediate, propanolLowest\n'), ((330, 356), 'kallisto.rmsd.rmsd', 'rmsd', (['nat1', 'coord1', 'coord2'], {}), '(nat1, coord1, coord2)\n', (334, 356), False, 'from kallisto.rmsd import rmsd\n'), ((368, 399), 'numpy.isclose', 'np.isclose', (['u[0, 0]', '(0.98139458)'], {}), '(u[0, 0], 0.98139458)\n', (378, 399), True, 'import numpy as np\n'), ((411, 443), 'numpy.isclose', 'np.isclose', (['u[0, 1]', '(-0.04965545)'], {}), '(u[0, 1], -0.04965545)\n', (421, 443), True, 'import numpy as np\n'), ((455, 487), 'numpy.isclose', 'np.isclose', (['u[0, 2]', '(-0.18546973)'], {}), '(u[0, 2], -0.18546973)\n', (465, 487), True, 'import numpy as np\n'), ((499, 530), 'numpy.isclose', 'np.isclose', (['u[1, 0]', '(0.06170977)'], {}), '(u[1, 0], 0.06170977)\n', (509, 530), True, 'import numpy as np\n'), ((542, 572), 'numpy.isclose', 'np.isclose', (['u[1, 1]', '(0.9963015)'], {}), '(u[1, 1], 0.9963015)\n', (552, 572), True, 'import numpy as np\n'), ((584, 615), 'numpy.isclose', 'np.isclose', (['u[1, 2]', '(0.05979323)'], {}), '(u[1, 2], 0.05979323)\n', (594, 615), True, 'import numpy as np\n'), ((627, 658), 'numpy.isclose', 'np.isclose', (['u[2, 0]', '(0.18181471)'], {}), '(u[2, 0], 0.18181471)\n', (637, 658), True, 'import numpy as np\n'), ((670, 702), 'numpy.isclose', 'np.isclose', (['u[2, 1]', '(-0.07012604)'], {}), '(u[2, 1], -0.07012604)\n', (680, 702), True, 'import numpy as np\n'), ((714, 745), 'numpy.isclose', 'np.isclose', (['u[2, 2]', '(0.98082911)'], {}), '(u[2, 2], 0.98082911)\n', (724, 745), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Random forest modeling for radiomics feature selection and for classification of high-risk histopathological markers of endometrial carcinoma Not for clinical use. SPDX-FileCopyrightText: 2021 Medical Physics Unit, McGill University, Montreal, CAN SPDX-FileCopyrightText: 2021 <NAME> SPDX-FileCopyrightText: 2021 <NAME> SPDX-License-Identifier: MIT """ # import required packages import h5py from sklearn.metrics import confusion_matrix, auc, plot_roc_curve, roc_auc_score,roc_curve,recall_score,precision_score import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier import seaborn as sns from imblearn.pipeline import Pipeline from imblearn.under_sampling import RandomUnderSampler from sklearn.model_selection import StratifiedKFold, RepeatedStratifiedKFold from scipy import interp from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict from scipy.stats import zscore, t from scipy.stats import spearmanr from scipy.cluster import hierarchy from collections import defaultdict # filter all the warnings import warnings warnings.filterwarnings('ignore') # import labels h5f_label = h5py.File('MYPROJECTFILEPATH/OUTPUT/label.h5', 'r') global_labels_string = h5f_label['dataset_1'] global_labels = np.array(global_labels_string) h5f_label.close() # import radiomics features global_features = pd.read_csv('MYPROJECTFILEPATH/OUTPUT/coeff.csv') # Saving feature names for later use feature_list = list(global_features.columns) global_features = global_features.apply(zscore) # zscore normalize features global_featuresInit = np.array(global_features.values) global_features = np.array(global_features.values) # import validation/testing labels h5f_labelval = h5py.File('MYPROJECTFILEPATH/OUTPUT/labelVal.h5', 'r') global_labels_stringval = h5f_labelval['dataset_1'] validation_labels = np.array(global_labels_stringval) h5f_labelval.close() # import validation/testing radiomics features validation_features = pd.read_csv('MYPROJECTFILEPATH/OUTPUT/coeffVal.csv') validation_features = validation_features.apply(zscore) # zscore normalize features validation_featuresInit = np.array(validation_features.values) validation_features = np.array(validation_features.values) # Verify the shape of the radiomics features matrix and labels print("features shape: {}".format(global_features.shape)) print("labels shape: {}".format(global_labels.shape)) ### REMOVE CORRELATED FEATURES ### X = global_features # Handling multi-collinear features corr = spearmanr(X).correlation corr_linkage = hierarchy.ward(corr) # Clusters with spearman's rho > 0.95 cluster_ids = hierarchy.fcluster(corr_linkage, 0.95, criterion='distance') cluster_id_to_feature_ids = defaultdict(list) for idx, cluster_id in enumerate(cluster_ids): cluster_id_to_feature_ids[cluster_id].append(idx) # Keep only one features per cluster selected_features = [v[0] for v in cluster_id_to_feature_ids.values()] # Select uncorrelated features global_features = global_features[:,selected_features] validation_features = validation_features[:,selected_features] feature_list = np.array(feature_list) feature_list = feature_list[selected_features] ### MACHINE LEARNING MODELING (RANDOM FORESTS) ### # Generate random seed seed = np.random.randint(1,50) # THESE HYPERPARAMETERS ARE SELECTED WITH LimitRandomForestHyperparameters6.py # Insert optimized random forest hyperparameters num_trees = 30 tree_depth = 5 max_split = 'sqrt' # Instantiate machine learning models models = [] models.append(('RF', RandomForestClassifier(n_estimators=num_trees,max_depth=tree_depth,max_features = max_split,random_state=seed))) # Variables to hold the results and names results = [] names = [] scoring = "roc_auc" ### IDENTIFY MOST IMPORTANT FEATURES ### # Store Gini impurity-based feature importance importancesList = [] # Resample majority class resample = RandomUnderSampler(sampling_strategy=0.75) # Confidence for intervals confidence = 0.95 # Bootstraps number bootnum = 1000 # k-fold cross validation for name, model in models: cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=bootnum) pipeline = Pipeline(steps=[('r',resample),('m',model)]) cv_results = cross_val_score(pipeline, global_features, global_labels, cv=cv, scoring=scoring) results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print(msg) if 'RF' in name: # Bootstrap starts here (# is the # of bootstraps) for kk in range(bootnum): cvoth = StratifiedKFold(n_splits=5, shuffle=True,random_state=seed+kk) for i, (train, test) in enumerate(cvoth.split(global_features, global_labels)): model.fit(global_features[train], global_labels[train]) if kk ==0: importancesList = np.array(model.feature_importances_) elif kk>0: importancesList = np.vstack((importancesList,np.array(model.feature_importances_))) model.fit(global_features, global_labels) # Get predictions and probabilities on the training dataset y_pred = cross_val_predict(pipeline, global_features, global_labels, cv=5) y_proba = cross_val_predict(model, global_features, global_labels, method='predict_proba',cv=5)[:, 1] # Validation probabilities and predictions y_predVal = model.predict(validation_features) y_probaVal =model.predict_proba(validation_features)[:, 1] # Get feature importances on the whole training dataset importancesList = np.vstack((importancesList,np.array(model.feature_importances_))) # Importances across CV bootstrapped samples stdstd = np.std(importancesList, axis=0) meanmean = np.mean(importancesList, axis=0) indicesAll = np.argsort(meanmean)[::-1] indices = indicesAll[0:20] feature_list = np.array(feature_list) # Plot the impurity-based feature importances of the random forest plt.figure() plt.ylabel('Importance'); plt.xlabel('Feature'); plt.title('Feature Importances');plt.bar(range(20), meanmean[indices],color="r", yerr=stdstd[indices]) plt.xticks(range(20), feature_list[indices],rotation=50,horizontalalignment='right') plt.rcParams["font.family"] = "sans-serif" plt.rcParams["font.sans-serif"]="Arial" plt.rcParams['font.size'] = 13 sns.despine(right = True) plt.show() ### TRAIN THE RANDOM FOREST WITH THE MOST IMPORTANT FEATURES # Most important feature names feat_list =np.array(feature_list) feat_list = feat_list[indicesAll] feature_list = list(feature_list) # Extract the 5 most important features important_indices = [feature_list.index(feat_list[0]), feature_list.index(feat_list[1]),feature_list.index(feat_list[2]), feature_list.index(feat_list[3]), feature_list.index(feat_list[4])] glob_feat_imp = global_features[:, important_indices] validation_feat_imp = validation_features[:, important_indices] # Print important features print(feat_list[0:5]) models1 = [] models1.append(('RF', RandomForestClassifier(n_estimators=num_trees,max_depth=tree_depth,max_features = max_split,random_state=seed))) results1 = [] names1=[] # k-fold cross validation for name, model in models1: cv = RepeatedStratifiedKFold(n_splits=5, n_repeats = bootnum) pipeline1 = Pipeline(steps=[('r',resample),('m',model)]) cv_results = cross_val_score(pipeline1, glob_feat_imp, global_labels, cv=cv, scoring=scoring) results1.append(cv_results) names1.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print(msg) if 'RF' in name: # Run classifier with cross-validation and plot ROC curves meanmean_aucs = [] meanmean_tprs = [] fig, ax = plt.subplots(figsize = (8, 8)) fig1, ax1 = plt.subplots() # Bootstrap for kk in range(bootnum): cvoth = StratifiedKFold(n_splits=5, shuffle=True,random_state=seed+kk) tprs = [] aucs = [] mean_fpr = np.linspace(0, 1, 100) for i, (train, test) in enumerate(cvoth.split(glob_feat_imp, global_labels)): model.fit(glob_feat_imp[train], global_labels[train]) viz = [] viz = plot_roc_curve(model, glob_feat_imp[test], global_labels[test], name='ROC fold {}'.format(i), alpha=0.3, lw=1, ax=ax1) ax1.get_legend().remove() interp_tpr = interp(mean_fpr, viz.fpr, viz.tpr) interp_tpr[0] = 0.0 tprs.append(interp_tpr) aucs.append(viz.roc_auc) interp_tpr = interp(mean_fpr, viz.fpr, viz.tpr) interp_tpr[0] = 0.0 tprs.append(interp_tpr) aucs.append(viz.roc_auc) mean_tpr = np.mean(tprs, axis=0) mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) if kk==0: meanmean_tprs = np.array(mean_tpr) else: meanmean_tprs = np.vstack([meanmean_tprs,mean_tpr]) meanmean_aucs.append(aucs) ax.plot([0, 1], [0, 1], linestyle='--', lw=2, color='b', label=None, alpha=.8) mean_tpr = np.mean(meanmean_tprs, axis=0) mean_auc = auc(mean_fpr, np.mean(meanmean_tprs, axis=0)) youdensi=(mean_tpr-mean_fpr) idxYi = np.argmax(youdensi) sensYi = mean_tpr[idxYi] specYi = 1-mean_fpr[idxYi] means_sens_Yi = meanmean_tprs[:,idxYi] std_sens = np.std(means_sens_Yi) n_sens=len(means_sens_Yi) h_sens = std_sens * t.ppf((1 + confidence) / 2, n_sens - 1) start_sens = sensYi - h_sens enfin_sens = sensYi + h_sens if enfin_sens > 1: enfin_sens = 1 print('sens') print(start_sens, sensYi, enfin_sens) print('spec') print(specYi-h_sens, specYi, specYi+h_sens) bal_acc = (mean_tpr+np.ones_like(mean_tpr)-mean_fpr)/2 idxMax = np.argmax(bal_acc) std_acc = np.std(bal_acc) n_acc=len(bal_acc) h_acc = std_acc * t.ppf((1 + confidence) / 2, n_acc - 1) start_acc = bal_acc[idxMax] - h_acc enfin_acc =bal_acc[idxMax]+ h_acc if enfin_acc > 1: enfin_acc = 1 print('balanced accuracy') print(start_acc, bal_acc[idxMax], enfin_acc) prev=np.count_nonzero(global_labels)/len(global_labels) PPV = means_sens_Yi*prev/(means_sens_Yi*prev+((1-specYi)*(1-prev))) std_PPV = np.std(PPV) n_PPV=len(PPV) h_PPV= std_PPV* t.ppf((1 + confidence) / 2, n_PPV- 1) start_PPV= np.mean(PPV) - h_PPV enfin_PPV= np.mean(PPV)+ h_PPV if enfin_PPV> 1: enfin_PPV= 1 print('PPV') print(start_PPV, np.mean(PPV), enfin_PPV) NPV = specYi*(1-prev)/((np.ones_like(means_sens_Yi)-means_sens_Yi)*prev+(specYi*(1-prev))) std_NPV = np.std(NPV) n_NPV=len(NPV) h_NPV= std_NPV* t.ppf((1 + confidence) / 2, n_NPV- 1) start_NPV= np.mean(NPV) - h_NPV enfin_NPV= np.mean(NPV)+ h_NPV if enfin_NPV> 1: enfin_NPV= 1 print('NPV') print(start_NPV, np.mean(NPV), enfin_NPV) std_auc = np.std(meanmean_aucs) n=len(meanmean_aucs) h = std_auc * t.ppf((1 + confidence) / 2, n - 1) start = mean_auc - h enfin = mean_auc + h if enfin > 1: enfin=1 print('auc') print(start,mean_auc,enfin) ax.plot(mean_fpr, mean_tpr, color='r', lw=2, alpha=.8) std_tpr = np.std(tprs, axis=0) tprs_upper = np.minimum(mean_tpr + std_tpr, 1) tprs_lower = np.maximum(mean_tpr - std_tpr, 0) ax.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2, label=r'$\pm$ 1 std. dev.') ax.set(xlim=[-0.01, 1.01], ylim=[-0.01, 1.01],title=r'ROC Curve, AUC = %0.2f (%0.2f, %0.2f)' % (mean_auc, start, enfin)) ax.set_aspect('equal', adjustable='box') sns.despine(fig=fig, ax=ax,right = True) ax.set_xlabel('False Positive Rate',fontfamily='sans-serif',fontsize=16) ax.set_ylabel('True Positive Rate',fontfamily='sans-serif',fontsize=16) plt.rcParams["font.family"] = "sans-serif" plt.rcParams['font.size'] = 16 plt.show() model.fit(glob_feat_imp, global_labels) # Get predictions and probabilities on the training dataset y_pred1 = cross_val_predict(pipeline1, glob_feat_imp, global_labels, cv=5) y_proba1 = cross_val_predict(pipeline1, glob_feat_imp, global_labels,method='predict_proba',cv=5)[:, 1] # Validation probabilities and predictions y_predVal1 = model.predict(validation_feat_imp) y_probaVal1 =model.predict_proba(validation_feat_imp)[:, 1] def evaluate_model1(predictions, probs, testLabel):#, train_predictions, train_probs): baseline = {} baseline['recall'] = recall_score(testLabel, [1 for _ in range(len(testLabel))]) baseline['precision'] = precision_score(testLabel, [1 for _ in range(len(testLabel))]) baseline['roc'] = 0.5 results = {} results['recall'] = recall_score(testLabel, predictions) results['precision'] = precision_score(testLabel, predictions) results['roc'] = roc_auc_score(testLabel, probs,average='samples') base_fpr, base_tpr, _ = roc_curve(testLabel, [1 for _ in range(len(testLabel))]) model_fpr, model_tpr, _ = roc_curve(testLabel, probs) fig12=[] ax12=[] fig12, ax12 = plt.subplots(figsize = (8, 8)) plt.plot(base_fpr, base_tpr, 'b--')#, label = 'baseline') plt.plot(model_fpr, model_tpr, 'r')#, label = 'model') plt.title('ROC Curve, AUC = '+str(results['roc'])[0:4]); ax12.set(xlim=[-0.01, 1.01], ylim=[-0.01, 1.01]) ax12.set_aspect('equal', adjustable='box') sns.despine(fig=fig12, ax=ax12,right = True) ax12.set_xlabel('False Positive Rate',fontfamily='sans-serif',fontsize=16) ax12.set_ylabel('True Positive Rate',fontfamily='sans-serif',fontsize=16) plt.rcParams["font.family"] = "sans-serif" plt.rcParams['font.size'] = 16 plt.show() #evaluate ROC curve of validation with most important features evaluate_model1(y_predVal1, y_probaVal1, validation_labels)
[ "pandas.read_csv", "matplotlib.pyplot.ylabel", "sklearn.metrics.auc", "sklearn.metrics.precision_score", "numpy.argsort", "numpy.array", "sklearn.metrics.recall_score", "sklearn.metrics.roc_auc_score", "sklearn.metrics.roc_curve", "sklearn.model_selection.StratifiedKFold", "numpy.count_nonzero",...
[((1190, 1223), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1213, 1223), False, 'import warnings\n'), ((1256, 1307), 'h5py.File', 'h5py.File', (['"""MYPROJECTFILEPATH/OUTPUT/label.h5"""', '"""r"""'], {}), "('MYPROJECTFILEPATH/OUTPUT/label.h5', 'r')\n", (1265, 1307), False, 'import h5py\n'), ((1372, 1402), 'numpy.array', 'np.array', (['global_labels_string'], {}), '(global_labels_string)\n', (1380, 1402), True, 'import numpy as np\n'), ((1472, 1521), 'pandas.read_csv', 'pd.read_csv', (['"""MYPROJECTFILEPATH/OUTPUT/coeff.csv"""'], {}), "('MYPROJECTFILEPATH/OUTPUT/coeff.csv')\n", (1483, 1521), True, 'import pandas as pd\n'), ((1706, 1738), 'numpy.array', 'np.array', (['global_features.values'], {}), '(global_features.values)\n', (1714, 1738), True, 'import numpy as np\n'), ((1758, 1790), 'numpy.array', 'np.array', (['global_features.values'], {}), '(global_features.values)\n', (1766, 1790), True, 'import numpy as np\n'), ((1847, 1901), 'h5py.File', 'h5py.File', (['"""MYPROJECTFILEPATH/OUTPUT/labelVal.h5"""', '"""r"""'], {}), "('MYPROJECTFILEPATH/OUTPUT/labelVal.h5', 'r')\n", (1856, 1901), False, 'import h5py\n'), ((1976, 2009), 'numpy.array', 'np.array', (['global_labels_stringval'], {}), '(global_labels_stringval)\n', (1984, 2009), True, 'import numpy as np\n'), ((2105, 2157), 'pandas.read_csv', 'pd.read_csv', (['"""MYPROJECTFILEPATH/OUTPUT/coeffVal.csv"""'], {}), "('MYPROJECTFILEPATH/OUTPUT/coeffVal.csv')\n", (2116, 2157), True, 'import pandas as pd\n'), ((2270, 2306), 'numpy.array', 'np.array', (['validation_features.values'], {}), '(validation_features.values)\n', (2278, 2306), True, 'import numpy as np\n'), ((2330, 2366), 'numpy.array', 'np.array', (['validation_features.values'], {}), '(validation_features.values)\n', (2338, 2366), True, 'import numpy as np\n'), ((2698, 2718), 'scipy.cluster.hierarchy.ward', 'hierarchy.ward', (['corr'], {}), '(corr)\n', (2712, 2718), False, 'from scipy.cluster import hierarchy\n'), ((2775, 2835), 'scipy.cluster.hierarchy.fcluster', 'hierarchy.fcluster', (['corr_linkage', '(0.95)'], {'criterion': '"""distance"""'}), "(corr_linkage, 0.95, criterion='distance')\n", (2793, 2835), False, 'from scipy.cluster import hierarchy\n'), ((2865, 2882), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2876, 2882), False, 'from collections import defaultdict\n'), ((3269, 3291), 'numpy.array', 'np.array', (['feature_list'], {}), '(feature_list)\n', (3277, 3291), True, 'import numpy as np\n'), ((3430, 3454), 'numpy.random.randint', 'np.random.randint', (['(1)', '(50)'], {}), '(1, 50)\n', (3447, 3454), True, 'import numpy as np\n'), ((4076, 4118), 'imblearn.under_sampling.RandomUnderSampler', 'RandomUnderSampler', ([], {'sampling_strategy': '(0.75)'}), '(sampling_strategy=0.75)\n', (4094, 4118), False, 'from imblearn.under_sampling import RandomUnderSampler\n'), ((6014, 6045), 'numpy.std', 'np.std', (['importancesList'], {'axis': '(0)'}), '(importancesList, axis=0)\n', (6020, 6045), True, 'import numpy as np\n'), ((6058, 6090), 'numpy.mean', 'np.mean', (['importancesList'], {'axis': '(0)'}), '(importancesList, axis=0)\n', (6065, 6090), True, 'import numpy as np\n'), ((6178, 6200), 'numpy.array', 'np.array', (['feature_list'], {}), '(feature_list)\n', (6186, 6200), True, 'import numpy as np\n'), ((6272, 6284), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6282, 6284), True, 'import matplotlib.pyplot as plt\n'), ((6286, 6310), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Importance"""'], {}), "('Importance')\n", (6296, 6310), True, 'import matplotlib.pyplot as plt\n'), ((6312, 6333), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Feature"""'], {}), "('Feature')\n", (6322, 6333), True, 'import matplotlib.pyplot as plt\n'), ((6335, 6367), 'matplotlib.pyplot.title', 'plt.title', (['"""Feature Importances"""'], {}), "('Feature Importances')\n", (6344, 6367), True, 'import matplotlib.pyplot as plt\n'), ((6642, 6665), 'seaborn.despine', 'sns.despine', ([], {'right': '(True)'}), '(right=True)\n', (6653, 6665), True, 'import seaborn as sns\n'), ((6669, 6679), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6677, 6679), True, 'import matplotlib.pyplot as plt\n'), ((6790, 6812), 'numpy.array', 'np.array', (['feature_list'], {}), '(feature_list)\n', (6798, 6812), True, 'import numpy as np\n'), ((2657, 2669), 'scipy.stats.spearmanr', 'spearmanr', (['X'], {}), '(X)\n', (2666, 2669), False, 'from scipy.stats import spearmanr\n'), ((4274, 4328), 'sklearn.model_selection.RepeatedStratifiedKFold', 'RepeatedStratifiedKFold', ([], {'n_splits': '(5)', 'n_repeats': 'bootnum'}), '(n_splits=5, n_repeats=bootnum)\n', (4297, 4328), False, 'from sklearn.model_selection import StratifiedKFold, RepeatedStratifiedKFold\n'), ((4345, 4392), 'imblearn.pipeline.Pipeline', 'Pipeline', ([], {'steps': "[('r', resample), ('m', model)]"}), "(steps=[('r', resample), ('m', model)])\n", (4353, 4392), False, 'from imblearn.pipeline import Pipeline\n'), ((4412, 4498), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['pipeline', 'global_features', 'global_labels'], {'cv': 'cv', 'scoring': 'scoring'}), '(pipeline, global_features, global_labels, cv=cv, scoring=\n scoring)\n', (4427, 4498), False, 'from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict\n'), ((6105, 6125), 'numpy.argsort', 'np.argsort', (['meanmean'], {}), '(meanmean)\n', (6115, 6125), True, 'import numpy as np\n'), ((7562, 7616), 'sklearn.model_selection.RepeatedStratifiedKFold', 'RepeatedStratifiedKFold', ([], {'n_splits': '(5)', 'n_repeats': 'bootnum'}), '(n_splits=5, n_repeats=bootnum)\n', (7585, 7616), False, 'from sklearn.model_selection import StratifiedKFold, RepeatedStratifiedKFold\n'), ((7636, 7683), 'imblearn.pipeline.Pipeline', 'Pipeline', ([], {'steps': "[('r', resample), ('m', model)]"}), "(steps=[('r', resample), ('m', model)])\n", (7644, 7683), False, 'from imblearn.pipeline import Pipeline\n'), ((7704, 7789), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['pipeline1', 'glob_feat_imp', 'global_labels'], {'cv': 'cv', 'scoring': 'scoring'}), '(pipeline1, glob_feat_imp, global_labels, cv=cv, scoring=scoring\n )\n', (7719, 7789), False, 'from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict\n'), ((14077, 14113), 'sklearn.metrics.recall_score', 'recall_score', (['testLabel', 'predictions'], {}), '(testLabel, predictions)\n', (14089, 14113), False, 'from sklearn.metrics import confusion_matrix, auc, plot_roc_curve, roc_auc_score, roc_curve, recall_score, precision_score\n'), ((14142, 14181), 'sklearn.metrics.precision_score', 'precision_score', (['testLabel', 'predictions'], {}), '(testLabel, predictions)\n', (14157, 14181), False, 'from sklearn.metrics import confusion_matrix, auc, plot_roc_curve, roc_auc_score, roc_curve, recall_score, precision_score\n'), ((14204, 14254), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['testLabel', 'probs'], {'average': '"""samples"""'}), "(testLabel, probs, average='samples')\n", (14217, 14254), False, 'from sklearn.metrics import confusion_matrix, auc, plot_roc_curve, roc_auc_score, roc_curve, recall_score, precision_score\n'), ((14371, 14398), 'sklearn.metrics.roc_curve', 'roc_curve', (['testLabel', 'probs'], {}), '(testLabel, probs)\n', (14380, 14398), False, 'from sklearn.metrics import confusion_matrix, auc, plot_roc_curve, roc_auc_score, roc_curve, recall_score, precision_score\n'), ((14445, 14473), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (14457, 14473), True, 'import matplotlib.pyplot as plt\n'), ((14487, 14522), 'matplotlib.pyplot.plot', 'plt.plot', (['base_fpr', 'base_tpr', '"""b--"""'], {}), "(base_fpr, base_tpr, 'b--')\n", (14495, 14522), True, 'import matplotlib.pyplot as plt\n'), ((14550, 14585), 'matplotlib.pyplot.plot', 'plt.plot', (['model_fpr', 'model_tpr', '"""r"""'], {}), "(model_fpr, model_tpr, 'r')\n", (14558, 14585), True, 'import matplotlib.pyplot as plt\n'), ((14774, 14817), 'seaborn.despine', 'sns.despine', ([], {'fig': 'fig12', 'ax': 'ax12', 'right': '(True)'}), '(fig=fig12, ax=ax12, right=True)\n', (14785, 14817), True, 'import seaborn as sns\n'), ((15068, 15078), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15076, 15078), True, 'import matplotlib.pyplot as plt\n'), ((3714, 3829), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': 'num_trees', 'max_depth': 'tree_depth', 'max_features': 'max_split', 'random_state': 'seed'}), '(n_estimators=num_trees, max_depth=tree_depth,\n max_features=max_split, random_state=seed)\n', (3736, 3829), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((5431, 5496), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['pipeline', 'global_features', 'global_labels'], {'cv': '(5)'}), '(pipeline, global_features, global_labels, cv=5)\n', (5448, 5496), False, 'from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict\n'), ((7355, 7470), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': 'num_trees', 'max_depth': 'tree_depth', 'max_features': 'max_split', 'random_state': 'seed'}), '(n_estimators=num_trees, max_depth=tree_depth,\n max_features=max_split, random_state=seed)\n', (7377, 7470), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((8107, 8135), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (8119, 8135), True, 'import matplotlib.pyplot as plt\n'), ((8159, 8173), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8171, 8173), True, 'import matplotlib.pyplot as plt\n'), ((9769, 9799), 'numpy.mean', 'np.mean', (['meanmean_tprs'], {'axis': '(0)'}), '(meanmean_tprs, axis=0)\n', (9776, 9799), True, 'import numpy as np\n'), ((9921, 9940), 'numpy.argmax', 'np.argmax', (['youdensi'], {}), '(youdensi)\n', (9930, 9940), True, 'import numpy as np\n'), ((10089, 10110), 'numpy.std', 'np.std', (['means_sens_Yi'], {}), '(means_sens_Yi)\n', (10095, 10110), True, 'import numpy as np\n'), ((10621, 10639), 'numpy.argmax', 'np.argmax', (['bal_acc'], {}), '(bal_acc)\n', (10630, 10639), True, 'import numpy as np\n'), ((10659, 10674), 'numpy.std', 'np.std', (['bal_acc'], {}), '(bal_acc)\n', (10665, 10674), True, 'import numpy as np\n'), ((11188, 11199), 'numpy.std', 'np.std', (['PPV'], {}), '(PPV)\n', (11194, 11199), True, 'import numpy as np\n'), ((11617, 11628), 'numpy.std', 'np.std', (['NPV'], {}), '(NPV)\n', (11623, 11628), True, 'import numpy as np\n'), ((11966, 11987), 'numpy.std', 'np.std', (['meanmean_aucs'], {}), '(meanmean_aucs)\n', (11972, 11987), True, 'import numpy as np\n'), ((12359, 12379), 'numpy.std', 'np.std', (['tprs'], {'axis': '(0)'}), '(tprs, axis=0)\n', (12365, 12379), True, 'import numpy as np\n'), ((12402, 12435), 'numpy.minimum', 'np.minimum', (['(mean_tpr + std_tpr)', '(1)'], {}), '(mean_tpr + std_tpr, 1)\n', (12412, 12435), True, 'import numpy as np\n'), ((12458, 12491), 'numpy.maximum', 'np.maximum', (['(mean_tpr - std_tpr)', '(0)'], {}), '(mean_tpr - std_tpr, 0)\n', (12468, 12491), True, 'import numpy as np\n'), ((12817, 12856), 'seaborn.despine', 'sns.despine', ([], {'fig': 'fig', 'ax': 'ax', 'right': '(True)'}), '(fig=fig, ax=ax, right=True)\n', (12828, 12856), True, 'import seaborn as sns\n'), ((13123, 13133), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13131, 13133), True, 'import matplotlib.pyplot as plt\n'), ((13273, 13337), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['pipeline1', 'glob_feat_imp', 'global_labels'], {'cv': '(5)'}), '(pipeline1, glob_feat_imp, global_labels, cv=5)\n', (13290, 13337), False, 'from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict\n'), ((4784, 4849), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(5)', 'shuffle': '(True)', 'random_state': '(seed + kk)'}), '(n_splits=5, shuffle=True, random_state=seed + kk)\n', (4799, 4849), False, 'from sklearn.model_selection import StratifiedKFold, RepeatedStratifiedKFold\n'), ((5516, 5607), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['model', 'global_features', 'global_labels'], {'method': '"""predict_proba"""', 'cv': '(5)'}), "(model, global_features, global_labels, method=\n 'predict_proba', cv=5)\n", (5533, 5607), False, 'from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict\n'), ((8253, 8318), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(5)', 'shuffle': '(True)', 'random_state': '(seed + kk)'}), '(n_splits=5, shuffle=True, random_state=seed + kk)\n', (8268, 8318), False, 'from sklearn.model_selection import StratifiedKFold, RepeatedStratifiedKFold\n'), ((8386, 8408), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (8397, 8408), True, 'import numpy as np\n'), ((9285, 9306), 'numpy.mean', 'np.mean', (['tprs'], {'axis': '(0)'}), '(tprs, axis=0)\n', (9292, 9306), True, 'import numpy as np\n'), ((9363, 9386), 'sklearn.metrics.auc', 'auc', (['mean_fpr', 'mean_tpr'], {}), '(mean_fpr, mean_tpr)\n', (9366, 9386), False, 'from sklearn.metrics import confusion_matrix, auc, plot_roc_curve, roc_auc_score, roc_curve, recall_score, precision_score\n'), ((9834, 9864), 'numpy.mean', 'np.mean', (['meanmean_tprs'], {'axis': '(0)'}), '(meanmean_tprs, axis=0)\n', (9841, 9864), True, 'import numpy as np\n'), ((10175, 10214), 'scipy.stats.t.ppf', 't.ppf', (['((1 + confidence) / 2)', '(n_sens - 1)'], {}), '((1 + confidence) / 2, n_sens - 1)\n', (10180, 10214), False, 'from scipy.stats import zscore, t\n'), ((10730, 10768), 'scipy.stats.t.ppf', 't.ppf', (['((1 + confidence) / 2)', '(n_acc - 1)'], {}), '((1 + confidence) / 2, n_acc - 1)\n', (10735, 10768), False, 'from scipy.stats import zscore, t\n'), ((11041, 11072), 'numpy.count_nonzero', 'np.count_nonzero', (['global_labels'], {}), '(global_labels)\n', (11057, 11072), True, 'import numpy as np\n'), ((11249, 11287), 'scipy.stats.t.ppf', 't.ppf', (['((1 + confidence) / 2)', '(n_PPV - 1)'], {}), '((1 + confidence) / 2, n_PPV - 1)\n', (11254, 11287), False, 'from scipy.stats import zscore, t\n'), ((11307, 11319), 'numpy.mean', 'np.mean', (['PPV'], {}), '(PPV)\n', (11314, 11319), True, 'import numpy as np\n'), ((11348, 11360), 'numpy.mean', 'np.mean', (['PPV'], {}), '(PPV)\n', (11355, 11360), True, 'import numpy as np\n'), ((11470, 11482), 'numpy.mean', 'np.mean', (['PPV'], {}), '(PPV)\n', (11477, 11482), True, 'import numpy as np\n'), ((11678, 11716), 'scipy.stats.t.ppf', 't.ppf', (['((1 + confidence) / 2)', '(n_NPV - 1)'], {}), '((1 + confidence) / 2, n_NPV - 1)\n', (11683, 11716), False, 'from scipy.stats import zscore, t\n'), ((11736, 11748), 'numpy.mean', 'np.mean', (['NPV'], {}), '(NPV)\n', (11743, 11748), True, 'import numpy as np\n'), ((11777, 11789), 'numpy.mean', 'np.mean', (['NPV'], {}), '(NPV)\n', (11784, 11789), True, 'import numpy as np\n'), ((11899, 11911), 'numpy.mean', 'np.mean', (['NPV'], {}), '(NPV)\n', (11906, 11911), True, 'import numpy as np\n'), ((12041, 12075), 'scipy.stats.t.ppf', 't.ppf', (['((1 + confidence) / 2)', '(n - 1)'], {}), '((1 + confidence) / 2, n - 1)\n', (12046, 12075), False, 'from scipy.stats import zscore, t\n'), ((13358, 13451), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['pipeline1', 'glob_feat_imp', 'global_labels'], {'method': '"""predict_proba"""', 'cv': '(5)'}), "(pipeline1, glob_feat_imp, global_labels, method=\n 'predict_proba', cv=5)\n", (13375, 13451), False, 'from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict\n'), ((5915, 5951), 'numpy.array', 'np.array', (['model.feature_importances_'], {}), '(model.feature_importances_)\n', (5923, 5951), True, 'import numpy as np\n'), ((8902, 8936), 'scipy.interp', 'interp', (['mean_fpr', 'viz.fpr', 'viz.tpr'], {}), '(mean_fpr, viz.fpr, viz.tpr)\n', (8908, 8936), False, 'from scipy import interp\n'), ((9087, 9121), 'scipy.interp', 'interp', (['mean_fpr', 'viz.fpr', 'viz.tpr'], {}), '(mean_fpr, viz.fpr, viz.tpr)\n', (9093, 9121), False, 'from scipy import interp\n'), ((9443, 9461), 'numpy.array', 'np.array', (['mean_tpr'], {}), '(mean_tpr)\n', (9451, 9461), True, 'import numpy as np\n'), ((9514, 9550), 'numpy.vstack', 'np.vstack', (['[meanmean_tprs, mean_tpr]'], {}), '([meanmean_tprs, mean_tpr])\n', (9523, 9550), True, 'import numpy as np\n'), ((5094, 5130), 'numpy.array', 'np.array', (['model.feature_importances_'], {}), '(model.feature_importances_)\n', (5102, 5130), True, 'import numpy as np\n'), ((10568, 10590), 'numpy.ones_like', 'np.ones_like', (['mean_tpr'], {}), '(mean_tpr)\n', (10580, 10590), True, 'import numpy as np\n'), ((11531, 11558), 'numpy.ones_like', 'np.ones_like', (['means_sens_Yi'], {}), '(means_sens_Yi)\n', (11543, 11558), True, 'import numpy as np\n'), ((5225, 5261), 'numpy.array', 'np.array', (['model.feature_importances_'], {}), '(model.feature_importances_)\n', (5233, 5261), True, 'import numpy as np\n')]
#! /usr/bin/env python import numpy as np def runningMeanFast(x, N): ''' Calculate the running mean of an array given a window. Ref: http://stackoverflow.com/questions/13728392/moving-average-or-running-mean Args: x (array-like): Data array N (int): Window width Returns: An array of averages over each window. ''' return np.convolve(x, np.ones((N,))/N)[(N-1):]
[ "numpy.ones" ]
[((411, 424), 'numpy.ones', 'np.ones', (['(N,)'], {}), '((N,))\n', (418, 424), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt # activate function def step_func(y): if y>0: return 1 return 0 # loss function def loss(y, t): #return 0.5 * (np.sum(y-t)**2) return 0.5*(y-t) class Neuron : def __init__(self, input_len): #self.x = np.zeros(input_len) # input_vec self.b = np.random.rand(1)[0] # bias self.w = np.random.rand(input_len) # weight def predict (self, x): self.x = x self.h = np.dot(self.x, self.w)-self.b # sigma(W[n]*X[n])+bias self.y = step_func(self.h) def back_prop (self, t): # t: teach_vec self.loss = loss(self.y, t) self.dw = self.x*self.loss self.w = self.w - self.dw self.b += self.loss class MatchLearning : def __init__(self, max_price, sweets_list): self.max_price = max_price self.sweets_list = sweets_list self.sweets_type_num = len(sweets_list) self.neuron = Neuron(len(sweets_list)) self.price_list = list(map(lambda cons : cons[1], sweets_list)) def predict(self, input_vec): return self.neuron.predict(input_vec) def back_prop(self, t): return self.neuron.back_prop(t) def input_vec_random(self, max_purchase_num=15): return np.random.randint(max_purchase_num,size=self.sweets_type_num) def teach_vec(self, x) : return 1 * (np.dot(x, self.price_list) > self.max_price) def print_status(self, num=None): neu = self.neuron t = self.teach_vec(neu.x) print("======= num_train:%d =========="% num) print("data\t:: price:%s" % np.dot(neu.x, self.price_list)) print("predict\t:: x:%s w:%s b:%s,\n\t h:%s y:%s" % (neu.x,neu.w,neu.b, neu.h, neu.y)) print("teach\t:: t:%s error:%s dw:%s" % (t, loss(t, neu.y), neu.dw)) def train1(self, x): self.predict(x) self.back_prop(self.teach_vec(x)) def plot_result(self): plt.plot(self.error_ave) plt.show() plt.plot(self.dw_list) plt.show() plt.plot(self.w_list) plt.show() def train(self, learn_par_epoch=5, train_num = 10000): self.error_ave = [] self.dw_list = [] self.w_list = [] for epoch in range(train_num): error=0 for i in range(learn_par_epoch): x = self.input_vec_random() self.train1(x) error += loss(self.neuron.y, self.teach_vec(x)) #self.print_status(num=epoch) self.error_ave = self.error_ave + [error/learn_par_epoch] self.dw_list = self.dw_list + [self.neuron.dw ] self.w_list = self.w_list + [self.neuron.w] self.plot_result() if __name__ == "__main__": sweets_list = [("candy", 40), ("chocolate", 80)]#, ("cookie", 200)] match_learning = MatchLearning(1000 , sweets_list) match_learning.train()
[ "numpy.random.rand", "matplotlib.pyplot.plot", "numpy.dot", "numpy.random.randint", "matplotlib.pyplot.show" ]
[((385, 410), 'numpy.random.rand', 'np.random.rand', (['input_len'], {}), '(input_len)\n', (399, 410), True, 'import numpy as np\n'), ((1327, 1389), 'numpy.random.randint', 'np.random.randint', (['max_purchase_num'], {'size': 'self.sweets_type_num'}), '(max_purchase_num, size=self.sweets_type_num)\n', (1344, 1389), True, 'import numpy as np\n'), ((2081, 2105), 'matplotlib.pyplot.plot', 'plt.plot', (['self.error_ave'], {}), '(self.error_ave)\n', (2089, 2105), True, 'import matplotlib.pyplot as plt\n'), ((2114, 2124), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2122, 2124), True, 'import matplotlib.pyplot as plt\n'), ((2134, 2156), 'matplotlib.pyplot.plot', 'plt.plot', (['self.dw_list'], {}), '(self.dw_list)\n', (2142, 2156), True, 'import matplotlib.pyplot as plt\n'), ((2165, 2175), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2173, 2175), True, 'import matplotlib.pyplot as plt\n'), ((2185, 2206), 'matplotlib.pyplot.plot', 'plt.plot', (['self.w_list'], {}), '(self.w_list)\n', (2193, 2206), True, 'import matplotlib.pyplot as plt\n'), ((2215, 2225), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2223, 2225), True, 'import matplotlib.pyplot as plt\n'), ((340, 357), 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), '(1)\n', (354, 357), True, 'import numpy as np\n'), ((484, 506), 'numpy.dot', 'np.dot', (['self.x', 'self.w'], {}), '(self.x, self.w)\n', (490, 506), True, 'import numpy as np\n'), ((1443, 1469), 'numpy.dot', 'np.dot', (['x', 'self.price_list'], {}), '(x, self.price_list)\n', (1449, 1469), True, 'import numpy as np\n'), ((1697, 1727), 'numpy.dot', 'np.dot', (['neu.x', 'self.price_list'], {}), '(neu.x, self.price_list)\n', (1703, 1727), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np import argparse ap = argparse.ArgumentParser() ap.add_argument("-m", "--model_path", type=str, default='model.tflite', help="path to tflite model") args = ap.parse_args() # Load MNIST dataset mnist = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # Normalize the input image so that each pixel value is between 0 to 1. train_images = train_images.astype(np.float32) / 255.0 test_images = test_images.astype(np.float32) / 255.0 train_images = np.expand_dims(train_images, -1) test_images = np.expand_dims(test_images, -1) # Helper function to run inference on a TFLite model def run_tflite_model(tflite_file, test_image_indices): global test_images # Initialize the interpreter interpreter = tf.lite.Interpreter(model_path=str(tflite_file)) interpreter.allocate_tensors() input_details = interpreter.get_input_details()[0] output_details = interpreter.get_output_details()[0] predictions = np.zeros((len(test_image_indices),), dtype=int) for i, test_image_index in enumerate(test_image_indices): test_image = test_images[test_image_index] test_label = test_labels[test_image_index] # Check if the input type is quantized, then rescale input data to uint8 if input_details['dtype'] == np.int8: input_scale, input_zero_point = input_details["quantization"] test_image = test_image / input_scale + input_zero_point test_image = np.expand_dims(test_image, axis=0).astype(input_details["dtype"]) interpreter.set_tensor(input_details["index"], test_image) interpreter.invoke() output = interpreter.get_tensor(output_details["index"])[0] predictions[i] = output.argmax() return predictions # Helper function to evaluate a TFLite model on all images def evaluate_model(tflite_file, model_type): global test_images global test_labels test_image_indices = range(test_images.shape[0]) predictions = run_tflite_model(tflite_file, test_image_indices) accuracy = (np.sum(test_labels== predictions) * 100) / len(test_images) print('%s model accuracy is %.4f%% (Number of test samples=%d)' % ( model_type, accuracy, len(test_images))) evaluate_model(args.model_path, model_type="Quantized")
[ "numpy.sum", "numpy.expand_dims", "argparse.ArgumentParser" ]
[((65, 90), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (88, 90), False, 'import argparse\n'), ((543, 575), 'numpy.expand_dims', 'np.expand_dims', (['train_images', '(-1)'], {}), '(train_images, -1)\n', (557, 575), True, 'import numpy as np\n'), ((590, 621), 'numpy.expand_dims', 'np.expand_dims', (['test_images', '(-1)'], {}), '(test_images, -1)\n', (604, 621), True, 'import numpy as np\n'), ((2037, 2071), 'numpy.sum', 'np.sum', (['(test_labels == predictions)'], {}), '(test_labels == predictions)\n', (2043, 2071), True, 'import numpy as np\n'), ((1479, 1513), 'numpy.expand_dims', 'np.expand_dims', (['test_image'], {'axis': '(0)'}), '(test_image, axis=0)\n', (1493, 1513), True, 'import numpy as np\n')]
import torch import numpy as np from PIL import Image from torchvision import transforms import h5py import matplotlib.pyplot as plt import random from torch.utils.data import Dataset, DataLoader, random_split import torch.nn as nn import torch.optim as optim import os from tqdm import tqdm import time import pickle import umetrics class MaskTrainer: def __init__(self, device, net, train_set, val_set, batch_size, optimizer, scheduler=None, loss = nn.MSELoss(), in_key = 0, target_key = 1, mask_key = 2, num_workers=0, checkpoint_dir='./models/', exp_name='net', mask=False, hingeloss=False, classification=False): self.device = device self.net = net.to(device) self.loss = loss self.batch_size = batch_size self.train_loader = DataLoader(train_set, batch_size=self.batch_size, num_workers=num_workers, shuffle=True) self.val_loader = DataLoader(val_set, batch_size=self.batch_size, num_workers=num_workers, shuffle=False) self.in_key = in_key self.target_key = target_key self.mask_key = mask_key self.optimizer = optimizer self.scheduler = scheduler logging_dir_name = exp_name + '_' + str(time.time()) + '/' self.checkpoint_dir = checkpoint_dir + logging_dir_name if not os.path.isdir(checkpoint_dir): os.mkdir(checkpoint_dir) os.mkdir(self.checkpoint_dir) self.epochs_so_far = 0 self.mask = mask self.hingeloss = hingeloss self.classification = classification def plot_predictions(self, img, graph_pred, graph_target): plt.subplot(1, 3, 1) plt.imshow(img.transpose(1, 2, 0)) plt.title("Input") plt.subplot(1, 3, 2) plt.imshow(graph_target.transpose(1, 2, 0)[:, :, 0]) plt.title("GT Graph 0") plt.subplot(1, 3, 3) if self.classification: graph_pred = np.squeeze(graph_pred[:, 0, :, :]) graph_pred = np.squeeze(np.argmax(graph_pred, axis=0)) plt.imshow(graph_pred - 1) else: plt.imshow(graph_pred.transpose(1, 2, 0)[:, :, 0]) plt.title("Pred Graph 0") plt.show() def train(self, epochs, checkpoint=False, train_loader=None, val_loader=None, start_epoch=0): # Phases and Logging phases = { 'train': train_loader if train_loader else self.train_loader, 'val': val_loader if val_loader else self.val_loader } start_time = time.time() train_log = [] # Training for i in range(start_epoch, epochs): epoch_data = { 'train_mean_loss': 0.0, 'val_mean_loss': 0.0, 'train_mean_iou': 0.0, 'val_mean_iou': 0.0, 'train_mean_jaccard': 0.0, 'val_mean_jaccard': 0.0 } for phase, loader in phases.items(): if phase == 'train': self.net.train() else: self.net.eval() running_loss = 0.0 total, correct = 0, 0 running_iou, running_jaccard = 0.0, 0.0 for j, batch in enumerate(tqdm(loader)): _in, _out, _mask = batch[self.in_key].to(self.device), batch[self.target_key].to(self.device), batch[self.mask_key].to(self.device) # Forward self.optimizer.zero_grad() output = self.net(_in) # Apply loss to masked outputs if self.mask: output, _out = output.permute(0, 2, 3, 1), _out.permute(0, 2, 3, 1) _mask = _mask.squeeze() output, _out = output[_mask != 0].float(), _out[_mask != 0].float() # if self.hingeloss: # output = output.reshape(output.shape[0], output.shape[1]*output.shape[2]*output.shape[3]) # _out = _out.reshape(_out.shape[0], _out.shape[1]*_out.shape[2]*_out.shape[3]) loss = self.loss(output, _out) # display if j == 0 and self.epochs_so_far % 5 == 4: self.plot_predictions(_in[0].cpu().numpy(), output[0].cpu().detach().numpy(), _out[0].cpu().detach().numpy()) # metrics graph_pred = np.argmax(output, axis=1).cpu().clone().detach().numpy() pred = graph_pred.transpose(0, 2, 3, 1) target = _out.cpu().clone().detach().numpy().transpose(0, 2, 3, 1) for k in range(target.shape[0]): result = umetrics.calculate(target[k], pred[k], strict=True) if len(result.per_object_IoU) > 0: running_iou += np.mean(result.per_object_IoU) tp = result.n_true_positives fn = result.n_false_negatives fp = result.n_false_positives running_jaccard += tp / (tp+fn+fp) # Optimize if phase == 'train': loss.backward() self.optimizer.step() # Log batch results running_loss += loss.item() torch.cuda.empty_cache() # Log phase results epoch_data[phase + '_mean_loss'] = running_loss / len(loader) epoch_data[phase + '_mean_iou'] = running_iou / len(loader) epoch_data[phase + '_mean_jaccard'] = running_jaccard / len(loader) # Display Progress duration_elapsed = time.time() - start_time print('\n-- Finished Epoch {}/{} --'.format(i, epochs - 1)) print('Training Loss: {}'.format(epoch_data['train_mean_loss'])) print('Validation Loss: {}'.format(epoch_data['val_mean_loss'])) if i % 5 == 0: print('Training Mean IoU: {}'.format(epoch_data['train_mean_iou'])) print('Validation Mean IoU: {}'.format(epoch_data['val_mean_iou'])) print('Training Mean Jaccard: {}'.format(epoch_data['train_mean_jaccard'])) print('Validation Mean Jaccard: {}'.format(epoch_data['val_mean_jaccard'])) print('Time since start: {}'.format(duration_elapsed)) epoch_data['time_elapsed'] = duration_elapsed train_log.append(epoch_data) # Scheduler if self.scheduler: self.scheduler.step() # Checkpoint checkpoint_time = time.time() if checkpoint: path = self.checkpoint_dir + 'checkpoint_optim_' + str(self.epochs_so_far) torch.save({ 'optim': self.optimizer.state_dict(), 'sched': self.scheduler.state_dict(), 'state_dict': self.net.state_dict(), 'start_epoch': self.epochs_so_far + 1, 'log': train_log }, path) self.epochs_so_far += 1 # Save train_log path = self.checkpoint_dir + 'train_log_' + str(self.epochs_so_far) with open(path, 'wb') as fp: pickle.dump(train_log, fp) return train_log def evaluate(self, batch): self.net.eval() _in = batch[self.in_key].to(self.device) output = self.net(_in) return output.cpu().detach().numpy() class DualMaskTrainer: def __init__(self, device, net, train_set, val_set, batch_size, optimizer, scheduler=None, losses = [nn.CrossEntropyLoss(), nn.MSELoss()], alpha = 0.5, in_key = 0, target_key = 1, mask_key = 2, num_workers=0, checkpoint_dir='./models/', exp_name='net', mask=False, classification=False): self.device = device self.net = net.to(device) self.losses = losses self.alpha = alpha self.batch_size = batch_size self.train_loader = DataLoader(train_set, batch_size=self.batch_size, num_workers=num_workers, shuffle=True) self.val_loader = DataLoader(val_set, batch_size=self.batch_size, num_workers=num_workers, shuffle=False) self.in_key = in_key self.target_key = target_key self.mask_key = mask_key self.optimizer = optimizer self.scheduler = scheduler logging_dir_name = exp_name + '_' + str(time.time()) + '/' self.checkpoint_dir = checkpoint_dir + logging_dir_name if not os.path.isdir(checkpoint_dir): os.mkdir(checkpoint_dir) os.mkdir(self.checkpoint_dir) self.epochs_so_far = 0 self.mask = mask self.classification = classification def plot_predictions_dual(self, img, graph_pred, graph_target, seg_pred, seg_target): plt.figure(figsize=(15, 5)) plt.subplot(1, 5, 1) plt.imshow(img.transpose(1, 2, 0)) plt.title("Input") plt.subplot(1, 5, 2) plt.imshow(graph_target.transpose(1, 2, 0)[:, :, 0]) plt.title("GT Graph 0") plt.subplot(1, 5, 3) plt.imshow(graph_pred.transpose(1, 2, 3, 0)[0, :, :, 0].squeeze()) plt.title("Pred Graph 0") plt.subplot(1, 5, 4) plt.imshow(seg_target) plt.title("GT Segmentation") plt.subplot(1, 5, 5) plt.imshow(seg_pred) plt.title("Pred Segmentation") plt.show() def train(self, epochs, checkpoint=False, train_loader=None, val_loader=None, start_epoch=0): loss_seg, loss_graph = self.losses # Phases and Logging phases = { 'train': train_loader if train_loader else self.train_loader, 'val': val_loader if val_loader else self.val_loader } start_time = time.time() train_log = [] # Training for i in range(start_epoch, epochs): epoch_data = { 'train_mean_loss_seg': 0.0, 'train_mean_loss_graph': 0.0, 'val_mean_loss_seg': 0.0, 'val_mean_loss_graph': 0.0, 'train_mean_iou_seg': 0.0, 'val_mean_iou_seg': 0.0, 'train_mean_jaccard_seg': 0.0, 'val_mean_jaccard_seg': 0.0, 'train_mean_iou_graph': 0.0, 'val_mean_iou_graph': 0.0, 'train_mean_jaccard_graph': 0.0, 'val_mean_jaccard_graph': 0.0} for phase, loader in phases.items(): if phase == 'train': self.net.train() else: self.net.eval() running_losses = np.zeros(2) total, correct = 0, 0 running_iou_seg, running_jaccard_seg = 0.0, 0.0 running_iou_graph, running_jaccard_graph = 0.0, 0.0 for j, batch in enumerate(tqdm(loader)): _in, _out, _mask = batch[self.in_key].to(self.device), batch[self.target_key], batch[self.mask_key].to(self.device) _out_seg, _out_graph = _out _out_seg, _out_graph = _out_seg.to(self.device).squeeze().long(), _out_graph.to(self.device).long() # Forward self.optimizer.zero_grad() output_seg, output_graph = self.net(_in) # Apply loss to masked outputs if self.mask: output_graph, _out_graph = output_graph.permute(0, 2, 3, 1), _out_graph.permute(0, 2, 3, 1) _mask = _mask.squeeze() output_graph, _out_graph = output_graph[_mask != 0].float(), _out_graph[_mask != 0].long() loss0, loss1 = loss_seg(output_seg, _out_seg), 0 output_graph = output_graph.permute(1, 0, 2, 3) output_graph = torch.stack(torch.split(output_graph, 3)) output_graph = output_graph.permute(2, 1, 0, 3, 4) loss1 = loss_graph(output_graph, _out_graph) loss = self.alpha * loss0 + (1 - self.alpha) * loss1 # metrics graph_pred = np.argmax(output_graph.data.to(torch.device("cpu")).numpy(), axis=1) pred = graph_pred.transpose(0, 2, 3, 1) target = _out_graph.data.to(torch.device("cpu")).numpy().transpose(0, 2, 3, 1) seg_pred = np.argmax(output_seg.clone().detach().cpu().numpy().transpose(0, 2, 3, 1), axis=3) seg_target = _out_seg.data.to(torch.device("cpu")).numpy() for k in range(target.shape[0]): result_graph = umetrics.calculate(target[k], pred[k], strict=True) result_seg = umetrics.calculate(seg_target[k], seg_pred[k], strict=True) if len(result_graph.per_object_IoU) > 0: running_iou_graph += np.mean(result_graph.per_object_IoU) tp = result_graph.n_true_positives fn = result_graph.n_false_negatives fp = result_graph.n_false_positives running_jaccard_graph += tp / (tp+fn+fp) # display if j == 0 and self.epochs_so_far % 5 == 4: _in_cpu = _in[0].cpu().numpy() output_graph_cpu = output_graph[0].cpu().detach().numpy() _out_graph_cpu = _out_graph[0].cpu().numpy() output_seg_cpu = output_seg[0].cpu().detach().numpy() output_seg_cpu = np.argmax(output_seg[0].cpu().detach().numpy(), axis=0) _out_seg_cpu = _out_seg[0].cpu().numpy() self.plot_predictions_dual(_in_cpu, output_graph_cpu, _out_graph_cpu, output_seg_cpu, _out_seg_cpu) # Optimize if phase == 'train': loss.backward() self.optimizer.step() # Log batch results running_losses += [loss0.item(), loss1.item()] torch.cuda.empty_cache() # Log phase results running_loss_seg, running_loss_graph = running_losses epoch_data[phase + '_mean_loss_seg'] = running_loss_seg / len(loader) epoch_data[phase + '_mean_loss_graph'] = running_loss_graph / len(loader) epoch_data[phase + '_mean_iou_seg'] = running_iou_seg / len(loader) epoch_data[phase + '_mean_jaccard_seg'] = running_jaccard_seg / len(loader) epoch_data[phase + '_mean_iou_graph'] = running_iou_graph / len(loader) epoch_data[phase + '_mean_jaccard_graph'] = running_jaccard_graph / len(loader) # Display Progress duration_elapsed = time.time() - start_time print('\n-- Finished Epoch {}/{} --'.format(i, epochs - 1)) print('Training Loss (Segmentation): {}'.format(epoch_data['train_mean_loss_seg'])) print('Training Loss (Graph): {}'.format(epoch_data['train_mean_loss_graph'])) print('Validation Loss (Segmentation): {}'.format(epoch_data['val_mean_loss_seg'])) print('Validation Loss (Graph): {}'.format(epoch_data['val_mean_loss_graph'])) if i % 5 == 4: print('Training Mean IoU (Segmentation): {}'.format(epoch_data['train_mean_iou_seg'])) print('Validation Mean IoU (Segmentation): {}'.format(epoch_data['val_mean_iou_seg'])) print('Training Mean Jaccard (Segmentation): {}'.format(epoch_data['train_mean_jaccard_seg'])) print('Validation Mean Jaccard (Segmentation): {}'.format(epoch_data['val_mean_jaccard_seg'])) print('Training Mean IoU (Graph): {}'.format(epoch_data['train_mean_iou_graph'])) print('Validation Mean IoU (Graph): {}'.format(epoch_data['val_mean_iou_graph'])) print('Training Mean Jaccard (Graph): {}'.format(epoch_data['train_mean_jaccard_graph'])) print('Validation Mean Jaccard (Graph): {}'.format(epoch_data['val_mean_jaccard_graph'])) print('Time since start: {}'.format(duration_elapsed)) train_log.append(epoch_data) # Scheduler if self.scheduler: self.scheduler.step() # Checkpoint checkpoint_time = time.time() if checkpoint: path = self.checkpoint_dir + 'checkpoint_' + str(self.epochs_so_far) + '_' + str(checkpoint_time) torch.save(self.net.state_dict(), path) self.epochs_so_far += 1 # Save train_log path = self.checkpoint_dir + 'train_log_' + str(checkpoint_time) with open(path, 'wb') as fp: pickle.dump(train_log, fp) return train_log def evaluate(self, batch): self.net.eval() _in = batch[self.in_key].to(self.device) output_seg, output_graph = self.net(_in) return output_seg.cpu().detach().numpy(), output_graph.cpu().detach().numpy()
[ "torch.nn.CrossEntropyLoss", "torch.nn.MSELoss", "matplotlib.pyplot.imshow", "numpy.mean", "os.path.isdir", "umetrics.calculate", "os.mkdir", "torch.split", "numpy.argmax", "numpy.squeeze", "matplotlib.pyplot.title", "time.time", "torch.cuda.empty_cache", "matplotlib.pyplot.show", "torch...
[((565, 577), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (575, 577), True, 'import torch.nn as nn\n'), ((1041, 1133), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': 'self.batch_size', 'num_workers': 'num_workers', 'shuffle': '(True)'}), '(train_set, batch_size=self.batch_size, num_workers=num_workers,\n shuffle=True)\n', (1051, 1133), False, 'from torch.utils.data import Dataset, DataLoader, random_split\n'), ((1196, 1287), 'torch.utils.data.DataLoader', 'DataLoader', (['val_set'], {'batch_size': 'self.batch_size', 'num_workers': 'num_workers', 'shuffle': '(False)'}), '(val_set, batch_size=self.batch_size, num_workers=num_workers,\n shuffle=False)\n', (1206, 1287), False, 'from torch.utils.data import Dataset, DataLoader, random_split\n'), ((1713, 1742), 'os.mkdir', 'os.mkdir', (['self.checkpoint_dir'], {}), '(self.checkpoint_dir)\n', (1721, 1742), False, 'import os\n'), ((1955, 1975), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(1)'], {}), '(1, 3, 1)\n', (1966, 1975), True, 'import matplotlib.pyplot as plt\n'), ((2027, 2045), 'matplotlib.pyplot.title', 'plt.title', (['"""Input"""'], {}), "('Input')\n", (2036, 2045), True, 'import matplotlib.pyplot as plt\n'), ((2054, 2074), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(2)'], {}), '(1, 3, 2)\n', (2065, 2074), True, 'import matplotlib.pyplot as plt\n'), ((2144, 2167), 'matplotlib.pyplot.title', 'plt.title', (['"""GT Graph 0"""'], {}), "('GT Graph 0')\n", (2153, 2167), True, 'import matplotlib.pyplot as plt\n'), ((2176, 2196), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(3)'], {}), '(1, 3, 3)\n', (2187, 2196), True, 'import matplotlib.pyplot as plt\n'), ((2518, 2528), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2526, 2528), True, 'import matplotlib.pyplot as plt\n'), ((2838, 2849), 'time.time', 'time.time', ([], {}), '()\n', (2847, 2849), False, 'import time\n'), ((8910, 9002), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': 'self.batch_size', 'num_workers': 'num_workers', 'shuffle': '(True)'}), '(train_set, batch_size=self.batch_size, num_workers=num_workers,\n shuffle=True)\n', (8920, 9002), False, 'from torch.utils.data import Dataset, DataLoader, random_split\n'), ((9065, 9156), 'torch.utils.data.DataLoader', 'DataLoader', (['val_set'], {'batch_size': 'self.batch_size', 'num_workers': 'num_workers', 'shuffle': '(False)'}), '(val_set, batch_size=self.batch_size, num_workers=num_workers,\n shuffle=False)\n', (9075, 9156), False, 'from torch.utils.data import Dataset, DataLoader, random_split\n'), ((9582, 9611), 'os.mkdir', 'os.mkdir', (['self.checkpoint_dir'], {}), '(self.checkpoint_dir)\n', (9590, 9611), False, 'import os\n'), ((9820, 9847), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 5)'}), '(figsize=(15, 5))\n', (9830, 9847), True, 'import matplotlib.pyplot as plt\n'), ((9856, 9876), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(5)', '(1)'], {}), '(1, 5, 1)\n', (9867, 9876), True, 'import matplotlib.pyplot as plt\n'), ((9928, 9946), 'matplotlib.pyplot.title', 'plt.title', (['"""Input"""'], {}), "('Input')\n", (9937, 9946), True, 'import matplotlib.pyplot as plt\n'), ((9955, 9975), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(5)', '(2)'], {}), '(1, 5, 2)\n', (9966, 9975), True, 'import matplotlib.pyplot as plt\n'), ((10045, 10068), 'matplotlib.pyplot.title', 'plt.title', (['"""GT Graph 0"""'], {}), "('GT Graph 0')\n", (10054, 10068), True, 'import matplotlib.pyplot as plt\n'), ((10077, 10097), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(5)', '(3)'], {}), '(1, 5, 3)\n', (10088, 10097), True, 'import matplotlib.pyplot as plt\n'), ((10181, 10206), 'matplotlib.pyplot.title', 'plt.title', (['"""Pred Graph 0"""'], {}), "('Pred Graph 0')\n", (10190, 10206), True, 'import matplotlib.pyplot as plt\n'), ((10215, 10235), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(5)', '(4)'], {}), '(1, 5, 4)\n', (10226, 10235), True, 'import matplotlib.pyplot as plt\n'), ((10244, 10266), 'matplotlib.pyplot.imshow', 'plt.imshow', (['seg_target'], {}), '(seg_target)\n', (10254, 10266), True, 'import matplotlib.pyplot as plt\n'), ((10275, 10303), 'matplotlib.pyplot.title', 'plt.title', (['"""GT Segmentation"""'], {}), "('GT Segmentation')\n", (10284, 10303), True, 'import matplotlib.pyplot as plt\n'), ((10312, 10332), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(5)', '(5)'], {}), '(1, 5, 5)\n', (10323, 10332), True, 'import matplotlib.pyplot as plt\n'), ((10341, 10361), 'matplotlib.pyplot.imshow', 'plt.imshow', (['seg_pred'], {}), '(seg_pred)\n', (10351, 10361), True, 'import matplotlib.pyplot as plt\n'), ((10370, 10400), 'matplotlib.pyplot.title', 'plt.title', (['"""Pred Segmentation"""'], {}), "('Pred Segmentation')\n", (10379, 10400), True, 'import matplotlib.pyplot as plt\n'), ((10409, 10419), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10417, 10419), True, 'import matplotlib.pyplot as plt\n'), ((10781, 10792), 'time.time', 'time.time', ([], {}), '()\n', (10790, 10792), False, 'import time\n'), ((1637, 1666), 'os.path.isdir', 'os.path.isdir', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (1650, 1666), False, 'import os\n'), ((1680, 1704), 'os.mkdir', 'os.mkdir', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (1688, 1704), False, 'import os\n'), ((2254, 2288), 'numpy.squeeze', 'np.squeeze', (['graph_pred[:, 0, :, :]'], {}), '(graph_pred[:, 0, :, :])\n', (2264, 2288), True, 'import numpy as np\n'), ((2368, 2394), 'matplotlib.pyplot.imshow', 'plt.imshow', (['(graph_pred - 1)'], {}), '(graph_pred - 1)\n', (2378, 2394), True, 'import matplotlib.pyplot as plt\n'), ((2484, 2509), 'matplotlib.pyplot.title', 'plt.title', (['"""Pred Graph 0"""'], {}), "('Pred Graph 0')\n", (2493, 2509), True, 'import matplotlib.pyplot as plt\n'), ((7220, 7231), 'time.time', 'time.time', ([], {}), '()\n', (7229, 7231), False, 'import time\n'), ((8383, 8404), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (8402, 8404), True, 'import torch.nn as nn\n'), ((8406, 8418), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (8416, 8418), True, 'import torch.nn as nn\n'), ((9506, 9535), 'os.path.isdir', 'os.path.isdir', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (9519, 9535), False, 'import os\n'), ((9549, 9573), 'os.mkdir', 'os.mkdir', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (9557, 9573), False, 'import os\n'), ((17720, 17731), 'time.time', 'time.time', ([], {}), '()\n', (17729, 17731), False, 'import time\n'), ((2325, 2354), 'numpy.argmax', 'np.argmax', (['graph_pred'], {'axis': '(0)'}), '(graph_pred, axis=0)\n', (2334, 2354), True, 'import numpy as np\n'), ((6250, 6261), 'time.time', 'time.time', ([], {}), '()\n', (6259, 6261), False, 'import time\n'), ((7888, 7914), 'pickle.dump', 'pickle.dump', (['train_log', 'fp'], {}), '(train_log, fp)\n', (7899, 7914), False, 'import pickle\n'), ((11624, 11635), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (11632, 11635), True, 'import numpy as np\n'), ((16104, 16115), 'time.time', 'time.time', ([], {}), '()\n', (16113, 16115), False, 'import time\n'), ((18142, 18168), 'pickle.dump', 'pickle.dump', (['train_log', 'fp'], {}), '(train_log, fp)\n', (18153, 18168), False, 'import pickle\n'), ((1539, 1550), 'time.time', 'time.time', ([], {}), '()\n', (1548, 1550), False, 'import time\n'), ((3485, 3497), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (3489, 3497), False, 'from tqdm import tqdm\n'), ((5871, 5895), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (5893, 5895), False, 'import torch\n'), ((9408, 9419), 'time.time', 'time.time', ([], {}), '()\n', (9417, 9419), False, 'import time\n'), ((11848, 11860), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (11852, 11860), False, 'from tqdm import tqdm\n'), ((15357, 15381), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (15379, 15381), False, 'import torch\n'), ((5129, 5180), 'umetrics.calculate', 'umetrics.calculate', (['target[k]', 'pred[k]'], {'strict': '(True)'}), '(target[k], pred[k], strict=True)\n', (5147, 5180), False, 'import umetrics\n'), ((12916, 12944), 'torch.split', 'torch.split', (['output_graph', '(3)'], {}), '(output_graph, 3)\n', (12927, 12944), False, 'import torch\n'), ((13773, 13824), 'umetrics.calculate', 'umetrics.calculate', (['target[k]', 'pred[k]'], {'strict': '(True)'}), '(target[k], pred[k], strict=True)\n', (13791, 13824), False, 'import umetrics\n'), ((13862, 13921), 'umetrics.calculate', 'umetrics.calculate', (['seg_target[k]', 'seg_pred[k]'], {'strict': '(True)'}), '(seg_target[k], seg_pred[k], strict=True)\n', (13880, 13921), False, 'import umetrics\n'), ((5308, 5338), 'numpy.mean', 'np.mean', (['result.per_object_IoU'], {}), '(result.per_object_IoU)\n', (5315, 5338), True, 'import numpy as np\n'), ((14061, 14097), 'numpy.mean', 'np.mean', (['result_graph.per_object_IoU'], {}), '(result_graph.per_object_IoU)\n', (14068, 14097), True, 'import numpy as np\n'), ((13652, 13671), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (13664, 13671), False, 'import torch\n'), ((13291, 13310), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (13303, 13310), False, 'import torch\n'), ((13437, 13456), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (13449, 13456), False, 'import torch\n'), ((4839, 4864), 'numpy.argmax', 'np.argmax', (['output'], {'axis': '(1)'}), '(output, axis=1)\n', (4848, 4864), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np from ahfhalotools.objects import Cluster import ahfhalotools.filetools as ft import ahfhalotools.analysis as analysis ## -----------Load Cluster Instances--------------## #define base file name (these are for full files) fileNameBaseGX = "GadgetX-NewMDCLUSTER_0001.snap_{snap:0=3d}.z{z:.3f}" fileNameBaseGiz = "GIZMO-NewMDCLUSTER_0001.snap_{snap:0=3d}.z{z:.3f}" fileNameBaseMus = "GadgetMUSIC-NewMDCLUSTER_0001.z{z:.3f}" #define directory gxdir = "GadgetX\\NewMDCLUSTER_0001\\" gizdir = "gizmo\\" musdir = "music\\" #define snapshots to load snapNosGX = np.arange(97,129) snapNosGiz = np.arange(97,129) #n.b. music doesnt have snapshot numbers (bruh) #get snap num to redshift map zsMus = ft.getMusZs(musdir) rsmapGiz = ft.getSnapNumToZMapGiz(gizdir) rsmapGX = ft.getSnapNumToZMapGX(gxdir) snapNosMus = np.arange(129-len(zsMus),129) #get redshifts from snapNos zsGX = np.array([rsmapGX[num] for num in snapNosGX]) zsGiz = np.array([rsmapGiz[num] for num in snapNosGiz]) #truncated file names truncFileGX = "first10\\GadgetX\\GX_first10_snap{snap:0=3d}.z{z:.3f}" truncFileGiz = "first10\\Gizmo\\giz_first10_snap{snap:0=3d}.z{z:.3f}" truncFileMus = "first10\\Music\\mus_first10_snap.z{z:.3f}" #locations of enclosed halo files gxEncHaloFileBase = "gadgetXenchalos//GadgetX-NewMDCLUSTER_0001.halo{haloID}.BDP_enchalos" gizEncHaloFileBase = "gizmoenchalos//GIZMO-NewMDCLUSTER_0001.halo{haloID}.BDP_enchalos" musEncHaloFileBase = "gadgetMUSICenchalos//GadgetMUSIC-NewMDCLUSTER_0001.halo{haloID}.BDP_enchalos" #CLUSTER OBJECTS gxCluster = Cluster(truncFileGX, snapNosGX, zsGX) gizCluster = Cluster(truncFileGiz, snapNosGiz, zsGiz) musCluster = Cluster(truncFileMus, snapNosMus, zsMus) clusters = [gxCluster,gizCluster,musCluster] clusterNames = ["GadgetX","Gizmo","GadgetMUSIC"] clusterColors = ["C0","C1","C2"] #gxCluster.generateEnclosedHaloFilesFromChain(128000000000001,inputFiles,gxEncHaloFileBase) #gizCluster.generateEnclosedHaloFilesFromChain(128000000000001,inputFilesGiz,gizEncHaloFileBase) #musCluster.generateEnclosedHaloFilesFromChain(128000000000001,inputFilesMus,musEncHaloFileBase) #LOAD ENCLOSED HALO FILES gxCluster.loadEnclosedHaloFilesFromChain(128000000000001,gxEncHaloFileBase) gizCluster.loadEnclosedHaloFilesFromChain(128000000000001,gizEncHaloFileBase) musCluster.loadEnclosedHaloFilesFromChain(128000000000001,musEncHaloFileBase) ##----------PLOT-----------## ## comparing sims on deltaM/M over time for total mass, gas mass and Stellar # mass fig, axes = plt.subplots(1,3,figsize=(15,6),sharey='row') haloID = 128000000000001 axisTitles = ["Total Mass", "Gas Mass", "Stellar Mass"] quantities = ["Mvir", "M_gas", "M_star"] #plot on each axis for i in range(3): ax = axes[i] #loop through each simulation for j in range(3): color = clusterColors[j] cluster = clusters[j] ## can get delta values in two ways: #age, deltaM = cluster.funcOfAgeDeltaHaloData(haloID,quantities[i]) age, deltaM = cluster.funcOfAgeHaloData(haloID,"delta"+quantities[i]) _, M = cluster.funcOfAgeHaloData(haloID,quantities[i]) #M is going to be 1 element longer than deltaM, as we cannot get delta # for a quantity with unknown previous value # note that delta M should be divided by M of halo of *earlier* snapshot M = M[:-1] deltaMoverM = deltaM/M #deltaMoverM = deltaM #plot ax.plot(age,deltaMoverM, label=clusterNames[j],c=color) #add in line to represent time of largest merge mergeZ, mergeSize = cluster.getLargestMergeZInRange(haloID,0,1,scheme="halodata",fractional=False) mergeTime = analysis.tfromz(mergeZ) ls = ["--","-.",":"][j] ax.axvline(mergeTime,c=color,alpha=0.7,lw=(4-j),ls=ls) #set labels ax.set_title(axisTitles[i]) ax.set_xlabel("age, $t$ / Gyr") ax.set_ylabel("$\\frac{\\Delta M}{M}$") ax.legend() #annotate merge lines pad=15 topCoord = ax.get_ylim()[1] toppad = 0.02*(topCoord-ax.get_ylim()[0]) ax.annotate('Largest merger events\nusing halo data',xy=(mergeTime,topCoord-toppad),xytext=(-pad,0),xycoords="data", textcoords="offset points", ha="right", va="top", c = 'dimgrey') #set figure title fig.suptitle("$\\frac{\\Delta M}{M}$ as a function of age") plt.tight_layout() plt.show()
[ "ahfhalotools.filetools.getMusZs", "ahfhalotools.filetools.getSnapNumToZMapGiz", "ahfhalotools.objects.Cluster", "numpy.array", "matplotlib.pyplot.tight_layout", "ahfhalotools.analysis.tfromz", "ahfhalotools.filetools.getSnapNumToZMapGX", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.p...
[((643, 661), 'numpy.arange', 'np.arange', (['(97)', '(129)'], {}), '(97, 129)\n', (652, 661), True, 'import numpy as np\n'), ((674, 692), 'numpy.arange', 'np.arange', (['(97)', '(129)'], {}), '(97, 129)\n', (683, 692), True, 'import numpy as np\n'), ((779, 798), 'ahfhalotools.filetools.getMusZs', 'ft.getMusZs', (['musdir'], {}), '(musdir)\n', (790, 798), True, 'import ahfhalotools.filetools as ft\n'), ((810, 840), 'ahfhalotools.filetools.getSnapNumToZMapGiz', 'ft.getSnapNumToZMapGiz', (['gizdir'], {}), '(gizdir)\n', (832, 840), True, 'import ahfhalotools.filetools as ft\n'), ((851, 879), 'ahfhalotools.filetools.getSnapNumToZMapGX', 'ft.getSnapNumToZMapGX', (['gxdir'], {}), '(gxdir)\n', (872, 879), True, 'import ahfhalotools.filetools as ft\n'), ((959, 1004), 'numpy.array', 'np.array', (['[rsmapGX[num] for num in snapNosGX]'], {}), '([rsmapGX[num] for num in snapNosGX])\n', (967, 1004), True, 'import numpy as np\n'), ((1013, 1060), 'numpy.array', 'np.array', (['[rsmapGiz[num] for num in snapNosGiz]'], {}), '([rsmapGiz[num] for num in snapNosGiz])\n', (1021, 1060), True, 'import numpy as np\n'), ((1627, 1664), 'ahfhalotools.objects.Cluster', 'Cluster', (['truncFileGX', 'snapNosGX', 'zsGX'], {}), '(truncFileGX, snapNosGX, zsGX)\n', (1634, 1664), False, 'from ahfhalotools.objects import Cluster\n'), ((1678, 1718), 'ahfhalotools.objects.Cluster', 'Cluster', (['truncFileGiz', 'snapNosGiz', 'zsGiz'], {}), '(truncFileGiz, snapNosGiz, zsGiz)\n', (1685, 1718), False, 'from ahfhalotools.objects import Cluster\n'), ((1732, 1772), 'ahfhalotools.objects.Cluster', 'Cluster', (['truncFileMus', 'snapNosMus', 'zsMus'], {}), '(truncFileMus, snapNosMus, zsMus)\n', (1739, 1772), False, 'from ahfhalotools.objects import Cluster\n'), ((2575, 2624), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(15, 6)', 'sharey': '"""row"""'}), "(1, 3, figsize=(15, 6), sharey='row')\n", (2587, 2624), True, 'import matplotlib.pyplot as plt\n'), ((4407, 4425), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4423, 4425), True, 'import matplotlib.pyplot as plt\n'), ((4426, 4436), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4434, 4436), True, 'import matplotlib.pyplot as plt\n'), ((3741, 3764), 'ahfhalotools.analysis.tfromz', 'analysis.tfromz', (['mergeZ'], {}), '(mergeZ)\n', (3756, 3764), True, 'import ahfhalotools.analysis as analysis\n')]
import geopandas as gpd import pandas as pd import xarray as xr import numpy as np from pathlib import Path import sys import netCDF4 import datetime import metpy.calc as mpcalc from metpy.units import units # prsr = 101.3 * (((293.0-0.0065*Hru_elev_meters(i))/293.0)**5.26) def std_pres(elev): return 101.325 * (((293.0-0.0065*elev)/293.0)**5.26) def getaverage(data, wghts): try: v_ave = np.average(data, weights=wghts) except ZeroDivisionError: v_ave = netCDF4.default_fillvals['f8'] return v_ave def np_get_wval(ndata, wghts, hru_id=0, verbose=False): """ [Returns weighted average of ndata with weights] Args: ndata ([float]): [The subset of values associated with the gridmet id's that are mapped to hru_id] wghts ([float]): [Interpolation weights, user provided] hru_id (int, optional): [geometry id - can be used in debugging]. Defaults to 0. verbose(bool, optional): [If True print geometry id of masked values] Returns: [float]: [The weighted average of ndata based on weights wghts] """ mdata = np.ma.masked_array(ndata, np.isnan(ndata)) tmp = np.ma.average(mdata, weights=wghts) if tmp is np.ma.masked: if verbose: print(f'returning masked value: {hru_id}', ndata) return netCDF4.default_fillvals['f8'] else: return tmp class Grd2Shp: """ Class to map or interpolate gridded data (netCDF, Grib) data (focused on climate for now) onto geometry (Polygon) using area-weighted averages or rasterstats zonal statistics """ def __init__(self): self.shp = None self.grd = None self.calctype = { 0: "area-weighted average", 1: "zonal average" } self.type = None self.wght_file = None self.wght_id = None self.gdf = None self.gdf1 = None self.numgeom = 0 self.numtimesteps = None self.unique_geom_ids = None self.time_var = None self.lat_var = None self.lon_var = None self.var = None self.var_output = None self._np_var = None self.str_start = None self.numvars = None self._start_date = None self._end_date = None self.current_time = None self.current_time_index = None def initialize(self, grd, shp, wght_file, time_var: str, lat_var: str, lon_var: str, var, var_output, opath: str, fileprefix: str = '', calctype: int = 0, ): if not isinstance(grd, list): raise ValueError(f'grd: {type(grd)} must be a list[xarray.Dataset]') else: for item in grd: if not isinstance(item, xr.Dataset): raise ValueError(f'Item {type(item)} - arg: grd must be an xarray.Dataset') self.grd = grd if not isinstance(shp, gpd.GeoDataFrame): raise ValueError( f'shp: {shp} must be a Geopandas Datafram') self.shp = shp stringdict = {'time_var': time_var, 'lat_var': lat_var, 'lon_var': lon_var, 'fileprefix': fileprefix} for key, value in stringdict.items(): if not isinstance(value, str): raise ValueError(f'arguement: {key}:{value} must be a string') self.time_var = time_var self.lat_var = lat_var self.lon_var = lon_var self.fileprefix = fileprefix if not isinstance(var, list): raise ValueError(f'Arguement var:{var} must be a list of strings. Enclose in []') if not len(grd) == len(var): raise ValueError(f'Length of grd: {len(grd)} must be equal to length of var: {len(var)}') for item in var: if not isinstance(item, str): raise ValueError(f'Item in var: {item} must be a string') self.var = var if not isinstance(var_output, list): raise ValueError(f'Arguement var:{var_output} must be a list of strings. Enclose in []') if not len(var_output) == len(var): raise ValueError(f'Length of var_output: {len(var_output)} must be equal to length of var: {len(var)}') for item in var_output: if not isinstance(item, str): raise ValueError(f'Item in var: {item} must be a string') self.var_output = var_output self.opath = Path(opath) if self.opath.exists(): print('output path exists', flush=True) else: sys.exit(f'Output Path does not exist: {self.opath} - EXITING') try: calctype in self.calctype except ValueError as ve: print(f'calctype {calctype} must be one of Calculation Types {self.calctype}') raise ve self.type = calctype try: self.wght_file = pd.read_csv(wght_file) except IOError as ie: raise IOError(f'Weight File error: {ie}') try: self.gdf = shp self.gdf.reset_index(drop=True, inplace=True) except IOError as ie: raise IOError(f'Geometry File error: {ie}') # grab the geom_id from the weights file and use as identifier below self.wght_id = self.wght_file.columns[1] # this geodataframe merges all hru-ids and dissolves so the length of the index # equals the number of hrus self.gdf1 = self.gdf.sort_values(self.wght_id).dissolve(by=self.wght_id) self.numgeom = len(self.gdf1.index) self.geomindex = np.asarray(self.gdf1.index, dtype=np.int) # group by the weights_id for processing self.unique_geom_ids = self.wght_file.groupby(self.wght_id) # grab some helpful vars. Assumption is dims are same for all vars! self.numvars = len(self.var) self.numtimesteps = self.grd[0].dims[self.time_var] self.str_start = np.datetime_as_string(self.grd[0][self.time_var][0], unit='D') self._start_date = self.grd[0][self.time_var][0] self._end_date = self.grd[0][self.time_var][self.numtimesteps-1] self.current_time_index = 0 self.current_time = self.grd[0][self.time_var][self.current_time_index] self._np_var = np.zeros((self.numvars, self.numtimesteps, self.numgeom)) print(f'numtimesteps: {self.numtimesteps} and Start date: {self.str_start}') def run_weights(self): for index, tvar in enumerate(self.var): grid = self.grd[index] timestep = self.current_time_index print(f'Processing timestep: {timestep}', flush=True) val_interp = np.zeros(self.numgeom) val_flat_interp = grid[tvar].values[timestep, :, :].flatten(order='K') for i in np.arange(len(self.geomindex)): try: weight_id_rows = self.unique_geom_ids.get_group(self.geomindex[i]) tw = weight_id_rows.w.values tgid = weight_id_rows.grid_ids.values tmp = getaverage(val_flat_interp[tgid], tw) if np.isnan(tmp): val_interp[i] = np_get_wval(val_flat_interp[tgid], tw, self.geomindex[i]) else: val_interp[i] = tmp except KeyError: val_interp[i] = netCDF4.default_fillvals['f8'] if i % 10000 == 0: print(f' Processing {tvar} for hru {i}', flush=True) self._np_var[index, timestep, :] = val_interp[:] self.current_time_index += 1 # self.current_time = self.grd[0][self.time_var][self.current_time_index] @property def start_date(self): return self._start_date @property def end_date(self): return self._end_date @property def current_date(self): return self.current_date @property def num_timesteps(self): return self.numtimesteps @property def current_mapped_data(self): return self._np_var[:, self.current_time_index, :] def write_file(self, elev_file, punits=0, datetag=None, filename=None, append=False): if datetag is None: datetag = str(datetime.datetime.now().strftime('%Y_%m_%d')) if not append: ncfile = netCDF4.Dataset( self.opath / (self.fileprefix + 'climate_' + datetag.strftime("%Y_%m_%d") + '.nc'), mode='w', format='NETCDF4_CLASSIC' ) def getxy(pt): return pt.x, pt.y centroidseries = self.gdf1.geometry.centroid.to_crs(epsg=4327) tlon, tlat = [list(t) for t in zip(*map(getxy, centroidseries))] # Global Attributes ncfile.Conventions = 'CF-1.8' ncfile.featureType = 'timeSeries' ncfile.history = '' sp_dim = len(self.gdf1.index) # Create dimensions ncfile.createDimension('geomid', size=sp_dim) # hru_id ncfile.createDimension('time', size=None) # unlimited axis (can be appended to). # Create Variables time = ncfile.createVariable('time', 'f4', ('time',)) time.long_name = 'time' time.standard_name = 'time' time.units = 'days since ' + self.str_start time.calendar = 'standard' time[:] = np.arange(0, self.current_time_index, dtype=np.float) hru = ncfile.createVariable('geomid', 'i', ('geomid',)) hru.cf_role = 'timeseries_id' hru.long_name = 'local model hru id' hru[:] = np.asarray(self.gdf1.index) lat = ncfile.createVariable('hru_lat', np.dtype(np.float32).char, ('geomid',)) lat.long_name = 'Latitude of HRU centroid' lat.units = 'degrees_north' lat.standard_name = 'hru_latitude' lat[:] = tlat lon = ncfile.createVariable('hru_lon', np.dtype(np.float32).char, ('geomid',)) lon.long_name = 'Longitude of HRU centroid' lon.units = 'degrees_east' lon.standard_name = 'hru_longitude' lon[:] = tlon # crs = ncfile.createVariable('crs', np.dtype(np.int)) # crs.GeoTransform = self.grd[0].crs.GeoTransform # # crs.NAME = self.grd[0].crs.NAME # crs.grid_mapping_name = self.grd[0].crs.grid_mapping_name # crs.inverse_flattening = self.grd[0].crs.inverse_flattening # crs.long_name = self.grd[0].crs.long_name # crs.longitude_of_prime_meridian = self.grd[0].crs.longitude_of_prime_meridian # crs.semi_major_axis = self.grd[0].crs.semi_major_axis # crs.spatial_ref = self.grd[0].crs.spatial_ref else: ncfile = netCDF4.Dataset( self.opath / (self.fileprefix + 'climate_' + str(datetime.datetime.now().strftime('%Y%m%d')) + '.nc'), mode='a', format='NETCDF_CLASSIC' ) for index, tvar in enumerate(self.var_output): vartype = self.grd[index][self.var[index]].dtype ncvar = ncfile.createVariable(tvar, vartype, ('time', 'geomid')) ncvar.fill_value = netCDF4.default_fillvals['f8'] ncvar.long_name = self.grd[index][self.var[index]].long_name ncvar.standard_name = self.grd[index][self.var[index]].standard_name ncvar.description = self.grd[index][self.var[index]].description # ncvar.grid_mapping = 'crs' ncvar.units = self.grd[index][self.var[index]].units if tvar in ['tmax', 'tmin']: if punits == 1: conv = units.degC ncvar[:, :] = units.Quantity(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\ .to(conv).magnitude ncvar.units = conv.format_babel() else: conv = units.degF # ncvar[:,:] = ((self._np_var[index, 0:self.current_time_index, :]-273.15)*1.8)+32.0 ncvar[:, :] = units.Quantity(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\ .to(conv).magnitude ncvar.units = conv.format_babel() elif tvar == 'prcp': if punits == 1: conv = units('mm') ncvar[:, :] = units.Quantity(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\ .to(conv).magnitude ncvar.units = conv.units.format_babel() else: conv = units('inch') ncvar[:, :] = units.Quantity(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\ .to(conv).magnitude ncvar.units = conv.units.format_babel() # else units are already in mm # ncvar[:,:] = np.multiply(self._np_var[index, 0:self.current_time_index, :], conv.magnitude) else: ncvar[:, :] = self._np_var[index, 0:self.current_time_index, :] ncvar.units = self.grd[index][self.var[index]].units elevf = gpd.read_file(elev_file, layer='hru_elev') elev = elevf['hru_elev'].values if all(x in self.var_output for x in ['tmax', 'tmin', 'shum']): tmax_ind = self.var_output.index('tmax') tmin_ind = self.var_output.index('tmin') shum_ind = self.var_output.index('shum') print(f'tmaxind: {tmax_ind}, tminind: {tmin_ind}, shumind: {shum_ind}') rel_h = np.zeros((self.current_time_index, self.numgeom)) for j in np.arange(np.int(self.numgeom)): pr = mpcalc.height_to_pressure_std(units.Quantity(elev[j], "m")) for i in np.arange(np.int(self.current_time_index)): tmax = units.Quantity(self._np_var[tmax_ind, i, j], units.kelvin) tmin = units.Quantity(self._np_var[tmin_ind, i, j], units.kelvin) spch = units.Quantity(self._np_var[shum_ind, i, j], "kg/kg") rhmax = mpcalc.relative_humidity_from_specific_humidity(pr, tmax, spch) rhmin = mpcalc.relative_humidity_from_specific_humidity(pr, tmin, spch) rel_h[i, j] = (rhmin.magnitude + rhmax.magnitude)/2.0 ncvar = ncfile.createVariable('humidity', rel_h.dtype, ('time', 'geomid')) ncvar.units = "1" ncvar.fill_value = netCDF4.default_fillvals['f8'] ncvar[:, :] = rel_h[0:self.current_time_index, :] ncfile.close()
[ "numpy.ma.average", "metpy.calc.relative_humidity_from_specific_humidity", "geopandas.read_file", "pathlib.Path", "numpy.average", "pandas.read_csv", "numpy.asarray", "datetime.datetime.now", "numpy.zeros", "numpy.isnan", "metpy.units.units", "sys.exit", "metpy.units.units.Quantity", "nump...
[((1163, 1198), 'numpy.ma.average', 'np.ma.average', (['mdata'], {'weights': 'wghts'}), '(mdata, weights=wghts)\n', (1176, 1198), True, 'import numpy as np\n'), ((410, 441), 'numpy.average', 'np.average', (['data'], {'weights': 'wghts'}), '(data, weights=wghts)\n', (420, 441), True, 'import numpy as np\n'), ((1136, 1151), 'numpy.isnan', 'np.isnan', (['ndata'], {}), '(ndata)\n', (1144, 1151), True, 'import numpy as np\n'), ((4646, 4657), 'pathlib.Path', 'Path', (['opath'], {}), '(opath)\n', (4650, 4657), False, 'from pathlib import Path\n'), ((5795, 5836), 'numpy.asarray', 'np.asarray', (['self.gdf1.index'], {'dtype': 'np.int'}), '(self.gdf1.index, dtype=np.int)\n', (5805, 5836), True, 'import numpy as np\n'), ((6154, 6216), 'numpy.datetime_as_string', 'np.datetime_as_string', (['self.grd[0][self.time_var][0]'], {'unit': '"""D"""'}), "(self.grd[0][self.time_var][0], unit='D')\n", (6175, 6216), True, 'import numpy as np\n'), ((6487, 6544), 'numpy.zeros', 'np.zeros', (['(self.numvars, self.numtimesteps, self.numgeom)'], {}), '((self.numvars, self.numtimesteps, self.numgeom))\n', (6495, 6544), True, 'import numpy as np\n'), ((13558, 13600), 'geopandas.read_file', 'gpd.read_file', (['elev_file'], {'layer': '"""hru_elev"""'}), "(elev_file, layer='hru_elev')\n", (13571, 13600), True, 'import geopandas as gpd\n'), ((13971, 14020), 'numpy.zeros', 'np.zeros', (['(self.current_time_index, self.numgeom)'], {}), '((self.current_time_index, self.numgeom))\n', (13979, 14020), True, 'import numpy as np\n'), ((4768, 4831), 'sys.exit', 'sys.exit', (['f"""Output Path does not exist: {self.opath} - EXITING"""'], {}), "(f'Output Path does not exist: {self.opath} - EXITING')\n", (4776, 4831), False, 'import sys\n'), ((5101, 5123), 'pandas.read_csv', 'pd.read_csv', (['wght_file'], {}), '(wght_file)\n', (5112, 5123), True, 'import pandas as pd\n'), ((6882, 6904), 'numpy.zeros', 'np.zeros', (['self.numgeom'], {}), '(self.numgeom)\n', (6890, 6904), True, 'import numpy as np\n'), ((9670, 9723), 'numpy.arange', 'np.arange', (['(0)', 'self.current_time_index'], {'dtype': 'np.float'}), '(0, self.current_time_index, dtype=np.float)\n', (9679, 9723), True, 'import numpy as np\n'), ((9905, 9932), 'numpy.asarray', 'np.asarray', (['self.gdf1.index'], {}), '(self.gdf1.index)\n', (9915, 9932), True, 'import numpy as np\n'), ((14048, 14068), 'numpy.int', 'np.int', (['self.numgeom'], {}), '(self.numgeom)\n', (14054, 14068), True, 'import numpy as np\n'), ((14118, 14146), 'metpy.units.units.Quantity', 'units.Quantity', (['elev[j]', '"""m"""'], {}), "(elev[j], 'm')\n", (14132, 14146), False, 'from metpy.units import units\n'), ((14179, 14210), 'numpy.int', 'np.int', (['self.current_time_index'], {}), '(self.current_time_index)\n', (14185, 14210), True, 'import numpy as np\n'), ((14236, 14294), 'metpy.units.units.Quantity', 'units.Quantity', (['self._np_var[tmax_ind, i, j]', 'units.kelvin'], {}), '(self._np_var[tmax_ind, i, j], units.kelvin)\n', (14250, 14294), False, 'from metpy.units import units\n'), ((14318, 14376), 'metpy.units.units.Quantity', 'units.Quantity', (['self._np_var[tmin_ind, i, j]', 'units.kelvin'], {}), '(self._np_var[tmin_ind, i, j], units.kelvin)\n', (14332, 14376), False, 'from metpy.units import units\n'), ((14400, 14453), 'metpy.units.units.Quantity', 'units.Quantity', (['self._np_var[shum_ind, i, j]', '"""kg/kg"""'], {}), "(self._np_var[shum_ind, i, j], 'kg/kg')\n", (14414, 14453), False, 'from metpy.units import units\n'), ((14478, 14541), 'metpy.calc.relative_humidity_from_specific_humidity', 'mpcalc.relative_humidity_from_specific_humidity', (['pr', 'tmax', 'spch'], {}), '(pr, tmax, spch)\n', (14525, 14541), True, 'import metpy.calc as mpcalc\n'), ((14566, 14629), 'metpy.calc.relative_humidity_from_specific_humidity', 'mpcalc.relative_humidity_from_specific_humidity', (['pr', 'tmin', 'spch'], {}), '(pr, tmin, spch)\n', (14613, 14629), True, 'import metpy.calc as mpcalc\n'), ((7344, 7357), 'numpy.isnan', 'np.isnan', (['tmp'], {}), '(tmp)\n', (7352, 7357), True, 'import numpy as np\n'), ((9985, 10005), 'numpy.dtype', 'np.dtype', (['np.float32'], {}), '(np.float32)\n', (9993, 10005), True, 'import numpy as np\n'), ((10245, 10265), 'numpy.dtype', 'np.dtype', (['np.float32'], {}), '(np.float32)\n', (10253, 10265), True, 'import numpy as np\n'), ((8470, 8493), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (8491, 8493), False, 'import datetime\n'), ((12705, 12716), 'metpy.units.units', 'units', (['"""mm"""'], {}), "('mm')\n", (12710, 12716), False, 'from metpy.units import units\n'), ((12984, 12997), 'metpy.units.units', 'units', (['"""inch"""'], {}), "('inch')\n", (12989, 12997), False, 'from metpy.units import units\n'), ((12058, 12136), 'metpy.units.units.Quantity', 'units.Quantity', (['self._np_var[index, 0:self.current_time_index, :]', 'ncvar.units'], {}), '(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\n', (12072, 12136), False, 'from metpy.units import units\n'), ((12435, 12513), 'metpy.units.units.Quantity', 'units.Quantity', (['self._np_var[index, 0:self.current_time_index, :]', 'ncvar.units'], {}), '(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\n', (12449, 12513), False, 'from metpy.units import units\n'), ((12751, 12829), 'metpy.units.units.Quantity', 'units.Quantity', (['self._np_var[index, 0:self.current_time_index, :]', 'ncvar.units'], {}), '(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\n', (12765, 12829), False, 'from metpy.units import units\n'), ((13032, 13110), 'metpy.units.units.Quantity', 'units.Quantity', (['self._np_var[index, 0:self.current_time_index, :]', 'ncvar.units'], {}), '(self._np_var[index, 0:self.current_time_index, :], ncvar.units)\n', (13046, 13110), False, 'from metpy.units import units\n'), ((11172, 11195), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (11193, 11195), False, 'import datetime\n')]
#!/usr/bin/python3 # -*- coding: utf-8 -*- ## Autor: <NAME> import numpy as np from bubble2 import Bubble2 from bworld import Bworld n = 1000 bubbles = [] bubbles.append(Bubble2(np.random.rand(n, 3) * 10, np.zeros((n, 3)), radius = (np.random.rand(n) / 6), color = (0.5, 0.8, 1.0, 0.8))) testworld = Bworld(bubbles, boundaries = np.asarray([[0, 20], [0,10], [0, 10]]))
[ "numpy.zeros", "numpy.asarray", "numpy.random.rand" ]
[((207, 223), 'numpy.zeros', 'np.zeros', (['(n, 3)'], {}), '((n, 3))\n', (215, 223), True, 'import numpy as np\n'), ((348, 387), 'numpy.asarray', 'np.asarray', (['[[0, 20], [0, 10], [0, 10]]'], {}), '([[0, 20], [0, 10], [0, 10]])\n', (358, 387), True, 'import numpy as np\n'), ((180, 200), 'numpy.random.rand', 'np.random.rand', (['n', '(3)'], {}), '(n, 3)\n', (194, 200), True, 'import numpy as np\n'), ((251, 268), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (265, 268), True, 'import numpy as np\n')]
""" This module provides helpers that describe some aspect of a layout. The two public classes are: * BasisBladeOrder * BasisVectorIds """ from typing import TypeVar, Generic, Sequence, Tuple, List, Optional import numpy as np import functools import operator from . import _numba_utils from ._bit_helpers import count_set_bits, set_bit_indices @_numba_utils.njit def canonical_reordering_sign_euclidean(bitmap_a, bitmap_b): """ Computes the sign for the product of bitmap_a and bitmap_b assuming a euclidean metric """ a = bitmap_a >> 1 sum_value = 0 while a != 0: sum_value = sum_value + count_set_bits(a & bitmap_b) a = a >> 1 if (sum_value & 1) == 0: return 1 else: return -1 def _is_unique(x) -> bool: return len(x) == len(set(x)) class BasisBladeOrder: """ Represents the storage order in memory of basis blade coefficients. Bitmaps represent which basis vectors are present in a basis blade. For instance, in an algebra with basis vectors :math:`e_w, e_x, e_y, e_z`, the basis blade :math:`e_xz` is represented with ``0b1010``. Note that this appears reversed because binary numbers are written with the nth bit first. Attributes ---------- index_to_bitmap : numpy.ndarray An array mapping storage indices to bitmaps. bitmap_to_indices : numpy.ndarray A reverse mapping of :attr:`index_to_bitmap`. If bitmaps are missing, this array contains ``-1``. grades : numpy.ndarray An array mapping indices to the grade of the basis vector, that is the number of bits in the bitmap. See also -------- BasisVectorIds.order_from_tuples """ def __init__(self, bitmaps): if not _is_unique(bitmaps): raise ValueError("blade bitmaps are not unique") self.index_to_bitmap = np.array(bitmaps, dtype=int) self.grades = np.zeros(len(self.index_to_bitmap)) for i, bitmap in enumerate(self.index_to_bitmap): self.grades[i] = count_set_bits(bitmap) # chosen so that no product of basis blades lies outside this mapping largest = np.bitwise_or.reduce(self.index_to_bitmap) + 1 self.bitmap_to_index = np.full(largest, -1, dtype=int) self.bitmap_to_index[self.index_to_bitmap] = np.arange(len(self.index_to_bitmap), dtype=int) def __repr__(self) -> str: bitmap_strs = ['{:b}'.format(bitmap) for bitmap in self.index_to_bitmap] max_bits = max((len(s) for s in bitmap_strs), default=0) bitmap_strs = ['0b' + s.rjust(max_bits, '0') for s in bitmap_strs] return "{}([{}])".format(type(self).__name__, ', '.join(bitmap_strs)) def __hash__(self) -> int: return hash(self.index_to_bitmap.tobytes()) def __eq__(self, other): if self is other: return True if not isinstance(other, BasisBladeOrder): return NotImplemented return np.array_equal(self.index_to_bitmap, other.index_to_bitmap) @classmethod def shortlex(cls, n_vectors: int) -> 'BasisBladeOrder': """ Get an optimized shortlex ordering. This sorts basis blades first by grade, and then lexicographically. """ return _ShortLexBasisBladeOrder(n_vectors) class _ShortLexBasisBladeOrder(BasisBladeOrder): # lgtm [py/missing-call-to-init] def __init__(self, n_vectors: int): # deliberately skip the base class init, we can do a little better self._n = n_vectors # could attempt to optimize this by avoiding going via python integers # and copying the raw logic from # python/cpython.git:Modules/itertoolsmodule.c@combinations_next. from clifford import _powerset self.index_to_bitmap = np.empty(2**n_vectors, dtype=int) self.grades = np.empty(2**n_vectors, dtype=int) self.bitmap_to_index = np.empty(2**n_vectors, dtype=int) for i, t in enumerate(_powerset([1 << i for i in range(n_vectors)])): bitmap = functools.reduce(operator.or_, t, 0) self.index_to_bitmap[i] = bitmap self.grades[i] = len(t) self.bitmap_to_index[bitmap] = i del t # enables an optimization inside itertools.combinations def __repr__(self): return 'BasisBladeOrder.shortlex({})'.format(self._n) def __eq__(self, other): if self is other: return True if not isinstance(other, _ShortLexBasisBladeOrder): return NotImplemented return self._n == other._n def __reduce__(self): return __class__, (self._n,) IdT = TypeVar('IdT') class BasisVectorIds(Generic[IdT]): """ Stores ids for the ordered set of basis vectors, typically integers. Provides helpers to convert between bitmaps indicating which vectors are present in a blade, and tuples of the original ids. For example:: >>> ids = BasisVectorIds([11, 22, 33]) >>> ids.bitmap_as_tuple(0b110) (22, 33) >>> sign, bitmap = ids.tuple_as_sign_and_bitmap((33, 22)) >>> assert sign, bitmap == (-1, 0b110) """ def __init__(self, blade_ids: Sequence[IdT]): if not _is_unique(blade_ids): raise ValueError("blade ids are not unique") self.values = blade_ids def bitmap_as_tuple(self, bitmap: int) -> Tuple[IdT]: """ Convert a bitmap representation into a tuple of ids. """ return tuple(self.values[n] for n in set_bit_indices(bitmap)) def id_as_bitmap(self, id: IdT) -> int: """ Convert the id of a single vector into a bitmap representation. """ try: return (1 << self.values.index(id)) except ValueError: raise ValueError("Unknown basis {}".format(id)) from None def tuple_as_sign_and_bitmap(self, blade: Tuple[IdT]) -> Tuple[int, int]: """ Convert a blade from a tuple of ids into a bitmap representation. """ bitmap_out = 0 s = 1 for b in blade: bitmap_b = self.id_as_bitmap(b) if bitmap_b & bitmap_out: raise ValueError("blade contains repeated basis vector {}".format(b)) # as we don't allow repeated indices, the euclidean version is fine s *= canonical_reordering_sign_euclidean(bitmap_out, bitmap_b) bitmap_out ^= bitmap_b return s, bitmap_out def order_from_tuples(self, blades: Sequence[Tuple[IdT]]) -> BasisBladeOrder: """ Produce an ordering from a set of tuples. This is the inverse of :meth:`order_as_tuples`. >>> ids = BasisVectorIds(['x', 'y']) >>> ids.order_from_tuples([(), ('y',), ('x', 'y'), ('x',)]) BasisBladeOrder([0b00, 0b10, 0b11, 0b01]) """ bitmaps = [] for blade in blades: s, bitmap = self.tuple_as_sign_and_bitmap(blade) if s != 1: raise NotImplementedError( "The blade {} is not canonical, and sign flips in storage " "are not supported. Did you mean {}?" .format(blade, self.bitmap_as_tuple(bitmap)) ) bitmaps.append(bitmap) return BasisBladeOrder(bitmaps) def order_as_tuples(self, ordering: BasisBladeOrder) -> List[Tuple[IdT]]: """ Represent an ordering with these ids. This is the inverse of :meth:`order_from_tuples`. >>> ids = BasisVectorIds(['x', 'y']) >>> ids.order_as_tuples(BasisBladeOrder([0b00, 0b10, 0b11, 0b01])) [(), ('y',), ('x', 'y'), ('x',)] """ return [self.bitmap_as_tuple(b) for b in ordering.index_to_bitmap] @classmethod def ordered_integers(cls, n: int, *, first_index: int = 1) -> 'BasisVectorIds[int]': """ Create a set of `n` sequential integers as ids, starting from `first_index`. """ # special type is an optimization return _OrderedIntegerBasisVectorIds(n, first_index=first_index) def augmented_with(self, n: int) -> 'BasisVectorIds': """ Return a new copy with `n` new ids at the end. """ value = list(self.values) next_id = max(value) + 1 value += list(range(next_id, next_id + n)) return BasisVectorIds(value) def __repr__(self) -> str: return '{}({!r})'.format(type(self).__name__, self.values) def __reduce__(self): return __class__, (self.values,) class _OrderedIntegerBasisVectorIds(BasisVectorIds[int]): def __init__(self, n, first_index=1): self._n = n self._first_index = first_index super().__init__(range(first_index, first_index + n)) def augmented_with(self, n): return _OrderedIntegerBasisVectorIds(self._n + n, first_index=self._first_index) def __repr__(self): if self._first_index == 1: return 'BasisVectorIds.ordered_integers({})'.format(self._n) else: return 'BasisVectorIds.ordered_integers({}, first_index={})'.format(self._n, self._first_index) def __reduce__(self): if self._first_index == 1: return __class__, (self._n,) else: return __class__, (self._n, self._first_index) def layout_short_name(layout) -> Optional[str]: """ helper to get the short name of a layout """ if hasattr(layout, '__name__') and '__module__' in layout.__dict__: return "{l.__module__}.{l.__name__}".format(l=layout) return None
[ "functools.reduce", "numpy.array", "numpy.empty", "numpy.array_equal", "numpy.bitwise_or.reduce", "numpy.full", "typing.TypeVar" ]
[((4666, 4680), 'typing.TypeVar', 'TypeVar', (['"""IdT"""'], {}), "('IdT')\n", (4673, 4680), False, 'from typing import TypeVar, Generic, Sequence, Tuple, List, Optional\n'), ((1879, 1907), 'numpy.array', 'np.array', (['bitmaps'], {'dtype': 'int'}), '(bitmaps, dtype=int)\n', (1887, 1907), True, 'import numpy as np\n'), ((2250, 2281), 'numpy.full', 'np.full', (['largest', '(-1)'], {'dtype': 'int'}), '(largest, -1, dtype=int)\n', (2257, 2281), True, 'import numpy as np\n'), ((2978, 3037), 'numpy.array_equal', 'np.array_equal', (['self.index_to_bitmap', 'other.index_to_bitmap'], {}), '(self.index_to_bitmap, other.index_to_bitmap)\n', (2992, 3037), True, 'import numpy as np\n'), ((3805, 3840), 'numpy.empty', 'np.empty', (['(2 ** n_vectors)'], {'dtype': 'int'}), '(2 ** n_vectors, dtype=int)\n', (3813, 3840), True, 'import numpy as np\n'), ((3861, 3896), 'numpy.empty', 'np.empty', (['(2 ** n_vectors)'], {'dtype': 'int'}), '(2 ** n_vectors, dtype=int)\n', (3869, 3896), True, 'import numpy as np\n'), ((3926, 3961), 'numpy.empty', 'np.empty', (['(2 ** n_vectors)'], {'dtype': 'int'}), '(2 ** n_vectors, dtype=int)\n', (3934, 3961), True, 'import numpy as np\n'), ((2172, 2214), 'numpy.bitwise_or.reduce', 'np.bitwise_or.reduce', (['self.index_to_bitmap'], {}), '(self.index_to_bitmap)\n', (2192, 2214), True, 'import numpy as np\n'), ((4060, 4096), 'functools.reduce', 'functools.reduce', (['operator.or_', 't', '(0)'], {}), '(operator.or_, t, 0)\n', (4076, 4096), False, 'import functools\n')]
from __future__ import absolute_import from builtins import next from builtins import range import os import math import os.path as op import re import shutil from nipype.interfaces.base import ( TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined) from arcana.exceptions import ArcanaUsageError from itertools import chain, groupby from nipype.interfaces.utility.base import Merge, MergeInputSpec from nipype.interfaces.utility import IdentityInterface from nipype.interfaces.io import IOBase, add_traits from nipype.utils.filemanip import filename_to_list from nipype.interfaces.base import OutputMultiPath, InputMultiPath import numpy as np from arcana.exceptions import ArcanaError, ArcanaDesignError from .base import split_extension bash_resources = op.abspath(op.join(op.dirname(__file__), 'resources', 'bash')) zip_path = op.join(bash_resources, 'zip.sh') targz_path = op.join(bash_resources, 'targz.sh') cp_path = op.join(bash_resources, 'copy_file.sh') cp_dir_path = op.join(bash_resources, 'copy_dir.sh') mkdir_path = op.join(bash_resources, 'make_dir.sh') special_char_re = re.compile(r'[^\w]') # class MergeInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): # axis = traits.Enum( # 'vstack', 'hstack', usedefault=True, # desc=('direction in which to merge, hstack requires same number ' # 'of elements in each input')) # no_flatten = traits.Bool( # False, usedefault=True, # desc='append to outlist instead of extending in vstack mode') # class MergeOutputSpec(TraitedSpec): # out = traits.List(desc='Merged output') # class Merge(IOBase): # """Basic interface class to merge inputs into a single list # Examples # -------- # >>> from nipype.interfaces.utility import Merge # >>> mi = Merge(3) # >>> mi.inputs.in1 = 1 # >>> mi.inputs.in2 = [2, 5] # >>> mi.inputs.in3 = 3 # >>> out = mi.run() # >>> out.outputs.out # [1, 2, 5, 3] # """ # input_spec = MergeInputSpec # output_spec = MergeOutputSpec # def __init__(self, numinputs=0, **inputs): # super(Merge, self).__init__(**inputs) # self._numinputs = numinputs # if numinputs > 0: # input_names = ['in%d' % (i + 1) for i in range(numinputs)] # elif numinputs == 0: # input_names = ['in_lists'] # else: # input_names = [] # add_traits(self.inputs, input_names) # def _list_outputs(self): # outputs = self._outputs().get() # out = [] # if self._numinputs == 0: # values = getattr(self.inputs, 'in_lists') # if not isdefined(values): # return outputs # else: # getval = lambda idx: getattr(self.inputs, 'in%d' % (idx + 1)) # values = [getval(idx) for idx in range(self._numinputs) # if isdefined(getval(idx))] # if self.inputs.axis == 'vstack': # for value in values: # if isinstance(value, list) and not self.inputs.no_flatten: # out.extend(value) # else: # out.append(value) # else: # lists = [filename_to_list(val) for val in values] # out = [[val[i] for val in lists] for i in range(len(lists[0]))] # if out: # outputs['out'] = out # return outputs class MergeTupleOutputSpec(TraitedSpec): # Not possible to specify variable length tuples given Nipype traits # extensions out = traits.Any(desc='Merged output') # @UndefinedVariable class MergeTuple(Merge): """Basic interface class to merge inputs into a single tuple Examples -------- >>> from nipype.interfaces.utility import Merge >>> mi = MergeTuple(3) >>> mi.inputs.in1 = 1 >>> mi.inputs.in2 = [2, 5] >>> mi.inputs.in3 = 3 >>> out = mi.run() >>> out.outputs.out (1, 2, 5, 3) """ input_spec = MergeInputSpec output_spec = MergeTupleOutputSpec def _list_outputs(self): outputs = super(MergeTuple, self)._list_outputs() outputs['out'] = tuple(outputs['out']) return outputs class Chain(IdentityInterface): def _list_outputs(self): outputs = super(Chain, self)._list_outputs() chained_outputs = {} for k, v in outputs.items(): chained_outputs[k] = list(chain(*v)) return chained_outputs def dicom_fname_sort_key(fname): in_parts = special_char_re.split(op.basename(fname)) out_parts = [] for part in in_parts: try: part = int(part) except ValueError: pass out_parts.append(part) return tuple(out_parts) class JoinPathInputSpec(TraitedSpec): dirname = Directory(mandatory=True, desc='directory name') filename = traits.Str(mandatory=True, desc='file name') class JoinPathOutputSpec(TraitedSpec): path = traits.Str(mandatory=True, desc="The joined path") class JoinPath(BaseInterface): """Joins a filename to a directory name""" input_spec = JoinPathInputSpec output_spec = JoinPathOutputSpec def _list_outputs(self): outputs = self._outputs().get() outputs['path'] = op.join(self.inputs.dirname, self.inputs.filename) return outputs def _run_interface(self, runtime): return runtime class CopyFileInputSpec(CommandLineInputSpec): src = File(mandatory=True, desc='source file', argstr='%s', position=0) base_dir = Directory(mandatory=True, desc='root directory', argstr='%s', position=1) dst = File(genfile=True, argstr='%s', position=2, desc=("The destination file")) class CopyFileOutputSpec(TraitedSpec): copied = File(exists=True, desc="The copied file") basedir = Directory(exists=True, desc='base directory') class CopyFile(CommandLine): """Creates a copy of a given file""" _cmd = cp_path input_spec = CopyFileInputSpec output_spec = CopyFileOutputSpec def _list_outputs(self): outputs = self._outputs().get() outputs['copied'] = op.join(self.inputs.base_dir, self.inputs.dst) outputs['basedir'] = op.join(self.inputs.base_dir) return outputs def _gen_filename(self, name): if name == 'copied': fname = op.basename(self.inputs.dst) else: assert False return fname class CopyDirInputSpec(CommandLineInputSpec): src = File(mandatory=True, desc='source file', argstr='%s', position=0) base_dir = Directory(mandatory=True, desc='root directory', argstr='%s', position=1) dst = File(genfile=True, argstr='%s', position=2, desc=("The destination file")) method = traits.Int(mandatory=True, desc='method', argstr='%s', position=3) class CopyDirOutputSpec(TraitedSpec): copied = Directory(exists=True, desc="The copied file") basedir = Directory(exists=True, desc='base directory') class CopyDir(CommandLine): """Creates a copy of a given file""" _cmd = cp_dir_path input_spec = CopyDirInputSpec output_spec = CopyDirOutputSpec def _list_outputs(self): outputs = self._outputs().get() if self.inputs.method == 1: outputs['copied'] = op.join(self.inputs.base_dir) outputs['basedir'] = op.join(self.inputs.base_dir) elif self.inputs.method == 2: outputs['copied'] = op.join(self.inputs.base_dir, self._gen_filename('copied')) outputs['basedir'] = op.join(self.inputs.base_dir) return outputs def _gen_filename(self, name): if name == 'copied': fname = op.basename(self.inputs.dst) else: assert False return fname class MakeDirInputSpec(CommandLineInputSpec): base_dir = Directory(mandatory=True, desc='root directory', argstr='%s', position=0) name_dir = Directory(genfile=True, argstr='%s', position=1, desc=("name of the new directory")) class MakeDirOutputSpec(TraitedSpec): new_dir = Directory(exists=True, desc="The created directory") class MakeDir(CommandLine): """Creates a new directory""" _cmd = mkdir_path input_spec = MakeDirInputSpec output_spec = MakeDirOutputSpec def _list_outputs(self): outputs = self._outputs().get() outputs['new_dir'] = op.join(self.inputs.base_dir) # self._gen_filename('new_dir')) return outputs def _gen_filename(self, name): if name == 'new_dir': fname = op.basename(self.inputs.name_dir) else: assert False return fname class ZipDirInputSpec(CommandLineInputSpec): dirname = Directory(mandatory=True, desc='directory name', argstr='%s', position=1) zipped = File(genfile=True, argstr='%s', position=0, desc=("The zipped zip file")) ext_prefix = traits.Str( mandatory=False, default='', usedefault=True, desc=("Extra extension to prepend before .zip is appended to " "file name")) class ZipDirOutputSpec(TraitedSpec): zipped = File(exists=True, desc="The zipped directory") class ZipDir(CommandLine): """Creates a zip repository from a given folder""" _cmd = zip_path input_spec = ZipDirInputSpec output_spec = ZipDirOutputSpec zip_ext = '.zip' def _list_outputs(self): outputs = self._outputs().get() outputs['zipped'] = op.abspath( self._gen_filename('zipped')) return outputs def _gen_filename(self, name): if name == 'zipped': if isdefined(self.inputs.zipped): fname = self.inputs.zipped else: fname = (op.basename(self.inputs.dirname) + self.inputs.ext_prefix + self.zip_ext) else: assert False return fname class UnzipDirInputSpec(CommandLineInputSpec): zipped = Directory(mandatory=True, desc='zipped file name', argstr='%s', position=0) class UnzipDirOutputSpec(TraitedSpec): unzipped = Directory(exists=True, desc="The unzipped directory") class UnzipDir(CommandLine): """Unzips a folder that was zipped by ZipDir""" _cmd = 'unzip -qo' input_spec = UnzipDirInputSpec output_spec = UnzipDirOutputSpec def _run_interface(self, *args, **kwargs): self.listdir_before = set(os.listdir(os.getcwd())) return super(UnzipDir, self)._run_interface(*args, **kwargs) def _list_outputs(self): outputs = self._outputs().get() new_files = set(os.listdir(os.getcwd())) - self.listdir_before if len(new_files) > 1: raise ArcanaUsageError( "Zip repositorys can only contain a single directory, found " "'{}'".format("', '".join(new_files))) try: unzipped = next(iter(new_files)) except StopIteration: raise ArcanaUsageError( "No files or directories found in unzipped directory") outputs['unzipped'] = op.join(os.getcwd(), unzipped) return outputs class CopyToDirInputSpec(TraitedSpec): in_files = traits.List( traits.Either(File(exists=True), Directory(exists=True)), mandatory=True, desc='input dicom files') out_dir = Directory(desc='the output dicom file') use_symlinks = traits.Bool( default=True, desc=("Whether it is okay to symlink the inputs into the directory " "instead of copying them"), usedefault=True) file_names = traits.List( traits.Str, desc=("The filenames to use to save the files with within " "the directory")) class CopyToDirOutputSpec(TraitedSpec): out_dir = Directory(exists=True, desc='the output dicom directory') file_names = traits.List( traits.Str, desc="the files/directories copied to the new directory") class CopyToDir(BaseInterface): """ Copies a list of files of directories into a directory. By default the input files/directories will only be symlinked into the output directory for performance reasons. """ input_spec = CopyToDirInputSpec output_spec = CopyToDirOutputSpec def _run_interface(self, runtime): return runtime def _list_outputs(self): outputs = self._outputs().get() dirname = self.out_dir os.makedirs(dirname) num_files = len(self.inputs.in_files) if isdefined(self.inputs.file_names): if len(self.inputs.file_names) != num_files: raise ArcanaError( "Number of provided filenames ({}) does not match number " "of provided files ({})".format( len(self.inputs.file_names), num_files)) out_files = (op.basename(f) for f in self.inputs.file_names) else: # Create filenames that will sort ascendingly with the order the # file is inputed to the interface ndigits = int(math.ceil(math.log10(num_files))) out_files = [] for i, fname in enumerate(self.inputs.in_files): ext = split_extension(fname)[1] if ext is None: ext_str = '' else: ext_str = ext out_files.append(str(i).zfill(ndigits) + ext_str) file_names = [] for in_file, out_file in zip(self.inputs.in_files, out_files): out_path = op.join(self.out_dir, out_file) if self.inputs.use_symlinks: os.symlink(in_file, out_path) else: if op.isdir(in_file): shutil.copytree(in_file, out_path) else: shutil.copy(in_file, out_path) file_names.append(op.basename(out_path)) outputs['out_dir'] = dirname outputs['file_names'] = file_names return outputs @property def out_dir(self): if isdefined(self.inputs.out_dir): dpath = self.inputs.out_dir else: dpath = op.abspath('store_dir') return dpath class ListDirInputSpec(TraitedSpec): directory = File(mandatory=True, desc='directory to read') filter = traits.Callable( desc=("A callable (e.g. function) used to filter the filenames")) sort_key = traits.Callable( desc=("A callable (e.g. function) that generates a key from the " "listed filenames with which to sort them with")) group_key = traits.Callable( desc=("A callable (e.g. function) that generates a key with which to" "group the filenames")) class ListDirOutputSpec(TraitedSpec): files = traits.List(File(exists=True), desc='The files present in the directory') groups = traits.Dict(traits.Str, traits.List(File(exists=True)), desc="The files grouped by the 'group_key' function") class ListDir(BaseInterface): """ Lists all files (not sub-directories) in a directory """ input_spec = ListDirInputSpec output_spec = ListDirOutputSpec def _run_interface(self, runtime): return runtime def _list_outputs(self): dname = self.inputs.directory outputs = self._outputs().get() key = self.inputs.sort_key if isdefined(self.inputs.sort_key) else None files = [] for fname in os.listdir(dname): path = op.join(dname, fname) if op.isfile(path) and (not isdefined(self.inputs.filter) or self.inputs.filter(fname)): files.append(fname) files = [op.join(dname, f) for f in sorted(files, key=key)] if isdefined(self.inputs.group_key): outputs['groups'] = dict( (k, list(values)) for k, values in groupby(files, key=self.inputs.group_key)) outputs['files'] = files return outputs class TarGzDirInputSpec(CommandLineInputSpec): dirname = Directory(mandatory=True, desc='directory name', argstr='%s', position=1) zipped = File(genfile=True, argstr='%s', position=0, desc=("The tar_gz file")) class TarGzDirOutputSpec(TraitedSpec): zipped = File(exists=True, desc="The tar_gz directory") class TarGzDir(CommandLine): """Creates a tar_gzip repository from a given folder""" _cmd = targz_path input_spec = TarGzDirInputSpec output_spec = TarGzDirOutputSpec targz_ext = '.tar.gz' def _list_outputs(self): outputs = self._outputs().get() outputs['zipped'] = op.join(os.getcwd(), self._gen_filename('zipped')) return outputs def _gen_filename(self, name): if name == 'zipped': fname = op.basename(self.inputs.dirname) + self.targz_ext else: assert False return fname class UnTarGzDirInputSpec(CommandLineInputSpec): gzipped = Directory(mandatory=True, argstr='%s', position=0, desc=("The tar_gz file")) class UnTarGzDirOutputSpec(TraitedSpec): gunzipped = Directory(exists=True, desc="The gunzipped directory") class UnTarGzDir(CommandLine): """Unzip a folder created using TarGz""" _cmd = 'tar -zxvf ' input_spec = UnTarGzDirInputSpec output_spec = UnTarGzDirOutputSpec def _run_interface(self, *args, **kwargs): self.listdir_before = set(os.listdir(os.getcwd())) return super(UnTarGzDir, self)._run_interface(*args, **kwargs) def _list_outputs(self): outputs = self._outputs().get() new_files = set(os.listdir(os.getcwd())) - self.listdir_before if len(new_files) > 1: raise ArcanaUsageError( "Zip repositorys can only contain a single directory, found " "'{}'".format("', '".join(new_files))) try: unzipped = next(iter(new_files)) except StopIteration: raise ArcanaUsageError( "No files or directories found in unzipped directory") outputs['gunzipped'] = op.join(os.getcwd(), unzipped) return outputs class SelectOneInputSpec(BaseInterfaceInputSpec): inlist = InputMultiPath( traits.Any, mandatory=True, desc='list of values to choose from') index = traits.Int(mandatory=True, desc='0-based indice of element to extract') class SelectOneOutputSpec(TraitedSpec): out = OutputMultiPath(traits.Any, desc='selected value') class SelectOne(IOBase): """Basic interface class to select an element from a list""" input_spec = SelectOneInputSpec output_spec = SelectOneOutputSpec def _list_outputs(self): outputs = self._outputs().get() out = np.array(self.inputs.inlist)[self.inputs.index] outputs['out'] = out return outputs class SelectSessionInputSpec(BaseInterfaceInputSpec): inlist = InputMultiPath( traits.Any, mandatory=True, desc='List of items to select from') subject_ids = traits.List(traits.Str, mandatory=True, desc=('List of subject IDs corresponding to the ' 'provided items')) visit_ids = traits.List(traits.Str, mandatory=True, desc=('List of visit IDs corresponding to the ' 'provided items')) subject_id = traits.Str(mandatory=True, desc='Subject ID') visit_id = traits.Str(mandatory=True, desc='Visit ID') class SelectSessionOutputSpec(TraitedSpec): out = traits.Any(desc='selected value') class SelectSession(IOBase): """Basic interface class to select session from a list""" input_spec = SelectSessionInputSpec output_spec = SelectSessionOutputSpec def _list_outputs(self): outputs = self._outputs().get() if len(self.inputs.subject_ids) != len(self.inputs.inlist): raise ArcanaDesignError( "Length of subject IDs ({}) doesn't match that of input items " "({})".format(len(self.inputs.subject_ids), len(self.inputs.inlist))) if len(self.inputs.visit_ids) != len(self.inputs.inlist): raise ArcanaDesignError( "Length of visit IDs ({}) doesn't match that of input items " "({})".format(len(self.inputs.visit_ids), len(self.inputs.inlist))) session_ids = list(zip(self.inputs.subject_ids, self.inputs.visit_ids)) index = session_ids.index((self.inputs.subject_id, self.inputs.visit_id)) outputs['out'] = self.inputs.inlist[index] return outputs
[ "nipype.interfaces.base.OutputMultiPath", "itertools.chain", "nipype.interfaces.base.InputMultiPath", "re.compile", "nipype.interfaces.base.traits.Bool", "numpy.array", "arcana.exceptions.ArcanaUsageError", "math.log10", "nipype.interfaces.base.Directory", "os.listdir", "nipype.interfaces.base.t...
[((935, 968), 'os.path.join', 'op.join', (['bash_resources', '"""zip.sh"""'], {}), "(bash_resources, 'zip.sh')\n", (942, 968), True, 'import os.path as op\n'), ((982, 1017), 'os.path.join', 'op.join', (['bash_resources', '"""targz.sh"""'], {}), "(bash_resources, 'targz.sh')\n", (989, 1017), True, 'import os.path as op\n'), ((1028, 1067), 'os.path.join', 'op.join', (['bash_resources', '"""copy_file.sh"""'], {}), "(bash_resources, 'copy_file.sh')\n", (1035, 1067), True, 'import os.path as op\n'), ((1082, 1120), 'os.path.join', 'op.join', (['bash_resources', '"""copy_dir.sh"""'], {}), "(bash_resources, 'copy_dir.sh')\n", (1089, 1120), True, 'import os.path as op\n'), ((1134, 1172), 'os.path.join', 'op.join', (['bash_resources', '"""make_dir.sh"""'], {}), "(bash_resources, 'make_dir.sh')\n", (1141, 1172), True, 'import os.path as op\n'), ((1193, 1213), 're.compile', 're.compile', (['"""[^\\\\w]"""'], {}), "('[^\\\\w]')\n", (1203, 1213), False, 'import re\n'), ((3657, 3689), 'nipype.interfaces.base.traits.Any', 'traits.Any', ([], {'desc': '"""Merged output"""'}), "(desc='Merged output')\n", (3667, 3689), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((4895, 4943), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""directory name"""'}), "(mandatory=True, desc='directory name')\n", (4904, 4943), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((4959, 5003), 'nipype.interfaces.base.traits.Str', 'traits.Str', ([], {'mandatory': '(True)', 'desc': '"""file name"""'}), "(mandatory=True, desc='file name')\n", (4969, 5003), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((5056, 5106), 'nipype.interfaces.base.traits.Str', 'traits.Str', ([], {'mandatory': '(True)', 'desc': '"""The joined path"""'}), "(mandatory=True, desc='The joined path')\n", (5066, 5106), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((5586, 5651), 'nipype.interfaces.base.File', 'File', ([], {'mandatory': '(True)', 'desc': '"""source file"""', 'argstr': '"""%s"""', 'position': '(0)'}), "(mandatory=True, desc='source file', argstr='%s', position=0)\n", (5590, 5651), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((5682, 5755), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""root directory"""', 'argstr': '"""%s"""', 'position': '(1)'}), "(mandatory=True, desc='root directory', argstr='%s', position=1)\n", (5691, 5755), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((5791, 5863), 'nipype.interfaces.base.File', 'File', ([], {'genfile': '(True)', 'argstr': '"""%s"""', 'position': '(2)', 'desc': '"""The destination file"""'}), "(genfile=True, argstr='%s', position=2, desc='The destination file')\n", (5795, 5863), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((5935, 5976), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)', 'desc': '"""The copied file"""'}), "(exists=True, desc='The copied file')\n", (5939, 5976), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((5991, 6036), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'desc': '"""base directory"""'}), "(exists=True, desc='base directory')\n", (6000, 6036), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((6661, 6726), 'nipype.interfaces.base.File', 'File', ([], {'mandatory': '(True)', 'desc': '"""source file"""', 'argstr': '"""%s"""', 'position': '(0)'}), "(mandatory=True, desc='source file', argstr='%s', position=0)\n", (6665, 6726), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((6757, 6830), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""root directory"""', 'argstr': '"""%s"""', 'position': '(1)'}), "(mandatory=True, desc='root directory', argstr='%s', position=1)\n", (6766, 6830), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((6866, 6938), 'nipype.interfaces.base.File', 'File', ([], {'genfile': '(True)', 'argstr': '"""%s"""', 'position': '(2)', 'desc': '"""The destination file"""'}), "(genfile=True, argstr='%s', position=2, desc='The destination file')\n", (6870, 6938), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((6969, 7035), 'nipype.interfaces.base.traits.Int', 'traits.Int', ([], {'mandatory': '(True)', 'desc': '"""method"""', 'argstr': '"""%s"""', 'position': '(3)'}), "(mandatory=True, desc='method', argstr='%s', position=3)\n", (6979, 7035), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((7089, 7135), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'desc': '"""The copied file"""'}), "(exists=True, desc='The copied file')\n", (7098, 7135), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((7150, 7195), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'desc': '"""base directory"""'}), "(exists=True, desc='base directory')\n", (7159, 7195), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((8085, 8158), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""root directory"""', 'argstr': '"""%s"""', 'position': '(0)'}), "(mandatory=True, desc='root directory', argstr='%s', position=0)\n", (8094, 8158), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((8199, 8286), 'nipype.interfaces.base.Directory', 'Directory', ([], {'genfile': '(True)', 'argstr': '"""%s"""', 'position': '(1)', 'desc': '"""name of the new directory"""'}), "(genfile=True, argstr='%s', position=1, desc=\n 'name of the new directory')\n", (8208, 8286), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((8363, 8415), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'desc': '"""The created directory"""'}), "(exists=True, desc='The created directory')\n", (8372, 8415), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((9041, 9114), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""directory name"""', 'argstr': '"""%s"""', 'position': '(1)'}), "(mandatory=True, desc='directory name', argstr='%s', position=1)\n", (9050, 9114), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((9152, 9223), 'nipype.interfaces.base.File', 'File', ([], {'genfile': '(True)', 'argstr': '"""%s"""', 'position': '(0)', 'desc': '"""The zipped zip file"""'}), "(genfile=True, argstr='%s', position=0, desc='The zipped zip file')\n", (9156, 9223), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((9261, 9394), 'nipype.interfaces.base.traits.Str', 'traits.Str', ([], {'mandatory': '(False)', 'default': '""""""', 'usedefault': '(True)', 'desc': '"""Extra extension to prepend before .zip is appended to file name"""'}), "(mandatory=False, default='', usedefault=True, desc=\n 'Extra extension to prepend before .zip is appended to file name')\n", (9271, 9394), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((9478, 9524), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)', 'desc': '"""The zipped directory"""'}), "(exists=True, desc='The zipped directory')\n", (9482, 9524), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((10312, 10387), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""zipped file name"""', 'argstr': '"""%s"""', 'position': '(0)'}), "(mandatory=True, desc='zipped file name', argstr='%s', position=0)\n", (10321, 10387), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((10467, 10520), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'desc': '"""The unzipped directory"""'}), "(exists=True, desc='The unzipped directory')\n", (10476, 10520), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((11695, 11734), 'nipype.interfaces.base.Directory', 'Directory', ([], {'desc': '"""the output dicom file"""'}), "(desc='the output dicom file')\n", (11704, 11734), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((11754, 11898), 'nipype.interfaces.base.traits.Bool', 'traits.Bool', ([], {'default': '(True)', 'desc': '"""Whether it is okay to symlink the inputs into the directory instead of copying them"""', 'usedefault': '(True)'}), "(default=True, desc=\n 'Whether it is okay to symlink the inputs into the directory instead of copying them'\n , usedefault=True)\n", (11765, 11898), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((11942, 12043), 'nipype.interfaces.base.traits.List', 'traits.List', (['traits.Str'], {'desc': '"""The filenames to use to save the files with within the directory"""'}), "(traits.Str, desc=\n 'The filenames to use to save the files with within the directory')\n", (11953, 12043), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((12135, 12192), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'desc': '"""the output dicom directory"""'}), "(exists=True, desc='the output dicom directory')\n", (12144, 12192), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((12210, 12296), 'nipype.interfaces.base.traits.List', 'traits.List', (['traits.Str'], {'desc': '"""the files/directories copied to the new directory"""'}), "(traits.Str, desc=\n 'the files/directories copied to the new directory')\n", (12221, 12296), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((14607, 14653), 'nipype.interfaces.base.File', 'File', ([], {'mandatory': '(True)', 'desc': '"""directory to read"""'}), "(mandatory=True, desc='directory to read')\n", (14611, 14653), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((14667, 14746), 'nipype.interfaces.base.traits.Callable', 'traits.Callable', ([], {'desc': '"""A callable (e.g. function) used to filter the filenames"""'}), "(desc='A callable (e.g. function) used to filter the filenames')\n", (14682, 14746), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((14773, 14909), 'nipype.interfaces.base.traits.Callable', 'traits.Callable', ([], {'desc': '"""A callable (e.g. function) that generates a key from the listed filenames with which to sort them with"""'}), "(desc=\n 'A callable (e.g. function) that generates a key from the listed filenames with which to sort them with'\n )\n", (14788, 14909), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((14944, 15058), 'nipype.interfaces.base.traits.Callable', 'traits.Callable', ([], {'desc': '"""A callable (e.g. function) that generates a key with which togroup the filenames"""'}), "(desc=\n 'A callable (e.g. function) that generates a key with which togroup the filenames'\n )\n", (14959, 15058), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((16455, 16528), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'desc': '"""directory name"""', 'argstr': '"""%s"""', 'position': '(1)'}), "(mandatory=True, desc='directory name', argstr='%s', position=1)\n", (16464, 16528), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((16566, 16633), 'nipype.interfaces.base.File', 'File', ([], {'genfile': '(True)', 'argstr': '"""%s"""', 'position': '(0)', 'desc': '"""The tar_gz file"""'}), "(genfile=True, argstr='%s', position=0, desc='The tar_gz file')\n", (16570, 16633), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((16708, 16754), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)', 'desc': '"""The tar_gz directory"""'}), "(exists=True, desc='The tar_gz directory')\n", (16712, 16754), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((17400, 17474), 'nipype.interfaces.base.Directory', 'Directory', ([], {'mandatory': '(True)', 'argstr': '"""%s"""', 'position': '(0)', 'desc': '"""The tar_gz file"""'}), "(mandatory=True, argstr='%s', position=0, desc='The tar_gz file')\n", (17409, 17474), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((17560, 17614), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)', 'desc': '"""The gunzipped directory"""'}), "(exists=True, desc='The gunzipped directory')\n", (17569, 17614), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((18658, 18743), 'nipype.interfaces.base.InputMultiPath', 'InputMultiPath', (['traits.Any'], {'mandatory': '(True)', 'desc': '"""list of values to choose from"""'}), "(traits.Any, mandatory=True, desc='list of values to choose from'\n )\n", (18672, 18743), False, 'from nipype.interfaces.base import OutputMultiPath, InputMultiPath\n'), ((18760, 18831), 'nipype.interfaces.base.traits.Int', 'traits.Int', ([], {'mandatory': '(True)', 'desc': '"""0-based indice of element to extract"""'}), "(mandatory=True, desc='0-based indice of element to extract')\n", (18770, 18831), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((18907, 18957), 'nipype.interfaces.base.OutputMultiPath', 'OutputMultiPath', (['traits.Any'], {'desc': '"""selected value"""'}), "(traits.Any, desc='selected value')\n", (18922, 18957), False, 'from nipype.interfaces.base import OutputMultiPath, InputMultiPath\n'), ((19378, 19457), 'nipype.interfaces.base.InputMultiPath', 'InputMultiPath', (['traits.Any'], {'mandatory': '(True)', 'desc': '"""List of items to select from"""'}), "(traits.Any, mandatory=True, desc='List of items to select from')\n", (19392, 19457), False, 'from nipype.interfaces.base import OutputMultiPath, InputMultiPath\n'), ((19485, 19593), 'nipype.interfaces.base.traits.List', 'traits.List', (['traits.Str'], {'mandatory': '(True)', 'desc': '"""List of subject IDs corresponding to the provided items"""'}), "(traits.Str, mandatory=True, desc=\n 'List of subject IDs corresponding to the provided items')\n", (19496, 19593), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((19676, 19782), 'nipype.interfaces.base.traits.List', 'traits.List', (['traits.Str'], {'mandatory': '(True)', 'desc': '"""List of visit IDs corresponding to the provided items"""'}), "(traits.Str, mandatory=True, desc=\n 'List of visit IDs corresponding to the provided items')\n", (19687, 19782), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((19862, 19907), 'nipype.interfaces.base.traits.Str', 'traits.Str', ([], {'mandatory': '(True)', 'desc': '"""Subject ID"""'}), "(mandatory=True, desc='Subject ID')\n", (19872, 19907), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((19923, 19966), 'nipype.interfaces.base.traits.Str', 'traits.Str', ([], {'mandatory': '(True)', 'desc': '"""Visit ID"""'}), "(mandatory=True, desc='Visit ID')\n", (19933, 19966), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((20023, 20056), 'nipype.interfaces.base.traits.Any', 'traits.Any', ([], {'desc': '"""selected value"""'}), "(desc='selected value')\n", (20033, 20056), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((879, 899), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (889, 899), True, 'import os.path as op\n'), ((4631, 4649), 'os.path.basename', 'op.basename', (['fname'], {}), '(fname)\n', (4642, 4649), True, 'import os.path as op\n'), ((5356, 5406), 'os.path.join', 'op.join', (['self.inputs.dirname', 'self.inputs.filename'], {}), '(self.inputs.dirname, self.inputs.filename)\n', (5363, 5406), True, 'import os.path as op\n'), ((6300, 6346), 'os.path.join', 'op.join', (['self.inputs.base_dir', 'self.inputs.dst'], {}), '(self.inputs.base_dir, self.inputs.dst)\n', (6307, 6346), True, 'import os.path as op\n'), ((6376, 6405), 'os.path.join', 'op.join', (['self.inputs.base_dir'], {}), '(self.inputs.base_dir)\n', (6383, 6405), True, 'import os.path as op\n'), ((8672, 8701), 'os.path.join', 'op.join', (['self.inputs.base_dir'], {}), '(self.inputs.base_dir)\n', (8679, 8701), True, 'import os.path as op\n'), ((12779, 12799), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (12790, 12799), False, 'import os\n'), ((12857, 12890), 'nipype.interfaces.base.isdefined', 'isdefined', (['self.inputs.file_names'], {}), '(self.inputs.file_names)\n', (12866, 12890), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((14401, 14431), 'nipype.interfaces.base.isdefined', 'isdefined', (['self.inputs.out_dir'], {}), '(self.inputs.out_dir)\n', (14410, 14431), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((15141, 15158), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)'}), '(exists=True)\n', (15145, 15158), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((15842, 15859), 'os.listdir', 'os.listdir', (['dname'], {}), '(dname)\n', (15852, 15859), False, 'import os\n'), ((16154, 16186), 'nipype.interfaces.base.isdefined', 'isdefined', (['self.inputs.group_key'], {}), '(self.inputs.group_key)\n', (16163, 16186), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((6514, 6542), 'os.path.basename', 'op.basename', (['self.inputs.dst'], {}), '(self.inputs.dst)\n', (6525, 6542), True, 'import os.path as op\n'), ((7499, 7528), 'os.path.join', 'op.join', (['self.inputs.base_dir'], {}), '(self.inputs.base_dir)\n', (7506, 7528), True, 'import os.path as op\n'), ((7562, 7591), 'os.path.join', 'op.join', (['self.inputs.base_dir'], {}), '(self.inputs.base_dir)\n', (7569, 7591), True, 'import os.path as op\n'), ((7933, 7961), 'os.path.basename', 'op.basename', (['self.inputs.dst'], {}), '(self.inputs.dst)\n', (7944, 7961), True, 'import os.path as op\n'), ((8886, 8919), 'os.path.basename', 'op.basename', (['self.inputs.name_dir'], {}), '(self.inputs.name_dir)\n', (8897, 8919), True, 'import os.path as op\n'), ((9974, 10003), 'nipype.interfaces.base.isdefined', 'isdefined', (['self.inputs.zipped'], {}), '(self.inputs.zipped)\n', (9983, 10003), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((11450, 11461), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (11459, 11461), False, 'import os\n'), ((11587, 11604), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)'}), '(exists=True)\n', (11591, 11604), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((11606, 11628), 'nipype.interfaces.base.Directory', 'Directory', ([], {'exists': '(True)'}), '(exists=True)\n', (11615, 11628), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((13893, 13924), 'os.path.join', 'op.join', (['self.out_dir', 'out_file'], {}), '(self.out_dir, out_file)\n', (13900, 13924), True, 'import os.path as op\n'), ((14507, 14530), 'os.path.abspath', 'op.abspath', (['"""store_dir"""'], {}), "('store_dir')\n", (14517, 14530), True, 'import os.path as op\n'), ((15276, 15293), 'nipype.interfaces.base.File', 'File', ([], {'exists': '(True)'}), '(exists=True)\n', (15280, 15293), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((15760, 15791), 'nipype.interfaces.base.isdefined', 'isdefined', (['self.inputs.sort_key'], {}), '(self.inputs.sort_key)\n', (15769, 15791), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((15880, 15901), 'os.path.join', 'op.join', (['dname', 'fname'], {}), '(dname, fname)\n', (15887, 15901), True, 'import os.path as op\n'), ((16092, 16109), 'os.path.join', 'op.join', (['dname', 'f'], {}), '(dname, f)\n', (16099, 16109), True, 'import os.path as op\n'), ((17073, 17084), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17082, 17084), False, 'import os\n'), ((18547, 18558), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (18556, 18558), False, 'import os\n'), ((19209, 19237), 'numpy.array', 'np.array', (['self.inputs.inlist'], {}), '(self.inputs.inlist)\n', (19217, 19237), True, 'import numpy as np\n'), ((4517, 4526), 'itertools.chain', 'chain', (['*v'], {}), '(*v)\n', (4522, 4526), False, 'from itertools import chain, groupby\n'), ((7795, 7824), 'os.path.join', 'op.join', (['self.inputs.base_dir'], {}), '(self.inputs.base_dir)\n', (7802, 7824), True, 'import os.path as op\n'), ((10793, 10804), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10802, 10804), False, 'import os\n'), ((11323, 11394), 'arcana.exceptions.ArcanaUsageError', 'ArcanaUsageError', (['"""No files or directories found in unzipped directory"""'], {}), "('No files or directories found in unzipped directory')\n", (11339, 11394), False, 'from arcana.exceptions import ArcanaUsageError\n'), ((13206, 13220), 'os.path.basename', 'op.basename', (['f'], {}), '(f)\n', (13217, 13220), True, 'import os.path as op\n'), ((13982, 14011), 'os.symlink', 'os.symlink', (['in_file', 'out_path'], {}), '(in_file, out_path)\n', (13992, 14011), False, 'import os\n'), ((14049, 14066), 'os.path.isdir', 'op.isdir', (['in_file'], {}), '(in_file)\n', (14057, 14066), True, 'import os.path as op\n'), ((14226, 14247), 'os.path.basename', 'op.basename', (['out_path'], {}), '(out_path)\n', (14237, 14247), True, 'import os.path as op\n'), ((15917, 15932), 'os.path.isfile', 'op.isfile', (['path'], {}), '(path)\n', (15926, 15932), True, 'import os.path as op\n'), ((17224, 17256), 'os.path.basename', 'op.basename', (['self.inputs.dirname'], {}), '(self.inputs.dirname)\n', (17235, 17256), True, 'import os.path as op\n'), ((17887, 17898), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17896, 17898), False, 'import os\n'), ((18419, 18490), 'arcana.exceptions.ArcanaUsageError', 'ArcanaUsageError', (['"""No files or directories found in unzipped directory"""'], {}), "('No files or directories found in unzipped directory')\n", (18435, 18490), False, 'from arcana.exceptions import ArcanaUsageError\n'), ((10981, 10992), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10990, 10992), False, 'import os\n'), ((13428, 13449), 'math.log10', 'math.log10', (['num_files'], {}), '(num_files)\n', (13438, 13449), False, 'import math\n'), ((14088, 14122), 'shutil.copytree', 'shutil.copytree', (['in_file', 'out_path'], {}), '(in_file, out_path)\n', (14103, 14122), False, 'import shutil\n'), ((14165, 14195), 'shutil.copy', 'shutil.copy', (['in_file', 'out_path'], {}), '(in_file, out_path)\n', (14176, 14195), False, 'import shutil\n'), ((18077, 18088), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (18086, 18088), False, 'import os\n'), ((10091, 10123), 'os.path.basename', 'op.basename', (['self.inputs.dirname'], {}), '(self.inputs.dirname)\n', (10102, 10123), True, 'import os.path as op\n'), ((15942, 15971), 'nipype.interfaces.base.isdefined', 'isdefined', (['self.inputs.filter'], {}), '(self.inputs.filter)\n', (15951, 15971), False, 'from nipype.interfaces.base import TraitedSpec, traits, BaseInterface, File, Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec, BaseInterfaceInputSpec, isdefined\n'), ((16293, 16334), 'itertools.groupby', 'groupby', (['files'], {'key': 'self.inputs.group_key'}), '(files, key=self.inputs.group_key)\n', (16300, 16334), False, 'from itertools import chain, groupby\n')]