prompt
stringlengths
15
655k
completion
stringlengths
3
32.4k
api
stringlengths
8
52
from tkinter import * from tkinter.filedialog import * from tkinter.messagebox import showerror from tkinter import messagebox from tkinter import ttk import os import numpy as np import pandas as pd from pandas import * import gdal from gdal import * import cython from cython.parallel import * from multiprocessing import Pool import math import numpy import statsmodels.api import statsmodels as sm import statsmodels.robust from rasterstats import zonal_stats from sklearn.svm import SVR from sklearn.neural_network import MLPRegressor from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import * from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestRegressor from sklearn.neighbors import KNeighborsRegressor #Field_sites,Independent_bands =0,0 # ask_yes_no.py import shutil from shutil import copyfile import glob #1 def normalize(array1,maxmins='not'): try: array1=np.array(array1) except: pass if maxmins=='not': maxmins=[] #i=-1 for i in range(np.shape(array1)[1]): #print(i) column1=array1[:,i] if maxmins=='not': max1,min1=max(column1),min(column1) else: max1,min1=maxmins[i] for j in range(len(column1)): column1[j]=(float(column1[j])-float(min1))/(float(max1)-float(min1)) array1[:,i]=column1 return array1,maxmins #array1,maxmins=normalize(xx) def inv_normalize(array1,maxmins): for i in range(np.shape(array1)[1]): column1=array1[:,i] for i in range(len(column1)): max1,min1=maxmins[i] column1[i]=float(column1[i])*(float(max1)-float(min1))+float(min1) array1[:,i]=column1 return column1 def FindFilesInFolder(folder1,extension): dr=os.getcwd() os.chdir(folder1) files=glob.glob(extension) os.chdir(dr) return files #1 def object_zonal_stats(shp,TIF): stats = zonal_stats(shp, TIF,stats=['mean']) return list([f['mean'] for f in stats]) def object_zonal_stats_list(shp,TIFs_list):#for the all images of the same band same dataset(all subsets) for tif in TIFs_list: #statsall=[] stats=np.array(object_zonal_stats(shp,tif)) try: statsall=statsall+stats except: statsall=np.array(stats) return statsall #test #shp='C:/Users/ahalboabidallah/Desktop/Hi_RS_Data/tree_Segments.shp' #TIFs_list=['C:/Users/ahalboabidallah/Desktop/20151209-01/20150630-WV3-NPA-PIX-GBR-PAN-L3-01.tif', 'C:/Users/ahalboabidallah/Desktop/20151209-01/20150630-WV3-NPA-PIX-GBR-MS8-L3-01.tif'] #stats0=object_zonal_stats(shp,TIFs_list[0]) #stats1=object_zonal_stats(shp,TIFs_list[1]) #statsall=object_zonal_stats_list(shp,TIFs_list) from gdal import * #import ntpath #def copy_tif(raster, outraster): # #src_ds = gdal.Open(raster) # #driver = gdal.GetDriverByName('GTiff') # #dst_ds = driver.CreateCopy(outraster, src_ds, 0 ) # Once we're done, close properly the dataset #dst_ds = None #src_ds = None #folder1, file1= os.path.split(raster)#ntpath.split(raster) # folder2, file2=os.path.split(outraster) # l=len(file1[:-4]) # files=FindFilesInFolder(folder1,file1[:l]+'*') # for f in files: # shutil.copy(folder1+'/'+f,folder2+'/'+file2[:-4]+f[l:]) def shift_raster(raster, Dx,Dy,Dt, outraster):#Dx,Dy,Dt=sp_errorsX[L],sp_errorsY[L],sp_errorsT[L]*3.14/180 shutil.copy(raster,outraster) #copy_tif(raster, outraster) dataset = gdal.Open(raster) projection = dataset.GetProjection() geotransform = np.array(dataset.GetGeoTransform())+(Dx,0,Dt,Dy,Dt,0) dataset2 = gdal.Open(outraster, gdal.GA_Update) dataset2.SetGeoTransform( geotransform ) dataset2.SetProjection( projection ) #test #raster='C:/Users/ahalboabidallah/Desktop/20151209-01/20150630-WV3-NPA-PIX-GBR-PAN-L3-01.tif' #outraster='C:/Users/ahalboabidallah/Desktop/test.tif' #Dx,Dy,Dt=10.0,1.0,np.pi/4 #shift_raster(raster,Dx,Dy,Dt , outraster) def writetofile(path,file1,list1,NoOfColumns=3): try: os.stat(path) except: os.makedirs(path) #convert to pandas df=DataFrame(list1) #write to csv df.to_csv(path+file1,index=False,header=False) def readtopandas(path1,file1,alradyhasheader=0):# #F='C:/Users/ahalboabidallah/Desktop/test.csv' F=path1+file1 #add header to the file if there is no header # if alradyhasheader==0: #generate a header df = pd.read_csv(F,header=None) else: df = pd.read_csv(F)#needs a csv with a header line return df def readtolist(path,file1,NoOfColumns=3,alradyhasheader=0): df=readtopandas(path,file1,alradyhasheader=0) list1=df.values.tolist() return list1 def img2pandas(path1,file1): #open file try: src_dataset = gdal.Open(path1+file1) except: src_dataset = gdal.Open(path1+'/'+file1) z = src_dataset.ReadAsArray() #read georeferencing (xmin,res1,tilt1,ymin,tilt2,res2)=src_dataset.GetGeoTransform() ys,xs=np.shape(z) x = np.array([list(np.linspace(xmin, xmin+(xs-1)*res1, xs))]*(ys)) y = np.transpose(np.array([list(np.linspace(ymin, ymin+(ys-1)*res1, ys))]*(xs))) #z1=list(z.ravel()) #y1=list(y.ravel()) #1=list(x.ravel()) data=np.array([list(x.ravel()),list(y.ravel()),list(z.ravel())]) #'C:/Users/ahalboabidallah/Desktop/ash_farm_new/profiles/profiles/results/AllGround.tiff' return pd.DataFrame(data,index=['X','Y','Z']).transpose() def frrot3(theta,U0=numpy.matrix(numpy.identity(3))): ct = np.mat([[math.cos(theta[0])],[math.cos(theta[1])],[math.cos(theta[2])]]) st = np.mat([[math.sin(theta[0])],[math.sin(theta[1])],[math.sin(theta[2])]]) if max((theta.shape)) > 0: R1 = np.mat([[1,0,0],[0,ct[0],-st[0]],[0,st[0],ct[0]]]) R = R1; if max((theta.shape)) > 1: R2 = np.mat([[float(ct[1]),0,-st[1]],[0,1,0],[st[1],0,ct[1]]]); R = R2*R; if max((theta.shape)) > 2: R3 = np.mat([[float(ct[2]),-st[2],0],[st[2],ct[2],0],[0,0,1]]); R = R3*R; R = R*U0; #checked and vetted return (R,R1,R2,R3) def add_degree(xx): cols=list(xx.columns.values) #cols = cols[-1] + cols[:-1] xx1 = xx[cols[:-1]] yy=cols[-1] xx2=xx1*1 cols=list(xx1.columns.values) i=len(cols) i_up=i i_down=i for col in cols: for ii in range(i_down): i_up+=1 xx2[i_up] = xx1[col]*xx1[cols[-ii]] print('i_up',i_up,'col',col,'*',cols[-ii]) i_down-=1 cols=list(xx2.columns.values) cols = cols[-1:] + cols[:-1] xx2['yy']=xx[yy] return xx2 import copy from sklearn.externals import joblib #joblib.dump(Reg, 'filename.pkl') def iteration1(table1):# #table1=tables[0] print('>',end="") #if 1==1: [field_data,RStable,Processing,model_spec]=table1[:] RStable2=[] i=0 #to include all subsets #if 1==1: for fd1 in field_data: #fd1=field_data[0] #print('fd1',fd1) i+=1 RStable1=RStable[:] for rs in RStable1: #rs=RStable1[2] #print('f',rs) rs1=[rs[0]+'subset/'+str(i)+'/'] if rs[-1]==1 or rs[-1]=='1': expected_spectral_error=rs[0]+'subset/'+str(i)+'/error'+rs[1] else: expected_spectral_error=rs[-2] rs1.extend(rs[1:-2]) rs1.extend([expected_spectral_error,rs[-1]]) RStable2.append(rs1) RStable=RStable2[:] if Processing[0]=='Pixel':#if it is a pixel based model RStable=sorted(RStable,key=lambda l:-float(l[4]))#sort by resolution Lowest_resolution=float(RStable[0][4])# find lowest resolution fields,Fsp_errorsX,Fsp_errorsY,Fsp_errorsT=add_error(field_data)# adds errors to the field data #fields=list(filter(lambda a: a[2] > 0 and a[2] < 100000,fields[0])) rss0=no_error(RStable) fields0=no_error(field_data) Biomass0,rs_bands0=creat_table4corlation(rss0,fields0,RStable) Biomass0= np.asarray(Biomass0, dtype=float) while len(Biomass0[0])==1:# to get rid of unnecessary brackets Biomass0=list(map(lambda x:x[0], Biomass0)) rs_bands0[0]=list(filter(lambda a: a[2] > 0 and a[2] < 100000,rs_bands0[0])) yy0=regression_images(rs_bands0[0],Lowest_resolution,Lowest_resolution,Biomass0) xx0=[np.array(rs_bands0[0])[:,2].tolist()] for i in rs_bands0[1:]: #print('i') try: xx0.append(regression_images(rs_bands0[0],Lowest_resolution,Lowest_resolution,i))# except: print ('error') xx0.append(yy0)# now the pixel based table is ready for the model xx0=pd.DataFrame(xx0) xx0=xx0.transpose() xx0=xx0.dropna() #XX0= rss,Rsp_errorsX,Rsp_errorsY,Rsp_errorsT=add_error(RStable)# adds errors to the rss data Biomass,rs_bands=creat_table4corlation(rss,fields,RStable)# combines field data #combines any similar band and dataset RS inputs because they are subsetted from the same origional raster Biomass1 = np.asarray(Biomass, dtype=float) #k=0 while len(Biomass1[0])==1:# to get rid of unnecessary brackets #k+=1 #print('k') Biomass1=list(map(lambda x:x[0], Biomass1)) print('<<>>') #Biomass1=list(filter(lambda a: a > -0.0001 and a[2] < 100000,Biomass1)) rs_bands[0]=list(filter(lambda a: a[2] > 0 and a[2] < 100000,rs_bands[0])) yy=regression_images(rs_bands[0],Lowest_resolution,Lowest_resolution,Biomass1) xx=[np.array(rs_bands[0])[:,2].tolist()] for i in rs_bands[1:]: #print('i') try: xx.append(regression_images(rs_bands[0],Lowest_resolution,Lowest_resolution,i))# except: print ('error') xx.append(yy)# now the pixel based table is ready for the model xx=pd.DataFrame(xx) xx=xx.transpose() xx=xx.dropna() else: #if it is an object based fields,Fsp_errorsX,Fsp_errorsY,Fsp_errorsT=add_error_object(field_data,Processing[1]) rss,Rsp_errorsX,Rsp_errorsY,Rsp_errorsT=add_error_object(RStable,Processing[1]) Biomass,rs_bands=creat_table4corlation_object(rss,fields,RStable) xx=(np.array(rs_bands)).tolist() #xx=np.transpose(np.array(rs_bands)).tolist() xx.extend([Biomass]) xx=(np.transpose(np.array(xx)).tolist()) #filter sum(n < 0 for n in nums) xx=list(filter(lambda a: sum(n <= 0 for n in a)==0,xx)) xx=(np.transpose(np.array(xx)).tolist()) xx=pd.DataFrame(xx) xx=xx.transpose() xx=xx.dropna() # fields0=no_error_object(field_data,Processing[1]) rss0=no_error_object(RStable,Processing[1]) Biomass0,rs_bands0=creat_table4corlation_object(rss0,fields0,RStable) xx0=(np.array(rs_bands0)).tolist() #xx=np.transpose(np.array(rs_bands)).tolist() xx0.extend([Biomass0]) xx0=(np.transpose(np.array(xx0)).tolist()) #filter sum(n < 0 for n in nums) xx0=list(filter(lambda a: sum(n <= 0 for n in a)==0,xx0)) xx0=(np.transpose(np.array(xx0)).tolist()) xx0=pd.DataFrame(xx0) xx0=xx0.transpose() xx0=xx0.dropna() print('xx0',xx0) #xx.to_csv('C:/Users/ahalboabidallah/Desktop/mont_carlo/xx.csv',index=False,header=False) if model_spec[0]=='Parametric_Regression':#if the model is regression xx=xx.values.tolist() yy=list(map(lambda x:x[-1], xx)) xx=list(map(lambda x:x[0:-1], xx)) xx0=xx0.values.tolist() #yy0=list(map(lambda x:x[-1], xx)) xx0=list(map(lambda x:x[0:-1], xx0)) if model_spec[1]>1: xx=add_degrees(xx,model_spec[1]) xx0=add_degrees(xx0,model_spec[1]) model = sm.api.OLS(yy,xx)#len(final_table[1:].values.tolist())==len(final_table[0].values.tolist()) results = model.fit() print(results.summary()) #print('Parameters: ', results.params) #print('R2: ', results.rsquared) #record.append([i,[results.params],results.rsquared]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','results_rsquared.csv',[results.rsquared]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','results_params.csv',list(results.params)) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','RS_spatial_errors_Dx.csv',Rsp_errorsX) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','RS_spatial_errors_Dy.csv',Rsp_errorsY) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','RS_spatial_errors_Dt.csv',Rsp_errorsT) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','F_spatial_errors_Dx.csv',Fsp_errorsX) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','F_spatial_errors_Dy.csv',Fsp_errorsY) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','F_spatial_errors_Dt.csv',Fsp_errorsT) #Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','maxmins.csv',maxmins) file1='C:/Users/ahalboabidallah/Desktop/reg/'+str(randint(1000, 9999))+str(randint(1000, 9999))+'.pkl' joblib.dump(model, file1) yy1=results.predict(xx0) #yy1=results.predict(xx) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','YY.csv',yy1.tolist()) #print('yy1',yy1) elif model_spec[0]=='Support_Vector_Machine':#if the model is 'Support_Vector_Machine' #http://scikit-learn.org/stable/auto_examples/svm/plot_svm_regression.html#sphx-glr-auto-examples-svm-plot-svm-regression-py #http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=170DE91A676E6D5C328F5438063F57FF?doi=10.1.1.114.4288&rep=rep1&type=pdf #n_samples, n_features = 10, 5 #np.random.seed(0) #y = np.random.randn(n_samples) #X = np.random.randn(n_samples, n_features) xx=xx.values.tolist() xx,maxmins=normalize(xx) xx=list(xx) yy=np.array(list(map(lambda x:x[-1], xx))) xx=np.array(list(map(lambda x:x[0:-1], xx))) #yy0=np.array(list(map(lambda x:x[-1], xx0))) xx0=np.array(list(map(lambda x:x[0:-1], xx0))) kernel,degree=model_spec[1:] Reg = SVR(kernel=kernel,C=2000, epsilon=0.2,degree=degree) Reg.fit(xx, yy) R2=np.corrcoef([yy,Reg.predict(xx)])[0,1] file1='C:/Users/ahalboabidallah/Desktop/SVM/'+str(randint(1000, 9999))+str(randint(1000, 9999))+'.pkl' Add_line_to_file('C:/Users/ahalboabidallah/Desktop/SVM/','results_rsquared.csv',[file1,R2]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/SVM/','maxmins.csv',[maxmins]) #read the last in the csv file #add line to the csv file #s = pickle.dumps(Reg) joblib.dump(Reg, file1)#joblib.dump(Reg, 'filename.pkl') #Reg1 = joblib.load(file1) #Reg = joblib.load('filename.pkl') xx0=xx0.values.tolist() xx0,maxmins=normalize(xx0,maxmins=maxmins) xx0=list(xx0) yy1=Reg.predict(xx0) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','YY.csv',yy1.tolist()) elif model_spec[0]=='Neural Network':#if the model is 'Neural Network' NumberOfLayers,Layers=model_spec[1:] xx=xx.values.tolist() xx,maxmins=normalize(xx) xx=list(xx) yy=np.array(list(map(lambda x:x[-1], xx))) xx=np.array(list(map(lambda x:x[0:-1], xx))) # Reg = MLPRegressor(hidden_layer_sizes=Layers, activation='relu', solver='adam', alpha=0.001, batch_size='auto',learning_rate='constant', learning_rate_init=0.01, power_t=0.5, max_iter=1000, shuffle=True,random_state=9, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True,early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-05) Reg.fit(xx, yy) R2=np.corrcoef([yy,Reg.predict(xx)])[0,1] file1='C:/Users/ahalboabidallah/Desktop/Neural/'+str(randint(1000, 9999))+str(randint(1000, 9999))+'.pkl' Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Neural/','files.csv',[file1]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Neural/','results_rsquared.csv',[R2]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Neural/','maxmins.csv',[maxmins]) #read the last in the csv file #add line to the csv file #s = pickle.dumps(Reg) joblib.dump(Reg, file1)#joblib.dump(Reg, 'filename.pkl') #Reg1 = joblib.load(file1) #Reg = joblib.load('filename.pkl') xx0=xx0.values.tolist() xx0,maxmins=normalize(xx0,maxmins=maxmins) xx0=list(xx0) yy1=Reg.predict(xx0) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','YY.csv',yy1.tolist()) elif model_spec[0]=='Gaussian_Process':#if the model is 'Gaussian_Process' Gaussian_Process_kernal=model_spec[1] xx=xx.values.tolist() xx,maxmins=normalize(xx) xx=list(xx) yy=np.array(list(map(lambda x:x[-1], xx))) xx=np.array(list(map(lambda x:x[0:-1], xx))) # Reg = GaussianProcessRegressor(kernel=Gaussian_Process_kernal) Reg.fit(xx, yy) R2=np.corrcoef([yy,Reg.predict(xx)])[0,1] file1='C:/Users/ahalboabidallah/Desktop/Gaussian_Process/'+str(randint(1000, 9999))+str(randint(1000, 9999))+'.pkl' Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Gaussian_Process/','files.csv',[file1]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Gaussian_Process/','results_rsquared.csv',[R2]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Gaussian_Process/','maxmins.csv',[maxmins]) #read the last in the csv file #add line to the csv file #s = pickle.dumps(Reg) joblib.dump(Reg, file1)#joblib.dump(Reg, 'filename.pkl') #Reg1 = joblib.load(file1) #Reg = joblib.load('filename.pkl') ''' xx0=xx0.values.tolist() xx0,maxmins=normalize(xx0,maxmins=maxmins) xx0=list(xx0) yy1=Reg.predict(xx0) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','YY.csv',yy1.tolist()) elif model_spec[0]=='Random_Forest':#if the model is 'Random_Forest' Random_Forest_Bootstrap=model_spec[1] xx=xx.values.tolist() xx,maxmins=normalize(xx) xx=list(xx) yy=np.array(list(map(lambda x:x[-1], xx))) xx=np.array(list(map(lambda x:x[0:-1], xx))) # Reg = RandomForestRegressor(bootstrap=Random_Forest_Bootstrap) Reg.fit(xx, yy) R2=np.corrcoef([yy,Reg.predict(xx)])[0,1] file1='C:/Users/ahalboabidallah/Desktop/Random_Forest/'+str(randint(1000, 9999))+str(randint(1000, 9999))+'.pkl' Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Random_Forest/','files.csv',[file1]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Random_Forest/','results_rsquared.csv',[R2]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Random_Forest/','maxmins.csv',[maxmins]) #read the last in the csv file #add line to the csv file #s = pickle.dumps(Reg) joblib.dump(Reg, file1)#joblib.dump(Reg, 'filename.pkl') #Reg1 = joblib.load(file1) #Reg = joblib.load('filename.pkl') ''' xx0=xx0.values.tolist() xx0,maxmins=normalize(xx0,maxmins=maxmins) xx0=list(xx0) yy1=Reg.predict(xx0) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','YY.csv',yy1.tolist()) elif model_spec[0]=='K_Nearest_Neighbours':#if the model is 'K_Nearest_Neighbours' K_Nearest_Neighbours_weights,K_Nearest_Neighbours_k=model_spec[1:] xx=xx.values.tolist() xx,maxmins=normalize(xx) xx=list(xx) yy=np.array(list(map(lambda x:x[-1], xx))) xx=np.array(list(map(lambda x:x[0:-1], xx))) # Reg = KNeighborsRegressor(n_neighbors=2,weights =K_Nearest_Neighbours_weights) Reg.fit(xx, yy) R2=np.corrcoef([yy,Reg.predict(xx)])[0,1] file1='C:/Users/ahalboabidallah/Desktop/Random_Forest/'+str(randint(1000, 9999))+str(randint(1000, 9999))+'.pkl' Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Random_Forest/','files.csv',[file1]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Random_Forest/','results_rsquared.csv',[R2]) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/Random_Forest/','maxmins.csv',[maxmins]) #read the last in the csv file #add line to the csv file #s = pickle.dumps(Reg) joblib.dump(Reg, file1)#joblib.dump(Reg, 'filename.pkl') #Reg1 = joblib.load(file1) #Reg = joblib.load('filename.pkl') ''' xx0=xx0.values.tolist() xx0,maxmins=normalize(xx0,maxmins=maxmins) xx0=list(xx0) yy1=Reg.predict(xx0) Add_line_to_file('C:/Users/ahalboabidallah/Desktop/mont_carlo/','YY.csv',yy1.tolist()) print(np.shape(xx0)) #return yy1,xx0 def spatial_error_xy(table3): #images of the same dataset should take the same spatial error datasets=np.array((np.array(table3)[:,3]),dtype=float) sp_errors=list(datasets) for data1 in list(set(datasets)): #print ('data1',data1) expected_spatial_error=float(list(filter(lambda x: float(x[3])==data1, table3))[0][7]) e=np.random.normal(0, expected_spatial_error, 1)[0] sp_errors=list(map(lambda x:x if x!=data1 else e,sp_errors)) #replace sp_errors dataset with a random error return sp_errors def spatial_error_t(table3): #images of the same dataset should take the same spatial error datasets=np.array((np.array(table3)[:,3]),dtype=float) sp_errors=list(datasets) for data1 in list(set(datasets)): #print ('data1',data1) expected_orientation_error=float(list(filter(lambda x: float(x[3])==data1, table3))[0][8]) if expected_orientation_error != 0: e=
np.random.normal(0, expected_orientation_error, 1)
numpy.random.normal
import os import cv2 import numpy as np from oc_stereo.builders.config_builder_util import ConfigObj from oc_stereo.dataloader.kitti import calib_utils, depth_map_utils, instance_utils, evaluation # KITTI difficulty thresholds (easy, moderate, hard) HEIGHT = (40, 25, 25) OCCLUSION = (0, 1, 2) TRUNCATION = (0.15, 0.3, 0.5) # Mean object heights from hist_labels.py MEAN_HEIGHTS = { 'Car': 1.526, 'Pedestrian': 1.761, 'Cyclist': 1.737, } class Difficulty: # Values as integers for indexing EASY = 0 MODERATE = 1 HARD = 2 ALL = 3 # Mappings from difficulty to string DIFF_TO_STR_MAPPING = { EASY: 'easy', MODERATE: 'moderate', HARD: 'hard', ALL: 'all', } # Mappings from strings to difficulty STR_TO_DIFF_MAPPING = { 'easy': EASY, 'moderate': MODERATE, 'hard': HARD, 'all': ALL, } @staticmethod def to_string(difficulty): return Difficulty.DIFF_TO_STR_MAPPING[difficulty] @staticmethod def from_string(difficulty_str): return Difficulty.STR_TO_DIFF_MAPPING[difficulty_str] class ObjectFilter: def __init__(self, config): self.classes = config.classes self.difficulty = Difficulty.from_string(config.difficulty_str) self.box_2d_height = config.box_2d_height self.truncation = config.truncation self.occlusion = config.occlusion self.depth_range = config.depth_range @staticmethod def create_obj_filter(classes, difficulty, occlusion, truncation, box_2d_height, depth_range): config = ConfigObj() config.classes = classes config.difficulty_str = Difficulty.to_string(difficulty) config.occlusion = occlusion config.truncation = truncation config.box_2d_height = box_2d_height config.depth_range = depth_range return ObjectFilter(config) class ObjectLabel: """Object Label Fields: type (str): Object type, one of 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc', or 'DontCare' truncation (float): Truncation level, float from 0 (non-truncated) to 1 (truncated), where truncated refers to the object leaving image boundaries occlusion (int): Occlusion level, indicating occlusion state: 0 = fully visible, 1 = partly occluded, 2 = largely occluded, 3 = unknown alpha (float): Observation angle of object [-pi, pi] x1, y1, x2, y2 (float): 2D bounding box of object in the image. (top left, bottom right) h, w, l: 3D object dimensions: height, width, length (in meters) t: 3D object centroid x, y, z in camera coordinates (in meters) ry: Rotation around Y-axis in camera coordinates [-pi, pi] score: Only for results, indicating confidence in detection, needed for p/r curves. """ def __init__(self): self.type = None # Type of object self.truncation = 0.0 self.occlusion = 0 self.alpha = 0.0 self.x1 = 0.0 self.y1 = 0.0 self.x2 = 0.0 self.y2 = 0.0 self.h = 0.0 self.w = 0.0 self.l = 0.0 self.t = (0.0, 0.0, 0.0) self.ry = 0.0 self.score = 0.0 def __eq__(self, other): """Compares the given object to the current ObjectLabel instance. :param other: object to compare to this instance against :return: True, if other and current instance is the same """ if not isinstance(other, ObjectLabel): return False if self.__dict__ != other.__dict__: return False else: return True def __repr__(self): return '({}, a:{}, t:{} lwh:({:.03f}, {:.03f}, {:.03f}), ry:{:.03f})'.format( self.type, self.alpha, self.t, self.l, self.w, self.h, self.ry) def read_labels(label_dir, sample_name): """Reads in label data file from Kitti Dataset Args: label_dir: label directory sample_name: sample_name Returns: obj_list: list of ObjectLabels """ # Check label file label_path = label_dir + '/{}.txt'.format(sample_name) if not os.path.exists(label_path): raise ValueError('Label file could not be found:', label_path) if os.stat(label_path).st_size == 0: return [] labels = np.loadtxt(label_path, delimiter=' ', dtype=str, ndmin=2) num_rows, num_cols = labels.shape if num_cols not in [15, 16]: raise ValueError('Invalid label format') num_labels = num_rows is_results = num_cols == 16 obj_list = [] for obj_idx in np.arange(num_labels): obj = ObjectLabel() # Fill in the object list obj.type = labels[obj_idx, 0] obj.truncation = float(labels[obj_idx, 1]) obj.occlusion = float(labels[obj_idx, 2]) obj.alpha = float(labels[obj_idx, 3]) obj.x1, obj.y1, obj.x2, obj.y2 = (labels[obj_idx, 4:8]).astype(np.float32) obj.h, obj.w, obj.l = (labels[obj_idx, 8:11]).astype(np.float32) obj.t = (labels[obj_idx, 11:14]).astype(np.float32) obj.ry = float(labels[obj_idx, 14]) if is_results: obj.score = float(labels[obj_idx, 15]) else: obj.score = 0.0 obj_list.append(obj) return np.asarray(obj_list) def filter_labels_by_class(obj_labels, classes): """Filters object labels by classes. Args: obj_labels: List of object labels classes: List of classes to keep, e.g. ['Car', 'Pedestrian', 'Cyclist'] Returns: obj_labels: List of filtered labels class_mask: Mask of labels to keep """ class_mask = [(obj.type in classes) for obj in obj_labels] return obj_labels[class_mask], class_mask def filter_labels_by_difficulty(obj_labels, difficulty): """Filters object labels by difficulty. Args: obj_labels: List of object labels difficulty: Difficulty level Returns: obj_labels: List of filtered labels difficulty_mask: Mask of labels to keep """ difficulty_mask = [_check_difficulty(obj, difficulty) for obj in obj_labels] return obj_labels[difficulty_mask], difficulty_mask def _check_difficulty(obj, difficulty): if difficulty == Difficulty.ALL: return True return ((obj.occlusion <= OCCLUSION[difficulty]) and (obj.truncation <= TRUNCATION[difficulty]) and (obj.y2 - obj.y1) >= HEIGHT[difficulty]) def filter_labels_by_box_2d_height(obj_labels, box_2d_height): """Filters object labels by 2D box height. Args: obj_labels: List of object labels box_2d_height: Minimum 2D box height Returns: obj_labels: List of filtered labels height_mask: Mask of labels to keep """ height_mask = [(obj_label.y2 - obj_label.y1) > box_2d_height for obj_label in obj_labels] return obj_labels[height_mask], height_mask def filter_labels_by_truncation(obj_labels, truncation): """Filters object labels by truncation. Args: obj_labels: List of object labels truncation: Maximum truncation Returns: obj_labels: List of filtered labels trunc_mask: Mask of labels to keep """ trunc_mask = [obj_label.truncation < truncation for obj_label in obj_labels] return obj_labels[trunc_mask], trunc_mask def filter_labels_by_occlusion(obj_labels, occlusion): """Filters object labels by truncation. Args: obj_labels: List of object labels occlusion: Maximum occlusion Returns: obj_labels: List of filtered labels occ_mask: Mask of labels to keep """ occ_mask = [obj_label.occlusion < occlusion for obj_label in obj_labels] return obj_labels[occ_mask], occ_mask def filter_labels_by_depth_range(obj_labels, depth_range): """Filters object labels within a range of depth values. Args: obj_labels: List of object labels depth_range: Range of depth to keep objects Returns: obj_labels: List of filtered labels depth_mask: Mask of labels to keep """ depth_mask = [depth_range[0] < obj_label.t[2] < depth_range[1] for obj_label in obj_labels] return obj_labels[depth_mask], depth_mask def filter_labels(obj_labels, classes=None, difficulty=None, box_2d_height=None, occlusion=None, truncation=None, depth_range=None): """Filters object labels by various metrics. Args: obj_labels: List of object labels classes: List of classes to keep, e.g. ['Car', 'Pedestrian', 'Cyclist'] difficulty: Difficulty level box_2d_height: Minimum 2D box height occlusion: Minimum occlusion level truncation: Minimum truncation level depth_range: Range of depth to keep objects Returns: obj_labels: List of filtered labels obj_mask: Mask of labels to keep """ obj_mask = np.full(len(obj_labels), True) if classes is not None: _, class_mask = filter_labels_by_class(obj_labels, classes) obj_mask &= class_mask if difficulty is not None: _, difficulty_mask = filter_labels_by_difficulty(obj_labels, difficulty) obj_mask &= difficulty_mask if box_2d_height is not None: _, height_mask = filter_labels_by_box_2d_height(obj_labels, box_2d_height) obj_mask &= height_mask if occlusion is not None: _, occ_mask = filter_labels_by_occlusion(obj_labels, occlusion) obj_mask &= occ_mask if truncation is not None: _, trunc_mask = filter_labels_by_truncation(obj_labels, truncation) obj_mask &= trunc_mask if depth_range is not None: _, depth_mask = filter_labels_by_depth_range(obj_labels, depth_range) obj_mask &= depth_mask return obj_labels[obj_mask], obj_mask def apply_obj_filter(obj_labels, obj_filter): """Applies an ObjectFilter to a list of labels Args: obj_labels: obj_filter (ObjectFilter): Returns: obj_labels: List of filtered labels obj_mask: Mask of labels to keep """ obj_labels, obj_mask = filter_labels( obj_labels, classes=obj_filter.classes, difficulty=obj_filter.difficulty, box_2d_height=obj_filter.box_2d_height, occlusion=obj_filter.occlusion, truncation=obj_filter.truncation, depth_range=obj_filter.depth_range) return obj_labels, obj_mask def boxes_2d_from_obj_labels(obj_labels): return np.asarray([object_label_to_box_2d(obj_label) for obj_label in obj_labels], np.float32) def boxes_3d_from_obj_labels(obj_labels): return np.asarray([object_label_to_box_3d(obj_label) for obj_label in obj_labels], np.float32) def obj_classes_from_obj_labels(obj_labels): return np.asarray([obj_label.type for obj_label in obj_labels]) def get_image(sample_name, image_dir): image_path = image_dir + '/{}.png'.format(sample_name) image = cv2.imread(image_path) return image def get_instance_masks(sample_name, instance_dir, num_objs): """Gets the instance masks Args: sample_name: Sample name instance_dir: Instance directory num_objs: Total number of objects in the scene Returns: instance_masks: (N, H, W) Instance masks """ instance_img = instance_utils.get_instance_image(sample_name, instance_dir) instance_masks = instance_utils.get_instance_mask_list(instance_img, num_objs) return instance_masks def read_lidar(velo_dir, sample_name): """Reads the lidar bin file for a sample Args: velo_dir: velodyne directory sample_name: sample name Returns: xyzi: (N, 4) points and intensities """ velo_path = velo_dir + '/{}.bin'.format(sample_name) if os.path.exists(velo_path): with open(velo_path, 'rb') as fid: data_array = np.fromfile(fid, np.single) xyzi = data_array.reshape(-1, 4) return xyzi else: raise ValueError('Velodyne file not found') def get_lidar_point_cloud(sample_name, frame_calib, velo_dir): """Gets the lidar point cloud in cam0 frame. Args: sample_name: Sample name frame_calib: FrameCalib velo_dir: Velodyne directory Returns: (3, N) point_cloud in the form [[x,...][y,...][z,...]] """ xyzi = read_lidar(velo_dir, sample_name) # Calculate the point cloud points_in_lidar_frame = xyzi[:, 0:3] points = calib_utils.lidar_to_cam_frame(points_in_lidar_frame, frame_calib) return points.T def get_lidar_point_cloud_for_cam(sample_name, frame_calib, velo_dir, image_shape=None, cam_idx=2): """Gets the lidar point cloud in cam0 frame, and optionally returns only the points that are projected to an image. Args: sample_name: sample name frame_calib: FrameCalib frame calibration velo_dir: velodyne directory image_shape: (optional) image shape [h, w] to filter points inside image cam_idx: (optional) cam index (2 or 3) for filtering Returns: (3, N) point_cloud in the form [[x,...][y,...][z,...]] """ # Get points in camera frame point_cloud = get_lidar_point_cloud(sample_name, frame_calib, velo_dir) # Only keep points in front of camera (positive z) point_cloud = point_cloud[:, point_cloud[2] > 1.0] if image_shape is None: return point_cloud else: # Project to image frame if cam_idx == 2: cam_p = frame_calib.p2 elif cam_idx == 3: cam_p = frame_calib.p3 else: raise ValueError('Invalid cam_idx', cam_idx) # Project to image points_in_img = calib_utils.project_pc_to_image(point_cloud, cam_p=cam_p) points_in_img_rounded = np.round(points_in_img) # Filter based on the given image shape image_filter = (points_in_img_rounded[0] >= 0) & \ (points_in_img_rounded[0] < image_shape[1]) & \ (points_in_img_rounded[1] >= 0) & \ (points_in_img_rounded[1] < image_shape[0]) filtered_point_cloud = point_cloud[:, image_filter].astype(np.float32) return filtered_point_cloud def get_stereo_point_cloud(sample_name, calib_dir, disp_dir): """ Gets the point cloud for an image calculated from the disparity map :param sample_name: sample name :param calib_dir: directory with calibration files :param disp_dir: directory with disparity images :return: (3, N) point_cloud in the form [[x,...][y,...][z,...]] """ # Read calibration info frame_calib = calib_utils.get_frame_calib(calib_dir, sample_name) stereo_calibration_info = calib_utils.get_stereo_calibration(frame_calib.p2, frame_calib.p3) # Read disparity disp = cv2.imread(disp_dir + '/{}.png'.format(sample_name), cv2.IMREAD_ANYDEPTH) disp = np.float32(disp) disp = np.divide(disp, 256) disp[disp == 0] = 0.1 # Calculate the point cloud point_cloud = calib_utils.depth_from_disparity(disp, stereo_calibration_info) return point_cloud def get_depth_map_path(sample_name, depth_dir): return depth_dir + '/{}.png'.format(sample_name) def get_disp_map_path(sample_name, disp_dir): return disp_dir + '/{}.png'.format(sample_name) def get_disp_map(sample_name, disp_dir): disp_map_path = get_disp_map_path(sample_name, disp_dir) disp_map = cv2.imread(disp_map_path, cv2.IMREAD_ANYDEPTH) disp_map = disp_map / 256.0 return disp_map def get_depth_map(sample_name, depth_dir): depth_map_path = get_depth_map_path(sample_name, depth_dir) depth_map = depth_map_utils.read_depth_map(depth_map_path) return depth_map def get_depth_map_point_cloud(sample_name, frame_calib, depth_dir): """Calculates the point cloud from a depth map Args: sample_name: sample name frame_calib: FrameCalib frame calibration depth_dir: folder with depth maps cam_idx: cam index (2 or 3) Returns: (3, N) point_cloud in the form [[x,...][y,...][z,...]] """ depth_map_path = get_depth_map_path(sample_name, depth_dir) depth_map = depth_map_utils.read_depth_map(depth_map_path) depth_map_shape = depth_map.shape[0:2] # Calculate point cloud from depth map cam_p = frame_calib.p2 # cam_p = frame_calib.p2 if cam_idx == 2 else frame_calib.p3 # # TODO: Call depth_map_utils version return depth_map_utils.get_depth_point_cloud(depth_map, cam_p) # Calculate points from depth map depth_map_flattened = depth_map.flatten() xx, yy = np.meshgrid(np.arange(0, depth_map_shape[1], 1), np.arange(0, depth_map_shape[0], 1)) xx = xx.flatten() - cam_p[0, 2] yy = yy.flatten() - cam_p[1, 2] temp = np.divide(depth_map_flattened, cam_p[0, 0]) x = np.multiply(xx, temp) y = np.multiply(yy, temp) z = depth_map_flattened # Get x offset (b_cam) from calibration: cam_mat[0, 3] = (-f_x * b_cam) x_offset = -cam_p[0, 3] / cam_p[0, 0] point_cloud = np.asarray([x + x_offset, y, z]) return point_cloud.astype(np.float32) def compute_obj_label_corners_3d(object_label): """ Computes the 3D bounding box corner positions from an ObjectLabel :param object_label: ObjectLabel to compute corners from :return: a numpy array of 3D corners if the box is in front of the camera, an empty array otherwise """ # compute rotational matrix rot = np.array([[+np.cos(object_label.ry), 0, +np.sin(object_label.ry)], [0, 1, 0], [-np.sin(object_label.ry), 0, +np.cos(object_label.ry)]]) l = object_label.l w = object_label.w h = object_label.h # 3D BB corners x_corners = np.array( [l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2]) y_corners = np.array([0, 0, 0, 0, -h, -h, -h, -h]) z_corners = np.array( [w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2]) corners_3d = np.dot(rot, np.array([x_corners, y_corners, z_corners])) corners_3d[0, :] = corners_3d[0, :] + object_label.t[0] corners_3d[1, :] = corners_3d[1, :] + object_label.t[1] corners_3d[2, :] = corners_3d[2, :] + object_label.t[2] return corners_3d def compute_box_3d_corners(box_3d): """Computes box corners :param box_3d: input 3D boxes 1 x 7 array represented as [x, y, z, l, w, h, ry] :return: corners_3d: array of box corners 8 x [x y z] """ tx, ty, tz, l, w, h, ry = box_3d half_l = l / 2 half_w = w / 2 # Compute rotation matrix rot = np.array([[+np.cos(ry), 0, +np.sin(ry)], [0, 1, 0], [-np.sin(ry), 0, +np.cos(ry)]]) # 3D BB corners x_corners = np.array( [half_l, half_l, -half_l, -half_l, half_l, half_l, -half_l, -half_l]) y_corners = np.array([0, 0, 0, 0, -h, -h, -h, -h]) z_corners = np.array( [half_w, -half_w, -half_w, half_w, half_w, -half_w, -half_w, half_w]) corners_3d = np.dot(rot, np.array([x_corners, y_corners, z_corners])) corners_3d[0, :] = corners_3d[0, :] + tx corners_3d[1, :] = corners_3d[1, :] + ty corners_3d[2, :] = corners_3d[2, :] + tz return np.array(corners_3d) def points_in_box_3d(box_3d, points): """Finds the points inside a box_3d. Args: box_3d: box_3d points: (N, 3) points Returns: points in box_3d mask of points """ # Find box corners corners_3d = compute_box_3d_corners(box_3d).T # Compute box's principle axes u = corners_3d[0, :] - corners_3d[1, :] v = corners_3d[0, :] - corners_3d[3, :] w = corners_3d[0, :] - corners_3d[4, :] # Compute test bounds for point to be included inside bounding box up0 = np.dot(u, corners_3d[0, :]) up1 = np.dot(u, corners_3d[1, :]) vp0 = np.dot(v, corners_3d[0, :]) vp3 = np.dot(v, corners_3d[3, :]) wp0 = np.dot(w, corners_3d[0, :]) wp4 = np.dot(w, corners_3d[4, :]) # Compute dot product between point cloud and principle axes u_dot = np.matmul(points, u) v_dot = np.matmul(points, v) w_dot = np.matmul(points, w) # Create mask from bounds and return points inside bounding box mask_u = np.logical_and(u_dot <= up0, u_dot >= up1) mask_v = np.logical_and(v_dot <= vp0, v_dot >= vp3) mask_w = np.logical_and(w_dot <= wp0, w_dot >= wp4) mask = np.logical_and(mask_u, mask_v) mask =
np.logical_and(mask, mask_w)
numpy.logical_and
# Copyright 2018 The TensorFlow Probability 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. # ============================================================================ """Numpy implementations of TensorFlow functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow_probability.python.internal.backend.numpy import _utils as utils from tensorflow_probability.python.internal.backend.numpy import ops from tensorflow_probability.python.internal.backend.numpy.numpy_math import softmax as _softmax __all__ = [ 'stateless_binomial', 'stateless_categorical', 'gamma', 'stateless_gamma', 'stateless_normal', 'stateless_poisson', 'stateless_shuffle', 'stateless_uniform', 'set_seed', # 'all_candidate_sampler', # 'experimental', # 'fixed_unigram_candidate_sampler', # 'learned_unigram_candidate_sampler', # 'log_uniform_candidate_sampler', # 'stateless_truncated_normal', # 'truncated_normal', # 'uniform_candidate_sampler', ] JAX_MODE = False def _ensure_tuple(t): try: return tuple(t) except TypeError: return (t,) def _bcast_shape(base_shape, args): base_shape = _ensure_tuple(base_shape) if not args: return base_shape bc_arr = np.zeros(base_shape + (0,)) for arg in args: if arg is not None: bc_arr = bc_arr + np.zeros(np.shape(arg) + (0,)) return bc_arr.shape[:-1] def _binomial(shape, seed, counts, probs, output_dtype=np.int32, name=None): # pylint: disable=unused-argument rng = np.random if seed is None else np.random.RandomState(seed & 0xffffffff) probs = np.where(counts > 0, probs, 0) samps = rng.binomial(np.int64(counts), np.float64(probs), shape) return samps.astype(utils.numpy_dtype(output_dtype)) def _categorical(logits, num_samples, dtype=None, seed=None, name=None): # pylint: disable=unused-argument rng = np.random if seed is None else np.random.RandomState(seed & 0xffffffff) dtype = utils.numpy_dtype(dtype or np.int64) if not hasattr(logits, 'shape'): logits = np.array(logits, np.float32) probs = _softmax(logits) n = logits.shape[-1] return np.apply_along_axis(lambda p: rng.choice(n, p=p, size=num_samples), 1, probs) def _categorical_jax(logits, num_samples, dtype=None, seed=None, name=None): # pylint: disable=unused-argument """Jax implementation of `tf.random.stateless_categorical`.""" dtype = utils.numpy_dtype(dtype or np.int64) if not hasattr(logits, 'shape') or not hasattr(logits, 'dtype'): logits = np.array(logits, np.float32) import jax.random as jaxrand # pylint: disable=g-import-not-at-top if seed is None: raise ValueError('Must provide PRNGKey to sample in JAX.') z = jaxrand.gumbel( key=seed, shape=logits.shape + (num_samples,), dtype=logits.dtype) return np.argmax(np.expand_dims(logits, -1) + z, axis=-2).astype(dtype) def _gamma(shape, alpha, beta=None, dtype=np.float32, seed=None, name=None): # pylint: disable=unused-argument rng = np.random if seed is None else np.random.RandomState(seed & 0xffffffff) dtype = utils.common_dtype([alpha, beta], dtype_hint=dtype) scale = 1. if beta is None else (1. / beta) shape = _ensure_tuple(shape) return rng.gamma(shape=alpha, scale=scale, size=shape).astype(dtype) def _gamma_jax(shape, alpha, beta=None, dtype=np.float32, seed=None, name=None): # pylint: disable=unused-argument """JAX-based reparameterized gamma sampler.""" dtype = utils.common_dtype([alpha, beta], dtype_hint=dtype) alpha = np.array(alpha, dtype=dtype) beta = None if beta is None else np.array(beta, dtype=dtype) shape = _ensure_tuple(shape) import jax.random as jaxrand # pylint: disable=g-import-not-at-top if seed is None: raise ValueError('Must provide PRNGKey to sample in JAX.') # TODO(srvasude): Sample in the given dtype once # https://github.com/google/jax/issues/2130 is fixed. samps = jaxrand.gamma( key=seed, a=alpha, shape=shape, dtype=np.float64).astype(dtype) # Match the 0->tiny behavior of tf.random.gamma. return np.maximum(np.finfo(dtype).tiny, samps if beta is None else samps / beta) def _normal(shape, mean=0.0, stddev=1.0, dtype=np.float32, seed=None, name=None): # pylint: disable=unused-argument rng = np.random if seed is None else np.random.RandomState(seed & 0xffffffff) dtype = utils.common_dtype([mean, stddev], dtype_hint=dtype) shape = _bcast_shape(shape, [mean, stddev]) return rng.normal(loc=mean, scale=stddev, size=shape).astype(dtype) def _normal_jax(shape, mean=0.0, stddev=1.0, dtype=np.float32, seed=None, name=None): # pylint: disable=unused-argument dtype = utils.common_dtype([mean, stddev], dtype_hint=dtype) shape = _bcast_shape(shape, [mean, stddev]) import jax.random as jaxrand # pylint: disable=g-import-not-at-top if seed is None: raise ValueError('Must provide PRNGKey to sample in JAX.') return jaxrand.normal(key=seed, shape=shape, dtype=dtype) * stddev + mean def _poisson(shape, lam, dtype=np.float32, seed=None, name=None): # pylint: disable=unused-argument rng = np.random if seed is None else
np.random.RandomState(seed & 0xffffffff)
numpy.random.RandomState
import numpy as np import tensorflow as tf from waymo_open_dataset import dataset_pb2 from waymo_open_dataset.utils import range_image_utils, transform_utils def convert_range_image_to_point_cloud( frame, range_images, camera_projections, range_image_top_pose ): """Convert range images to point cloud. Args: frame: open dataset frame range_images: A dict of {laser_name, [range_image_first_return, range_image_second_return]}. camera_projections: A dict of {laser_name, [camera_projection_from_first_return, camera_projection_from_second_return]}. range_image_top_pose: range image pixel pose for top lidar. Returns: points: {[N, 3]} list of 3d lidar points of length 5 (number of lidars). cp_points: {[N, 6]} list of camera projections of length 5 (number of lidars). """ calibrations = sorted(frame.context.laser_calibrations, key=lambda c: c.name) points = [] r_points = [] i_points = [] e_points = [] cp_points = [] frame_pose = tf.convert_to_tensor(value=np.reshape(np.array(frame.pose.transform), [4, 4])) # [H, W, 6] range_image_top_pose_tensor = tf.reshape( tf.convert_to_tensor(value=range_image_top_pose.data), range_image_top_pose.shape.dims ) # [H, W, 3, 3] range_image_top_pose_tensor_rotation = transform_utils.get_rotation_matrix( range_image_top_pose_tensor[..., 0], range_image_top_pose_tensor[..., 1], range_image_top_pose_tensor[..., 2], ) range_image_top_pose_tensor_translation = range_image_top_pose_tensor[..., 3:] range_image_top_pose_tensor = transform_utils.get_transform( range_image_top_pose_tensor_rotation, range_image_top_pose_tensor_translation ) for c in calibrations: for ri_index in range(2): range_image = range_images[c.name][ri_index] if len(c.beam_inclinations) == 0: # pylint: disable=g-explicit-length-test beam_inclinations = range_image_utils.compute_inclination( tf.constant([c.beam_inclination_min, c.beam_inclination_max]), height=range_image.shape.dims[0], ) else: beam_inclinations = tf.constant(c.beam_inclinations) beam_inclinations = tf.reverse(beam_inclinations, axis=[-1]) extrinsic = np.reshape(np.array(c.extrinsic.transform), [4, 4]) range_image_tensor = tf.reshape( tf.convert_to_tensor(value=range_image.data), range_image.shape.dims ) pixel_pose_local = None frame_pose_local = None if c.name == dataset_pb2.LaserName.TOP: pixel_pose_local = range_image_top_pose_tensor pixel_pose_local = tf.expand_dims(pixel_pose_local, axis=0) frame_pose_local = tf.expand_dims(frame_pose, axis=0) range_image_mask = range_image_tensor[..., 0] > 0 label_zone_mask = range_image_tensor[..., -1] != 1 range_image_mask = tf.logical_and(range_image_mask, label_zone_mask) range_image_cartesian = range_image_utils.extract_point_cloud_from_range_image( tf.expand_dims(range_image_tensor[..., 0], axis=0), tf.expand_dims(extrinsic, axis=0), tf.expand_dims(tf.convert_to_tensor(value=beam_inclinations), axis=0), pixel_pose=pixel_pose_local, frame_pose=frame_pose_local, ) range_image_cartesian = tf.squeeze(range_image_cartesian, axis=0) range_image_cartesian = range_image_cartesian[range_image_mask] range_image_features = range_image_tensor[..., :-1] range_image_features = range_image_features[range_image_mask] cp = camera_projections[c.name][ri_index] cp_tensor = tf.reshape(tf.convert_to_tensor(value=cp.data), cp.shape.dims) cp_points_tensor = cp_tensor[range_image_mask] points.append(range_image_cartesian.numpy()) r_points.append(range_image_features[..., 0].numpy()) i_points.append(range_image_features[..., 1].numpy()) e_points.append(range_image_features[..., 2].numpy()) cp_points.append(cp_points_tensor.numpy()) points =
np.concatenate(points, axis=0)
numpy.concatenate
from typing import Callable, Any, Union from copy import deepcopy, copy import numpy as np from scipy.integrate import solve_ivp from scipy import interpolate as sci_interp from bioptim import SolutionIntegrator, Shooting, OptimalControlProgram, Solution, ControlType import biorbd class Integration: """ Integration Attributes ---------- ocp: SimplifiedOCP The OCP simplified ns: list The number of shooting point for each phase is_interpolated: bool If the current structure is interpolated is_integrated: bool If the current structure is integrated is_merged: bool If the phases were merged vector: np.ndarray The data in the vector format _states: list The data structure that holds the states _controls: list The data structure that holds the controls parameters: dict The data structure that holds the parameters phase_time: list The total time for each phases Methods ------- copy(self, skip_data: bool = False) -> Any Create a deepcopy of the Solution @property states(self) -> Union[list, dict] Returns the state in list if more than one phases, otherwise it returns the only dict @property controls(self) -> Union[list, dict] Returns the controls in list if more than one phases, otherwise it returns the only dict integrate(self, shooting_type: Shooting = Shooting.MULTIPLE, keep_intermediate_points: bool = True, merge_phases: bool = False, continuous: bool = True) -> Solution Integrate the states interpolate(self, n_frames: Union[int, list, tuple]) -> Solution Interpolate the states merge_phases(self) -> Solution Get a data structure where all the phases are merged into one _merge_phases(self, skip_states: bool = False, skip_controls: bool = False) -> tuple Actually performing the phase merging _complete_control(self) Controls don't necessarily have dimensions that matches the states. This method aligns them graphs(self, automatically_organize: bool, show_bounds: bool, show_now: bool, shooting_type: Shooting) Show the graphs of the simulation animate(self, n_frames: int = 0, show_now: bool = True, **kwargs: Any) -> Union[None, list] Animate the simulation print(self, cost_type: CostType = CostType.ALL) Print the objective functions and/or constraints to the console """ def __init__( self, ocp: OptimalControlProgram, solution: Solution, state_keys: list = None, control_keys: list = None, function: Callable = None, **extra_variables, ): """ Parameters ---------- ocp: OptimalControlProgram The OCP state_keys: list The state keys control_keys: list The control keys function: Callable The function that will be used to evaluate the system dynamics extra_variables: dict The extra variables that will be used to evaluate the system dynamics """ self.is_integrated = False self.is_interpolated = False self.is_merged = False self.recomputed_time_steps = False self.ocp = ocp self.ns = [nlp.ns for nlp in self.ocp.nlp] self.model = [biorbd.Model(nlp.model.path().absolutePath().to_string()) for nlp in self.ocp.nlp] self.control_keys = control_keys self.state_keys = state_keys # Extract the data now for further use self._states = self._update_variable_with_keys(solution._states, self.state_keys) self._controls = self._update_variable_with_keys(solution._controls, self.control_keys) self.parameters = solution.parameters self.vector = solution.vector self.time_vector = None self.phase_time = solution.phase_time self.function = function if function is not None else [nlp.dynamics for nlp in self.ocp.nlp] @staticmethod def _update_variable_with_keys(variable: list[dict], keys: list) -> list: """ Update the variable removing the key of the dictionary """ cleaned_list = [{k: v for k, v in d.items() if k in keys} for d in variable] # add all key gathering all the keys in one item for i, phase_list in enumerate(cleaned_list): # empty numpy array named all_variables all_variables = np.empty((0, 0)) # concatenate all the data of all items of the dictionary for key, value in phase_list.items(): all_variables = value if all_variables.size == 0 else np.concatenate((all_variables, value), axis=0) # add the data to the dictionary cleaned_list[i]["all"] = all_variables return cleaned_list @property def states(self) -> Union[list, dict]: """ Returns the state in list if more than one phases, otherwise it returns the only dict Returns ------- The states data """ return self._states[0] if len(self._states) == 1 else self._states @property def controls(self) -> Union[list, dict]: """ Returns the controls in list if more than one phases, otherwise it returns the only dict Returns ------- The controls data """ if not self._controls: raise RuntimeError( "There is no controls in the solution. " "This may happen in " "previously integrated and interpolated structure" ) return self._controls[0] if len(self._controls) == 1 else self._controls def integrate( self, shooting_type: Shooting = Shooting.SINGLE_CONTINUOUS, keep_intermediate_points: bool = False, merge_phases: bool = False, continuous: bool = True, integrator: SolutionIntegrator = SolutionIntegrator.DEFAULT, ) -> Any: """ Integrate the states Parameters ---------- shooting_type: Shooting Which type of integration keep_intermediate_points: bool If the integration should returns the intermediate values of the integration [False] or only keep the node [True] effective keeping the initial size of the states merge_phases: bool If the phase should be merged in a unique phase continuous: bool If the arrival value of a node should be discarded [True] or kept [False]. The value of an integrated arrival node and the beginning of the next one are expected to be almost equal when the problem converged integrator: SolutionIntegrator Use the ode defined by OCP or use a separate integrator provided by scipy Returns ------- A Solution data structure with the states integrated. The controls are removed from this structure """ # Sanity check if self.is_integrated: raise RuntimeError("Cannot integrate twice") if self.is_interpolated: raise RuntimeError("Cannot integrate after interpolating") if self.is_merged: raise RuntimeError("Cannot integrate after merging phases") if shooting_type == Shooting.MULTIPLE and not keep_intermediate_points: raise ValueError( "Shooting.MULTIPLE and keep_intermediate_points=False cannot be used simultaneously " "since it would do nothing" ) if shooting_type == Shooting.SINGLE_CONTINUOUS and not continuous: raise ValueError( "Shooting.SINGLE_CONTINUOUS and continuous=False cannot be used simultaneously it is a contradiction" ) out = self.__perform_integration(shooting_type, keep_intermediate_points, continuous, merge_phases, integrator) if merge_phases: if continuous: out = out.interpolate(sum(out.ns) + 1) else: out._states, _, out.phase_time, out.ns = out._merge_phases(skip_controls=True, continuous=continuous) out.is_merged = True out.is_integrated = True return out def _generate_time_vector( self, time_phase, keep_intermediate_points: bool, continuous: bool, merge_phases: bool, integrator: SolutionIntegrator, ): """ Generate time integration vector, at which the points from intagrate are evaluated """ t_integrated = [] last_t = 0 for phase_idx, nlp in enumerate(self.ocp.nlp): n_int_steps = ( nlp.ode_solver.steps_scipy if integrator != SolutionIntegrator.DEFAULT else nlp.ode_solver.steps ) dt_ns = time_phase[phase_idx + 1] / nlp.ns time_phase_integrated = [] last_t_int = copy(last_t) for _ in range(nlp.ns): if nlp.ode_solver.is_direct_collocation and integrator == SolutionIntegrator.DEFAULT: time_phase_integrated += (np.array(nlp.dynamics[0].step_time) * dt_ns + last_t_int).tolist() else: time_interval = np.linspace(last_t_int, last_t_int + dt_ns, n_int_steps + 1) if continuous and _ != nlp.ns - 1: time_interval = time_interval[:-1] if not keep_intermediate_points: if _ == nlp.ns - 1: time_interval = time_interval[[0, -1]] else: time_interval = np.array([time_interval[0]]) time_phase_integrated += time_interval.tolist() if not continuous and _ == nlp.ns - 1: time_phase_integrated += [time_phase_integrated[-1]] last_t_int += dt_ns if continuous and merge_phases and phase_idx != len(self.ocp.nlp) - 1: t_integrated += time_phase_integrated[:-1] else: t_integrated += time_phase_integrated last_t += time_phase[phase_idx + 1] return t_integrated def copy(self, skip_data: bool = False) -> Any: """ Create a deepcopy of the Solution Parameters ---------- skip_data: bool If data should be ignored in the copy Returns ------- Return a Solution data structure """ new = Solution(self.ocp, None) new.vector = deepcopy(self.vector) new.is_interpolated = deepcopy(self.is_interpolated) new.is_integrated = deepcopy(self.is_integrated) new.is_merged = deepcopy(self.is_merged) new.phase_time = deepcopy(self.phase_time) new.ns = deepcopy(self.ns) new.time_vector = deepcopy(self.time_vector) if skip_data: new._states, new._controls, new.parameters = [], [], {} else: new._states = deepcopy(self._states) new._controls = deepcopy(self._controls) new.parameters = deepcopy(self.parameters) return new def __perform_integration( self, shooting_type: Shooting, keep_intermediate_points: bool, continuous: bool, merge_phases: bool, integrator: SolutionIntegrator, ): n_direct_collocation = sum([nlp.ode_solver.is_direct_collocation for nlp in self.ocp.nlp]) if n_direct_collocation > 0 and integrator == SolutionIntegrator.DEFAULT: if continuous: raise RuntimeError( "Integration with direct collocation must be not continuous if a scipy integrator is used" ) if shooting_type != Shooting.MULTIPLE: raise RuntimeError( "Integration with direct collocation must using shooting_type=Shooting.MULTIPLE " "if a scipy integrator is not used" ) # Copy the data out = self.copy(skip_data=True) out.recomputed_time_steps = integrator != SolutionIntegrator.DEFAULT out._states = [] out.time_vector = self._generate_time_vector( out.phase_time, keep_intermediate_points, continuous, merge_phases, integrator ) for _ in range(len(self._states)): out._states.append({}) sum_states_len = 0 params = self.parameters["all"] x0 = self._states[0]["all"][:, 0] for p, nlp in enumerate(self.ocp.nlp): param_scaling = nlp.parameters.scaling n_states = self._states[p]["all"].shape[0] n_steps = nlp.ode_solver.steps_scipy if integrator != SolutionIntegrator.DEFAULT else nlp.ode_solver.steps if not continuous: n_steps += 1 if keep_intermediate_points: out.ns[p] *= n_steps out._states[p]["all"] = np.ndarray((n_states, out.ns[p] + 1)) # Get the first frame of the phase if shooting_type == Shooting.SINGLE_CONTINUOUS: if p != 0: u0 = self._controls[p - 1]["all"][:, -1] val = self.ocp.phase_transitions[p - 1].function(np.vstack((x0, x0)), np.vstack((u0, u0)), params) if val.shape[0] != x0.shape[0]: raise RuntimeError( f"Phase transition must have the same number of states ({val.shape[0]}) " f"when integrating with Shooting.SINGLE_CONTINUOUS. If it is not possible, " f"please integrate with Shooting.SINGLE" ) x0 += np.array(val)[:, 0] else: col = ( slice(0, n_steps) if nlp.ode_solver.is_direct_collocation and integrator == SolutionIntegrator.DEFAULT else 0 ) x0 = self._states[p]["all"][:, col] for s in range(self.ns[p]): if nlp.control_type == ControlType.CONSTANT: u = self._controls[p]["all"][:, s] elif nlp.control_type == ControlType.LINEAR_CONTINUOUS: u = self._controls[p]["all"][:, s : s + 2] else: raise NotImplementedError(f"ControlType {nlp.control_type} " f"not yet implemented in integrating") if integrator != SolutionIntegrator.DEFAULT: t_init = sum(out.phase_time[:p]) / nlp.ns t_end = sum(out.phase_time[: (p + 2)]) / nlp.ns n_points = n_steps + 1 if continuous else n_steps t_eval = np.linspace(t_init, t_end, n_points) if keep_intermediate_points else [t_init, t_end] integrated = solve_ivp( # lambda t, x: np.array(nlp.dynamics_func(x, u, params))[:, 0], lambda t, x: np.array(self.function(self.model[p], x, u, params)), [t_init, t_end], x0, t_eval=t_eval, method=integrator.value, ).y next_state_col = ( (s + 1) * (nlp.ode_solver.steps + 1) if nlp.ode_solver.is_direct_collocation else s + 1 ) cols_in_out = [s * n_steps, (s + 1) * n_steps] if keep_intermediate_points else [s, s + 2] # else: # if nlp.ode_solver.is_direct_collocation: # if keep_intermediate_points: # integrated = x0 # That is only for continuous=False # cols_in_out = [s * n_steps, (s + 1) * n_steps] # else: # integrated = x0[:, [0, -1]] # cols_in_out = [s, s + 2] # next_state_col = slice((s + 1) * n_steps, (s + 2) * n_steps) # # else: # if keep_intermediate_points: # integrated = np.array(nlp.dynamics[s](x0=x0, p=u, params=params / param_scaling)["xall"]) # cols_in_out = [s * n_steps, (s + 1) * n_steps] # else: # integrated = np.concatenate( # (x0[:, np.newaxis], nlp.dynamics[s](x0=x0, p=u, params=params / param_scaling)["xf"]), # axis=1, # ) # cols_in_out = [s, s + 2] # next_state_col = s + 1 cols_in_out = slice( cols_in_out[0], cols_in_out[1] + 1 if continuous and keep_intermediate_points else cols_in_out[1], ) out._states[p]["all"][:, cols_in_out] = integrated x0 = ( np.array(self._states[p]["all"][:, next_state_col]) if shooting_type == Shooting.MULTIPLE else integrated[:, -1] ) if not continuous: out._states[p]["all"][:, -1] = self._states[p]["all"][:, -1] # Dispatch the integrated values to all the keys for key in nlp.states: out._states[p][key] = out._states[p]["all"][nlp.states[key].index, :] sum_states_len += out._states[p]["all"].shape[1] return out def interpolate(self, n_frames: Union[int, list, tuple]) -> Any: """ Interpolate the states Parameters ---------- n_frames: Union[int, list, tuple] If the value is an int, the Solution returns merges the phases, otherwise, it interpolates them independently Returns ------- A Solution data structure with the states integrated. The controls are removed from this structure """ out = self.copy(skip_data=True) t_all = [] for p, data in enumerate(self._states): nlp = self.ocp.nlp[p] if nlp.ode_solver.is_direct_collocation and not self.recomputed_time_steps: time_offset = sum(out.phase_time[: p + 1]) step_time = np.array(nlp.dynamics[0].step_time) dt = out.phase_time[p + 1] / nlp.ns t_tp = np.array([step_time * dt + s * dt + time_offset for s in range(nlp.ns)]).reshape(-1, 1) t_all.append(np.concatenate((t_tp, [[t_tp[-1, 0]]]))[:, 0]) else: t_all.append(np.linspace(sum(out.phase_time[: p + 1]), sum(out.phase_time[: p + 2]), out.ns[p] + 1)) if isinstance(n_frames, int): data_states, _, out.phase_time, out.ns = self._merge_phases(skip_controls=True) t_all = [np.concatenate((np.concatenate([_t[:-1] for _t in t_all]), [t_all[-1][-1]]))] n_frames = [n_frames] out.is_merged = True elif isinstance(n_frames, (list, tuple)) and len(n_frames) == len(self._states): data_states = self._states else: raise ValueError( "n_frames should either be a int to merge_phases phases " "or a list of int of the number of phases dimension" ) out._states = [] for _ in range(len(data_states)): out._states.append({}) for p in range(len(data_states)): x_phase = data_states[p]["all"] n_elements = x_phase.shape[0] t_phase = t_all[p] t_phase, time_index = np.unique(t_phase, return_index=True) t_int =
np.linspace(t_phase[0], t_phase[-1], n_frames[p])
numpy.linspace
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 1 23:04:36 2019 @author: rainfall """ from __future__ import absolute_import, division, print_function import os import time import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.externals import joblib from sklearn.model_selection import train_test_split from sklearn.preprocessing import Normalizer from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from collections import Counter from src.meteoro_skills import CategoricalScores from src.meteoro_skills import ContinuousScores from keras.models import load_model import tensorflow as tf from tensorflow import keras from keras import backend from tensorflow.keras import layers from keras.layers import GaussianNoise from keras.layers import GaussianDropout from keras.models import Sequential from keras.layers import Dense #from keras.wrappers.scikit_learn import KerasClassifier from keras.models import model_from_yaml print('TF version '+tf.__version__) # ------------------------------------------------------------------------------ def tic(): global _start_time _start_time = time.time() def tac(): t_sec = round(time.time() - _start_time) (t_min, t_sec) = divmod(t_sec, 60) (t_hour, t_min) = divmod(t_min, 60) print('Time passed: {}hour:{}min:{}sec'.format(t_hour, t_min, t_sec)) def mean_squared_error(y_true, y_pred): return K.mean(K.square(y_pred - y_true), axis=-1) # ------------------------------------------------------------------------------ class Prediction: """ This module is intended to automate the TensorFlow Neural Network training. """ PCA = PCA() seed = 0 run_prefix = '' tver = '' vernick = '' file = '' path = '' fig_title = '' path_fig = '' mod_out_pth = '' mod_out_name = '' ymlv = '' ymlp = '' ymlf = '' def __init__(self, random_seed=0, run_prefix='', version='', version_nickname='', file_csv='', path_csv='', fig_title='', figure_path='', model_out_path='', model_out_name='', yaml_version='', yaml_path='', yaml_file=''): self.seed=random_seed self.run_prefix=run_prefix self.tver=version self.vernick=version_nickname self.file=file_csv self.path=path_csv self.path_fig=figure_path self.fig_title=run_prefix+version+version_nickname self.mod_out_pth=model_out_path self.mod_out_name=model_out_name self.ymlv=yaml_version self.ymlp=yaml_path self.ymlf=yaml_file # ------------------------------------------------------------------------- # DROP DATA OUTSIDE INTERVAL # ------------------------------------------------------------------------- @staticmethod def keep_interval(keepfrom: 0.0, keepto: 1.0, dataframe, target_col: str): keepinterval = np.where((dataframe[target_col] >= keepfrom) & (dataframe[target_col] <= keepto)) result = dataframe.iloc[keepinterval] return result #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ def PredictScreening(self): #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ ## load YAML and create model # yaml_file = open(self.ymlp+'screening_'+self.ymlv+'.yaml', 'r') # loaded_model_yaml = yaml_file.read() # yaml_file.close() # loaded_model = model_from_yaml(loaded_model_yaml) # # load weights into new model # loaded_model.load_weights(self.ymlp+'screening_'+self.ymlv+'.h5') # print("Loaded models yaml and h5 from disk!") # loaded_model = keras.models.load_model(self.ymlp+self.ymlf) # loaded_model.summary() loaded_model = joblib.load('screening_TESTE.pkl') #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Fix random seed for reproducibility: np.random.seed(self.seed) # Load dataset: df = pd.read_csv(os.path.join(self.path, self.file), sep=',', decimal='.') x = df.loc[:,['36V', '89V', '166V', '190V']] y = df.loc[:,['TagRain']] y_true = np.ravel(y) x_arr = np.asanyarray(x) # Scaling the input paramaters: # scaler_min_max = MinMaxScaler() norm_sc = Normalizer() x_normalized= norm_sc.fit_transform(x_arr) # Split the dataset in test and train samples: # x_train, x_test, y_train, y_test = train_test_split(x_normalized, # y_arr, test_size=0.10, # random_state=101) # Doing prediction from the test dataset: y_pred = loaded_model.predict_classes(x_normalized) y_pred = np.ravel(y_pred) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # Appplying meteorological skills to verify the performance of the model, in this case, categorical scores: skills = CategoricalScores() val_accuracy, val_bias, val_pod, val_pofd, val_far, val_csi, val_ph, val_ets, val_hss, val_hkd, val_num_pixels = skills.metrics(y_true, y_pred) #converting to text file print("converting arrays to text files") my_scores = {'val_accuracy': val_accuracy, 'val_bias': val_bias, 'val_pod': val_pod, 'val_pofd': val_pofd, 'val_far': val_far, 'val_csi': val_csi, 'val_ph': val_ph, 'val_ets': val_ets, 'val_hss': val_hss, 'val_hkd': val_hkd, 'val_num_pixels': val_num_pixels} with open('cateorical_scores_TESTE.txt', 'w') as myfile: myfile.write(str(my_scores)) print("Text file saved!") # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ df['SCR'] = "" df['SCR'] = y_pred filename=self.file[22:58] filename = 'validation_SCR_TESTE'+filename+'.csv' df.to_csv(os.path.join(self.path, filename), index=False, sep=",", decimal='.') return df def PredictRetrieval(self): #------------------------------------------------------------------------------ #load YAML and create model yaml_file = open(self.ymlp+'final_'+self.ymlv+'.yaml', 'r') loaded_model_yaml = yaml_file.read() yaml_file.close() loaded_model = model_from_yaml(loaded_model_yaml) # load weights into new model loaded_model.load_weights(self.ymlp+'final_'+self.ymlv+'.h5') print("Loaded models yaml and h5 from disk!") #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Fix random seed for reproducibility:
np.random.seed(self.seed)
numpy.random.seed
#--------------------------------- # AUTHOR: <NAME> #--------------------------------- import tensorflow as tf import numpy as np import argparse import pprint as pp import sys from replay_buffer import ReplayBuffer from AandC import * from noise import * from gym_torcs import TorcsEnv mu = np.array([0.0, 0.5, 0.01]) theta = np.array([0.0, 0.0, 0.0]) sigma =
np.array([0.1, 0.1, 0.1])
numpy.array
"""Utilities for computing active and inactive subspaces.""" import numpy as np from .utils.misc import process_inputs, process_inputs_outputs from .utils.response_surfaces import PolynomialApproximation from .gradients import local_linear_gradients SQRTEPS = np.sqrt(np.finfo(float).eps) class Subspaces(): """A class for computing active and inactive subspaces. Attributes ---------- eigenvals : ndarray m-by-1 matrix of eigenvalues eigenvecs : ndarray m-by-m matrix, eigenvectors oriented column-wise W1 : ndarray m-by-n matrix, basis for the active subspace W2 : ndarray m-by-(m-n) matrix, basis for the inactive subspace e_br : ndarray m-by-2 matrix, bootstrap ranges for the eigenvalues sub_br : ndarray m-by-3 matrix, bootstrap ranges (first and third column) and the mean (second column) of the error in the estimated active subspace approximated by bootstrap Notes ----- The attributes `W1` and `W2` are convenience variables. They are identical to the first n and last (m-n) columns of `eigenvecs`, respectively. """ eigenvals, eigenvecs = None, None W1, W2 = None, None e_br, sub_br = None, None def compute(self, X=None, f=None, df=None, weights=None, sstype='AS', ptype='EVG', nboot=0): """Compute the active and inactive subspaces. Given input points and corresponding outputs, or given samples of the gradients, estimate an active subspace. This method has four different algorithms for estimating the active subspace: 'AS' is the standard active subspace that requires gradients, 'OLS' uses a global linear model to estimate a one-dimensional active subspace, 'QPHD' uses a global quadratic model to estimate subspaces, and 'OPG' uses a set of local linear models computed from subsets of give input/output pairs. The function also sets the dimension of the active subspace (and, consequently, the dimenison of the inactive subspace). There are three heuristic choices for the dimension of the active subspace. The default is the largest gap in the eigenvalue spectrum, which is 'EVG'. The other two choices are 'RS', which estimates the error in a low-dimensional response surface using the eigenvalues and the estimated subspace errors, and 'LI' which is a heuristic from Bing Li on order determination. Note that either `df` or `X` and `f` must be given, although formally all are optional. Parameters ---------- X : ndarray, optional M-by-m matrix of samples of inputs points, arranged as rows (default None) f : ndarray, optional M-by-1 matrix of outputs corresponding to rows of `X` (default None) df : ndarray, optional M-by-m matrix of samples of gradients, arranged as rows (default None) weights : ndarray, optional M-by-1 matrix of weights associated with rows of `X` sstype : str, optional defines subspace type to compute. Default is 'AS' for active subspace, which requires `df`. Other options are `OLS` for a global linear model, `QPHD` for a global quadratic model, and `OPG` for local linear models. The latter three require `X` and `f`. ptype : str, optional defines the partition type. Default is 'EVG' for largest eigenvalue gap. Other options are 'RS', which is an estimate of the response surface error, and 'LI', which is a heuristic proposed by Bing Li based on subspace errors and eigenvalue decay. nboot : int, optional number of bootstrap samples used to estimate the error in the estimated subspace (default 0 means no bootstrap estimates) Notes ----- Partition type 'RS' and 'LI' require nboot to be greater than 0 (and probably something more like 100) to get bootstrap estimates of the subspace error. """ # Check inputs if X is not None: X, M, m = process_inputs(X) elif df is not None: df, M, m = process_inputs(df) else: raise Exception('One of input/output pairs (X,f) or gradients (df) must not be None') if weights is None: # default weights is for Monte Carlo weights = np.ones((M, 1)) / M # Compute the subspace if sstype == 'AS': if df is None: raise Exception('df is None') e, W = active_subspace(df, weights) ssmethod = lambda X, f, df, weights: active_subspace(df, weights) elif sstype == 'OLS': if X is None or f is None: raise Exception('X or f is None') e, W = ols_subspace(X, f, weights) ssmethod = lambda X, f, df, weights: ols_subspace(X, f, weights) elif sstype == 'QPHD': if X is None or f is None: raise Exception('X or f is None') e, W = qphd_subspace(X, f, weights) ssmethod = lambda X, f, df, weights: qphd_subspace(X, f, weights) elif sstype == 'OPG': if X is None or f is None: raise Exception('X or f is None') e, W = opg_subspace(X, f, weights) ssmethod = lambda X, f, df, weights: opg_subspace(X, f, weights) else: e, W = None, None ssmethod = None raise Exception('Unrecognized subspace type: {}'.format(sstype)) self.eigenvals, self.eigenvecs = e, W # Compute bootstrap ranges and partition if nboot > 0: e_br, sub_br, li_F = _bootstrap_ranges(e, W, X, f, df, weights, ssmethod, nboot) else: if ptype == 'RS' or ptype == 'LI': raise Exception('Need to run bootstrap for partition type {}'.format(ptype)) e_br, sub_br = None, None self.e_br, self.sub_br = e_br, sub_br # Compute the partition if ptype == 'EVG': n = eig_partition(e)[0] elif ptype == 'RS': sub_err = sub_br[:,1].reshape((m-1, 1)) n = errbnd_partition(e, sub_err)[0] elif ptype == 'LI': n = ladle_partition(e, li_F)[0] else: raise Exception('Unrecognized partition type: {}'.format(ptype)) self.partition(n) def partition(self, n): """Partition the eigenvectors to define the active subspace. A convenience function for partitioning the full set of eigenvectors to separate the active from inactive subspaces. Parameters ---------- n : int the dimension of the active subspace """ if not isinstance(n, int): #raise TypeError('n should be an integer') n = int(n) #print(Warning("n should be an integer. Performing conversion.")) m = self.eigenvecs.shape[0] if n<1 or n>m: raise ValueError('n must be positive and less than the dimension of the eigenvectors.') self.W1, self.W2 = self.eigenvecs[:,:n], self.eigenvecs[:,n:] def active_subspace(df, weights): """Compute the active subspace. Parameters ---------- df : ndarray M-by-m matrix containing the gradient samples oriented as rows weights : ndarray M-by-1 weight vector, corresponds to numerical quadrature rule used to estimate matrix whose eigenspaces define the active subspace Returns ------- e : ndarray m-by-1 vector of eigenvalues W : ndarray m-by-m orthogonal matrix of eigenvectors """ df, M, m = process_inputs(df) # compute the matrix C = np.dot(df.transpose(), df * weights) return sorted_eigh(C) def ols_subspace(X, f, weights): """Estimate one-dimensional subspace with global linear model. Parameters ---------- X : ndarray M-by-m matrix of input samples, oriented as rows f : ndarray M-by-1 vector of output samples corresponding to the rows of `X` weights : ndarray M-by-1 weight vector, corresponds to numerical quadrature rule used to estimate matrix whose eigenspaces define the active subspace Returns ------- e : ndarray m-by-1 vector of eigenvalues W : ndarray m-by-m orthogonal matrix of eigenvectors Notes ----- Although the method returns a full set of eigenpairs (to be consistent with the other subspace functions), only the first eigenvalue will be nonzero, and only the first eigenvector will have any relationship to the input parameters. The remaining m-1 eigenvectors are only orthogonal to the first. """ X, f, M, m = process_inputs_outputs(X, f) # solve weighted least squares A = np.hstack((np.ones((M, 1)), X)) * np.sqrt(weights) b = f * np.sqrt(weights) u = np.linalg.lstsq(A, b, rcond=None)[0] w = u[1:].reshape((m, 1)) # compute rank-1 C C = np.dot(w, w.transpose()) return sorted_eigh(C) def qphd_subspace(X, f, weights): """Estimate active subspace with global quadratic model. This approach is similar to Ker-Chau Li's approach for principal Hessian directions based on a global quadratic model of the data. In contrast to Li's approach, this method uses the average outer product of the gradient of the quadratic model, as opposed to just its Hessian. Parameters ---------- X : ndarray M-by-m matrix of input samples, oriented as rows f : ndarray M-by-1 vector of output samples corresponding to the rows of `X` weights : ndarray M-by-1 weight vector, corresponds to numerical quadrature rule used to estimate matrix whose eigenspaces define the active subspace Returns ------- e : ndarray m-by-1 vector of eigenvalues W : ndarray m-by-m orthogonal matrix of eigenvectors """ X, f, M, m = process_inputs_outputs(X, f) # check if the points are uniform or Gaussian, set 2nd moment if np.amax(X) > 1.0 or np.amin(X) < -1.0: gamma = 1.0 else: gamma = 1.0 / 3.0 # compute a quadratic approximation pr = PolynomialApproximation(2) pr.train(X, f, weights) # get regression coefficients b, A = pr.g, pr.H # compute C C = np.outer(b, b.transpose()) + gamma*np.dot(A, A.transpose()) return sorted_eigh(C) def opg_subspace(X, f, weights): """Estimate active subspace with local linear models. This approach is related to the sufficient dimension reduction method known sometimes as the outer product of gradient method. See the 2001 paper 'Structure adaptive approach for dimension reduction' from Hristache, et al. Parameters ---------- X : ndarray M-by-m matrix of input samples, oriented as rows f : ndarray M-by-1 vector of output samples corresponding to the rows of `X` weights : ndarray M-by-1 weight vector, corresponds to numerical quadrature rule used to estimate matrix whose eigenspaces define the active subspace Returns ------- e : ndarray m-by-1 vector of eigenvalues W : ndarray m-by-m orthogonal matrix of eigenvectors """ X, f, M, m = process_inputs_outputs(X, f) # Obtain gradient approximations using local linear regressions df = local_linear_gradients(X, f, weights=weights) # Use gradient approximations to compute active subspace opg_weights = np.ones((df.shape[0], 1)) / df.shape[0] e, W = active_subspace(df, opg_weights) return e, W def eig_partition(e): """Partition the active subspace according to largest eigenvalue gap. Parameters ---------- e : ndarray m-by-1 vector of eigenvalues Returns ------- n : int dimension of active subspace ediff : float largest eigenvalue gap """ # dealing with zeros for the log ediff = np.fabs(np.diff(e.reshape((e.size,)))) # crappy threshold for choosing active subspace dimension n = np.argmax(ediff) + 1 return n, ediff def errbnd_partition(e, sub_err): """Partition the active subspace according to response surface error. Uses an a priori estimate of the response surface error based on the eigenvalues and subspace error to determine the active subspace dimension. Parameters ---------- e : ndarray m-by-1 vector of eigenvalues sub_err : ndarray m-by-1 vector of estimates of subspace error Returns ------- n : int dimension of active subspace errbnd : float estimate of error bound Notes ----- The error bound should not be used as an estimated error. The bound is only used to estimate the subspace dimension. """ m = e.shape[0] errbnd = np.zeros((m-1, 1)) for i in range(m-1): errbnd[i] = np.sqrt(np.sum(e[:i+1]))*sub_err[i] + np.sqrt(np.sum(e[i+1:])) n = np.argmin(errbnd) + 1 return n, errbnd def ladle_partition(e, li_F): """Partition the active subspace according to Li's criterion. Uses a criterion proposed by Bing Li that combines estimates of the subspace with estimates of the eigenvalues. Parameters ---------- e : ndarray m-by-1 vector of eigenvalues li_F : float measures error in the subspace Returns ------- n : int dimension of active subspace G : ndarray metrics used to determine active subspace dimension """ G = li_F + e.reshape((e.size, 1)) / np.sum(e) n = np.argmin(G) + 1 return n, G def _bootstrap_ranges(e, W, X, f, df, weights, ssmethod, nboot=100): """Compute bootstrap ranges for eigenvalues and subspaces. An implementation of the nonparametric bootstrap that we use in conjunction with the subspace estimation methods to estimate the errors in the eigenvalues and subspaces. Parameters ---------- e : ndarray m-by-1 vector of eigenvalues W : ndarray m-by-m orthogonal matrix of eigenvectors X : ndarray M-by-m matrix of input samples, oriented as rows f : ndarray M-by-1 vector of outputs corresponding to rows of `X` df : ndarray M-by-m matrix of gradient samples weights : ndarray M-by-1 vector of weights corresponding to samples ssmethod : function a function that returns eigenpairs given input/output or gradient samples nboot : int, optional number of bootstrap samples (default 100) Returns ------- e_br : ndarray m-by-2 matrix, first column contains bootstrap lower bound on eigenvalues, second column contains bootstrap upper bound on eigenvalues sub_br : ndarray (m-1)-by-3 matrix, first column contains bootstrap lower bound on estimated subspace error, second column contains estimated mean of subspace error (a reasonable subspace error estimate), third column contains estimated upper bound on subspace error li_F : float Bing Li's metric for order determination based on determinants """ if df is not None: df, M, m = process_inputs(df) else: X, M, m = process_inputs(X) e_boot = np.zeros((m, nboot)) sub_dist =
np.zeros((m-1, nboot))
numpy.zeros
import numpy as np # Gotran generated code for the "grandi" model def init_state_values_single(**values): """ Initialize state values """ # Init values # m=0.003793087414436, h=0.626221949492493, j=0.624553572490432, # x_kr=0.0210022533039071, x_ks=0.00428016666258923, # x_to_s=0.000440445885642567, y_to_s=0.785115828275182, # x_to_f=0.000440438103758954, y_to_f=0.999995844038706, # d=2.92407183949469e-06, f=0.995135796703515, # f_Ca_Bj=0.0246760872105795, f_Ca_Bsl=0.0152723084239416, # Ry_Rr=0.890806040818203, Ry_Ro=7.40481128853622e-07, # Ry_Ri=9.07666168960848e-08, Na_Bj=3.4543773303328, # Na_Bsl=0.753740951477775, Tn_CL=0.00893455096919132, # Tn_CHc=0.117412025936615, Tn_CHm=0.0106160166692932, # CaM=0.000295573424135051, Myo_c=0.00192322252438022, # Myo_m=0.137560495022823, SRB=0.00217360235649355, # SLL_j=0.00740524521680039, SLL_sl=0.00990339304377132, # SLH_j=0.0735890020284214, SLH_sl=0.114583623436917, # Csqn_b=1.19723145924432, Ca_sr=0.554760499828172, # Na_j=8.40537012592918, Na_sl=8.40491910001025, Na_i=8.40513364344858, # K_i=120, Ca_j=0.000175882395147342, Ca_sl=0.000106779509977354, # Ca_i=8.72509677797499e-05, V_m=-81.4552030512661 init_values = np.array( [ 0.003793087414436, 0.626221949492493, 0.624553572490432, 0.0210022533039071, 0.00428016666258923, 0.000440445885642567, 0.785115828275182, 0.000440438103758954, 0.999995844038706, 2.92407183949469e-06, 0.995135796703515, 0.0246760872105795, 0.0152723084239416, 0.890806040818203, 7.40481128853622e-07, 9.07666168960848e-08, 3.4543773303328, 0.753740951477775, 0.00893455096919132, 0.117412025936615, 0.0106160166692932, 0.000295573424135051, 0.00192322252438022, 0.137560495022823, 0.00217360235649355, 0.00740524521680039, 0.00990339304377132, 0.0735890020284214, 0.114583623436917, 1.19723145924432, 0.554760499828172, 8.40537012592918, 8.40491910001025, 8.40513364344858, 120, 0.000175882395147342, 0.000106779509977354, 8.72509677797499e-05, -81.4552030512661, ], dtype=np.float_, ) # State indices and limit checker state_ind = dict( [ ("m", 0), ("h", 1), ("j", 2), ("x_kr", 3), ("x_ks", 4), ("x_to_s", 5), ("y_to_s", 6), ("x_to_f", 7), ("y_to_f", 8), ("d", 9), ("f", 10), ("f_Ca_Bj", 11), ("f_Ca_Bsl", 12), ("Ry_Rr", 13), ("Ry_Ro", 14), ("Ry_Ri", 15), ("Na_Bj", 16), ("Na_Bsl", 17), ("Tn_CL", 18), ("Tn_CHc", 19), ("Tn_CHm", 20), ("CaM", 21), ("Myo_c", 22), ("Myo_m", 23), ("SRB", 24), ("SLL_j", 25), ("SLL_sl", 26), ("SLH_j", 27), ("SLH_sl", 28), ("Csqn_b", 29), ("Ca_sr", 30), ("Na_j", 31), ("Na_sl", 32), ("Na_i", 33), ("K_i", 34), ("Ca_j", 35), ("Ca_sl", 36), ("Ca_i", 37), ("V_m", 38), ] ) for state_name, value in values.items(): if state_name not in state_ind: raise ValueError("{0} is not a state.".format(state_name)) ind = state_ind[state_name] # Assign value init_values[ind] = value return init_values def init_parameter_values_single(**values): """ Initialize parameter values """ # Param values # Fjunc=0.11, Fjunc_CaL=0.9, cellLength=100, cellRadius=10.25, # distJuncSL=0.5, distSLcyto=0.45, junctionLength=0.16, # junctionRadius=0.015, GNa=23, GNaB=0.000597, IbarNaK=1.8, # KmKo=1.5, KmNaip=11, Q10KmNai=1.39, Q10NaK=1.63, GKr=0.035, # GKp=0.002, GKs=0.0035, pNaK=0.01833, GK1=0.35, Gto=0.13, epi=1, # GClB=0.009, GClCa=0.0548125, KdClCa=0.1, GCaL=0.5, Q10CaL=1.8, # pCa=0.00054, pK=2.7e-07, pNa=1.5e-08, IbarNCX=4.5, Kdact=0.00015, # KmCai=0.00359, KmCao=1.3, KmNai=12.29, KmNao=87.5, Q10NCX=1.57, # ksat=0.32, nu=0.27, IbarSLCaP=0.0673, KmPCa=0.0005, # Q10SLCaP=2.35, GCaB=0.0005513, Kmf=0.000246, Kmr=1.7, MaxSR=15, # MinSR=1, Q10SRCaP=2.6, Vmax_SRCaP=0.0053114, ec50SR=0.45, # hillSRCaP=1.787, kiCa=0.5, kim=0.005, koCa=10, kom=0.06, ks=25, # Bmax_Naj=7.561, Bmax_Nasl=1.65, koff_na=0.001, kon_na=0.0001, # Bmax_CaM=0.024, Bmax_SR=0.0171, Bmax_TnChigh=0.14, # Bmax_TnClow=0.07, Bmax_myosin=0.14, koff_cam=0.238, # koff_myoca=0.00046, koff_myomg=5.7e-05, koff_sr=0.06, # koff_tnchca=3.2e-05, koff_tnchmg=0.00333, koff_tncl=0.0196, # kon_cam=34, kon_myoca=13.8, kon_myomg=0.0157, kon_sr=100, # kon_tnchca=2.37, kon_tnchmg=0.003, kon_tncl=32.7, # Bmax_SLhighj0=0.000165, Bmax_SLhighsl0=0.0134, Bmax_SLlowj0=0.00046, # Bmax_SLlowsl0=0.0374, koff_slh=0.03, koff_sll=1.3, kon_slh=100, # kon_sll=100, Bmax_Csqn0=0.14, DcaJuncSL=1.64e-06, # DcaSLcyto=1.22e-06, J_ca_juncsl=8.2413e-13, J_ca_slmyo=3.7243e-12, # koff_csqn=65, kon_csqn=100, DnaJuncSL=1.09e-05, DnaSLcyto=1.79e-05, # J_na_juncsl=1.8313e-14, J_na_slmyo=1.6386e-12, Nao=140, Ko=5.4, # Cao=1.8, Cli=15, Clo=150, Mgi=1, Cmem=1.381e-10, Frdy=96485, # R=8314, Temp=310, stim_amplitude=40.0, stim_duration=1.0, # stim_period=1000.0, stim_start=0.0 init_values = np.array( [ 0.11, 0.9, 100, 10.25, 0.5, 0.45, 0.16, 0.015, 23, 0.000597, 1.8, 1.5, 11, 1.39, 1.63, 0.035, 0.002, 0.0035, 0.01833, 0.35, 0.13, 1, 0.009, 0.0548125, 0.1, 0.5, 1.8, 0.00054, 2.7e-07, 1.5e-08, 4.5, 0.00015, 0.00359, 1.3, 12.29, 87.5, 1.57, 0.32, 0.27, 0.0673, 0.0005, 2.35, 0.0005513, 0.000246, 1.7, 15, 1, 2.6, 0.0053114, 0.45, 1.787, 0.5, 0.005, 10, 0.06, 25, 7.561, 1.65, 0.001, 0.0001, 0.024, 0.0171, 0.14, 0.07, 0.14, 0.238, 0.00046, 5.7e-05, 0.06, 3.2e-05, 0.00333, 0.0196, 34, 13.8, 0.0157, 100, 2.37, 0.003, 32.7, 0.000165, 0.0134, 0.00046, 0.0374, 0.03, 1.3, 100, 100, 0.14, 1.64e-06, 1.22e-06, 8.2413e-13, 3.7243e-12, 65, 100, 1.09e-05, 1.79e-05, 1.8313e-14, 1.6386e-12, 140, 5.4, 1.8, 15, 150, 1, 1.381e-10, 96485, 8314, 310, 40.0, 1.0, 1000.0, 0.0, ], dtype=np.float_, ) # Parameter indices and limit checker param_ind = dict( [ ("Fjunc", 0), ("Fjunc_CaL", 1), ("cellLength", 2), ("cellRadius", 3), ("distJuncSL", 4), ("distSLcyto", 5), ("junctionLength", 6), ("junctionRadius", 7), ("GNa", 8), ("GNaB", 9), ("IbarNaK", 10), ("KmKo", 11), ("KmNaip", 12), ("Q10KmNai", 13), ("Q10NaK", 14), ("GKr", 15), ("GKp", 16), ("GKs", 17), ("pNaK", 18), ("GK1", 19), ("Gto", 20), ("epi", 21), ("GClB", 22), ("GClCa", 23), ("KdClCa", 24), ("GCaL", 25), ("Q10CaL", 26), ("pCa", 27), ("pK", 28), ("pNa", 29), ("IbarNCX", 30), ("Kdact", 31), ("KmCai", 32), ("KmCao", 33), ("KmNai", 34), ("KmNao", 35), ("Q10NCX", 36), ("ksat", 37), ("nu", 38), ("IbarSLCaP", 39), ("KmPCa", 40), ("Q10SLCaP", 41), ("GCaB", 42), ("Kmf", 43), ("Kmr", 44), ("MaxSR", 45), ("MinSR", 46), ("Q10SRCaP", 47), ("Vmax_SRCaP", 48), ("ec50SR", 49), ("hillSRCaP", 50), ("kiCa", 51), ("kim", 52), ("koCa", 53), ("kom", 54), ("ks", 55), ("Bmax_Naj", 56), ("Bmax_Nasl", 57), ("koff_na", 58), ("kon_na", 59), ("Bmax_CaM", 60), ("Bmax_SR", 61), ("Bmax_TnChigh", 62), ("Bmax_TnClow", 63), ("Bmax_myosin", 64), ("koff_cam", 65), ("koff_myoca", 66), ("koff_myomg", 67), ("koff_sr", 68), ("koff_tnchca", 69), ("koff_tnchmg", 70), ("koff_tncl", 71), ("kon_cam", 72), ("kon_myoca", 73), ("kon_myomg", 74), ("kon_sr", 75), ("kon_tnchca", 76), ("kon_tnchmg", 77), ("kon_tncl", 78), ("Bmax_SLhighj0", 79), ("Bmax_SLhighsl0", 80), ("Bmax_SLlowj0", 81), ("Bmax_SLlowsl0", 82), ("koff_slh", 83), ("koff_sll", 84), ("kon_slh", 85), ("kon_sll", 86), ("Bmax_Csqn0", 87), ("DcaJuncSL", 88), ("DcaSLcyto", 89), ("J_ca_juncsl", 90), ("J_ca_slmyo", 91), ("koff_csqn", 92), ("kon_csqn", 93), ("DnaJuncSL", 94), ("DnaSLcyto", 95), ("J_na_juncsl", 96), ("J_na_slmyo", 97), ("Nao", 98), ("Ko", 99), ("Cao", 100), ("Cli", 101), ("Clo", 102), ("Mgi", 103), ("Cmem", 104), ("Frdy", 105), ("R", 106), ("Temp", 107), ("stim_amplitude", 108), ("stim_duration", 109), ("stim_period", 110), ("stim_start", 111), ] ) for param_name, value in values.items(): if param_name not in param_ind: raise ValueError("{0} is not a parameter.".format(param_name)) ind = param_ind[state_name] # Assign value init_values[ind] = value return init_values def state_indices(*states): """ State indices """ state_inds = dict( [ ("m", 0), ("h", 1), ("j", 2), ("x_kr", 3), ("x_ks", 4), ("x_to_s", 5), ("y_to_s", 6), ("x_to_f", 7), ("y_to_f", 8), ("d", 9), ("f", 10), ("f_Ca_Bj", 11), ("f_Ca_Bsl", 12), ("Ry_Rr", 13), ("Ry_Ro", 14), ("Ry_Ri", 15), ("Na_Bj", 16), ("Na_Bsl", 17), ("Tn_CL", 18), ("Tn_CHc", 19), ("Tn_CHm", 20), ("CaM", 21), ("Myo_c", 22), ("Myo_m", 23), ("SRB", 24), ("SLL_j", 25), ("SLL_sl", 26), ("SLH_j", 27), ("SLH_sl", 28), ("Csqn_b", 29), ("Ca_sr", 30), ("Na_j", 31), ("Na_sl", 32), ("Na_i", 33), ("K_i", 34), ("Ca_j", 35), ("Ca_sl", 36), ("Ca_i", 37), ("V_m", 38), ] ) indices = [] for state in states: if state not in state_inds: raise ValueError("Unknown state: '{0}'".format(state)) indices.append(state_inds[state]) if len(indices) > 1: return indices else: return indices[0] def parameter_indices(*params): """ Parameter indices """ param_inds = dict( [ ("Fjunc", 0), ("Fjunc_CaL", 1), ("cellLength", 2), ("cellRadius", 3), ("distJuncSL", 4), ("distSLcyto", 5), ("junctionLength", 6), ("junctionRadius", 7), ("GNa", 8), ("GNaB", 9), ("IbarNaK", 10), ("KmKo", 11), ("KmNaip", 12), ("Q10KmNai", 13), ("Q10NaK", 14), ("GKr", 15), ("GKp", 16), ("GKs", 17), ("pNaK", 18), ("GK1", 19), ("Gto", 20), ("epi", 21), ("GClB", 22), ("GClCa", 23), ("KdClCa", 24), ("GCaL", 25), ("Q10CaL", 26), ("pCa", 27), ("pK", 28), ("pNa", 29), ("IbarNCX", 30), ("Kdact", 31), ("KmCai", 32), ("KmCao", 33), ("KmNai", 34), ("KmNao", 35), ("Q10NCX", 36), ("ksat", 37), ("nu", 38), ("IbarSLCaP", 39), ("KmPCa", 40), ("Q10SLCaP", 41), ("GCaB", 42), ("Kmf", 43), ("Kmr", 44), ("MaxSR", 45), ("MinSR", 46), ("Q10SRCaP", 47), ("Vmax_SRCaP", 48), ("ec50SR", 49), ("hillSRCaP", 50), ("kiCa", 51), ("kim", 52), ("koCa", 53), ("kom", 54), ("ks", 55), ("Bmax_Naj", 56), ("Bmax_Nasl", 57), ("koff_na", 58), ("kon_na", 59), ("Bmax_CaM", 60), ("Bmax_SR", 61), ("Bmax_TnChigh", 62), ("Bmax_TnClow", 63), ("Bmax_myosin", 64), ("koff_cam", 65), ("koff_myoca", 66), ("koff_myomg", 67), ("koff_sr", 68), ("koff_tnchca", 69), ("koff_tnchmg", 70), ("koff_tncl", 71), ("kon_cam", 72), ("kon_myoca", 73), ("kon_myomg", 74), ("kon_sr", 75), ("kon_tnchca", 76), ("kon_tnchmg", 77), ("kon_tncl", 78), ("Bmax_SLhighj0", 79), ("Bmax_SLhighsl0", 80), ("Bmax_SLlowj0", 81), ("Bmax_SLlowsl0", 82), ("koff_slh", 83), ("koff_sll", 84), ("kon_slh", 85), ("kon_sll", 86), ("Bmax_Csqn0", 87), ("DcaJuncSL", 88), ("DcaSLcyto", 89), ("J_ca_juncsl", 90), ("J_ca_slmyo", 91), ("koff_csqn", 92), ("kon_csqn", 93), ("DnaJuncSL", 94), ("DnaSLcyto", 95), ("J_na_juncsl", 96), ("J_na_slmyo", 97), ("Nao", 98), ("Ko", 99), ("Cao", 100), ("Cli", 101), ("Clo", 102), ("Mgi", 103), ("Cmem", 104), ("Frdy", 105), ("R", 106), ("Temp", 107), ("stim_amplitude", 108), ("stim_duration", 109), ("stim_period", 110), ("stim_start", 111), ] ) indices = [] for param in params: if param not in param_inds: raise ValueError("Unknown param: '{0}'".format(param)) indices.append(param_inds[param]) if len(indices) > 1: return indices else: return indices[0] def monitor_indices(*monitored): """ Monitor indices """ monitor_inds = dict( [ ("Vcell", 0), ("Vmyo", 1), ("Vsr", 2), ("Vsl", 3), ("Vjunc", 4), ("SAjunc", 5), ("SAsl", 6), ("Fsl", 7), ("Fsl_CaL", 8), ("mss", 9), ("taum", 10), ("ah", 11), ("bh", 12), ("tauh", 13), ("hss", 14), ("aj", 15), ("bj", 16), ("tauj", 17), ("jss", 18), ("I_Na_junc", 19), ("I_Na_sl", 20), ("I_Na", 21), ("I_nabk_junc", 22), ("I_nabk_sl", 23), ("I_nabk", 24), ("sigma", 25), ("fnak", 26), ("I_nak_junc", 27), ("I_nak_sl", 28), ("I_nak", 29), ("gkr", 30), ("xrss", 31), ("tauxr", 32), ("rkr", 33), ("I_kr", 34), ("kp_kp", 35), ("I_kp_junc", 36), ("I_kp_sl", 37), ("I_kp", 38), ("eks", 39), ("gks_junc", 40), ("gks_sl", 41), ("xsss", 42), ("tauxs", 43), ("I_ks_junc", 44), ("I_ks_sl", 45), ("I_ks", 46), ("GtoSlow", 47), ("GtoFast", 48), ("xtoss", 49), ("ytoss", 50), ("tauxtos", 51), ("tauytos", 52), ("I_tos", 53), ("tauxtof", 54), ("tauytof", 55), ("I_tof", 56), ("I_to", 57), ("I_ClCa_junc", 58), ("I_ClCa_sl", 59), ("I_ClCa", 60), ("I_Clbk", 61), ("fss", 62), ("dss", 63), ("taud", 64), ("tauf", 65), ("fcaCaMSL", 66), ("fcaCaj", 67), ("ibarca_j", 68), ("ibarca_sl", 69), ("ibark", 70), ("ibarna_j", 71), ("ibarna_sl", 72), ("I_Ca_junc", 73), ("I_Ca_sl", 74), ("I_Ca", 75), ("I_CaK", 76), ("I_CaNa_junc", 77), ("I_CaNa_sl", 78), ("I_CaNa", 79), ("I_Catot", 80), ("Ka_junc", 81), ("Ka_sl", 82), ("s1_junc", 83), ("s1_sl", 84), ("s2_junc", 85), ("s3_junc", 86), ("s2_sl", 87), ("s3_sl", 88), ("I_ncx_junc", 89), ("I_ncx_sl", 90), ("I_ncx", 91), ("I_pca_junc", 92), ("I_pca_sl", 93), ("I_pca", 94), ("I_cabk_junc", 95), ("I_cabk_sl", 96), ("I_cabk", 97), ("kCaSR", 98), ("koSRCa", 99), ("kiSRCa", 100), ("RI", 101), ("J_SRCarel", 102), ("J_serca", 103), ("J_SRleak", 104), ("J_CaB_cytosol", 105), ("Bmax_SLlowsl", 106), ("Bmax_SLlowj", 107), ("Bmax_SLhighsl", 108), ("Bmax_SLhighj", 109), ("J_CaB_junction", 110), ("J_CaB_sl", 111), ("Bmax_Csqn", 112), ("I_Na_tot_junc", 113), ("I_Na_tot_sl", 114), ("I_Na_tot_sl2", 115), ("I_Na_tot_junc2", 116), ("I_K_tot", 117), ("I_Ca_tot_junc", 118), ("I_Ca_tot_sl", 119), ("i_Stim", 120), ("I_Na_tot", 121), ("I_Cl_tot", 122), ("I_Ca_tot", 123), ("I_tot", 124), ("FoRT", 125), ("ena_junc", 126), ("ena_sl", 127), ("ek", 128), ("eca_junc", 129), ("eca_sl", 130), ("ecl", 131), ("Qpow", 132), ("aki", 133), ("bki", 134), ("kiss", 135), ("I_K1", 136), ("dm_dt", 137), ("dh_dt", 138), ("dj_dt", 139), ("dx_kr_dt", 140), ("dx_ks_dt", 141), ("dx_to_s_dt", 142), ("dy_to_s_dt", 143), ("dx_to_f_dt", 144), ("dy_to_f_dt", 145), ("dd_dt", 146), ("df_dt", 147), ("df_Ca_Bj_dt", 148), ("df_Ca_Bsl_dt", 149), ("dRy_Rr_dt", 150), ("dRy_Ro_dt", 151), ("dRy_Ri_dt", 152), ("dNa_Bj_dt", 153), ("dNa_Bsl_dt", 154), ("dTn_CL_dt", 155), ("dTn_CHc_dt", 156), ("dTn_CHm_dt", 157), ("dCaM_dt", 158), ("dMyo_c_dt", 159), ("dMyo_m_dt", 160), ("dSRB_dt", 161), ("dSLL_j_dt", 162), ("dSLL_sl_dt", 163), ("dSLH_j_dt", 164), ("dSLH_sl_dt", 165), ("dCsqn_b_dt", 166), ("dCa_sr_dt", 167), ("dNa_j_dt", 168), ("dNa_sl_dt", 169), ("dNa_i_dt", 170), ("dK_i_dt", 171), ("dCa_j_dt", 172), ("dCa_sl_dt", 173), ("dCa_i_dt", 174), ("dV_m_dt", 175), ] ) indices = [] for monitor in monitored: if monitor not in monitor_inds: raise ValueError("Unknown monitored: '{0}'".format(monitor)) indices.append(monitor_inds[monitor]) if len(indices) > 1: return indices else: return indices[0] def rhs(states, t, parameters, values=None): """ Compute the right hand side of the grandi ODE """ # Assign states assert len(states) == 39 ( m, h, j, x_kr, x_ks, x_to_s, y_to_s, x_to_f, y_to_f, d, f, f_Ca_Bj, f_Ca_Bsl, Ry_Rr, Ry_Ro, Ry_Ri, Na_Bj, Na_Bsl, Tn_CL, Tn_CHc, Tn_CHm, CaM, Myo_c, Myo_m, SRB, SLL_j, SLL_sl, SLH_j, SLH_sl, Csqn_b, Ca_sr, Na_j, Na_sl, Na_i, K_i, Ca_j, Ca_sl, Ca_i, V_m, ) = states # Assign parameters assert len(parameters) == 112 Fjunc = parameters[0] Fjunc_CaL = parameters[1] cellLength = parameters[2] cellRadius = parameters[3] GNa = parameters[8] GNaB = parameters[9] IbarNaK = parameters[10] KmKo = parameters[11] KmNaip = parameters[12] GKr = parameters[15] GKp = parameters[16] GKs = parameters[17] pNaK = parameters[18] GK1 = parameters[19] Gto = parameters[20] epi = parameters[21] GClB = parameters[22] GClCa = parameters[23] KdClCa = parameters[24] GCaL = parameters[25] Q10CaL = parameters[26] pCa = parameters[27] pK = parameters[28] pNa = parameters[29] IbarNCX = parameters[30] Kdact = parameters[31] KmCai = parameters[32] KmCao = parameters[33] KmNai = parameters[34] KmNao = parameters[35] Q10NCX = parameters[36] ksat = parameters[37] nu = parameters[38] IbarSLCaP = parameters[39] KmPCa = parameters[40] Q10SLCaP = parameters[41] GCaB = parameters[42] Kmf = parameters[43] Kmr = parameters[44] MaxSR = parameters[45] MinSR = parameters[46] Q10SRCaP = parameters[47] Vmax_SRCaP = parameters[48] ec50SR = parameters[49] hillSRCaP = parameters[50] kiCa = parameters[51] kim = parameters[52] koCa = parameters[53] kom = parameters[54] ks = parameters[55] Bmax_Naj = parameters[56] Bmax_Nasl = parameters[57] koff_na = parameters[58] kon_na = parameters[59] Bmax_CaM = parameters[60] Bmax_SR = parameters[61] Bmax_TnChigh = parameters[62] Bmax_TnClow = parameters[63] Bmax_myosin = parameters[64] koff_cam = parameters[65] koff_myoca = parameters[66] koff_myomg = parameters[67] koff_sr = parameters[68] koff_tnchca = parameters[69] koff_tnchmg = parameters[70] koff_tncl = parameters[71] kon_cam = parameters[72] kon_myoca = parameters[73] kon_myomg = parameters[74] kon_sr = parameters[75] kon_tnchca = parameters[76] kon_tnchmg = parameters[77] kon_tncl = parameters[78] Bmax_SLhighj0 = parameters[79] Bmax_SLhighsl0 = parameters[80] Bmax_SLlowj0 = parameters[81] Bmax_SLlowsl0 = parameters[82] koff_slh = parameters[83] koff_sll = parameters[84] kon_slh = parameters[85] kon_sll = parameters[86] Bmax_Csqn0 = parameters[87] J_ca_juncsl = parameters[90] J_ca_slmyo = parameters[91] koff_csqn = parameters[92] kon_csqn = parameters[93] J_na_juncsl = parameters[96] J_na_slmyo = parameters[97] Nao = parameters[98] Ko = parameters[99] Cao = parameters[100] Cli = parameters[101] Clo = parameters[102] Mgi = parameters[103] Cmem = parameters[104] Frdy = parameters[105] R = parameters[106] Temp = parameters[107] stim_amplitude = parameters[108] stim_duration = parameters[109] stim_period = parameters[110] stim_start = parameters[111] # Init return args if values is None: values = np.zeros_like(states) else: assert isinstance(values, np.ndarray) and values.shape == states.shape # Expressions for the Geometry component Vcell = 1e-15 * np.pi * cellLength * (cellRadius * cellRadius) Vmyo = 0.65 * Vcell Vsr = 0.035 * Vcell Vsl = 0.02 * Vcell Vjunc = 0.0005390000000000001 * Vcell Fsl = 1 - Fjunc Fsl_CaL = 1 - Fjunc_CaL # Expressions for the Reversal potentials component FoRT = Frdy / (R * Temp) ena_junc = np.log(Nao / Na_j) / FoRT ena_sl = np.log(Nao / Na_sl) / FoRT ek = np.log(Ko / K_i) / FoRT eca_junc = np.log(Cao / Ca_j) / (2 * FoRT) eca_sl = np.log(Cao / Ca_sl) / (2 * FoRT) ecl = np.log(Cli / Clo) / FoRT Qpow = -31 + Temp / 10 # Expressions for the I_Na component mss = 1.0 / ( (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) * (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) ) taum = 0.1292 * np.exp( -( (2.9465894465894467 + 0.06435006435006435 * V_m) * (2.9465894465894467 + 0.06435006435006435 * V_m) ) ) + 0.06487 * np.exp( -( (-0.09434663536776214 + 0.019561815336463225 * V_m) * (-0.09434663536776214 + 0.019561815336463225 * V_m) ) ) ah = np.where( V_m >= -40, 0, 4.4312679295805147e-07 * np.exp(-0.14705882352941177 * V_m) ) bh = np.where( V_m >= -40, 0.77 / (0.13 + 0.049758141083938695 * np.exp(-0.0900900900900901 * V_m)), 310000.0 * np.exp(0.3485 * V_m) + 2.7 * np.exp(0.079 * V_m), ) tauh = 1.0 / (ah + bh) hss = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) aj = np.where( V_m >= -40, 0, (37.78 + V_m) * (-25428.0 * np.exp(0.2444 * V_m) - 6.948e-06 * np.exp(-0.04391 * V_m)) / (1 + 50262745825.95399 * np.exp(0.311 * V_m)), ) bj = np.where( V_m >= -40, 0.6 * np.exp(0.057 * V_m) / (1 + 0.040762203978366204 * np.exp(-0.1 * V_m)), 0.02424 * np.exp(-0.01052 * V_m) / (1 + 0.003960868339904256 * np.exp(-0.1378 * V_m)), ) tauj = 1.0 / (aj + bj) jss = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) values[0] = (-m + mss) / taum values[1] = (-h + hss) / tauh values[2] = (-j + jss) / tauj I_Na_junc = Fjunc * GNa * (m * m * m) * (-ena_junc + V_m) * h * j I_Na_sl = GNa * (m * m * m) * (-ena_sl + V_m) * Fsl * h * j # Expressions for the I_NaBK component I_nabk_junc = Fjunc * GNaB * (-ena_junc + V_m) I_nabk_sl = GNaB * (-ena_sl + V_m) * Fsl # Expressions for the I_NaK component sigma = -1 / 7 + np.exp(0.01485884101040119 * Nao) / 7 fnak = 1.0 / ( 1 + 0.1245 * np.exp(-0.1 * FoRT * V_m) + 0.0365 * np.exp(-FoRT * V_m) * sigma ) I_nak_junc = ( Fjunc * IbarNaK * Ko * fnak / ((1 + np.power(KmNaip, 4) / np.power(Na_j, 4)) * (KmKo + Ko)) ) I_nak_sl = ( IbarNaK * Ko * Fsl * fnak / ((1 + np.power(KmNaip, 4) / np.power(Na_sl, 4)) * (KmKo + Ko)) ) I_nak = I_nak_junc + I_nak_sl # Expressions for the I_Kr component gkr = 0.4303314829119352 * GKr * np.sqrt(Ko) xrss = 1.0 / (1 + np.exp(-2 - V_m / 5)) tauxr = 230 / (1 + np.exp(2 + V_m / 20)) + 3300 / ( (1 + np.exp(-22 / 9 - V_m / 9)) * (1 + np.exp(11 / 9 + V_m / 9)) ) values[3] = (-x_kr + xrss) / tauxr rkr = 1.0 / (1 + np.exp(37 / 12 + V_m / 24)) I_kr = (-ek + V_m) * gkr * rkr * x_kr # Expressions for the I_Kp component kp_kp = 1.0 / (1 + 1786.4755653786237 * np.exp(-0.16722408026755853 * V_m)) I_kp_junc = Fjunc * GKp * (-ek + V_m) * kp_kp I_kp_sl = GKp * (-ek + V_m) * Fsl * kp_kp I_kp = I_kp_junc + I_kp_sl # Expressions for the I_Ks component eks = np.log((Ko + Nao * pNaK) / (pNaK * Na_i + K_i)) / FoRT gks_junc = GKs gks_sl = GKs xsss = 1.0 / (1 + 0.7659283383646487 * np.exp(-0.07017543859649122 * V_m)) tauxs = 990.1 / (1 + 0.8415404088681017 * np.exp(-0.0708215297450425 * V_m)) values[4] = (-x_ks + xsss) / tauxs I_ks_junc = Fjunc * (x_ks * x_ks) * (-eks + V_m) * gks_junc I_ks_sl = (x_ks * x_ks) * (-eks + V_m) * Fsl * gks_sl I_ks = I_ks_junc + I_ks_sl # Expressions for the I_to component GtoSlow = np.where(epi == 1, 0.12 * Gto, 0.28919999999999996 * Gto) GtoFast = np.where(epi == 1, 0.88 * Gto, 0.010799999999999999 * Gto) xtoss = 1.0 / (1 + np.exp(19 / 13 - V_m / 13)) ytoss = 1.0 / (1 + 49.40244910553019 * np.exp(V_m / 5)) tauxtos = 0.5 + 9 / (1 + np.exp(1 / 5 + V_m / 15)) tauytos = 30 + 800 / (1 + np.exp(6 + V_m / 10)) values[5] = (-x_to_s + xtoss) / tauxtos values[6] = (-y_to_s + ytoss) / tauytos I_tos = (-ek + V_m) * GtoSlow * x_to_s * y_to_s tauxtof = 0.5 + 8.5 * np.exp(-((9 / 10 + V_m / 50) * (9 / 10 + V_m / 50))) tauytof = 7 + 85 * np.exp(-((40 + V_m) * (40 + V_m)) / 220) values[7] = (-x_to_f + xtoss) / tauxtof values[8] = (-y_to_f + ytoss) / tauytof I_tof = (-ek + V_m) * GtoFast * x_to_f * y_to_f I_to = I_tof + I_tos # Expressions for the I_K1 component aki = 1.02 / (1 + 7.35454251046446e-07 * np.exp(0.2385 * V_m - 0.2385 * ek)) bki = ( 0.7626240065063081 * np.exp(0.08032 * V_m - 0.08032 * ek) + 1.1534056351865558e-16 * np.exp(0.06175 * V_m - 0.06175 * ek) ) / (1 + 0.08677229415769332 * np.exp(0.5143 * ek - 0.5143 * V_m)) kiss = aki / (aki + bki) I_K1 = 0.4303314829119352 * GK1 * np.sqrt(Ko) * (-ek + V_m) * kiss # Expressions for the I_ClCa component I_ClCa_junc = Fjunc * GClCa * (-ecl + V_m) / (1 + KdClCa / Ca_j) I_ClCa_sl = GClCa * (-ecl + V_m) * Fsl / (1 + KdClCa / Ca_sl) I_ClCa = I_ClCa_junc + I_ClCa_sl I_Clbk = GClB * (-ecl + V_m) # Expressions for the I_Ca component fss = 1.0 / (1 + np.exp(35 / 9 + V_m / 9)) + 0.6 / (1 + np.exp(5 / 2 - V_m / 20)) dss = 1.0 / (1 + np.exp(-5 / 6 - V_m / 6)) taud = (1 - np.exp(-5 / 6 - V_m / 6)) * dss / (0.17500000000000002 + 0.035 * V_m) tauf = 1.0 / ( 0.02 + 0.0197 * np.exp( -( (0.48865000000000003 + 0.0337 * V_m) * (0.48865000000000003 + 0.0337 * V_m) ) ) ) values[9] = (-d + dss) / taud values[10] = (-f + fss) / tauf values[11] = -0.0119 * f_Ca_Bj + 1.7 * (1 - f_Ca_Bj) * Ca_j values[12] = -0.0119 * f_Ca_Bsl + 1.7 * (1 - f_Ca_Bsl) * Ca_sl fcaCaMSL = 0 fcaCaj = 0 ibarca_j = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_j * np.exp(2 * FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(2 * FoRT * V_m)) ) ibarca_sl = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_sl * np.exp(2 * FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(2 * FoRT * V_m)) ) ibark = ( Frdy * GCaL * pK * (-0.75 * Ko + 0.75 * K_i * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) ibarna_j = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_j * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) ibarna_sl = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_sl * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) I_Ca_junc = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f * ibarca_j ) I_Ca_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f * ibarca_sl ) I_CaK = ( 0.45 * np.power(Q10CaL, Qpow) * (Fjunc_CaL * (1 + fcaCaj - f_Ca_Bj) + (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL) * d * f * ibark ) I_CaNa_junc = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f * ibarna_j ) I_CaNa_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f * ibarna_sl ) # Expressions for the I_NCX component Ka_junc = 1.0 / (1 + (Kdact * Kdact) / (Ca_j * Ca_j)) Ka_sl = 1.0 / (1 + (Kdact * Kdact) / (Ca_sl * Ca_sl)) s1_junc = Cao * (Na_j * Na_j * Na_j) * np.exp(nu * FoRT * V_m) s1_sl = Cao * (Na_sl * Na_sl * Na_sl) * np.exp(nu * FoRT * V_m) s2_junc = (Nao * Nao * Nao) * Ca_j * np.exp((-1 + nu) * FoRT * V_m) s3_junc = ( Cao * (Na_j * Na_j * Na_j) + KmCao * (Na_j * Na_j * Na_j) + (Nao * Nao * Nao) * Ca_j + KmCai * (Nao * Nao * Nao) * (1 + (Na_j * Na_j * Na_j) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_j / KmCai) * Ca_j ) s2_sl = (Nao * Nao * Nao) * Ca_sl * np.exp((-1 + nu) * FoRT * V_m) s3_sl = ( Cao * (Na_sl * Na_sl * Na_sl) + KmCao * (Na_sl * Na_sl * Na_sl) + (Nao * Nao * Nao) * Ca_sl + KmCai * (Nao * Nao * Nao) * (1 + (Na_sl * Na_sl * Na_sl) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_sl / KmCai) * Ca_sl ) I_ncx_junc = ( Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * (-s2_junc + s1_junc) * Ka_junc / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_junc) ) I_ncx_sl = ( IbarNCX * np.power(Q10NCX, Qpow) * (-s2_sl + s1_sl) * Fsl * Ka_sl / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_sl) ) # Expressions for the I_PCa component I_pca_junc = ( Fjunc * IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power(Ca_j, 1.6) / (np.power(KmPCa, 1.6) + np.power(Ca_j, 1.6)) ) I_pca_sl = ( IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power(Ca_sl, 1.6) * Fsl / (np.power(KmPCa, 1.6) + np.power(Ca_sl, 1.6)) ) # Expressions for the I_CaBK component I_cabk_junc = Fjunc * GCaB * (-eca_junc + V_m) I_cabk_sl = GCaB * (-eca_sl + V_m) * Fsl # Expressions for the SR Fluxes component kCaSR = MaxSR - (MaxSR - MinSR) / (1 + np.power(ec50SR / Ca_sr, 2.5)) koSRCa = koCa / kCaSR kiSRCa = kiCa * kCaSR RI = 1 - Ry_Ri - Ry_Ro - Ry_Rr values[13] = ( kim * RI + kom * Ry_Ro - (Ca_j * Ca_j) * Ry_Rr * koSRCa - Ca_j * Ry_Rr * kiSRCa ) values[14] = ( kim * Ry_Ri - kom * Ry_Ro + (Ca_j * Ca_j) * Ry_Rr * koSRCa - Ca_j * Ry_Ro * kiSRCa ) values[15] = ( -kim * Ry_Ri - kom * Ry_Ri + (Ca_j * Ca_j) * RI * koSRCa + Ca_j * Ry_Ro * kiSRCa ) J_SRCarel = ks * (-Ca_j + Ca_sr) * Ry_Ro J_serca = ( Vmax_SRCaP * np.power(Q10SRCaP, Qpow) * (np.power(Ca_i / Kmf, hillSRCaP) - np.power(Ca_sr / Kmr, hillSRCaP)) / (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) ) J_SRleak = 5.348e-06 * Ca_sr - 5.348e-06 * Ca_j # Expressions for the Na Buffers component values[16] = -koff_na * Na_Bj + kon_na * (Bmax_Naj - Na_Bj) * Na_j values[17] = -koff_na * Na_Bsl + kon_na * (Bmax_Nasl - Na_Bsl) * Na_sl # Expressions for the Cytosolic Ca Buffers component values[18] = -koff_tncl * Tn_CL + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i values[19] = ( -koff_tnchca * Tn_CHc + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i ) values[20] = -koff_tnchmg * Tn_CHm + Mgi * kon_tnchmg * ( Bmax_TnChigh - Tn_CHc - Tn_CHm ) values[21] = -koff_cam * CaM + kon_cam * (Bmax_CaM - CaM) * Ca_i values[22] = -koff_myoca * Myo_c + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i values[23] = -koff_myomg * Myo_m + Mgi * kon_myomg * (Bmax_myosin - Myo_c - Myo_m) values[24] = -koff_sr * SRB + kon_sr * (Bmax_SR - SRB) * Ca_i J_CaB_cytosol = ( -koff_cam * CaM - koff_myoca * Myo_c - koff_myomg * Myo_m - koff_sr * SRB - koff_tnchca * Tn_CHc - koff_tnchmg * Tn_CHm - koff_tncl * Tn_CL + Mgi * kon_myomg * (Bmax_myosin - Myo_c - Myo_m) + Mgi * kon_tnchmg * (Bmax_TnChigh - Tn_CHc - Tn_CHm) + kon_cam * (Bmax_CaM - CaM) * Ca_i + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i + kon_sr * (Bmax_SR - SRB) * Ca_i + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i ) # Expressions for the Junctional and SL Ca Buffers component Bmax_SLlowsl = Bmax_SLlowsl0 * Vmyo / Vsl Bmax_SLlowj = Bmax_SLlowj0 * Vmyo / Vjunc Bmax_SLhighsl = Bmax_SLhighsl0 * Vmyo / Vsl Bmax_SLhighj = Bmax_SLhighj0 * Vmyo / Vjunc values[25] = -koff_sll * SLL_j + kon_sll * (-SLL_j + Bmax_SLlowj) * Ca_j values[26] = -koff_sll * SLL_sl + kon_sll * (-SLL_sl + Bmax_SLlowsl) * Ca_sl values[27] = -koff_slh * SLH_j + kon_slh * (-SLH_j + Bmax_SLhighj) * Ca_j values[28] = -koff_slh * SLH_sl + kon_slh * (-SLH_sl + Bmax_SLhighsl) * Ca_sl J_CaB_junction = ( -koff_slh * SLH_j - koff_sll * SLL_j + kon_slh * (-SLH_j + Bmax_SLhighj) * Ca_j + kon_sll * (-SLL_j + Bmax_SLlowj) * Ca_j ) J_CaB_sl = ( -koff_slh * SLH_sl - koff_sll * SLL_sl + kon_slh * (-SLH_sl + Bmax_SLhighsl) * Ca_sl + kon_sll * (-SLL_sl + Bmax_SLlowsl) * Ca_sl ) # Expressions for the SR Ca Concentrations component Bmax_Csqn = Bmax_Csqn0 * Vmyo / Vsr values[29] = -koff_csqn * Csqn_b + kon_csqn * (-Csqn_b + Bmax_Csqn) * Ca_sr values[30] = ( -J_SRCarel + koff_csqn * Csqn_b - kon_csqn * (-Csqn_b + Bmax_Csqn) * Ca_sr - J_SRleak * Vmyo / Vsr + J_serca ) # Expressions for the Na Concentrations component I_Na_tot_junc = ( 3 * I_nak_junc + 3 * I_ncx_junc + I_CaNa_junc + I_Na_junc + I_nabk_junc ) I_Na_tot_sl = 3 * I_nak_sl + 3 * I_ncx_sl + I_CaNa_sl + I_Na_sl + I_nabk_sl values[31] = ( -values[16] + J_na_juncsl * (-Na_j + Na_sl) / Vjunc - Cmem * I_Na_tot_junc / (Frdy * Vjunc) ) values[32] = ( -values[17] + J_na_juncsl * (-Na_sl + Na_j) / Vsl + J_na_slmyo * (-Na_sl + Na_i) / Vsl - Cmem * I_Na_tot_sl / (Frdy * Vsl) ) values[33] = J_na_slmyo * (-Na_i + Na_sl) / Vmyo # Expressions for the K Concentration component I_K_tot = -2 * I_nak + I_CaK + I_K1 + I_kp + I_kr + I_ks + I_to values[34] = 0 # Expressions for the Ca Concentrations component I_Ca_tot_junc = -2 * I_ncx_junc + I_Ca_junc + I_cabk_junc + I_pca_junc I_Ca_tot_sl = -2 * I_ncx_sl + I_Ca_sl + I_cabk_sl + I_pca_sl values[35] = ( -J_CaB_junction + J_ca_juncsl * (-Ca_j + Ca_sl) / Vjunc + J_SRCarel * Vsr / Vjunc + J_SRleak * Vmyo / Vjunc - Cmem * I_Ca_tot_junc / (2 * Frdy * Vjunc) ) values[36] = ( -J_CaB_sl + J_ca_juncsl * (-Ca_sl + Ca_j) / Vsl + J_ca_slmyo * (-Ca_sl + Ca_i) / Vsl - Cmem * I_Ca_tot_sl / (2 * Frdy * Vsl) ) values[37] = ( -J_CaB_cytosol + J_ca_slmyo * (-Ca_i + Ca_sl) / Vmyo - J_serca * Vsr / Vmyo ) # Expressions for the Membrane potential component i_Stim = np.where( np.logical_and( t - stim_period * np.floor(t / stim_period) <= stim_duration + stim_start, t - stim_period * np.floor(t / stim_period) >= stim_start, ), -stim_amplitude, 0, ) I_Na_tot = I_Na_tot_junc + I_Na_tot_sl I_Cl_tot = I_ClCa + I_Clbk I_Ca_tot = I_Ca_tot_junc + I_Ca_tot_sl I_tot = I_Ca_tot + I_Cl_tot + I_K_tot + I_Na_tot values[38] = -I_tot - i_Stim # Return results return values def monitor(states, t, parameters, monitored=None): """ Computes monitored expressions of the grandi ODE """ # Assign states assert len(states) == 39 ( m, h, j, x_kr, x_ks, x_to_s, y_to_s, x_to_f, y_to_f, d, f, f_Ca_Bj, f_Ca_Bsl, Ry_Rr, Ry_Ro, Ry_Ri, Na_Bj, Na_Bsl, Tn_CL, Tn_CHc, Tn_CHm, CaM, Myo_c, Myo_m, SRB, SLL_j, SLL_sl, SLH_j, SLH_sl, Csqn_b, Ca_sr, Na_j, Na_sl, Na_i, K_i, Ca_j, Ca_sl, Ca_i, V_m, ) = states # Assign parameters assert len(parameters) == 112 Fjunc = parameters[0] Fjunc_CaL = parameters[1] cellLength = parameters[2] cellRadius = parameters[3] junctionLength = parameters[6] junctionRadius = parameters[7] GNa = parameters[8] GNaB = parameters[9] IbarNaK = parameters[10] KmKo = parameters[11] KmNaip = parameters[12] GKr = parameters[15] GKp = parameters[16] GKs = parameters[17] pNaK = parameters[18] GK1 = parameters[19] Gto = parameters[20] epi = parameters[21] GClB = parameters[22] GClCa = parameters[23] KdClCa = parameters[24] GCaL = parameters[25] Q10CaL = parameters[26] pCa = parameters[27] pK = parameters[28] pNa = parameters[29] IbarNCX = parameters[30] Kdact = parameters[31] KmCai = parameters[32] KmCao = parameters[33] KmNai = parameters[34] KmNao = parameters[35] Q10NCX = parameters[36] ksat = parameters[37] nu = parameters[38] IbarSLCaP = parameters[39] KmPCa = parameters[40] Q10SLCaP = parameters[41] GCaB = parameters[42] Kmf = parameters[43] Kmr = parameters[44] MaxSR = parameters[45] MinSR = parameters[46] Q10SRCaP = parameters[47] Vmax_SRCaP = parameters[48] ec50SR = parameters[49] hillSRCaP = parameters[50] kiCa = parameters[51] kim = parameters[52] koCa = parameters[53] kom = parameters[54] ks = parameters[55] Bmax_Naj = parameters[56] Bmax_Nasl = parameters[57] koff_na = parameters[58] kon_na = parameters[59] Bmax_CaM = parameters[60] Bmax_SR = parameters[61] Bmax_TnChigh = parameters[62] Bmax_TnClow = parameters[63] Bmax_myosin = parameters[64] koff_cam = parameters[65] koff_myoca = parameters[66] koff_myomg = parameters[67] koff_sr = parameters[68] koff_tnchca = parameters[69] koff_tnchmg = parameters[70] koff_tncl = parameters[71] kon_cam = parameters[72] kon_myoca = parameters[73] kon_myomg = parameters[74] kon_sr = parameters[75] kon_tnchca = parameters[76] kon_tnchmg = parameters[77] kon_tncl = parameters[78] Bmax_SLhighj0 = parameters[79] Bmax_SLhighsl0 = parameters[80] Bmax_SLlowj0 = parameters[81] Bmax_SLlowsl0 = parameters[82] koff_slh = parameters[83] koff_sll = parameters[84] kon_slh = parameters[85] kon_sll = parameters[86] Bmax_Csqn0 = parameters[87] J_ca_juncsl = parameters[90] J_ca_slmyo = parameters[91] koff_csqn = parameters[92] kon_csqn = parameters[93] J_na_juncsl = parameters[96] J_na_slmyo = parameters[97] Nao = parameters[98] Ko = parameters[99] Cao = parameters[100] Cli = parameters[101] Clo = parameters[102] Mgi = parameters[103] Cmem = parameters[104] Frdy = parameters[105] R = parameters[106] Temp = parameters[107] stim_amplitude = parameters[108] stim_duration = parameters[109] stim_period = parameters[110] stim_start = parameters[111] # Init return args if monitored is None: monitored = np.zeros((176,), dtype=np.float_) else: assert isinstance(monitored, np.ndarray) and monitored.shape == (176,) # Expressions for the Geometry component monitored[0] = 1e-15 * np.pi * cellLength * (cellRadius * cellRadius) monitored[1] = 0.65 * monitored[0] monitored[2] = 0.035 * monitored[0] monitored[3] = 0.02 * monitored[0] monitored[4] = 0.0005390000000000001 * monitored[0] monitored[5] = 40300 * np.pi * junctionLength * junctionRadius monitored[6] = 2 * np.pi * cellLength * cellRadius monitored[7] = 1 - Fjunc monitored[8] = 1 - Fjunc_CaL # Expressions for the Reversal potentials component monitored[125] = Frdy / (R * Temp) monitored[126] = np.log(Nao / Na_j) / monitored[125] monitored[127] = np.log(Nao / Na_sl) / monitored[125] monitored[128] = np.log(Ko / K_i) / monitored[125] monitored[129] = np.log(Cao / Ca_j) / (2 * monitored[125]) monitored[130] = np.log(Cao / Ca_sl) / (2 * monitored[125]) monitored[131] = np.log(Cli / Clo) / monitored[125] monitored[132] = -31 + Temp / 10 # Expressions for the I_Na component monitored[9] = 1.0 / ( (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) * (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) ) monitored[10] = 0.1292 * np.exp( -( (2.9465894465894467 + 0.06435006435006435 * V_m) * (2.9465894465894467 + 0.06435006435006435 * V_m) ) ) + 0.06487 * np.exp( -( (-0.09434663536776214 + 0.019561815336463225 * V_m) * (-0.09434663536776214 + 0.019561815336463225 * V_m) ) ) monitored[11] = np.where( V_m >= -40, 0, 4.4312679295805147e-07 * np.exp(-0.14705882352941177 * V_m) ) monitored[12] = np.where( V_m >= -40, 0.77 / (0.13 + 0.049758141083938695 * np.exp(-0.0900900900900901 * V_m)), 310000.0 * np.exp(0.3485 * V_m) + 2.7 * np.exp(0.079 * V_m), ) monitored[13] = 1.0 / (monitored[11] + monitored[12]) monitored[14] = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) monitored[15] = np.where( V_m >= -40, 0, (37.78 + V_m) * (-25428.0 * np.exp(0.2444 * V_m) - 6.948e-06 * np.exp(-0.04391 * V_m)) / (1 + 50262745825.95399 * np.exp(0.311 * V_m)), ) monitored[16] = np.where( V_m >= -40, 0.6 * np.exp(0.057 * V_m) / (1 + 0.040762203978366204 * np.exp(-0.1 * V_m)), 0.02424 * np.exp(-0.01052 * V_m) / (1 + 0.003960868339904256 * np.exp(-0.1378 * V_m)), ) monitored[17] = 1.0 / (monitored[15] + monitored[16]) monitored[18] = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) monitored[137] = (-m + monitored[9]) / monitored[10] monitored[138] = (-h + monitored[14]) / monitored[13] monitored[139] = (-j + monitored[18]) / monitored[17] monitored[19] = Fjunc * GNa * (m * m * m) * (-monitored[126] + V_m) * h * j monitored[20] = GNa * (m * m * m) * (-monitored[127] + V_m) * h * j * monitored[7] monitored[21] = monitored[19] + monitored[20] # Expressions for the I_NaBK component monitored[22] = Fjunc * GNaB * (-monitored[126] + V_m) monitored[23] = GNaB * (-monitored[127] + V_m) * monitored[7] monitored[24] = monitored[22] + monitored[23] # Expressions for the I_NaK component monitored[25] = -1 / 7 + np.exp(0.01485884101040119 * Nao) / 7 monitored[26] = 1.0 / ( 1 + 0.1245 * np.exp(-0.1 * V_m * monitored[125]) + 0.0365 * np.exp(-V_m * monitored[125]) * monitored[25] ) monitored[27] = ( Fjunc * IbarNaK * Ko * monitored[26] / ((1 + np.power(KmNaip, 4) / np.power(Na_j, 4)) * (KmKo + Ko)) ) monitored[28] = ( IbarNaK * Ko * monitored[26] * monitored[7] / ((1 + np.power(KmNaip, 4) / np.power(Na_sl, 4)) * (KmKo + Ko)) ) monitored[29] = monitored[27] + monitored[28] # Expressions for the I_Kr component monitored[30] = 0.4303314829119352 * GKr * np.sqrt(Ko) monitored[31] = 1.0 / (1 + np.exp(-2 - V_m / 5)) monitored[32] = 230 / (1 + np.exp(2 + V_m / 20)) + 3300 / ( (1 + np.exp(-22 / 9 - V_m / 9)) * (1 + np.exp(11 / 9 + V_m / 9)) ) monitored[140] = (-x_kr + monitored[31]) / monitored[32] monitored[33] = 1.0 / (1 + np.exp(37 / 12 + V_m / 24)) monitored[34] = (-monitored[128] + V_m) * monitored[30] * monitored[33] * x_kr # Expressions for the I_Kp component monitored[35] = 1.0 / (1 + 1786.4755653786237 * np.exp(-0.16722408026755853 * V_m)) monitored[36] = Fjunc * GKp * (-monitored[128] + V_m) * monitored[35] monitored[37] = GKp * (-monitored[128] + V_m) * monitored[35] * monitored[7] monitored[38] = monitored[36] + monitored[37] # Expressions for the I_Ks component monitored[39] = np.log((Ko + Nao * pNaK) / (pNaK * Na_i + K_i)) / monitored[125] monitored[40] = GKs monitored[41] = GKs monitored[42] = 1.0 / (1 + 0.7659283383646487 * np.exp(-0.07017543859649122 * V_m)) monitored[43] = 990.1 / (1 + 0.8415404088681017 * np.exp(-0.0708215297450425 * V_m)) monitored[141] = (-x_ks + monitored[42]) / monitored[43] monitored[44] = Fjunc * (x_ks * x_ks) * (-monitored[39] + V_m) * monitored[40] monitored[45] = ( (x_ks * x_ks) * (-monitored[39] + V_m) * monitored[41] * monitored[7] ) monitored[46] = monitored[44] + monitored[45] # Expressions for the I_to component monitored[47] = np.where(epi == 1, 0.12 * Gto, 0.28919999999999996 * Gto) monitored[48] = np.where(epi == 1, 0.88 * Gto, 0.010799999999999999 * Gto) monitored[49] = 1.0 / (1 + np.exp(19 / 13 - V_m / 13)) monitored[50] = 1.0 / (1 + 49.40244910553019 * np.exp(V_m / 5)) monitored[51] = 0.5 + 9 / (1 + np.exp(1 / 5 + V_m / 15)) monitored[52] = 30 + 800 / (1 + np.exp(6 + V_m / 10)) monitored[142] = (-x_to_s + monitored[49]) / monitored[51] monitored[143] = (-y_to_s + monitored[50]) / monitored[52] monitored[53] = (-monitored[128] + V_m) * monitored[47] * x_to_s * y_to_s monitored[54] = 0.5 + 8.5 * np.exp(-((9 / 10 + V_m / 50) * (9 / 10 + V_m / 50))) monitored[55] = 7 + 85 * np.exp(-((40 + V_m) * (40 + V_m)) / 220) monitored[144] = (-x_to_f + monitored[49]) / monitored[54] monitored[145] = (-y_to_f + monitored[50]) / monitored[55] monitored[56] = (-monitored[128] + V_m) * monitored[48] * x_to_f * y_to_f monitored[57] = monitored[53] + monitored[56] # Expressions for the I_K1 component monitored[133] = 1.02 / ( 1 + 7.35454251046446e-07 * np.exp(0.2385 * V_m - 0.2385 * monitored[128]) ) monitored[134] = ( 0.7626240065063081 * np.exp(0.08032 * V_m - 0.08032 * monitored[128]) + 1.1534056351865558e-16 * np.exp(0.06175 * V_m - 0.06175 * monitored[128]) ) / (1 + 0.08677229415769332 * np.exp(0.5143 * monitored[128] - 0.5143 * V_m)) monitored[135] = monitored[133] / (monitored[133] + monitored[134]) monitored[136] = ( 0.4303314829119352 * GK1 * np.sqrt(Ko) * (-monitored[128] + V_m) * monitored[135] ) # Expressions for the I_ClCa component monitored[58] = Fjunc * GClCa * (-monitored[131] + V_m) / (1 + KdClCa / Ca_j) monitored[59] = ( GClCa * (-monitored[131] + V_m) * monitored[7] / (1 + KdClCa / Ca_sl) ) monitored[60] = monitored[58] + monitored[59] monitored[61] = GClB * (-monitored[131] + V_m) # Expressions for the I_Ca component monitored[62] = 1.0 / (1 + np.exp(35 / 9 + V_m / 9)) + 0.6 / ( 1 + np.exp(5 / 2 - V_m / 20) ) monitored[63] = 1.0 / (1 + np.exp(-5 / 6 - V_m / 6)) monitored[64] = ( (1 - np.exp(-5 / 6 - V_m / 6)) * monitored[63] / (0.17500000000000002 + 0.035 * V_m) ) monitored[65] = 1.0 / ( 0.02 + 0.0197 * np.exp( -( (0.48865000000000003 + 0.0337 * V_m) * (0.48865000000000003 + 0.0337 * V_m) ) ) ) monitored[146] = (-d + monitored[63]) / monitored[64] monitored[147] = (-f + monitored[62]) / monitored[65] monitored[148] = -0.0119 * f_Ca_Bj + 1.7 * (1 - f_Ca_Bj) * Ca_j monitored[149] = -0.0119 * f_Ca_Bsl + 1.7 * (1 - f_Ca_Bsl) * Ca_sl monitored[66] = 0 monitored[67] = 0 monitored[68] = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_j * np.exp(2 * V_m * monitored[125])) * V_m * monitored[125] / (-1 + np.exp(2 * V_m * monitored[125])) ) monitored[69] = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_sl * np.exp(2 * V_m * monitored[125])) * V_m * monitored[125] / (-1 + np.exp(2 * V_m * monitored[125])) ) monitored[70] = ( Frdy * GCaL * pK * (-0.75 * Ko + 0.75 * K_i * np.exp(V_m * monitored[125])) * V_m * monitored[125] / (-1 + np.exp(V_m * monitored[125])) ) monitored[71] = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_j * np.exp(V_m * monitored[125])) * V_m * monitored[125] / (-1 + np.exp(V_m * monitored[125])) ) monitored[72] = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_sl * np.exp(V_m * monitored[125])) * V_m * monitored[125] / (-1 + np.exp(V_m * monitored[125])) ) monitored[73] = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, monitored[132]) * (1 + monitored[67] - f_Ca_Bj) * d * f * monitored[68] ) monitored[74] = ( 0.45 * np.power(Q10CaL, monitored[132]) * (1 + monitored[66] - f_Ca_Bsl) * d * f * monitored[69] * monitored[8] ) monitored[75] = monitored[73] + monitored[74] monitored[76] = ( 0.45 * np.power(Q10CaL, monitored[132]) * ( Fjunc_CaL * (1 + monitored[67] - f_Ca_Bj) + (1 + monitored[66] - f_Ca_Bsl) * monitored[8] ) * d * f * monitored[70] ) monitored[77] = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, monitored[132]) * (1 + monitored[67] - f_Ca_Bj) * d * f * monitored[71] ) monitored[78] = ( 0.45 * np.power(Q10CaL, monitored[132]) * (1 + monitored[66] - f_Ca_Bsl) * d * f * monitored[72] * monitored[8] ) monitored[79] = monitored[77] + monitored[78] monitored[80] = monitored[75] + monitored[76] + monitored[79] # Expressions for the I_NCX component monitored[81] = 1.0 / (1 + (Kdact * Kdact) / (Ca_j * Ca_j)) monitored[82] = 1.0 / (1 + (Kdact * Kdact) / (Ca_sl * Ca_sl)) monitored[83] = Cao * (Na_j * Na_j * Na_j) * np.exp(nu * V_m * monitored[125]) monitored[84] = Cao * (Na_sl * Na_sl * Na_sl) * np.exp(nu * V_m * monitored[125]) monitored[85] = (Nao * Nao * Nao) * Ca_j * np.exp((-1 + nu) * V_m * monitored[125]) monitored[86] = ( Cao * (Na_j * Na_j * Na_j) + KmCao * (Na_j * Na_j * Na_j) + (Nao * Nao * Nao) * Ca_j + KmCai * (Nao * Nao * Nao) * (1 + (Na_j * Na_j * Na_j) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_j / KmCai) * Ca_j ) monitored[87] = (Nao * Nao * Nao) * Ca_sl * np.exp((-1 + nu) * V_m * monitored[125]) monitored[88] = ( Cao * (Na_sl * Na_sl * Na_sl) + KmCao * (Na_sl * Na_sl * Na_sl) + (Nao * Nao * Nao) * Ca_sl + KmCai * (Nao * Nao * Nao) * (1 + (Na_sl * Na_sl * Na_sl) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_sl / KmCai) * Ca_sl ) monitored[89] = ( Fjunc * IbarNCX * np.power(Q10NCX, monitored[132]) * (-monitored[85] + monitored[83]) * monitored[81] / ((1 + ksat * np.exp((-1 + nu) * V_m * monitored[125])) * monitored[86]) ) monitored[90] = ( IbarNCX * np.power(Q10NCX, monitored[132]) * (-monitored[87] + monitored[84]) * monitored[7] * monitored[82] / ((1 + ksat * np.exp((-1 + nu) * V_m * monitored[125])) * monitored[88]) ) monitored[91] = monitored[89] + monitored[90] # Expressions for the I_PCa component monitored[92] = ( Fjunc * IbarSLCaP * np.power(Q10SLCaP, monitored[132]) * np.power(Ca_j, 1.6) / (np.power(KmPCa, 1.6) + np.power(Ca_j, 1.6)) ) monitored[93] = ( IbarSLCaP * np.power(Q10SLCaP, monitored[132]) * np.power(Ca_sl, 1.6) * monitored[7] / (np.power(KmPCa, 1.6) + np.power(Ca_sl, 1.6)) ) monitored[94] = monitored[92] + monitored[93] # Expressions for the I_CaBK component monitored[95] = Fjunc * GCaB * (-monitored[129] + V_m) monitored[96] = GCaB * (-monitored[130] + V_m) * monitored[7] monitored[97] = monitored[95] + monitored[96] # Expressions for the SR Fluxes component monitored[98] = MaxSR - (MaxSR - MinSR) / (1 + np.power(ec50SR / Ca_sr, 2.5)) monitored[99] = koCa / monitored[98] monitored[100] = kiCa * monitored[98] monitored[101] = 1 - Ry_Ri - Ry_Ro - Ry_Rr monitored[150] = ( kim * monitored[101] + kom * Ry_Ro - (Ca_j * Ca_j) * Ry_Rr * monitored[99] - Ca_j * Ry_Rr * monitored[100] ) monitored[151] = ( kim * Ry_Ri - kom * Ry_Ro + (Ca_j * Ca_j) * Ry_Rr * monitored[99] - Ca_j * Ry_Ro * monitored[100] ) monitored[152] = ( -kim * Ry_Ri - kom * Ry_Ri + (Ca_j * Ca_j) * monitored[101] * monitored[99] + Ca_j * Ry_Ro * monitored[100] ) monitored[102] = ks * (-Ca_j + Ca_sr) * Ry_Ro monitored[103] = ( Vmax_SRCaP * np.power(Q10SRCaP, monitored[132]) * (np.power(Ca_i / Kmf, hillSRCaP) - np.power(Ca_sr / Kmr, hillSRCaP)) / (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) ) monitored[104] = 5.348e-06 * Ca_sr - 5.348e-06 * Ca_j # Expressions for the Na Buffers component monitored[153] = -koff_na * Na_Bj + kon_na * (Bmax_Naj - Na_Bj) * Na_j monitored[154] = -koff_na * Na_Bsl + kon_na * (Bmax_Nasl - Na_Bsl) * Na_sl # Expressions for the Cytosolic Ca Buffers component monitored[155] = -koff_tncl * Tn_CL + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i monitored[156] = ( -koff_tnchca * Tn_CHc + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i ) monitored[157] = -koff_tnchmg * Tn_CHm + Mgi * kon_tnchmg * ( Bmax_TnChigh - Tn_CHc - Tn_CHm ) monitored[158] = -koff_cam * CaM + kon_cam * (Bmax_CaM - CaM) * Ca_i monitored[159] = ( -koff_myoca * Myo_c + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i ) monitored[160] = -koff_myomg * Myo_m + Mgi * kon_myomg * ( Bmax_myosin - Myo_c - Myo_m ) monitored[161] = -koff_sr * SRB + kon_sr * (Bmax_SR - SRB) * Ca_i monitored[105] = ( -koff_cam * CaM - koff_myoca * Myo_c - koff_myomg * Myo_m - koff_sr * SRB - koff_tnchca * Tn_CHc - koff_tnchmg * Tn_CHm - koff_tncl * Tn_CL + Mgi * kon_myomg * (Bmax_myosin - Myo_c - Myo_m) + Mgi * kon_tnchmg * (Bmax_TnChigh - Tn_CHc - Tn_CHm) + kon_cam * (Bmax_CaM - CaM) * Ca_i + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i + kon_sr * (Bmax_SR - SRB) * Ca_i + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i ) # Expressions for the Junctional and SL Ca Buffers component monitored[106] = Bmax_SLlowsl0 * monitored[1] / monitored[3] monitored[107] = Bmax_SLlowj0 * monitored[1] / monitored[4] monitored[108] = Bmax_SLhighsl0 * monitored[1] / monitored[3] monitored[109] = Bmax_SLhighj0 * monitored[1] / monitored[4] monitored[162] = -koff_sll * SLL_j + kon_sll * (-SLL_j + monitored[107]) * Ca_j monitored[163] = -koff_sll * SLL_sl + kon_sll * (-SLL_sl + monitored[106]) * Ca_sl monitored[164] = -koff_slh * SLH_j + kon_slh * (-SLH_j + monitored[109]) * Ca_j monitored[165] = -koff_slh * SLH_sl + kon_slh * (-SLH_sl + monitored[108]) * Ca_sl monitored[110] = ( -koff_slh * SLH_j - koff_sll * SLL_j + kon_slh * (-SLH_j + monitored[109]) * Ca_j + kon_sll * (-SLL_j + monitored[107]) * Ca_j ) monitored[111] = ( -koff_slh * SLH_sl - koff_sll * SLL_sl + kon_slh * (-SLH_sl + monitored[108]) * Ca_sl + kon_sll * (-SLL_sl + monitored[106]) * Ca_sl ) # Expressions for the SR Ca Concentrations component monitored[112] = Bmax_Csqn0 * monitored[1] / monitored[2] monitored[166] = -koff_csqn * Csqn_b + kon_csqn * (-Csqn_b + monitored[112]) * Ca_sr monitored[167] = ( -monitored[102] + koff_csqn * Csqn_b - kon_csqn * (-Csqn_b + monitored[112]) * Ca_sr - monitored[104] * monitored[1] / monitored[2] + monitored[103] ) # Expressions for the Na Concentrations component monitored[113] = ( 3 * monitored[27] + 3 * monitored[89] + monitored[19] + monitored[22] + monitored[77] ) monitored[114] = ( 3 * monitored[28] + 3 * monitored[90] + monitored[20] + monitored[23] + monitored[78] ) monitored[115] = 3 * monitored[28] + 3 * monitored[90] + monitored[78] monitored[116] = 3 * monitored[27] + 3 * monitored[89] + monitored[77] monitored[168] = ( -monitored[153] + J_na_juncsl * (-Na_j + Na_sl) / monitored[4] - Cmem * monitored[113] / (Frdy * monitored[4]) ) monitored[169] = ( -monitored[154] + J_na_juncsl * (-Na_sl + Na_j) / monitored[3] + J_na_slmyo * (-Na_sl + Na_i) / monitored[3] - Cmem * monitored[114] / (Frdy * monitored[3]) ) monitored[170] = J_na_slmyo * (-Na_i + Na_sl) / monitored[1] # Expressions for the K Concentration component monitored[117] = ( -2 * monitored[29] + monitored[136] + monitored[34] + monitored[38] + monitored[46] + monitored[57] + monitored[76] ) monitored[171] = 0 # Expressions for the Ca Concentrations component monitored[118] = -2 * monitored[89] + monitored[73] + monitored[92] + monitored[95] monitored[119] = -2 * monitored[90] + monitored[74] + monitored[93] + monitored[96] monitored[172] = ( -monitored[110] + J_ca_juncsl * (-Ca_j + Ca_sl) / monitored[4] + monitored[102] * monitored[2] / monitored[4] + monitored[104] * monitored[1] / monitored[4] - Cmem * monitored[118] / (2 * Frdy * monitored[4]) ) monitored[173] = ( -monitored[111] + J_ca_juncsl * (-Ca_sl + Ca_j) / monitored[3] + J_ca_slmyo * (-Ca_sl + Ca_i) / monitored[3] - Cmem * monitored[119] / (2 * Frdy * monitored[3]) ) monitored[174] = ( -monitored[105] + J_ca_slmyo * (-Ca_i + Ca_sl) / monitored[1] - monitored[103] * monitored[2] / monitored[1] ) # Expressions for the Membrane potential component monitored[120] = np.where( np.logical_and( t - stim_period * np.floor(t / stim_period) <= stim_duration + stim_start, t - stim_period * np.floor(t / stim_period) >= stim_start, ), -stim_amplitude, 0, ) monitored[121] = monitored[113] + monitored[114] monitored[122] = monitored[60] + monitored[61] monitored[123] = monitored[118] + monitored[119] monitored[124] = monitored[117] + monitored[121] + monitored[122] + monitored[123] monitored[175] = -monitored[120] - monitored[124] # Return results return monitored def FE(states, t, dt, parameters): """ Compute a forward step using the explicit Euler algorithm to the grandi ODE """ # Assign states assert len(states) == 39 ( m, h, j, x_kr, x_ks, x_to_s, y_to_s, x_to_f, y_to_f, d, f, f_Ca_Bj, f_Ca_Bsl, Ry_Rr, Ry_Ro, Ry_Ri, Na_Bj, Na_Bsl, Tn_CL, Tn_CHc, Tn_CHm, CaM, Myo_c, Myo_m, SRB, SLL_j, SLL_sl, SLH_j, SLH_sl, Csqn_b, Ca_sr, Na_j, Na_sl, Na_i, K_i, Ca_j, Ca_sl, Ca_i, V_m, ) = states # Assign parameters assert len(parameters) == 112 Fjunc = parameters[0] Fjunc_CaL = parameters[1] cellLength = parameters[2] cellRadius = parameters[3] GNa = parameters[8] GNaB = parameters[9] IbarNaK = parameters[10] KmKo = parameters[11] KmNaip = parameters[12] GKr = parameters[15] GKp = parameters[16] GKs = parameters[17] pNaK = parameters[18] GK1 = parameters[19] Gto = parameters[20] epi = parameters[21] GClB = parameters[22] GClCa = parameters[23] KdClCa = parameters[24] GCaL = parameters[25] Q10CaL = parameters[26] pCa = parameters[27] pK = parameters[28] pNa = parameters[29] IbarNCX = parameters[30] Kdact = parameters[31] KmCai = parameters[32] KmCao = parameters[33] KmNai = parameters[34] KmNao = parameters[35] Q10NCX = parameters[36] ksat = parameters[37] nu = parameters[38] IbarSLCaP = parameters[39] KmPCa = parameters[40] Q10SLCaP = parameters[41] GCaB = parameters[42] Kmf = parameters[43] Kmr = parameters[44] MaxSR = parameters[45] MinSR = parameters[46] Q10SRCaP = parameters[47] Vmax_SRCaP = parameters[48] ec50SR = parameters[49] hillSRCaP = parameters[50] kiCa = parameters[51] kim = parameters[52] koCa = parameters[53] kom = parameters[54] ks = parameters[55] Bmax_Naj = parameters[56] Bmax_Nasl = parameters[57] koff_na = parameters[58] kon_na = parameters[59] Bmax_CaM = parameters[60] Bmax_SR = parameters[61] Bmax_TnChigh = parameters[62] Bmax_TnClow = parameters[63] Bmax_myosin = parameters[64] koff_cam = parameters[65] koff_myoca = parameters[66] koff_myomg = parameters[67] koff_sr = parameters[68] koff_tnchca = parameters[69] koff_tnchmg = parameters[70] koff_tncl = parameters[71] kon_cam = parameters[72] kon_myoca = parameters[73] kon_myomg = parameters[74] kon_sr = parameters[75] kon_tnchca = parameters[76] kon_tnchmg = parameters[77] kon_tncl = parameters[78] Bmax_SLhighj0 = parameters[79] Bmax_SLhighsl0 = parameters[80] Bmax_SLlowj0 = parameters[81] Bmax_SLlowsl0 = parameters[82] koff_slh = parameters[83] koff_sll = parameters[84] kon_slh = parameters[85] kon_sll = parameters[86] Bmax_Csqn0 = parameters[87] J_ca_juncsl = parameters[90] J_ca_slmyo = parameters[91] koff_csqn = parameters[92] kon_csqn = parameters[93] J_na_juncsl = parameters[96] J_na_slmyo = parameters[97] Nao = parameters[98] Ko = parameters[99] Cao = parameters[100] Cli = parameters[101] Clo = parameters[102] Mgi = parameters[103] Cmem = parameters[104] Frdy = parameters[105] R = parameters[106] Temp = parameters[107] stim_amplitude = parameters[108] stim_duration = parameters[109] stim_period = parameters[110] stim_start = parameters[111] # Expressions for the Geometry component Vcell = 1e-15 * np.pi * cellLength * (cellRadius * cellRadius) Vmyo = 0.65 * Vcell Vsr = 0.035 * Vcell Vsl = 0.02 * Vcell Vjunc = 0.0005390000000000001 * Vcell Fsl = 1 - Fjunc Fsl_CaL = 1 - Fjunc_CaL # Expressions for the Reversal potentials component FoRT = Frdy / (R * Temp) ena_junc = np.log(Nao / Na_j) / FoRT ena_sl = np.log(Nao / Na_sl) / FoRT ek = np.log(Ko / K_i) / FoRT eca_junc = np.log(Cao / Ca_j) / (2 * FoRT) eca_sl = np.log(Cao / Ca_sl) / (2 * FoRT) ecl = np.log(Cli / Clo) / FoRT Qpow = -31 + Temp / 10 # Expressions for the I_Na component mss = 1.0 / ( (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) * (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) ) taum = 0.1292 * np.exp( -( (2.9465894465894467 + 0.06435006435006435 * V_m) * (2.9465894465894467 + 0.06435006435006435 * V_m) ) ) + 0.06487 * np.exp( -( (-0.09434663536776214 + 0.019561815336463225 * V_m) * (-0.09434663536776214 + 0.019561815336463225 * V_m) ) ) ah = np.where( V_m >= -40, 0, 4.4312679295805147e-07 * np.exp(-0.14705882352941177 * V_m) ) bh = np.where( V_m >= -40, 0.77 / (0.13 + 0.049758141083938695 * np.exp(-0.0900900900900901 * V_m)), 310000.0 * np.exp(0.3485 * V_m) + 2.7 * np.exp(0.079 * V_m), ) tauh = 1.0 / (ah + bh) hss = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) aj = np.where( V_m >= -40, 0, (37.78 + V_m) * (-25428.0 * np.exp(0.2444 * V_m) - 6.948e-06 * np.exp(-0.04391 * V_m)) / (1 + 50262745825.95399 * np.exp(0.311 * V_m)), ) bj = np.where( V_m >= -40, 0.6 * np.exp(0.057 * V_m) / (1 + 0.040762203978366204 * np.exp(-0.1 * V_m)), 0.02424 * np.exp(-0.01052 * V_m) / (1 + 0.003960868339904256 * np.exp(-0.1378 * V_m)), ) tauj = 1.0 / (aj + bj) jss = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) dm_dt = (-m + mss) / taum states[0] = dt * dm_dt + m dh_dt = (-h + hss) / tauh states[1] = dt * dh_dt + h dj_dt = (-j + jss) / tauj states[2] = dt * dj_dt + j I_Na_junc = Fjunc * GNa * (m * m * m) * (-ena_junc + V_m) * h * j I_Na_sl = GNa * (m * m * m) * (-ena_sl + V_m) * Fsl * h * j # Expressions for the I_NaBK component I_nabk_junc = Fjunc * GNaB * (-ena_junc + V_m) I_nabk_sl = GNaB * (-ena_sl + V_m) * Fsl # Expressions for the I_NaK component sigma = -1 / 7 + np.exp(0.01485884101040119 * Nao) / 7 fnak = 1.0 / ( 1 + 0.1245 * np.exp(-0.1 * FoRT * V_m) + 0.0365 * np.exp(-FoRT * V_m) * sigma ) I_nak_junc = ( Fjunc * IbarNaK * Ko * fnak / ((1 + np.power(KmNaip, 4) / np.power(Na_j, 4)) * (KmKo + Ko)) ) I_nak_sl = ( IbarNaK * Ko * Fsl * fnak / ((1 + np.power(KmNaip, 4) / np.power(Na_sl, 4)) * (KmKo + Ko)) ) I_nak = I_nak_junc + I_nak_sl # Expressions for the I_Kr component gkr = 0.4303314829119352 * GKr * np.sqrt(Ko) xrss = 1.0 / (1 + np.exp(-2 - V_m / 5)) tauxr = 230 / (1 + np.exp(2 + V_m / 20)) + 3300 / ( (1 + np.exp(-22 / 9 - V_m / 9)) * (1 + np.exp(11 / 9 + V_m / 9)) ) dx_kr_dt = (-x_kr + xrss) / tauxr states[3] = dt * dx_kr_dt + x_kr rkr = 1.0 / (1 + np.exp(37 / 12 + V_m / 24)) I_kr = (-ek + V_m) * gkr * rkr * x_kr # Expressions for the I_Kp component kp_kp = 1.0 / (1 + 1786.4755653786237 * np.exp(-0.16722408026755853 * V_m)) I_kp_junc = Fjunc * GKp * (-ek + V_m) * kp_kp I_kp_sl = GKp * (-ek + V_m) * Fsl * kp_kp I_kp = I_kp_junc + I_kp_sl # Expressions for the I_Ks component eks = np.log((Ko + Nao * pNaK) / (pNaK * Na_i + K_i)) / FoRT gks_junc = GKs gks_sl = GKs xsss = 1.0 / (1 + 0.7659283383646487 * np.exp(-0.07017543859649122 * V_m)) tauxs = 990.1 / (1 + 0.8415404088681017 * np.exp(-0.0708215297450425 * V_m)) dx_ks_dt = (-x_ks + xsss) / tauxs states[4] = dt * dx_ks_dt + x_ks I_ks_junc = Fjunc * (x_ks * x_ks) * (-eks + V_m) * gks_junc I_ks_sl = (x_ks * x_ks) * (-eks + V_m) * Fsl * gks_sl I_ks = I_ks_junc + I_ks_sl # Expressions for the I_to component GtoSlow = np.where(epi == 1, 0.12 * Gto, 0.28919999999999996 * Gto) GtoFast = np.where(epi == 1, 0.88 * Gto, 0.010799999999999999 * Gto) xtoss = 1.0 / (1 + np.exp(19 / 13 - V_m / 13)) ytoss = 1.0 / (1 + 49.40244910553019 * np.exp(V_m / 5)) tauxtos = 0.5 + 9 / (1 + np.exp(1 / 5 + V_m / 15)) tauytos = 30 + 800 / (1 + np.exp(6 + V_m / 10)) dx_to_s_dt = (-x_to_s + xtoss) / tauxtos states[5] = dt * dx_to_s_dt + x_to_s dy_to_s_dt = (-y_to_s + ytoss) / tauytos states[6] = dt * dy_to_s_dt + y_to_s I_tos = (-ek + V_m) * GtoSlow * x_to_s * y_to_s tauxtof = 0.5 + 8.5 * np.exp(-((9 / 10 + V_m / 50) * (9 / 10 + V_m / 50))) tauytof = 7 + 85 * np.exp(-((40 + V_m) * (40 + V_m)) / 220) dx_to_f_dt = (-x_to_f + xtoss) / tauxtof states[7] = dt * dx_to_f_dt + x_to_f dy_to_f_dt = (-y_to_f + ytoss) / tauytof states[8] = dt * dy_to_f_dt + y_to_f I_tof = (-ek + V_m) * GtoFast * x_to_f * y_to_f I_to = I_tof + I_tos # Expressions for the I_K1 component aki = 1.02 / (1 + 7.35454251046446e-07 * np.exp(0.2385 * V_m - 0.2385 * ek)) bki = ( 0.7626240065063081 * np.exp(0.08032 * V_m - 0.08032 * ek) + 1.1534056351865558e-16 * np.exp(0.06175 * V_m - 0.06175 * ek) ) / (1 + 0.08677229415769332 * np.exp(0.5143 * ek - 0.5143 * V_m)) kiss = aki / (aki + bki) I_K1 = 0.4303314829119352 * GK1 * np.sqrt(Ko) * (-ek + V_m) * kiss # Expressions for the I_ClCa component I_ClCa_junc = Fjunc * GClCa * (-ecl + V_m) / (1 + KdClCa / Ca_j) I_ClCa_sl = GClCa * (-ecl + V_m) * Fsl / (1 + KdClCa / Ca_sl) I_ClCa = I_ClCa_junc + I_ClCa_sl I_Clbk = GClB * (-ecl + V_m) # Expressions for the I_Ca component fss = 1.0 / (1 + np.exp(35 / 9 + V_m / 9)) + 0.6 / (1 + np.exp(5 / 2 - V_m / 20)) dss = 1.0 / (1 + np.exp(-5 / 6 - V_m / 6)) taud = (1 - np.exp(-5 / 6 - V_m / 6)) * dss / (0.17500000000000002 + 0.035 * V_m) tauf = 1.0 / ( 0.02 + 0.0197 * np.exp( -( (0.48865000000000003 + 0.0337 * V_m) * (0.48865000000000003 + 0.0337 * V_m) ) ) ) dd_dt = (-d + dss) / taud states[9] = dt * dd_dt + d df_dt = (-f + fss) / tauf states[10] = dt * df_dt + f df_Ca_Bj_dt = -0.0119 * f_Ca_Bj + 1.7 * (1 - f_Ca_Bj) * Ca_j states[11] = dt * df_Ca_Bj_dt + f_Ca_Bj df_Ca_Bsl_dt = -0.0119 * f_Ca_Bsl + 1.7 * (1 - f_Ca_Bsl) * Ca_sl states[12] = dt * df_Ca_Bsl_dt + f_Ca_Bsl fcaCaMSL = 0 fcaCaj = 0 ibarca_j = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_j * np.exp(2 * FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(2 * FoRT * V_m)) ) ibarca_sl = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_sl * np.exp(2 * FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(2 * FoRT * V_m)) ) ibark = ( Frdy * GCaL * pK * (-0.75 * Ko + 0.75 * K_i * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) ibarna_j = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_j * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) ibarna_sl = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_sl * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) I_Ca_junc = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f * ibarca_j ) I_Ca_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f * ibarca_sl ) I_CaK = ( 0.45 * np.power(Q10CaL, Qpow) * (Fjunc_CaL * (1 + fcaCaj - f_Ca_Bj) + (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL) * d * f * ibark ) I_CaNa_junc = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f * ibarna_j ) I_CaNa_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f * ibarna_sl ) # Expressions for the I_NCX component Ka_junc = 1.0 / (1 + (Kdact * Kdact) / (Ca_j * Ca_j)) Ka_sl = 1.0 / (1 + (Kdact * Kdact) / (Ca_sl * Ca_sl)) s1_junc = Cao * (Na_j * Na_j * Na_j) * np.exp(nu * FoRT * V_m) s1_sl = Cao * (Na_sl * Na_sl * Na_sl) * np.exp(nu * FoRT * V_m) s2_junc = (Nao * Nao * Nao) * Ca_j * np.exp((-1 + nu) * FoRT * V_m) s3_junc = ( Cao * (Na_j * Na_j * Na_j) + KmCao * (Na_j * Na_j * Na_j) + (Nao * Nao * Nao) * Ca_j + KmCai * (Nao * Nao * Nao) * (1 + (Na_j * Na_j * Na_j) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_j / KmCai) * Ca_j ) s2_sl = (Nao * Nao * Nao) * Ca_sl * np.exp((-1 + nu) * FoRT * V_m) s3_sl = ( Cao * (Na_sl * Na_sl * Na_sl) + KmCao * (Na_sl * Na_sl * Na_sl) + (Nao * Nao * Nao) * Ca_sl + KmCai * (Nao * Nao * Nao) * (1 + (Na_sl * Na_sl * Na_sl) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_sl / KmCai) * Ca_sl ) I_ncx_junc = ( Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * (-s2_junc + s1_junc) * Ka_junc / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_junc) ) I_ncx_sl = ( IbarNCX * np.power(Q10NCX, Qpow) * (-s2_sl + s1_sl) * Fsl * Ka_sl / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_sl) ) # Expressions for the I_PCa component I_pca_junc = ( Fjunc * IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power(Ca_j, 1.6) / (np.power(KmPCa, 1.6) + np.power(Ca_j, 1.6)) ) I_pca_sl = ( IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power(Ca_sl, 1.6) * Fsl / (np.power(KmPCa, 1.6) + np.power(Ca_sl, 1.6)) ) # Expressions for the I_CaBK component I_cabk_junc = Fjunc * GCaB * (-eca_junc + V_m) I_cabk_sl = GCaB * (-eca_sl + V_m) * Fsl # Expressions for the SR Fluxes component kCaSR = MaxSR - (MaxSR - MinSR) / (1 + np.power(ec50SR / Ca_sr, 2.5)) koSRCa = koCa / kCaSR kiSRCa = kiCa * kCaSR RI = 1 - Ry_Ri - Ry_Ro - Ry_Rr dRy_Rr_dt = ( kim * RI + kom * Ry_Ro - (Ca_j * Ca_j) * Ry_Rr * koSRCa - Ca_j * Ry_Rr * kiSRCa ) states[13] = dt * dRy_Rr_dt + Ry_Rr dRy_Ro_dt = ( kim * Ry_Ri - kom * Ry_Ro + (Ca_j * Ca_j) * Ry_Rr * koSRCa - Ca_j * Ry_Ro * kiSRCa ) states[14] = dt * dRy_Ro_dt + Ry_Ro dRy_Ri_dt = ( -kim * Ry_Ri - kom * Ry_Ri + (Ca_j * Ca_j) * RI * koSRCa + Ca_j * Ry_Ro * kiSRCa ) states[15] = dt * dRy_Ri_dt + Ry_Ri J_SRCarel = ks * (-Ca_j + Ca_sr) * Ry_Ro J_serca = ( Vmax_SRCaP * np.power(Q10SRCaP, Qpow) * (np.power(Ca_i / Kmf, hillSRCaP) - np.power(Ca_sr / Kmr, hillSRCaP)) / (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) ) J_SRleak = 5.348e-06 * Ca_sr - 5.348e-06 * Ca_j # Expressions for the Na Buffers component dNa_Bj_dt = -koff_na * Na_Bj + kon_na * (Bmax_Naj - Na_Bj) * Na_j states[16] = dt * dNa_Bj_dt + Na_Bj dNa_Bsl_dt = -koff_na * Na_Bsl + kon_na * (Bmax_Nasl - Na_Bsl) * Na_sl states[17] = dt * dNa_Bsl_dt + Na_Bsl # Expressions for the Cytosolic Ca Buffers component dTn_CL_dt = -koff_tncl * Tn_CL + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i states[18] = dt * dTn_CL_dt + Tn_CL dTn_CHc_dt = ( -koff_tnchca * Tn_CHc + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i ) states[19] = dt * dTn_CHc_dt + Tn_CHc dTn_CHm_dt = -koff_tnchmg * Tn_CHm + Mgi * kon_tnchmg * ( Bmax_TnChigh - Tn_CHc - Tn_CHm ) states[20] = dt * dTn_CHm_dt + Tn_CHm dCaM_dt = -koff_cam * CaM + kon_cam * (Bmax_CaM - CaM) * Ca_i states[21] = dt * dCaM_dt + CaM dMyo_c_dt = -koff_myoca * Myo_c + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i states[22] = dt * dMyo_c_dt + Myo_c dMyo_m_dt = -koff_myomg * Myo_m + Mgi * kon_myomg * (Bmax_myosin - Myo_c - Myo_m) states[23] = dt * dMyo_m_dt + Myo_m dSRB_dt = -koff_sr * SRB + kon_sr * (Bmax_SR - SRB) * Ca_i states[24] = dt * dSRB_dt + SRB J_CaB_cytosol = ( -koff_cam * CaM - koff_myoca * Myo_c - koff_myomg * Myo_m - koff_sr * SRB - koff_tnchca * Tn_CHc - koff_tnchmg * Tn_CHm - koff_tncl * Tn_CL + Mgi * kon_myomg * (Bmax_myosin - Myo_c - Myo_m) + Mgi * kon_tnchmg * (Bmax_TnChigh - Tn_CHc - Tn_CHm) + kon_cam * (Bmax_CaM - CaM) * Ca_i + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i + kon_sr * (Bmax_SR - SRB) * Ca_i + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i ) # Expressions for the Junctional and SL Ca Buffers component Bmax_SLlowsl = Bmax_SLlowsl0 * Vmyo / Vsl Bmax_SLlowj = Bmax_SLlowj0 * Vmyo / Vjunc Bmax_SLhighsl = Bmax_SLhighsl0 * Vmyo / Vsl Bmax_SLhighj = Bmax_SLhighj0 * Vmyo / Vjunc dSLL_j_dt = -koff_sll * SLL_j + kon_sll * (-SLL_j + Bmax_SLlowj) * Ca_j states[25] = dt * dSLL_j_dt + SLL_j dSLL_sl_dt = -koff_sll * SLL_sl + kon_sll * (-SLL_sl + Bmax_SLlowsl) * Ca_sl states[26] = dt * dSLL_sl_dt + SLL_sl dSLH_j_dt = -koff_slh * SLH_j + kon_slh * (-SLH_j + Bmax_SLhighj) * Ca_j states[27] = dt * dSLH_j_dt + SLH_j dSLH_sl_dt = -koff_slh * SLH_sl + kon_slh * (-SLH_sl + Bmax_SLhighsl) * Ca_sl states[28] = dt * dSLH_sl_dt + SLH_sl J_CaB_junction = ( -koff_slh * SLH_j - koff_sll * SLL_j + kon_slh * (-SLH_j + Bmax_SLhighj) * Ca_j + kon_sll * (-SLL_j + Bmax_SLlowj) * Ca_j ) J_CaB_sl = ( -koff_slh * SLH_sl - koff_sll * SLL_sl + kon_slh * (-SLH_sl + Bmax_SLhighsl) * Ca_sl + kon_sll * (-SLL_sl + Bmax_SLlowsl) * Ca_sl ) # Expressions for the SR Ca Concentrations component Bmax_Csqn = Bmax_Csqn0 * Vmyo / Vsr dCsqn_b_dt = -koff_csqn * Csqn_b + kon_csqn * (-Csqn_b + Bmax_Csqn) * Ca_sr states[29] = dt * dCsqn_b_dt + Csqn_b dCa_sr_dt = ( -J_SRCarel + koff_csqn * Csqn_b - kon_csqn * (-Csqn_b + Bmax_Csqn) * Ca_sr - J_SRleak * Vmyo / Vsr + J_serca ) states[30] = dt * dCa_sr_dt + Ca_sr # Expressions for the Na Concentrations component I_Na_tot_junc = ( 3 * I_nak_junc + 3 * I_ncx_junc + I_CaNa_junc + I_Na_junc + I_nabk_junc ) I_Na_tot_sl = 3 * I_nak_sl + 3 * I_ncx_sl + I_CaNa_sl + I_Na_sl + I_nabk_sl dNa_j_dt = ( -dNa_Bj_dt + J_na_juncsl * (-Na_j + Na_sl) / Vjunc - Cmem * I_Na_tot_junc / (Frdy * Vjunc) ) states[31] = dt * dNa_j_dt + Na_j dNa_sl_dt = ( -dNa_Bsl_dt + J_na_juncsl * (-Na_sl + Na_j) / Vsl + J_na_slmyo * (-Na_sl + Na_i) / Vsl - Cmem * I_Na_tot_sl / (Frdy * Vsl) ) states[32] = dt * dNa_sl_dt + Na_sl dNa_i_dt = J_na_slmyo * (-Na_i + Na_sl) / Vmyo states[33] = dt * dNa_i_dt + Na_i # Expressions for the K Concentration component I_K_tot = -2 * I_nak + I_CaK + I_K1 + I_kp + I_kr + I_ks + I_to dK_i_dt = 0 states[34] = dt * dK_i_dt + K_i # Expressions for the Ca Concentrations component I_Ca_tot_junc = -2 * I_ncx_junc + I_Ca_junc + I_cabk_junc + I_pca_junc I_Ca_tot_sl = -2 * I_ncx_sl + I_Ca_sl + I_cabk_sl + I_pca_sl dCa_j_dt = ( -J_CaB_junction + J_ca_juncsl * (-Ca_j + Ca_sl) / Vjunc + J_SRCarel * Vsr / Vjunc + J_SRleak * Vmyo / Vjunc - Cmem * I_Ca_tot_junc / (2 * Frdy * Vjunc) ) states[35] = dt * dCa_j_dt + Ca_j dCa_sl_dt = ( -J_CaB_sl + J_ca_juncsl * (-Ca_sl + Ca_j) / Vsl + J_ca_slmyo * (-Ca_sl + Ca_i) / Vsl - Cmem * I_Ca_tot_sl / (2 * Frdy * Vsl) ) states[36] = dt * dCa_sl_dt + Ca_sl dCa_i_dt = ( -J_CaB_cytosol + J_ca_slmyo * (-Ca_i + Ca_sl) / Vmyo - J_serca * Vsr / Vmyo ) states[37] = dt * dCa_i_dt + Ca_i # Expressions for the Membrane potential component i_Stim = np.where( np.logical_and( t - stim_period * np.floor(t / stim_period) <= stim_duration + stim_start, t - stim_period * np.floor(t / stim_period) >= stim_start, ), -stim_amplitude, 0, ) I_Na_tot = I_Na_tot_junc + I_Na_tot_sl I_Cl_tot = I_ClCa + I_Clbk I_Ca_tot = I_Ca_tot_junc + I_Ca_tot_sl I_tot = I_Ca_tot + I_Cl_tot + I_K_tot + I_Na_tot dV_m_dt = -I_tot - i_Stim states[38] = dt * dV_m_dt + V_m # Return results return states def GRL1(states, t, dt, parameters): """ Compute a forward step using the rush larsen algorithm to the grandi ODE """ # Assign states assert len(states) == 39 ( m, h, j, x_kr, x_ks, x_to_s, y_to_s, x_to_f, y_to_f, d, f, f_Ca_Bj, f_Ca_Bsl, Ry_Rr, Ry_Ro, Ry_Ri, Na_Bj, Na_Bsl, Tn_CL, Tn_CHc, Tn_CHm, CaM, Myo_c, Myo_m, SRB, SLL_j, SLL_sl, SLH_j, SLH_sl, Csqn_b, Ca_sr, Na_j, Na_sl, Na_i, K_i, Ca_j, Ca_sl, Ca_i, V_m, ) = states # Assign parameters assert len(parameters) == 112 Fjunc = parameters[0] Fjunc_CaL = parameters[1] cellLength = parameters[2] cellRadius = parameters[3] GNa = parameters[8] GNaB = parameters[9] IbarNaK = parameters[10] KmKo = parameters[11] KmNaip = parameters[12] GKr = parameters[15] GKp = parameters[16] GKs = parameters[17] pNaK = parameters[18] GK1 = parameters[19] Gto = parameters[20] epi = parameters[21] GClB = parameters[22] GClCa = parameters[23] KdClCa = parameters[24] GCaL = parameters[25] Q10CaL = parameters[26] pCa = parameters[27] pK = parameters[28] pNa = parameters[29] IbarNCX = parameters[30] Kdact = parameters[31] KmCai = parameters[32] KmCao = parameters[33] KmNai = parameters[34] KmNao = parameters[35] Q10NCX = parameters[36] ksat = parameters[37] nu = parameters[38] IbarSLCaP = parameters[39] KmPCa = parameters[40] Q10SLCaP = parameters[41] GCaB = parameters[42] Kmf = parameters[43] Kmr = parameters[44] MaxSR = parameters[45] MinSR = parameters[46] Q10SRCaP = parameters[47] Vmax_SRCaP = parameters[48] ec50SR = parameters[49] hillSRCaP = parameters[50] kiCa = parameters[51] kim = parameters[52] koCa = parameters[53] kom = parameters[54] ks = parameters[55] Bmax_Naj = parameters[56] Bmax_Nasl = parameters[57] koff_na = parameters[58] kon_na = parameters[59] Bmax_CaM = parameters[60] Bmax_SR = parameters[61] Bmax_TnChigh = parameters[62] Bmax_TnClow = parameters[63] Bmax_myosin = parameters[64] koff_cam = parameters[65] koff_myoca = parameters[66] koff_myomg = parameters[67] koff_sr = parameters[68] koff_tnchca = parameters[69] koff_tnchmg = parameters[70] koff_tncl = parameters[71] kon_cam = parameters[72] kon_myoca = parameters[73] kon_myomg = parameters[74] kon_sr = parameters[75] kon_tnchca = parameters[76] kon_tnchmg = parameters[77] kon_tncl = parameters[78] Bmax_SLhighj0 = parameters[79] Bmax_SLhighsl0 = parameters[80] Bmax_SLlowj0 = parameters[81] Bmax_SLlowsl0 = parameters[82] koff_slh = parameters[83] koff_sll = parameters[84] kon_slh = parameters[85] kon_sll = parameters[86] Bmax_Csqn0 = parameters[87] J_ca_juncsl = parameters[90] J_ca_slmyo = parameters[91] koff_csqn = parameters[92] kon_csqn = parameters[93] J_na_juncsl = parameters[96] J_na_slmyo = parameters[97] Nao = parameters[98] Ko = parameters[99] Cao = parameters[100] Cli = parameters[101] Clo = parameters[102] Mgi = parameters[103] Cmem = parameters[104] Frdy = parameters[105] R = parameters[106] Temp = parameters[107] stim_amplitude = parameters[108] stim_duration = parameters[109] stim_period = parameters[110] stim_start = parameters[111] # Expressions for the Geometry component Vcell = 1e-15 * np.pi * cellLength * (cellRadius * cellRadius) Vmyo = 0.65 * Vcell Vsr = 0.035 * Vcell Vsl = 0.02 * Vcell Vjunc = 0.0005390000000000001 * Vcell Fsl = 1 - Fjunc Fsl_CaL = 1 - Fjunc_CaL # Expressions for the Reversal potentials component FoRT = Frdy / (R * Temp) ena_junc = np.log(Nao / Na_j) / FoRT ena_sl = np.log(Nao / Na_sl) / FoRT ek = np.log(Ko / K_i) / FoRT eca_junc = np.log(Cao / Ca_j) / (2 * FoRT) eca_sl = np.log(Cao / Ca_sl) / (2 * FoRT) ecl = np.log(Cli / Clo) / FoRT Qpow = -31 + Temp / 10 # Expressions for the I_Na component mss = 1.0 / ( (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) * (1 + 0.0018422115811651339 * np.exp(-0.1107419712070875 * V_m)) ) taum = 0.1292 * np.exp( -( (2.9465894465894467 + 0.06435006435006435 * V_m) * (2.9465894465894467 + 0.06435006435006435 * V_m) ) ) + 0.06487 * np.exp( -( (-0.09434663536776214 + 0.019561815336463225 * V_m) * (-0.09434663536776214 + 0.019561815336463225 * V_m) ) ) ah = np.where( V_m >= -40, 0, 4.4312679295805147e-07 * np.exp(-0.14705882352941177 * V_m) ) bh = np.where( V_m >= -40, 0.77 / (0.13 + 0.049758141083938695 * np.exp(-0.0900900900900901 * V_m)), 310000.0 * np.exp(0.3485 * V_m) + 2.7 * np.exp(0.079 * V_m), ) tauh = 1.0 / (ah + bh) hss = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) aj = np.where( V_m >= -40, 0, (37.78 + V_m) * (-25428.0 * np.exp(0.2444 * V_m) - 6.948e-06 * np.exp(-0.04391 * V_m)) / (1 + 50262745825.95399 * np.exp(0.311 * V_m)), ) bj = np.where( V_m >= -40, 0.6 * np.exp(0.057 * V_m) / (1 + 0.040762203978366204 * np.exp(-0.1 * V_m)), 0.02424 * np.exp(-0.01052 * V_m) / (1 + 0.003960868339904256 * np.exp(-0.1378 * V_m)), ) tauj = 1.0 / (aj + bj) jss = 1.0 / ( (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) * (1 + 15212.593285654404 * np.exp(0.13458950201884254 * V_m)) ) dm_dt = (-m + mss) / taum dm_dt_linearized = -1 / taum states[0] = ( np.where( np.abs(dm_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dm_dt_linearized)) * dm_dt / dm_dt_linearized, dt * dm_dt, ) + m ) dh_dt = (-h + hss) / tauh dh_dt_linearized = -1 / tauh states[1] = ( np.where( np.abs(dh_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dh_dt_linearized)) * dh_dt / dh_dt_linearized, dt * dh_dt, ) + h ) dj_dt = (-j + jss) / tauj dj_dt_linearized = -1 / tauj states[2] = ( np.where( np.abs(dj_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dj_dt_linearized)) * dj_dt / dj_dt_linearized, dt * dj_dt, ) + j ) I_Na_junc = Fjunc * GNa * (m * m * m) * (-ena_junc + V_m) * h * j I_Na_sl = GNa * (m * m * m) * (-ena_sl + V_m) * Fsl * h * j # Expressions for the I_NaBK component I_nabk_junc = Fjunc * GNaB * (-ena_junc + V_m) I_nabk_sl = GNaB * (-ena_sl + V_m) * Fsl # Expressions for the I_NaK component sigma = -1 / 7 + np.exp(0.01485884101040119 * Nao) / 7 fnak = 1.0 / ( 1 + 0.1245 * np.exp(-0.1 * FoRT * V_m) + 0.0365 * np.exp(-FoRT * V_m) * sigma ) I_nak_junc = ( Fjunc * IbarNaK * Ko * fnak / ((1 + np.power(KmNaip, 4) / np.power(Na_j, 4)) * (KmKo + Ko)) ) I_nak_sl = ( IbarNaK * Ko * Fsl * fnak / ((1 + np.power(KmNaip, 4) / np.power(Na_sl, 4)) * (KmKo + Ko)) ) I_nak = I_nak_junc + I_nak_sl # Expressions for the I_Kr component gkr = 0.4303314829119352 * GKr * np.sqrt(Ko) xrss = 1.0 / (1 + np.exp(-2 - V_m / 5)) tauxr = 230 / (1 + np.exp(2 + V_m / 20)) + 3300 / ( (1 + np.exp(-22 / 9 - V_m / 9)) * (1 + np.exp(11 / 9 + V_m / 9)) ) dx_kr_dt = (-x_kr + xrss) / tauxr dx_kr_dt_linearized = -1 / tauxr states[3] = ( np.where( np.abs(dx_kr_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dx_kr_dt_linearized)) * dx_kr_dt / dx_kr_dt_linearized, dt * dx_kr_dt, ) + x_kr ) rkr = 1.0 / (1 + np.exp(37 / 12 + V_m / 24)) I_kr = (-ek + V_m) * gkr * rkr * x_kr # Expressions for the I_Kp component kp_kp = 1.0 / (1 + 1786.4755653786237 * np.exp(-0.16722408026755853 * V_m)) I_kp_junc = Fjunc * GKp * (-ek + V_m) * kp_kp I_kp_sl = GKp * (-ek + V_m) * Fsl * kp_kp I_kp = I_kp_junc + I_kp_sl # Expressions for the I_Ks component eks = np.log((Ko + Nao * pNaK) / (pNaK * Na_i + K_i)) / FoRT gks_junc = GKs gks_sl = GKs xsss = 1.0 / (1 + 0.7659283383646487 * np.exp(-0.07017543859649122 * V_m)) tauxs = 990.1 / (1 + 0.8415404088681017 * np.exp(-0.0708215297450425 * V_m)) dx_ks_dt = (-x_ks + xsss) / tauxs dx_ks_dt_linearized = -1 / tauxs states[4] = ( np.where( np.abs(dx_ks_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dx_ks_dt_linearized)) * dx_ks_dt / dx_ks_dt_linearized, dt * dx_ks_dt, ) + x_ks ) I_ks_junc = Fjunc * (x_ks * x_ks) * (-eks + V_m) * gks_junc I_ks_sl = (x_ks * x_ks) * (-eks + V_m) * Fsl * gks_sl I_ks = I_ks_junc + I_ks_sl # Expressions for the I_to component GtoSlow = np.where(epi == 1, 0.12 * Gto, 0.28919999999999996 * Gto) GtoFast = np.where(epi == 1, 0.88 * Gto, 0.010799999999999999 * Gto) xtoss = 1.0 / (1 + np.exp(19 / 13 - V_m / 13)) ytoss = 1.0 / (1 + 49.40244910553019 * np.exp(V_m / 5)) tauxtos = 0.5 + 9 / (1 + np.exp(1 / 5 + V_m / 15)) tauytos = 30 + 800 / (1 + np.exp(6 + V_m / 10)) dx_to_s_dt = (-x_to_s + xtoss) / tauxtos dx_to_s_dt_linearized = -1 / tauxtos states[5] = ( np.where( np.abs(dx_to_s_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dx_to_s_dt_linearized)) * dx_to_s_dt / dx_to_s_dt_linearized, dt * dx_to_s_dt, ) + x_to_s ) dy_to_s_dt = (-y_to_s + ytoss) / tauytos dy_to_s_dt_linearized = -1 / tauytos states[6] = ( np.where( np.abs(dy_to_s_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dy_to_s_dt_linearized)) * dy_to_s_dt / dy_to_s_dt_linearized, dt * dy_to_s_dt, ) + y_to_s ) I_tos = (-ek + V_m) * GtoSlow * x_to_s * y_to_s tauxtof = 0.5 + 8.5 * np.exp(-((9 / 10 + V_m / 50) * (9 / 10 + V_m / 50))) tauytof = 7 + 85 * np.exp(-((40 + V_m) * (40 + V_m)) / 220) dx_to_f_dt = (-x_to_f + xtoss) / tauxtof dx_to_f_dt_linearized = -1 / tauxtof states[7] = ( np.where( np.abs(dx_to_f_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dx_to_f_dt_linearized)) * dx_to_f_dt / dx_to_f_dt_linearized, dt * dx_to_f_dt, ) + x_to_f ) dy_to_f_dt = (-y_to_f + ytoss) / tauytof dy_to_f_dt_linearized = -1 / tauytof states[8] = ( np.where( np.abs(dy_to_f_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dy_to_f_dt_linearized)) * dy_to_f_dt / dy_to_f_dt_linearized, dt * dy_to_f_dt, ) + y_to_f ) I_tof = (-ek + V_m) * GtoFast * x_to_f * y_to_f I_to = I_tof + I_tos # Expressions for the I_K1 component aki = 1.02 / (1 + 7.35454251046446e-07 * np.exp(0.2385 * V_m - 0.2385 * ek)) bki = ( 0.7626240065063081 * np.exp(0.08032 * V_m - 0.08032 * ek) + 1.1534056351865558e-16 * np.exp(0.06175 * V_m - 0.06175 * ek) ) / (1 + 0.08677229415769332 * np.exp(0.5143 * ek - 0.5143 * V_m)) kiss = aki / (aki + bki) I_K1 = 0.4303314829119352 * GK1 * np.sqrt(Ko) * (-ek + V_m) * kiss # Expressions for the I_ClCa component I_ClCa_junc = Fjunc * GClCa * (-ecl + V_m) / (1 + KdClCa / Ca_j) I_ClCa_sl = GClCa * (-ecl + V_m) * Fsl / (1 + KdClCa / Ca_sl) I_ClCa = I_ClCa_junc + I_ClCa_sl I_Clbk = GClB * (-ecl + V_m) # Expressions for the I_Ca component fss = 1.0 / (1 + np.exp(35 / 9 + V_m / 9)) + 0.6 / (1 + np.exp(5 / 2 - V_m / 20)) dss = 1.0 / (1 + np.exp(-5 / 6 - V_m / 6)) taud = (1 - np.exp(-5 / 6 - V_m / 6)) * dss / (0.17500000000000002 + 0.035 * V_m) tauf = 1.0 / ( 0.02 + 0.0197 * np.exp( -( (0.48865000000000003 + 0.0337 * V_m) * (0.48865000000000003 + 0.0337 * V_m) ) ) ) dd_dt = (-d + dss) / taud dd_dt_linearized = -1 / taud states[9] = ( np.where( np.abs(dd_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dd_dt_linearized)) * dd_dt / dd_dt_linearized, dt * dd_dt, ) + d ) df_dt = (-f + fss) / tauf df_dt_linearized = -1 / tauf states[10] = ( np.where( np.abs(df_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * df_dt_linearized)) * df_dt / df_dt_linearized, dt * df_dt, ) + f ) df_Ca_Bj_dt = -0.0119 * f_Ca_Bj + 1.7 * (1 - f_Ca_Bj) * Ca_j df_Ca_Bj_dt_linearized = -0.0119 - 1.7 * Ca_j states[11] = ( np.where( np.abs(df_Ca_Bj_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * df_Ca_Bj_dt_linearized)) * df_Ca_Bj_dt / df_Ca_Bj_dt_linearized, dt * df_Ca_Bj_dt, ) + f_Ca_Bj ) df_Ca_Bsl_dt = -0.0119 * f_Ca_Bsl + 1.7 * (1 - f_Ca_Bsl) * Ca_sl df_Ca_Bsl_dt_linearized = -0.0119 - 1.7 * Ca_sl states[12] = ( np.where( np.abs(df_Ca_Bsl_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * df_Ca_Bsl_dt_linearized)) * df_Ca_Bsl_dt / df_Ca_Bsl_dt_linearized, dt * df_Ca_Bsl_dt, ) + f_Ca_Bsl ) fcaCaMSL = 0 fcaCaj = 0 ibarca_j = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_j * np.exp(2 * FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(2 * FoRT * V_m)) ) ibarca_sl = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_sl * np.exp(2 * FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(2 * FoRT * V_m)) ) ibark = ( Frdy * GCaL * pK * (-0.75 * Ko + 0.75 * K_i * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) ibarna_j = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_j * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) ibarna_sl = ( Frdy * GCaL * pNa * (-0.75 * Nao + 0.75 * Na_sl * np.exp(FoRT * V_m)) * FoRT * V_m / (-1 + np.exp(FoRT * V_m)) ) I_Ca_junc = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f * ibarca_j ) I_Ca_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f * ibarca_sl ) I_CaK = ( 0.45 * np.power(Q10CaL, Qpow) * (Fjunc_CaL * (1 + fcaCaj - f_Ca_Bj) + (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL) * d * f * ibark ) I_CaNa_junc = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f * ibarna_j ) I_CaNa_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f * ibarna_sl ) # Expressions for the I_NCX component Ka_junc = 1.0 / (1 + (Kdact * Kdact) / (Ca_j * Ca_j)) Ka_sl = 1.0 / (1 + (Kdact * Kdact) / (Ca_sl * Ca_sl)) s1_junc = Cao * (Na_j * Na_j * Na_j) * np.exp(nu * FoRT * V_m) s1_sl = Cao * (Na_sl * Na_sl * Na_sl) * np.exp(nu * FoRT * V_m) s2_junc = (Nao * Nao * Nao) * Ca_j * np.exp((-1 + nu) * FoRT * V_m) s3_junc = ( Cao * (Na_j * Na_j * Na_j) + KmCao * (Na_j * Na_j * Na_j) + (Nao * Nao * Nao) * Ca_j + KmCai * (Nao * Nao * Nao) * (1 + (Na_j * Na_j * Na_j) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_j / KmCai) * Ca_j ) s2_sl = (Nao * Nao * Nao) * Ca_sl * np.exp((-1 + nu) * FoRT * V_m) s3_sl = ( Cao * (Na_sl * Na_sl * Na_sl) + KmCao * (Na_sl * Na_sl * Na_sl) + (Nao * Nao * Nao) * Ca_sl + KmCai * (Nao * Nao * Nao) * (1 + (Na_sl * Na_sl * Na_sl) / (KmNai * KmNai * KmNai)) + (KmNao * KmNao * KmNao) * (1 + Ca_sl / KmCai) * Ca_sl ) I_ncx_junc = ( Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * (-s2_junc + s1_junc) * Ka_junc / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_junc) ) I_ncx_sl = ( IbarNCX * np.power(Q10NCX, Qpow) * (-s2_sl + s1_sl) * Fsl * Ka_sl / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_sl) ) # Expressions for the I_PCa component I_pca_junc = ( Fjunc * IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power(Ca_j, 1.6) / (np.power(KmPCa, 1.6) + np.power(Ca_j, 1.6)) ) I_pca_sl = ( IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power(Ca_sl, 1.6) * Fsl / (np.power(KmPCa, 1.6) + np.power(Ca_sl, 1.6)) ) # Expressions for the I_CaBK component I_cabk_junc = Fjunc * GCaB * (-eca_junc + V_m) I_cabk_sl = GCaB * (-eca_sl + V_m) * Fsl # Expressions for the SR Fluxes component kCaSR = MaxSR - (MaxSR - MinSR) / (1 + np.power(ec50SR / Ca_sr, 2.5)) koSRCa = koCa / kCaSR kiSRCa = kiCa * kCaSR RI = 1 - Ry_Ri - Ry_Ro - Ry_Rr dRy_Rr_dt = ( kim * RI + kom * Ry_Ro - (Ca_j * Ca_j) * Ry_Rr * koSRCa - Ca_j * Ry_Rr * kiSRCa ) dRy_Rr_dt_linearized = -kim - (Ca_j * Ca_j) * koSRCa - Ca_j * kiSRCa states[13] = ( np.where( np.abs(dRy_Rr_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dRy_Rr_dt_linearized)) * dRy_Rr_dt / dRy_Rr_dt_linearized, dt * dRy_Rr_dt, ) + Ry_Rr ) dRy_Ro_dt = ( kim * Ry_Ri - kom * Ry_Ro + (Ca_j * Ca_j) * Ry_Rr * koSRCa - Ca_j * Ry_Ro * kiSRCa ) dRy_Ro_dt_linearized = -kom - Ca_j * kiSRCa states[14] = ( np.where( np.abs(dRy_Ro_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dRy_Ro_dt_linearized)) * dRy_Ro_dt / dRy_Ro_dt_linearized, dt * dRy_Ro_dt, ) + Ry_Ro ) dRy_Ri_dt = ( -kim * Ry_Ri - kom * Ry_Ri + (Ca_j * Ca_j) * RI * koSRCa + Ca_j * Ry_Ro * kiSRCa ) dRy_Ri_dt_linearized = -kim - kom - (Ca_j * Ca_j) * koSRCa states[15] = ( np.where( np.abs(dRy_Ri_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dRy_Ri_dt_linearized)) * dRy_Ri_dt / dRy_Ri_dt_linearized, dt * dRy_Ri_dt, ) + Ry_Ri ) J_SRCarel = ks * (-Ca_j + Ca_sr) * Ry_Ro J_serca = ( Vmax_SRCaP * np.power(Q10SRCaP, Qpow) * (np.power(Ca_i / Kmf, hillSRCaP) - np.power(Ca_sr / Kmr, hillSRCaP)) / (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) ) J_SRleak = 5.348e-06 * Ca_sr - 5.348e-06 * Ca_j # Expressions for the Na Buffers component dNa_Bj_dt = -koff_na * Na_Bj + kon_na * (Bmax_Naj - Na_Bj) * Na_j dNa_Bj_dt_linearized = -koff_na - kon_na * Na_j states[16] = Na_Bj + np.where( np.abs(dNa_Bj_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dNa_Bj_dt_linearized)) * dNa_Bj_dt / dNa_Bj_dt_linearized, dt * dNa_Bj_dt, ) dNa_Bsl_dt = -koff_na * Na_Bsl + kon_na * (Bmax_Nasl - Na_Bsl) * Na_sl dNa_Bsl_dt_linearized = -koff_na - kon_na * Na_sl states[17] = Na_Bsl + np.where( np.abs(dNa_Bsl_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dNa_Bsl_dt_linearized)) * dNa_Bsl_dt / dNa_Bsl_dt_linearized, dt * dNa_Bsl_dt, ) # Expressions for the Cytosolic Ca Buffers component dTn_CL_dt = -koff_tncl * Tn_CL + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i dTn_CL_dt_linearized = -koff_tncl - kon_tncl * Ca_i states[18] = ( np.where( np.abs(dTn_CL_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dTn_CL_dt_linearized)) * dTn_CL_dt / dTn_CL_dt_linearized, dt * dTn_CL_dt, ) + Tn_CL ) dTn_CHc_dt = ( -koff_tnchca * Tn_CHc + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i ) dTn_CHc_dt_linearized = -koff_tnchca - kon_tnchca * Ca_i states[19] = ( np.where( np.abs(dTn_CHc_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dTn_CHc_dt_linearized)) * dTn_CHc_dt / dTn_CHc_dt_linearized, dt * dTn_CHc_dt, ) + Tn_CHc ) dTn_CHm_dt = -koff_tnchmg * Tn_CHm + Mgi * kon_tnchmg * ( Bmax_TnChigh - Tn_CHc - Tn_CHm ) dTn_CHm_dt_linearized = -koff_tnchmg - Mgi * kon_tnchmg states[20] = ( np.where( np.abs(dTn_CHm_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dTn_CHm_dt_linearized)) * dTn_CHm_dt / dTn_CHm_dt_linearized, dt * dTn_CHm_dt, ) + Tn_CHm ) dCaM_dt = -koff_cam * CaM + kon_cam * (Bmax_CaM - CaM) * Ca_i dCaM_dt_linearized = -koff_cam - kon_cam * Ca_i states[21] = CaM + np.where( np.abs(dCaM_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dCaM_dt_linearized)) * dCaM_dt / dCaM_dt_linearized, dt * dCaM_dt, ) dMyo_c_dt = -koff_myoca * Myo_c + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i dMyo_c_dt_linearized = -koff_myoca - kon_myoca * Ca_i states[22] = Myo_c + np.where( np.abs(dMyo_c_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dMyo_c_dt_linearized)) * dMyo_c_dt / dMyo_c_dt_linearized, dt * dMyo_c_dt, ) dMyo_m_dt = -koff_myomg * Myo_m + Mgi * kon_myomg * (Bmax_myosin - Myo_c - Myo_m) dMyo_m_dt_linearized = -koff_myomg - Mgi * kon_myomg states[23] = Myo_m + np.where( np.abs(dMyo_m_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dMyo_m_dt_linearized)) * dMyo_m_dt / dMyo_m_dt_linearized, dt * dMyo_m_dt, ) dSRB_dt = -koff_sr * SRB + kon_sr * (Bmax_SR - SRB) * Ca_i dSRB_dt_linearized = -koff_sr - kon_sr * Ca_i states[24] = ( np.where( np.abs(dSRB_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dSRB_dt_linearized)) * dSRB_dt / dSRB_dt_linearized, dt * dSRB_dt, ) + SRB ) J_CaB_cytosol = ( -koff_cam * CaM - koff_myoca * Myo_c - koff_myomg * Myo_m - koff_sr * SRB - koff_tnchca * Tn_CHc - koff_tnchmg * Tn_CHm - koff_tncl * Tn_CL + Mgi * kon_myomg * (Bmax_myosin - Myo_c - Myo_m) + Mgi * kon_tnchmg * (Bmax_TnChigh - Tn_CHc - Tn_CHm) + kon_cam * (Bmax_CaM - CaM) * Ca_i + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) * Ca_i + kon_sr * (Bmax_SR - SRB) * Ca_i + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) * Ca_i + kon_tncl * (Bmax_TnClow - Tn_CL) * Ca_i ) # Expressions for the Junctional and SL Ca Buffers component Bmax_SLlowsl = Bmax_SLlowsl0 * Vmyo / Vsl Bmax_SLlowj = Bmax_SLlowj0 * Vmyo / Vjunc Bmax_SLhighsl = Bmax_SLhighsl0 * Vmyo / Vsl Bmax_SLhighj = Bmax_SLhighj0 * Vmyo / Vjunc dSLL_j_dt = -koff_sll * SLL_j + kon_sll * (-SLL_j + Bmax_SLlowj) * Ca_j dSLL_j_dt_linearized = -koff_sll - kon_sll * Ca_j states[25] = ( np.where( np.abs(dSLL_j_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dSLL_j_dt_linearized)) * dSLL_j_dt / dSLL_j_dt_linearized, dt * dSLL_j_dt, ) + SLL_j ) dSLL_sl_dt = -koff_sll * SLL_sl + kon_sll * (-SLL_sl + Bmax_SLlowsl) * Ca_sl dSLL_sl_dt_linearized = -koff_sll - kon_sll * Ca_sl states[26] = ( np.where( np.abs(dSLL_sl_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dSLL_sl_dt_linearized)) * dSLL_sl_dt / dSLL_sl_dt_linearized, dt * dSLL_sl_dt, ) + SLL_sl ) dSLH_j_dt = -koff_slh * SLH_j + kon_slh * (-SLH_j + Bmax_SLhighj) * Ca_j dSLH_j_dt_linearized = -koff_slh - kon_slh * Ca_j states[27] = ( np.where( np.abs(dSLH_j_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dSLH_j_dt_linearized)) * dSLH_j_dt / dSLH_j_dt_linearized, dt * dSLH_j_dt, ) + SLH_j ) dSLH_sl_dt = -koff_slh * SLH_sl + kon_slh * (-SLH_sl + Bmax_SLhighsl) * Ca_sl dSLH_sl_dt_linearized = -koff_slh - kon_slh * Ca_sl states[28] = ( np.where( np.abs(dSLH_sl_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dSLH_sl_dt_linearized)) * dSLH_sl_dt / dSLH_sl_dt_linearized, dt * dSLH_sl_dt, ) + SLH_sl ) J_CaB_junction = ( -koff_slh * SLH_j - koff_sll * SLL_j + kon_slh * (-SLH_j + Bmax_SLhighj) * Ca_j + kon_sll * (-SLL_j + Bmax_SLlowj) * Ca_j ) J_CaB_sl = ( -koff_slh * SLH_sl - koff_sll * SLL_sl + kon_slh * (-SLH_sl + Bmax_SLhighsl) * Ca_sl + kon_sll * (-SLL_sl + Bmax_SLlowsl) * Ca_sl ) # Expressions for the SR Ca Concentrations component Bmax_Csqn = Bmax_Csqn0 * Vmyo / Vsr dCsqn_b_dt = -koff_csqn * Csqn_b + kon_csqn * (-Csqn_b + Bmax_Csqn) * Ca_sr dCsqn_b_dt_linearized = -koff_csqn - kon_csqn * Ca_sr states[29] = Csqn_b + np.where( np.abs(dCsqn_b_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dCsqn_b_dt_linearized)) * dCsqn_b_dt / dCsqn_b_dt_linearized, dt * dCsqn_b_dt, ) dCa_sr_dt = ( -J_SRCarel + koff_csqn * Csqn_b - kon_csqn * (-Csqn_b + Bmax_Csqn) * Ca_sr - J_SRleak * Vmyo / Vsr + J_serca ) dJ_serca_dCa_sr = -Vmax_SRCaP * hillSRCaP * np.power(Q10SRCaP, Qpow) * np.power( Ca_sr / Kmr, hillSRCaP ) / ( (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) * Ca_sr ) - Vmax_SRCaP * hillSRCaP * np.power( Q10SRCaP, Qpow ) * np.power( Ca_sr / Kmr, hillSRCaP ) * ( np.power(Ca_i / Kmf, hillSRCaP) - np.power(Ca_sr / Kmr, hillSRCaP) ) / ( ( (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) * (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) ) * Ca_sr ) dCa_sr_dt_linearized = ( -kon_csqn * (-Csqn_b + Bmax_Csqn) - ks * Ry_Ro - 5.348e-06 * Vmyo / Vsr + dJ_serca_dCa_sr ) states[30] = Ca_sr + np.where( np.abs(dCa_sr_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dCa_sr_dt_linearized)) * dCa_sr_dt / dCa_sr_dt_linearized, dt * dCa_sr_dt, ) # Expressions for the Na Concentrations component I_Na_tot_junc = ( 3 * I_nak_junc + 3 * I_ncx_junc + I_CaNa_junc + I_Na_junc + I_nabk_junc ) I_Na_tot_sl = 3 * I_nak_sl + 3 * I_ncx_sl + I_CaNa_sl + I_Na_sl + I_nabk_sl dNa_j_dt = ( -dNa_Bj_dt + J_na_juncsl * (-Na_j + Na_sl) / Vjunc - Cmem * I_Na_tot_junc / (Frdy * Vjunc) ) dI_CaNa_junc_dibarna_j = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f ) ds3_junc_dNa_j = ( 3 * Cao * (Na_j * Na_j) + 3 * KmCao * (Na_j * Na_j) + 3 * KmCai * (Nao * Nao * Nao) * (Na_j * Na_j) / (KmNai * KmNai * KmNai) ) dena_junc_dNa_j = -1 / (FoRT * Na_j) ds1_junc_dNa_j = 3 * Cao * (Na_j * Na_j) * np.exp(nu * FoRT * V_m) dI_nabk_junc_dena_junc = -Fjunc * GNaB dibarna_j_dNa_j = ( 0.75 * Frdy * GCaL * pNa * FoRT * V_m * np.exp(FoRT * V_m) / (-1 + np.exp(FoRT * V_m)) ) dI_Na_junc_dena_junc = -Fjunc * GNa * (m * m * m) * h * j dI_ncx_junc_ds1_junc = ( Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * Ka_junc / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_junc) ) dI_nak_junc_dNa_j = ( 4 * Fjunc * IbarNaK * Ko * np.power(KmNaip, 4) * fnak / ( ( (1 + np.power(KmNaip, 4) / np.power(Na_j, 4)) * (1 + np.power(KmNaip, 4) / np.power(Na_j, 4)) ) * (KmKo + Ko) * np.power(Na_j, 5) ) ) dI_ncx_junc_ds3_junc = ( -Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * (-s2_junc + s1_junc) * Ka_junc / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * (s3_junc * s3_junc)) ) dNa_j_dt_linearized = -J_na_juncsl / Vjunc - Cmem * ( 3 * dI_nak_junc_dNa_j + dI_CaNa_junc_dibarna_j * dibarna_j_dNa_j + dI_Na_junc_dena_junc * dena_junc_dNa_j + dI_nabk_junc_dena_junc * dena_junc_dNa_j + 3 * dI_ncx_junc_ds1_junc * ds1_junc_dNa_j + 3 * dI_ncx_junc_ds3_junc * ds3_junc_dNa_j ) / (Frdy * Vjunc) states[31] = Na_j + np.where( np.abs(dNa_j_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dNa_j_dt_linearized)) * dNa_j_dt / dNa_j_dt_linearized, dt * dNa_j_dt, ) dNa_sl_dt = ( -dNa_Bsl_dt + J_na_juncsl * (-Na_sl + Na_j) / Vsl + J_na_slmyo * (-Na_sl + Na_i) / Vsl - Cmem * I_Na_tot_sl / (Frdy * Vsl) ) dI_nabk_sl_dena_sl = -GNaB * Fsl dI_CaNa_sl_dibarna_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f ) dibarna_sl_dNa_sl = ( 0.75 * Frdy * GCaL * pNa * FoRT * V_m * np.exp(FoRT * V_m) / (-1 + np.exp(FoRT * V_m)) ) dI_Na_sl_dena_sl = -GNa * (m * m * m) * Fsl * h * j dI_ncx_sl_ds1_sl = ( IbarNCX * np.power(Q10NCX, Qpow) * Fsl * Ka_sl / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_sl) ) ds3_sl_dNa_sl = ( 3 * Cao * (Na_sl * Na_sl) + 3 * KmCao * (Na_sl * Na_sl) + 3 * KmCai * (Nao * Nao * Nao) * (Na_sl * Na_sl) / (KmNai * KmNai * KmNai) ) dI_nak_sl_dNa_sl = ( 4 * IbarNaK * Ko * np.power(KmNaip, 4) * Fsl * fnak / ( ( (1 + np.power(KmNaip, 4) / np.power(Na_sl, 4)) * (1 + np.power(KmNaip, 4) / np.power(Na_sl, 4)) ) * (KmKo + Ko) * np.power(Na_sl, 5) ) ) dI_ncx_sl_ds3_sl = ( -IbarNCX * np.power(Q10NCX, Qpow) * (-s2_sl + s1_sl) * Fsl * Ka_sl / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * (s3_sl * s3_sl)) ) dena_sl_dNa_sl = -1 / (FoRT * Na_sl) ds1_sl_dNa_sl = 3 * Cao * (Na_sl * Na_sl) * np.exp(nu * FoRT * V_m) dNa_sl_dt_linearized = ( -J_na_juncsl / Vsl - J_na_slmyo / Vsl - Cmem * ( 3 * dI_nak_sl_dNa_sl + dI_CaNa_sl_dibarna_sl * dibarna_sl_dNa_sl + dI_Na_sl_dena_sl * dena_sl_dNa_sl + dI_nabk_sl_dena_sl * dena_sl_dNa_sl + 3 * dI_ncx_sl_ds1_sl * ds1_sl_dNa_sl + 3 * dI_ncx_sl_ds3_sl * ds3_sl_dNa_sl ) / (Frdy * Vsl) ) states[32] = Na_sl + np.where( np.abs(dNa_sl_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dNa_sl_dt_linearized)) * dNa_sl_dt / dNa_sl_dt_linearized, dt * dNa_sl_dt, ) dNa_i_dt = J_na_slmyo * (-Na_i + Na_sl) / Vmyo dNa_i_dt_linearized = -J_na_slmyo / Vmyo states[33] = Na_i + np.where( np.abs(dNa_i_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dNa_i_dt_linearized)) * dNa_i_dt / dNa_i_dt_linearized, dt * dNa_i_dt, ) # Expressions for the K Concentration component I_K_tot = -2 * I_nak + I_CaK + I_K1 + I_kp + I_kr + I_ks + I_to dK_i_dt = 0 states[34] = dt * dK_i_dt + K_i # Expressions for the Ca Concentrations component I_Ca_tot_junc = -2 * I_ncx_junc + I_Ca_junc + I_cabk_junc + I_pca_junc I_Ca_tot_sl = -2 * I_ncx_sl + I_Ca_sl + I_cabk_sl + I_pca_sl dCa_j_dt = ( -J_CaB_junction + J_ca_juncsl * (-Ca_j + Ca_sl) / Vjunc + J_SRCarel * Vsr / Vjunc + J_SRleak * Vmyo / Vjunc - Cmem * I_Ca_tot_junc / (2 * Frdy * Vjunc) ) dI_Ca_junc_dibarca_j = ( 0.45 * Fjunc_CaL * np.power(Q10CaL, Qpow) * (1 + fcaCaj - f_Ca_Bj) * d * f ) dI_cabk_junc_deca_junc = -Fjunc * GCaB dibarca_j_dCa_j = ( 1.364 * Frdy * GCaL * pCa * FoRT * V_m * np.exp(2 * FoRT * V_m) / (-1 + np.exp(2 * FoRT * V_m)) ) dKa_junc_dCa_j = ( 2 * (Kdact * Kdact) / ( ( (1 + (Kdact * Kdact) / (Ca_j * Ca_j)) * (1 + (Kdact * Kdact) / (Ca_j * Ca_j)) ) * (Ca_j * Ca_j * Ca_j) ) ) dJ_CaB_junction_dCa_j = kon_slh * (-SLH_j + Bmax_SLhighj) + kon_sll * ( -SLL_j + Bmax_SLlowj ) dI_ncx_junc_ds2_junc = ( -Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * Ka_junc / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_junc) ) ds2_junc_dCa_j = (Nao * Nao * Nao) * np.exp((-1 + nu) * FoRT * V_m) ds3_junc_dCa_j = ( (Nao * Nao * Nao) + (KmNao * KmNao * KmNao) * (1 + Ca_j / KmCai) + (KmNao * KmNao * KmNao) * Ca_j / KmCai ) dJ_SRCarel_dCa_j = -ks * Ry_Ro dI_pca_junc_dCa_j = 1.6 * Fjunc * IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power( Ca_j, 0.6000000000000001 ) / ( np.power(KmPCa, 1.6) + np.power(Ca_j, 1.6) ) - 1.6 * Fjunc * IbarSLCaP * np.power( Q10SLCaP, Qpow ) * np.power( Ca_j, 2.2 ) / ( (np.power(KmPCa, 1.6) + np.power(Ca_j, 1.6)) * (np.power(KmPCa, 1.6) + np.power(Ca_j, 1.6)) ) dI_ncx_junc_dKa_junc = ( Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * (-s2_junc + s1_junc) / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_junc) ) deca_junc_dCa_j = -1 / (2 * Ca_j * FoRT) dCa_j_dt_linearized = ( -dJ_CaB_junction_dCa_j - J_ca_juncsl / Vjunc - 5.348e-06 * Vmyo / Vjunc + Vsr * dJ_SRCarel_dCa_j / Vjunc - Cmem * ( dI_Ca_junc_dibarca_j * dibarca_j_dCa_j + dI_cabk_junc_deca_junc * deca_junc_dCa_j - 2 * dI_ncx_junc_dKa_junc * dKa_junc_dCa_j - 2 * dI_ncx_junc_ds2_junc * ds2_junc_dCa_j - 2 * dI_ncx_junc_ds3_junc * ds3_junc_dCa_j + dI_pca_junc_dCa_j ) / (2 * Frdy * Vjunc) ) states[35] = Ca_j + np.where( np.abs(dCa_j_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dCa_j_dt_linearized)) * dCa_j_dt / dCa_j_dt_linearized, dt * dCa_j_dt, ) dCa_sl_dt = ( -J_CaB_sl + J_ca_juncsl * (-Ca_sl + Ca_j) / Vsl + J_ca_slmyo * (-Ca_sl + Ca_i) / Vsl - Cmem * I_Ca_tot_sl / (2 * Frdy * Vsl) ) dI_Ca_sl_dibarca_sl = ( 0.45 * np.power(Q10CaL, Qpow) * (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL * d * f ) ds2_sl_dCa_sl = (Nao * Nao * Nao) * np.exp((-1 + nu) * FoRT * V_m) dKa_sl_dCa_sl = ( 2 * (Kdact * Kdact) / ( ( (1 + (Kdact * Kdact) / (Ca_sl * Ca_sl)) * (1 + (Kdact * Kdact) / (Ca_sl * Ca_sl)) ) * (Ca_sl * Ca_sl * Ca_sl) ) ) ds3_sl_dCa_sl = ( (Nao * Nao * Nao) + (KmNao * KmNao * KmNao) * (1 + Ca_sl / KmCai) + (KmNao * KmNao * KmNao) * Ca_sl / KmCai ) dI_ncx_sl_dKa_sl = ( IbarNCX * np.power(Q10NCX, Qpow) * (-s2_sl + s1_sl) * Fsl / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_sl) ) dibarca_sl_dCa_sl = ( 1.364 * Frdy * GCaL * pCa * FoRT * V_m * np.exp(2 * FoRT * V_m) / (-1 + np.exp(2 * FoRT * V_m)) ) dI_pca_sl_dCa_sl = 1.6 * IbarSLCaP * np.power(Q10SLCaP, Qpow) * np.power( Ca_sl, 0.6000000000000001 ) * Fsl / ( np.power(KmPCa, 1.6) + np.power(Ca_sl, 1.6) ) - 1.6 * IbarSLCaP * np.power( Q10SLCaP, Qpow ) * np.power( Ca_sl, 2.2 ) * Fsl / ( (np.power(KmPCa, 1.6) + np.power(Ca_sl, 1.6)) * (np.power(KmPCa, 1.6) + np.power(Ca_sl, 1.6)) ) dJ_CaB_sl_dCa_sl = kon_slh * (-SLH_sl + Bmax_SLhighsl) + kon_sll * ( -SLL_sl + Bmax_SLlowsl ) deca_sl_dCa_sl = -1 / (2 * Ca_sl * FoRT) dI_ncx_sl_ds2_sl = ( -IbarNCX * np.power(Q10NCX, Qpow) * Fsl * Ka_sl / ((1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_sl) ) dI_cabk_sl_deca_sl = -GCaB * Fsl dCa_sl_dt_linearized = ( -dJ_CaB_sl_dCa_sl - J_ca_juncsl / Vsl - J_ca_slmyo / Vsl - Cmem * ( dI_Ca_sl_dibarca_sl * dibarca_sl_dCa_sl + dI_cabk_sl_deca_sl * deca_sl_dCa_sl - 2 * dI_ncx_sl_dKa_sl * dKa_sl_dCa_sl - 2 * dI_ncx_sl_ds2_sl * ds2_sl_dCa_sl - 2 * dI_ncx_sl_ds3_sl * ds3_sl_dCa_sl + dI_pca_sl_dCa_sl ) / (2 * Frdy * Vsl) ) states[36] = Ca_sl + np.where( np.abs(dCa_sl_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dCa_sl_dt_linearized)) * dCa_sl_dt / dCa_sl_dt_linearized, dt * dCa_sl_dt, ) dCa_i_dt = ( -J_CaB_cytosol + J_ca_slmyo * (-Ca_i + Ca_sl) / Vmyo - J_serca * Vsr / Vmyo ) dJ_serca_dCa_i = Vmax_SRCaP * hillSRCaP * np.power(Q10SRCaP, Qpow) * np.power( Ca_i / Kmf, hillSRCaP ) / ( (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) * Ca_i ) - Vmax_SRCaP * hillSRCaP * np.power( Q10SRCaP, Qpow ) * np.power( Ca_i / Kmf, hillSRCaP ) * ( np.power(Ca_i / Kmf, hillSRCaP) - np.power(Ca_sr / Kmr, hillSRCaP) ) / ( ( (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) * (1 + np.power(Ca_i / Kmf, hillSRCaP) + np.power(Ca_sr / Kmr, hillSRCaP)) ) * Ca_i ) dJ_CaB_cytosol_dCa_i = ( kon_cam * (Bmax_CaM - CaM) + kon_myoca * (Bmax_myosin - Myo_c - Myo_m) + kon_sr * (Bmax_SR - SRB) + kon_tnchca * (Bmax_TnChigh - Tn_CHc - Tn_CHm) + kon_tncl * (Bmax_TnClow - Tn_CL) ) dCa_i_dt_linearized = ( -dJ_CaB_cytosol_dCa_i - J_ca_slmyo / Vmyo - Vsr * dJ_serca_dCa_i / Vmyo ) states[37] = Ca_i + np.where( np.abs(dCa_i_dt_linearized) > 1e-08, (-1.0 + np.exp(dt * dCa_i_dt_linearized)) * dCa_i_dt / dCa_i_dt_linearized, dt * dCa_i_dt, ) # Expressions for the Membrane potential component i_Stim = np.where( np.logical_and( t - stim_period * np.floor(t / stim_period) <= stim_duration + stim_start, t - stim_period * np.floor(t / stim_period) >= stim_start, ), -stim_amplitude, 0, ) I_Na_tot = I_Na_tot_junc + I_Na_tot_sl I_Cl_tot = I_ClCa + I_Clbk I_Ca_tot = I_Ca_tot_junc + I_Ca_tot_sl I_tot = I_Ca_tot + I_Cl_tot + I_K_tot + I_Na_tot dV_m_dt = -I_tot - i_Stim dI_nak_sl_dfnak = ( IbarNaK * Ko * Fsl / ((1 + np.power(KmNaip, 4) / np.power(Na_sl, 4)) * (KmKo + Ko)) ) dibarca_j_dV_m = ( 4 * Frdy * GCaL * pCa * (-0.341 * Cao + 0.341 * Ca_j * np.exp(2 * FoRT * V_m)) * FoRT / (-1 + np.exp(2 * FoRT * V_m)) - 8 * Frdy * GCaL * pCa * (FoRT * FoRT) * (-0.341 * Cao + 0.341 * Ca_j * np.exp(2 * FoRT * V_m)) * V_m * np.exp(2 * FoRT * V_m) / ((-1 + np.exp(2 * FoRT * V_m)) * (-1 + np.exp(2 * FoRT * V_m))) + 2.728 * Frdy * GCaL * pCa * (FoRT * FoRT) * Ca_j * V_m * np.exp(2 * FoRT * V_m) / (-1 + np.exp(2 * FoRT * V_m)) ) dI_Na_sl_dV_m = GNa * (m * m * m) * Fsl * h * j ds1_junc_dV_m = Cao * nu * (Na_j * Na_j * Na_j) * FoRT * np.exp(nu * FoRT * V_m) ds2_junc_dV_m = ( (Nao * Nao * Nao) * (-1 + nu) * Ca_j * FoRT * np.exp((-1 + nu) * FoRT * V_m) ) dI_ncx_junc_dV_m = Fjunc * IbarNCX * np.power(Q10NCX, Qpow) * ( -ds2_junc_dV_m + ds1_junc_dV_m ) * Ka_junc / ( (1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * s3_junc ) - Fjunc * IbarNCX * ksat * np.power( Q10NCX, Qpow ) * ( -1 + nu ) * ( -s2_junc + s1_junc ) * FoRT * Ka_junc * np.exp( (-1 + nu) * FoRT * V_m ) / ( ( (1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) * (1 + ksat * np.exp((-1 + nu) * FoRT * V_m)) ) * s3_junc ) dibark_dV_m = ( Frdy * GCaL * pK * (-0.75 * Ko + 0.75 * K_i * np.exp(FoRT * V_m)) * FoRT / (-1 + np.exp(FoRT * V_m)) - Frdy * GCaL * pK * (FoRT * FoRT) * (-0.75 * Ko + 0.75 * K_i * np.exp(FoRT * V_m)) * V_m * np.exp(FoRT * V_m) / ((-1 + np.exp(FoRT * V_m)) * (-1 + np.exp(FoRT * V_m))) + 0.75 * Frdy * GCaL * pK * (FoRT * FoRT) * K_i * V_m * np.exp(FoRT * V_m) / (-1 + np.exp(FoRT * V_m)) ) dI_kp_sl_dkp_kp = GKp * (-ek + V_m) * Fsl dI_CaK_dibark = ( 0.45 * np.power(Q10CaL, Qpow) * (Fjunc_CaL * (1 + fcaCaj - f_Ca_Bj) + (1 + fcaCaMSL - f_Ca_Bsl) * Fsl_CaL) * d * f ) dI_kp_junc_dkp_kp = Fjunc * GKp * (-ek + V_m) dI_ClCa_sl_dV_m = GClCa * Fsl / (1 + KdClCa / Ca_sl) dkp_kp_dV_m = ( 298.741733340907 * np.exp(-0.16722408026755853 * V_m) / ( (1 + 1786.4755653786237 * np.exp(-0.16722408026755853 * V_m)) * (1 + 1786.4755653786237 * np.exp(-0.16722408026755853 * V_m)) ) ) drkr_dV_m = -np.exp(37 / 12 + V_m / 24) / ( 24 * ((1 + np.exp(37 / 12 + V_m / 24)) * (1 + np.exp(37 / 12 + V_m / 24))) ) dI_ks_sl_dV_m = (x_ks * x_ks) * Fsl * gks_sl dI_tos_dV_m = GtoSlow * x_to_s * y_to_s dfnak_dV_m = ( 0.012450000000000001 * FoRT * np.exp(-0.1 * FoRT * V_m) + 0.0365 * FoRT * np.exp(-FoRT * V_m) * sigma ) / ( (1 + 0.1245 *
np.exp(-0.1 * FoRT * V_m)
numpy.exp
import os,sys import bpy import numpy as np from random import randint from random import random from numpy.random import normal from random import uniform from random import choice as Rchoice from random import sample import cv2 import yaml import itertools from math import radians,degrees,tan,cos from numpy.linalg import inv # visible vertices import bmesh from mathutils import Vector from bpy_extras.object_utils import world_to_camera_view ply_header = '''ply format ascii 1.0 element vertex %(vert_num)d property float x property float y property float z property uchar red property uchar green property uchar blue end_header ''' pcd_header = '''VERSION 0.7 FIELDS x y z rgb SIZE 4 4 4 4 TYPE F F F F COUNT 1 1 1 1 WIDTH 640 HEIGHT 480 VIEWPOINT 0 0 0 1 0 0 0 POINTS 307200 DATA ascii ''' #Height : 480 for kinect, 512 for ensenso #Points : 307200 for kinect, 327680 for ensenso # tless: 720x540 def getVerticesVisible(obj): scene = bpy.context.scene cam = bpy.data.objects['cam_R'] mesh = obj.data mat_world = obj.matrix_world cs, ce = cam.data.clip_start, cam.data.clip_end # edit mode to edit meshes scene.objects.active = obj bpy.ops.object.mode_set(mode='EDIT') #bpy.ops.mesh.remove_doubles(threshold=0.0001) bm = bmesh.from_edit_mesh(mesh) limit = 0.1 #vertices = [mat_world * v.co for v in obj.data.vertices] #for i, v in enumerate( vertices ): for v in bm.verts: v.select = True # need it for vertices hidden in last iteration vec = mat_world * v.co co_ndc = world_to_camera_view(scene, cam, vec) #co_ndc = world_to_camera_view(scene, cam, v) #check wether point is inside frustum #if (0.0 < co_ndc.x < 1.0 and # 0.0 < co_ndc.y < 1.0 and # cs < co_ndc.z < ce): # ray_cast if point is visible # results, obj, mat, location, normal = scene.ray_cast(cam.location, (vec - cam.location).normalized() ) # if location and (vec - location).length < limit: # v.select = False # else: # v.select = True #else: # v.select = True # limit selection to visible from certain camera view #bpy.ops.mesh.hide(unselected=False) #bmesh.update_edit_mesh(mesh, False, False) bpy.ops.object.mode_set(mode='OBJECT') def getVisibleBoundingBox(objectPassIndex): S = bpy.context.scene width = int( S.render.resolution_x * S.render.resolution_percentage / 100 ) height = int( S.render.resolution_y * S.render.resolution_percentage / 100 ) depth = 4 pixels = np.array( bpy.data.images['Render Result'].pixels[:] ).reshape( [height, width, depth] ) # Keep only one value for each pixel (white pixels have 1 in all RGBA channels anyway), thus converting the image to black and white pixels = np.array( [ [ pixel[0] for pixel in row ] for row in pixels ] ) bbox = np.argwhere( pixels == objectPassIndex ) (ystart, xstart), (ystop, xstop) = bbox.min(0), bbox.max(0) + 1 bb = (xstart, xstart, height - ystart, height - ystop) return bb, bbox print('---------------') print('###############') print('---------------') # Quasi Main print('Setting variables and clear memory') #Realsense D415 # vanilla #Image sensor OV2740 #1,4 x 1,4 um/pixel #image sensor: 2.7288 x 1.5498 mm #1920 x 1080 #f=1.93 mm #Fov_h = 42.5 #Fov-v = 69.4 #Realsense D415 #cropped and resized #crop to #640 x 480 #fov_h = 42.5 #fov_v = 54.89, blender says 54.4 #image_sensor = 2.0466 x 1.5498 #F(mm) = F(pixels) * SensorWidth(mm) / ImageWidth (pixel) f_x = ((bpy.data.cameras['Camera.001'].lens) * 640) / 2.0466 f_y = ((bpy.data.cameras['Camera.001'].lens) * 480) / 1.5498 print('fx: ', f_x, 'fy: ', f_y) # 23.4.2018 # render image 350 of object 23 # cam_K: [1076.74064739, 0.0, 215.98264967, 0.0, 1075.17825536, 204.59181836, 0.0, 0.0, 1.0] # depth_scale: 0.1 # elev: 45 # mode: 0 # cam_R_m2c: [0.62268218, -0.78164004, -0.03612308, -0.56354950, -0.41595975, -0.71371609, 0.54284357, 0.46477486, -0.69950372] # cam_t_m2c: [-9.10674129, -2.47862668, 634.81667094] # obj_bb: [120, 121, 197, 190] # obj_id: 23 # f = 580 # b = 0.0075 #base_dir = "/home/sthalham/data/LINEMOD/models_stl_red_13" base_dir = "/home/stefan/data/Meshes/CIT_color" back_img_path = '/home/stefan/data/datasets/cocoval2017' all_backgrounds = os.listdir(back_img_path) total_set = 5 #10000 set of scenes, each set has identical objects with varied poses to anchor pose (+-15) pair_set = 5 #number of pair scene for each set, 10 sample_dir = '/home/stefan/data/renderings/CIT_render' #directory for temporary files (cam_L, cam_R, masks..~) target_dir = '/home/stefan/data/renderings/CIT_render/patches' index=0 isfile=True while isfile: prefix='{:08}_'.format(index) if(os.path.exists(os.path.join(target_dir,prefix+'gt.yaml'))): index+=1 else: isfile=False if not(os.path.exists(target_dir+"/mask")): os.makedirs(target_dir+"/mask") if not(os.path.exists(target_dir+"/rgb")): os.makedirs(target_dir+"/rgb") model_file=[] model_solo=[] for root, dirs, files in os.walk(base_dir): for file in sorted(files): if file.endswith(".ply"): temp_fn =os.path.join(root, file) model_file.append(temp_fn) model_solo.append(file) #print(len(model_file),temp_fn) dis_objects = ['dis1_1', 'dis1_2', 'dis1_3', 'dis2_1', 'dis2_2', 'dis2_3'] # FOR BACKGROUND OBJECTS print('Done') print('----------------') print('Start looping through scenes') iteration_counter = 0 for num_set in np.arange(total_set): bpy.ops.object.select_all(action='DESELECT') scene = bpy.context.scene scene.objects.active = bpy.data.objects["template"] for obj in scene.objects: if obj.type == 'MESH': if obj.name == 'template': obj.select = False elif obj.name[0:5] == 'Plane': obj.select = False elif obj.name[0:3] == 'dis': obj.select = False elif obj.name == 'InvisibleCube': obj.select = False else: obj.select = True if obj.name[0:6] == 'light_': obj.select = True bpy.ops.object.delete() bpy.ops.object.select_all(action='DESELECT') obj_object = bpy.data.objects["template"] obj_object.pass_index = 1 mat = obj_object.active_material # memory is leaking # that should fix it for block in bpy.data.meshes: if block.users == 0: bpy.data.meshes.remove(block) for block in bpy.data.materials: if block.users == 0: bpy.data.materials.remove(block) for block in bpy.data.textures: if block.users == 0: bpy.data.textures.remove(block) for block in bpy.data.images: if block.users == 0: bpy.data.images.remove(block) print('----------------') print('Loading and placing objects') # load ply # sample object drop location # objects are dropped thorugh physics # sample objects num_object = np.random.randint(low=4, high=12) num_distractor = np.random.randint(low=2, high=4) ObjDraw = np.random.choice(np.arange(len(model_solo)), size=num_object, replace=True) DisDraw = np.random.choice(np.arange(len(dis_objects)), size=num_distractor, replace=False) object_label =[] anchor_pose = np.zeros(((num_distractor + num_object+1),6)) object_idx = 0 for file_idx in ObjDraw: file_model = model_file[file_idx] solo_model = model_solo[file_idx] imported_object = bpy.ops.import_mesh.ply(filepath=file_model, filter_glob="*.ply", files=[{"name":solo_model, "name":solo_model}], directory=root) obj_object = bpy.context.selected_objects[0] object_label.append(int(obj_object.name[:2])) mat_obj = mat.copy() nodes = mat_obj.node_tree.nodes pbr = nodes.get("Principled BSDF") attr = nodes.get("Attribute") if obj_object.name[:2] == '01': #ior = 1.49 # Polypropylen ior = 1.3 + random() * 0.3 #pbr.inputs[0].default_value[:3] = (0.66, 0.66, 0.66) #pbr.inputs[0].default_value[:3] = (143/255, 155/255, 174/255) pbr.inputs[0].default_value[:3] = (152/255, 164/255, 174/255) #Pantone 7543c pbr.inputs[4].default_value = 0.0 # Metallic pbr.inputs[5].default_value = np.power(((ior - 1)/(ior + 1)), 2)/0.08 # specular #pbr.inputs[6].default_value = 0.9 # specular tint #pbr.inputs[7].default_value = 0.4 # reoghness pbr.inputs[6].default_value = 0.6 + random() * 0.4 # specular tint pbr.inputs[7].default_value = 0.2 + random() * 0.5 # reoghness # plastics 1.3 - 1.6, higly refractive ~ 1.75 # polished stainless steel 2.75 #pbr.inputs[14].default_value = ior elif obj_object.name[:2] == '03' or obj_object.name[:2] == '06': ior = 2.75 # stainless steel 224, 223, 219 #pbr.inputs[0].default_value[:3] = (0.879, 0.874, 0.859) #pbr.inputs[4].default_value = 1.0 # Metallic #pbr.inputs[5].default_value = np.power(((ior - 1)/(ior + 1)), 2)/0.08 # specular #pbr.inputs[5].default_value = 0.8 #pbr.inputs[6].default_value = 0.1 # specular tint #pbr.inputs[7].default_value = 0.2 # reoghness pbr.inputs[4].default_value = 0.8 + random() * 0.2 # Metallic pbr.inputs[5].default_value = 0.6 + random() * 0.4 pbr.inputs[6].default_value = 0.0 + random() * 0.2 pbr.inputs[7].default_value = random() * 0.5 # reoghness # plastics 1.3 - 1.6, higly refractive ~ 1.75 # polished stainless steel 2.75 #pbr.inputs[14].default_value = ior else: #pbr.inputs[0].default_value[:3] = (0.7725, 0.7843, 0.8078) pbr.inputs[0].default_value[:3] = (152/255, 164/255, 174/255) #Pantone 7543c #pbr.inputs[0].default_value[:3] = (143/255, 155/255, 174/255) #ior = 1.49 # Polypropylen ior = 1.3 + random() * 0.3 pbr.inputs[4].default_value = 0.0 # Metallic #print(np.power(((ior - 1)/(ior + 1)), 2)/0.08) pbr.inputs[5].default_value = np.power(((ior - 1)/(ior + 1)), 2)/0.08 # specular #pbr.inputs[6].default_value = 0.8 # specular tint #pbr.inputs[7].default_value = 0.2 # reoghness pbr.inputs[6].default_value = 0.6 + random() * 0.4 # specular tint pbr.inputs[7].default_value = 0.0 + random() * 0.4 # reoghness # plastics 1.3 - 1.6, higly refractive ~ 1.75 # polished stainless steel 2.75 #pbr.inputs[14].default_value = ior obj_object.active_material = mat_obj obj_object.pass_index = object_idx +2 # don't add? #anchor_pose[object_idx+1,0] = random()*0.5 - 0.25 #anchor_pose[object_idx+1, 1] = random()*0.5 - 0.25 anchor_pose[object_idx+1,0] = normal(loc=0, scale=0.05) anchor_pose[object_idx+1, 1] = normal(loc=0, scale=0.05) anchor_pose[object_idx+1,2] = 0.3 + random()*0.5 anchor_pose[object_idx+1,3] = radians(random()*360.0) anchor_pose[object_idx+1,4] = radians(random()*360.0) anchor_pose[object_idx+1,5] = radians(random()*360.0) object_idx += 1 print('object_labels: ', object_label) print("FOREGROUND IMPORTED") # Background objects for name in dis_objects: obj_object = bpy.data.objects[name] obj_object.hide_render = True for file_idx in DisDraw: #object_label.append(object_idx + num_object) obj_object = bpy.data.objects[dis_objects[file_idx]] obj_object.hide_render = False mat_obj = mat.copy() nodes = mat_obj.node_tree.nodes pbr = nodes.get("Principled BSDF") attr = nodes.get("Attribute") #ior = 1.8 #pbr.inputs[4].default_value = 0.5 # Metallic #pbr.inputs[5].default_value = np.power(((ior - 1)/(ior + 1)), 2)/0.08 # specular #pbr.inputs[6].default_value = 0.7 # specular tint #pbr.inputs[7].default_value = 0.5 # reoghness ior = 1 + random() * 0.8 pbr.inputs[4].default_value = 0.4 + random() * 0.3 # Metallic pbr.inputs[5].default_value = np.power(((ior - 1)/(ior + 1)), 2)/0.08 # specular pbr.inputs[6].default_value = 0.1 + random() * 0.4 # specular tint pbr.inputs[7].default_value = 0.2 + random() * 0.5 # reoghness obj_object.active_material = mat_obj obj_object.pass_index = object_idx+2 #anchor_pose[object_idx+1,0] = random()*0.5 - 0.25 #anchor_pose[object_idx+1, 1] = random()*0.5 - 0.25 anchor_pose[object_idx+1,0] = normal(loc=0, scale=0.05) anchor_pose[object_idx+1, 1] = normal(loc=0, scale=0.05) anchor_pose[object_idx+1,2] = 0.3 + random()*0.5 anchor_pose[object_idx+1,3] = radians(random()*360.0) anchor_pose[object_idx+1,4] = radians(random()*360.0) anchor_pose[object_idx+1,5] = radians(random()*360.0) object_idx += 1 # FOR BACKGROUND OBJECTS print("BACKGROUND IMPORTED") #bpy.data.worlds["World"].light_settings.use_ambient_occlusion = True #Set object physics scene = bpy.context.scene scene.objects.active = bpy.data.objects["template"] for obj in scene.objects: if obj.type == 'MESH': #print("objects parsed: ", obj) if obj.name == 'template': obj.select = False elif obj.name[0:5] == 'Plane': obj.select = False elif obj.name == 'InvisibleCube': obj.select = False else: obj.select = True print("BACKGROUND objects set to inactive for physics") bpy.ops.rigidbody.object_settings_copy() #Define Object position&rotation tree = bpy.context.scene.node_tree nodes = tree.nodes ind_obj_counter = 0 scene.frame_set(0) for obj in scene.objects: if obj.type == 'MESH': obj_object= bpy.data.objects[obj.name] if obj.name[0:5] == 'Plane': obj_object= bpy.data.objects[obj.name] img_choice = Rchoice(all_backgrounds) img_path = os.path.join(back_img_path, img_choice) mat_now = obj_object.active_material tree_mesh = mat_now.node_tree nodes_mesh = tree_mesh.nodes image = bpy.data.images.load(filepath = img_path) nodes_mesh['Image Texture'].image = image if obj_object.pass_index > 1: idx = obj_object.pass_index -1 print(obj_object, obj_object.pass_index, idx) obj_object.location.x=anchor_pose[idx,0] obj_object.location.y=anchor_pose[idx,1] obj_object.location.z=anchor_pose[idx,2] obj_object.rotation_euler.x= anchor_pose[idx,3] obj_object.rotation_euler.y= anchor_pose[idx,4] obj_object.rotation_euler.z= anchor_pose[idx,5] # assign different color rand_color = (random(), random(), random()) obj_object.active_material.diffuse_color = rand_color if obj.name[:3] == 'dis': #if obj_object.pass_index > (num_object+1): obj_object.pass_index = 0 #if obj.name == 'InvisibleCube': #obj_object.rotation_euler.x=radians(random()*60.0 + 15.0) #0~90 #obj_object.rotation_euler.y=radians(random()*5.0 - 10.0) #-45-45 #obj_object.rotation_euler.z=radians(random()*360.0) #0-360 #if obj.type == 'CAMERA' and obj.name=='cam_L': #obj_object = bpy.data.objects[obj.name] #obj_object.location.z = random()*0.2+0.5 #1.0-2.5 print("Running physics") #Run physics count = 60 scene.frame_start = 1 scene.frame_end = count + 1 print("Start physics") for f in range(1,scene.frame_end+1): print("scene iteration: ", f, "/60") scene.frame_set(f) if f <= 1: continue print("Done") print('---------------') print('Creating pairs') print('---> randomize camera location') print('---> randomize lights') for iii in np.arange(pair_set): #randomize camera obj_object = bpy.data.objects['InvisibleCube'] obj_object.rotation_euler.x=radians(random()*60.0 + 15.0) #0~90 obj_object.rotation_euler.y=radians(random()*5.0 - 10.0) #-45-45 obj_object.rotation_euler.z=radians(random()*360.0) #0-360 obj_object = bpy.data.objects['cam_L'] obj_object.location.z = random()*0.2+0.5 #1.0-2.5 # spawn lamps and randomize properties print('Spawning lamps') # need to remove old lamps first for lam in bpy.data.lamps: bpy.data.lamps.remove(lamp=lam) # randomize lights and position lights = np.random.randint(low=2, high=4) for lamp in range(0, lights): lamp_types = ['SPOT', 'AREA'] lamp_type = Rchoice(lamp_types) lamp_name = 'light_' + str(lamp) lamp_position = ((random()*5.0-2.5), (random()*2.5-1.25), (random()*2.0+1.5)) lamp_data = bpy.data.lamps.new(name=lamp_name, type=lamp_type) lamp_object = bpy.data.objects.new(name=lamp_name, object_data=lamp_data) scene.objects.link(lamp_object) lamp_object.location = lamp_position lamp_object.select = True bpy.data.lamps[lamp_name].use_nodes = True # light emission has to be adjusted depending on the lamp type emission = (100.0 + random()* 50.0) * (1/lights) # to normalize scene illuminations if lamp_type == 'AREA': bpy.data.lamps[lamp_name].shape = 'RECTANGLE' bpy.data.lamps[lamp_name].size = 0.5 + random() * 0.5 bpy.data.lamps[lamp_name].size_y = 0.1 elif lamp_type == 'SPOT': emission *= 2.0 #elif lamp_type == 'SUN': # emission *= 0.1 bpy.data.lamps[lamp_name].node_tree.nodes["Emission"].inputs[1].default_value = emission bpy.data.lamps[lamp_name].node_tree.nodes["Emission"].inputs[0].default_value[:3] = (random() * 0.03 + 0.97, random() * 0.1 + 0.9, random() * 0.2 + 0.8) #bpy.data.lamps[lamp_name].node_tree.nodes["Emission"].inputs[0].default_value[:3] = (random() * 0.03 + 0.97, random() * 0.06 + 0.94, random() * 0.1 + 0.9) print('Done') print('---------------') print("Rendering images") #When Rander cam_L, render mask together prefix='{:08}_'.format(index) index+=1 scene.cycles.samples=250 maskfile = os.path.join(target_dir+'/mask' , 'mask.png') # correspondence mask rgbfile= os.path.join(target_dir+"/rgb", prefix+'rgb.png') # rgb image tree = bpy.context.scene.node_tree nodes = tree.nodes for ob in scene.objects: if ob.type == 'CAMERA': if ob.name=='cam_L': #ob.name =='mask': #Render image and Mask bpy.context.scene.camera = ob print('Set camera %s for IR' % ob.name ) file_L = os.path.join(sample_dir , ob.name ) auto_file = os.path.join(sample_dir, ob.name+'0061.png') node= nodes['maskout'] node.file_slots[0].path = ob.name node_mix = nodes['ColorRamp'] link_mask= tree.links.new(node_mix.outputs["Image"], node.inputs[0]) node.base_path=sample_dir auto_file_rgb = os.path.join(sample_dir+'/rgb/', ob.name+'0061.png') node= nodes['rgbimage.001'] node.file_slots[0].path = ob.name node_mix = nodes['Render Layers'] link_rgb = tree.links.new(node_mix.outputs["Image"], node.inputs[0]) node.base_path=sample_dir+'/rgb/' scene.render.filepath = file_L bpy.ops.render.render( write_still=True ) tree.links.remove(link_mask) tree.links.remove(link_rgb) os.rename(auto_file, maskfile) os.rename(auto_file_rgb, rgbfile) print('Done') print('------------------') # Compute annotations and export # Visibility ratios are not calculated here, needs separate step. # computationally too expensive in blender because of rendering step print('Computing annotations') mask = cv2.imread(maskfile) minmax_vu = np.zeros((num_object,4),dtype=np.int) #min v, min u, max v, max u label_vu = np.zeros((mask.shape[0],mask.shape[1]),dtype=np.int8) #min v, min u, max v, max u colors = np.zeros((num_object,3),dtype=mask.dtype) n_label=0 color_index=np.array([ [ 0, 0, 0], [ 0, 100, 0], [ 0, 139, 0], [ 0, 167, 0], [ 0, 190, 0], [ 0, 210, 0], [ 0, 228, 0], [ 0, 244, 0], [ 0, 252, 50], [ 0, 236, 112], [ 0, 220, 147], [ 0, 201, 173], [ 0, 179, 196], [ 0, 154, 215], [ 0, 122, 232], [ 0, 72, 248], [ 72, 0, 248], [122, 0, 232], [154, 0, 215], [179, 0, 196], [201, 0, 173], [220, 0, 147], [236, 0, 112], [252, 0, 50], [255, 87, 87], [255, 131, 131], [255, 161, 161], [255, 185, 185], [255, 206, 206], [255, 224, 224], [255, 240, 240], [255, 255, 255]]) for v in np.arange(mask.shape[0]): for u in np.arange(mask.shape[1]): has_color = False if not(mask[v,u,0] ==0 and mask[v,u,1] ==0 and mask[v,u,2] ==0): for ob_index in np.arange(n_label): if colors[ob_index,0]== mask[v,u,0] and colors[ob_index,1]== mask[v,u,1] and colors[ob_index,2]== mask[v,u,2]: has_color = True minmax_vu[ob_index,0] = min(minmax_vu[ob_index,0], v) minmax_vu[ob_index,1] = min(minmax_vu[ob_index,1], u) minmax_vu[ob_index,2] = max(minmax_vu[ob_index,2], v) minmax_vu[ob_index,3] = max(minmax_vu[ob_index,3], u) label_vu[v,u]=ob_index+1 continue if has_color ==False: #new label colors[n_label] = mask[v,u] label_vu[v,u]=n_label+1 #identical to object_index in blender minmax_vu[n_label,0] = v minmax_vu[n_label,1] = u minmax_vu[n_label,2] = v minmax_vu[n_label,3] = u n_label=n_label+1 else: label_vu[v,u]=0 bbox_refined = mask color_map=np.zeros(n_label) for k in np.arange(n_label): for i in np.arange(color_index.shape[0]): if(color_index[i,0] == colors[k,0] and color_index[i,1] == colors[k,1] and color_index[i,2] == colors[k,2] ): color_map[k]=i continue object_no=[] refined=[] for ob_index in np.arange(n_label): min_v=minmax_vu[ob_index,0] min_u=minmax_vu[ob_index,1] max_v=minmax_vu[ob_index,2] max_u=minmax_vu[ob_index,3] bbox = label_vu[min_v:max_v,min_u:max_u] bbox=bbox.reshape(-1) counts = np.bincount(bbox) if(counts.shape[0]>1): if(np.argmax(counts[1:]) ==(ob_index)): #(mask.shape[0],mask.shape[1] #if(min_v>30 and min_u>30 and max_v < (mask.shape[0]-30) and max_u < (mask.shape[1]-30) ): #cv2.rectangle(bbox_refined,(min_u,min_v),(max_u,max_v),(0,255,0),1) refined.append(ob_index) object_no.append(color_map[ob_index]) #cv2.imwrite(os.path.join(sample_dir,'bbox_refined.png'),bbox_refined) bbox_refined = minmax_vu[refined] poses =np.zeros((len(object_no),4,4),dtype=np.float) names = ['a'] * len(object_no) camera_rot =np.zeros((4,4),dtype=np.float) for obj in scene.objects: if obj.type == 'MESH': if obj.pass_index in object_no: idx = object_no.index(obj.pass_index) poses[idx]=obj.matrix_world img_name = obj.name + '.png' #names[idx] = os.path.join(sample_dir, img_name) if obj.name=='InvisibleCube': camera_rot[:,:] = obj.matrix_world camera_rot = camera_rot[:3,:3] #only rotation (z was recorded seprately) init_rot = np.zeros((3,3)) init_rot[0,0]=1 init_rot[1,1]=-1 init_rot[2,2]=-1 fin_rot =np.matmul(camera_rot,init_rot) fin_rot = inv(fin_rot) world_rot=np.zeros((4,4)) world_rot[:3,:3] = fin_rot world_rot[3,3]=1 if obj.type == 'CAMERA' and obj.name=='cam_L': obj_object = bpy.data.objects[obj.name] camera_z = obj_object.location.z #camera_ext[:,:] = obj_object.matrix_world #camera_ext = camera_ext.reshape(-1) np.save(target_dir+"/mask/"+prefix+"mask.npy",label_vu) cam_trans = -np.matmul(camera_rot[:3, :3],np.array([0,0,camera_z])) world_trans =
np.zeros((4,4))
numpy.zeros
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: visualizer Project Name: octNet Author : 康 Date: 2018/9/22 ------------------------------------------------- Change Activity: 2018/9/22: ------------------------------------------------- """ import cv2 import torch import visdom import numpy as np class Visualizer(object): def __init__(self, env='main', port=8097, **kwargs): self.viz = visdom.Visdom(env=env, port=port, **kwargs) # 画的第几个数,相当于横坐标 # 比如(’loss',23) 即loss的第23个点 self.index = {} self.log_text = '' # plot line def plot_multi_win(self, d, loop_flag=None): ''' 一次plot多个或者一个 @params d: dict (name, value) i.e. ('loss', 0.11) ''' long_update = True if loop_flag == 0: long_update = False for k, v in d.items(): self.plot(k, v, long_update) def plot_single_win(self, d, win, loop_i=1): """ :param d: dict (name, value) i.e. ('loss', 0.11) :param win: only one win :param loop_i: i.e. plot testing loss and label :return: """ for k, v in d.items(): x = self.index.get(k, 0) self.viz.line( Y=np.array([v]), X=np.array([x]), name=k, win=win, opts=dict(title=win, showlegend=True), update='append' if (x > 0 and loop_i > 0) else None) # update=None if (x == 0 or loop_i == 0) else 'append') self.index[k] = x + 1 def plot_legend(self, win, name, y, long_update=True, **kwargs): ''' plot different line in different time in the same window One mame, one win: only one lie in a win. ''' # eg. # self.vis.plot_legend(win='iou', name='val', y=iou.mean()) x = self.index.get( name, 0) # dict.get(key, default=None). 返回指定键的值,如果值不在字典中返回default值 self.viz.line( Y=np.array([y]), X=
np.array([x])
numpy.array
import numpy from scipy import optimize import sys home_dir = '../' sys.path.append(home_dir) import Util.CG as CG class Solver: def __init__(self, X=None, y=None): if (X is not None) and (y is not None): self.n, self.d = X.shape print('logistic solver') print(X.shape) print(y.shape) self.xMat = X self.yVec = y # self.xMat = X * y.reshape(self.n, 1) def fit(self, xMat, yVec): self.n, self.d = xMat.shape # self.xMat = xMat * yVec.reshape(self.n, 1) self.xMat = xMat self.yVec = yVec def objFun(self, wVec, *args): gamma = args[0] zVec = numpy.dot(self.xMat, wVec.reshape(self.d, 1)) # add label yVec zVec = numpy.multiply(zVec, self.yVec) lVec = numpy.log(1 + numpy.exp(-zVec)) return numpy.mean(lVec) + gamma / 2 * numpy.sum(wVec ** 2) def grad(self, wVec, *args): gamma = args[0] zVec = numpy.dot(self.xMat, wVec.reshape(self.d, 1)) # add label yVec zVec = numpy.multiply(zVec, self.yVec) expZVec = numpy.exp(zVec) vec1 = 1 + expZVec vec2 = -1 / vec1 # add label yVec vec2 = numpy.multiply(vec2, self.yVec) # grad1 = numpy.mean(self.xMat.T * vec2, axis=0) grad1 = self.xMat.T * vec2 grad = grad1 / self.n + gamma * wVec.reshape(self.d, 1) return grad def cg(self, gamma, tol=1e-20, maxiter=5000): wVec0 = numpy.zeros(self.d) args = (gamma,) print(self.objFun(wVec0, *args)) wVec, _, _, gradCalls, _ = optimize.fmin_cg(self.objFun, wVec0, args=args, fprime=self.grad, gtol=tol, maxiter=maxiter, disp=True, full_output=True) print(self.objFun(wVec, *args)) return wVec def newton(self, gamma, maxIter=50, tol=1e-15): wVec = numpy.zeros((self.d, 1)) etaList = 1 / (2 **
numpy.arange(0, 10)
numpy.arange
import numpy as np import scipy as sp from ffthompy.trigpol import Grid, get_Nodd, mean_index, fft_form_default from ffthompy.matvecs import Matrix from ffthompy.tensors import Tensor import itertools def scalar(N, Y, NyqNul=True, tensor=True, fft_form=fft_form_default): """ Assembly of discrete kernels in Fourier space for scalar elliptic problems. Parameters ---------- N : numpy.ndarray no. of discretization points Y : numpy.ndarray size of periodic unit cell Returns ------- G1l : numpy.ndarray discrete kernel in Fourier space; provides projection on curl-free fields with zero mean G2l : numpy.ndarray discrete kernel in Fourier space; provides projection on divergence-free fields with zero mean """ if fft_form in ['r']: fft_form_r=True fft_form=0 else: fft_form_r=False d = np.size(N) N = np.array(N, dtype=np.int) if NyqNul: Nred = get_Nodd(N) else: Nred = N xi = Grid.get_xil(Nred, Y, fft_form=fft_form) xi2 = [] for m in np.arange(d): xi2.append(xi[m]**2) G0l = np.zeros(np.hstack([d, d, Nred])) G1l = np.zeros(np.hstack([d, d, Nred])) G2l = np.zeros(np.hstack([d, d, Nred])) num = np.zeros(np.hstack([d, d, Nred])) denom = np.zeros(Nred) ind_center = mean_index(Nred, fft_form=fft_form) for m in np.arange(d): # diagonal components Nshape = np.ones(d, dtype=np.int) Nshape[m] = Nred[m] Nrep = np.copy(Nred) Nrep[m] = 1 a = np.reshape(xi2[m], Nshape) num[m][m] = np.tile(a, Nrep) # numerator denom = denom + num[m][m] G0l[m, m][ind_center] = 1 for m in np.arange(d): # upper diagonal components for n in np.arange(m+1, d): NshapeM = np.ones(d, dtype=np.int) NshapeM[m] = Nred[m] NrepM = np.copy(Nred) NrepM[m] = 1 NshapeN = np.ones(d, dtype=np.int) NshapeN[n] = Nred[n] NrepN = np.copy(Nred) NrepN[n] = 1 num[m][n] = np.tile(np.reshape(xi[m], NshapeM), NrepM) \ * np.tile(np.reshape(xi[n], NshapeN), NrepN) # avoiding a division by zero denom[ind_center] = 1 # calculation of projections for m in np.arange(d): for n in np.arange(m, d): G1l[m][n] = num[m][n]/denom G2l[m][n] = (m == n)*np.ones(Nred) - G1l[m][n] G2l[m][n][ind_center] = 0 # symmetrization for m in np.arange(1, d): for n in np.arange(m): G1l[m][n] = G1l[n][m] G2l[m][n] = G2l[n][m] if tensor: G0l = Tensor(name='hG0', val=G0l, order=2, N=N, multype=21, Fourier=True, fft_form=fft_form) G1l = Tensor(name='hG1', val=G1l, order=2, N=N, multype=21, Fourier=True, fft_form=fft_form) G2l = Tensor(name='hG2', val=G2l, order=2, N=N, multype=21, Fourier=True, fft_form=fft_form) else: G0l = Matrix(name='hG0', val=G0l, Fourier=True) G1l = Matrix(name='hG1', val=G1l, Fourier=True) G2l = Matrix(name='hG2', val=G2l, Fourier=True) if NyqNul: G0l = G0l.enlarge(N) G1l = G1l.enlarge(N) G2l = G2l.enlarge(N) if fft_form_r: for tensor in [G0l, G1l, G2l]: tensor.set_fft_form(fft_form='r') tensor.val/=np.prod(tensor.N) return G0l, G1l, G2l def elasticity(N, Y, NyqNul=True, tensor=True, fft_form=fft_form_default): """ Projection matrix on a space of admissible strain fields INPUT = N : ndarray of e.g. stiffness coefficients d : dimension; d = 2 D : dimension in engineering notation; D = 3 Y : the size of periodic unit cell OUTPUT = G1h,G1s,G2h,G2s : projection matrices of size DxDxN """ if fft_form in ['r']: fft_form_r=True fft_form=0 else: fft_form_r=False xi = Grid.get_xil(N, Y, fft_form=fft_form) N = np.array(N, dtype=np.int) d = N.size D = int(d*(d+1)/2) if NyqNul: Nred = get_Nodd(N) else: Nred = N xi2 = [] for ii in range(d): xi2.append(xi[ii]**2) num = np.zeros(np.hstack([d, d, Nred])) norm2_xi = np.zeros(Nred) for mm in np.arange(d): # diagonal components Nshape = np.ones(d, dtype=np.int) Nshape[mm] = Nred[mm] Nrep = np.copy(Nred) Nrep[mm] = 1 num[mm][mm] = np.tile(np.reshape(xi2[mm], Nshape), Nrep) # numerator norm2_xi += num[mm][mm] norm4_xi = norm2_xi**2 ind_center = mean_index(Nred, fft_form=fft_form) # avoid division by zero norm2_xi[ind_center] = 1 norm4_xi[ind_center] = 1 for m in np.arange(d): # upper diagonal components for n in np.arange(m+1, d): NshapeM = np.ones(d, dtype=np.int) NshapeM[m] = Nred[m] NrepM = np.copy(Nred) NrepM[m] = 1 NshapeN = np.ones(d, dtype=np.int) NshapeN[n] = Nred[n] NrepN = np.copy(Nred) NrepN[n] = 1 num[m][n] = np.tile(np.reshape(xi[m], NshapeM), NrepM) \ * np.tile(np.reshape(xi[n], NshapeN), NrepN) # G1h = np.zeros([D,D]).tolist() G1h = np.zeros(np.hstack([D, D, Nred])) G1s = np.zeros(np.hstack([D, D, Nred])) IS0 = np.zeros(np.hstack([D, D, Nred])) mean = np.zeros(np.hstack([D, D, Nred])) Lamh = np.zeros(np.hstack([D, D, Nred])) S = np.zeros(np.hstack([D, D, Nred])) W = np.zeros(np.hstack([D, D, Nred])) WT = np.zeros(np.hstack([D, D, Nred])) for m in np.arange(d): S[m][m] = 2*num[m][m]/norm2_xi for n in np.arange(d): G1h[m][n] = num[m][m]*num[n][n]/norm4_xi Lamh[m][n] =
np.ones(Nred)
numpy.ones
""" Imperceptible ASR attack (https://arxiv.org/abs/1903.10346) """ import math from typing import List, Optional, Tuple import numpy as np import speechbrain as sb import torch import torch.nn as nn import torch.optim as optim from scipy.signal import argrelextrema from torch.autograd import Variable import robust_speech as rs from robust_speech.adversarial.attacks.attacker import Attacker class ImperceptibleASRAttack(Attacker): """ An implementation of the Imperceptible ASR attack (https://arxiv.org/abs/1903.10346). Based on the ART implementation of Imperceptible (https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/art/attacks/evasion/imperceptible_asr/imperceptible_asr_pytorch.py) Arguments --------- asr_brain : rs.adversarial.brain.ASRBrain the brain object to attack targeted: bool if the attack is targeted (always true for now). eps: float Linf bound applied to the perturbation. learning_rate_1: float the learning rate for the attack algorithm in phase 1 max_iter_1: int the maximum number of iterations in phase 1 learning_rate_2: float the learning rate for the attack algorithm in phase 2 max_iter_2: int the maximum number of iterations in phase 2 clip_min: float mininum value per input dimension (ignored: herefor compatibility). clip_max: float maximum value per input dimension (ignored: herefor compatibility). train_mode_for_backward: bool whether to force training mode in backward passes (necessary for RNN models) win_length: int window length for computing spectral density hop_length: int hop length for computing spectral density n_fft: int number of FFT bins for computing spectral density. global_max_length: int max length of a perturbation initial_rescale: float initial factor by which to rescale the perturbation num_iter_decrease_eps: int Number of times to increase epsilon in case of success decrease_factor_eps: int Factor by which to decrease epsilon in case of failure alpha: float regularization constant for threshold loss term num_iter_decrease_alpha: int Number of times to decrease alpha in case of failure num_iter_decrease_alpha: int Number of times to increase alpha in case of success decrease_factor_alpha: int Factor by which to decrease alpha in case of failure increase_factor_alpha: int Factor by which to increase alpha in case of success optimizer_1: Optional["torch.optim.Optimizer"] the optimizer to use in phase 1 optimizer_2: Optional["torch.optim.Optimizer"] the optimizer to use in phase 2 """ def __init__( self, asr_brain: rs.adversarial.brain.ASRBrain, eps: float = 0.05, max_iter_1: int = 10, max_iter_2: int = 4000, learning_rate_1: float = 0.001, learning_rate_2: float = 5e-4, optimizer_1: Optional["torch.optim.Optimizer"] = None, optimizer_2: Optional["torch.optim.Optimizer"] = None, global_max_length: int = 200000, initial_rescale: float = 1.0, decrease_factor_eps: float = 0.8, num_iter_decrease_eps: int = 1, max_num_decrease_eps: Optional[int] = None, alpha: float = 1.2, increase_factor_alpha: float = 1.2, num_iter_increase_alpha: int = 20, decrease_factor_alpha: float = 0.8, num_iter_decrease_alpha: int = 20, win_length: int = 2048, hop_length: int = 512, n_fft: int = 2048, targeted: bool = True, train_mode_for_backward: bool = True, clip_min: Optional[float] = None, clip_max: Optional[float] = None, ): self.asr_brain = asr_brain self.eps = eps self.max_iter_1 = max_iter_1 self.max_iter_2 = max_iter_2 self.learning_rate_1 = learning_rate_1 self.learning_rate_2 = learning_rate_2 self.global_max_length = global_max_length self.initial_rescale = initial_rescale self.decrease_factor_eps = decrease_factor_eps self.num_iter_decrease_eps = num_iter_decrease_eps self.alpha = alpha self.increase_factor_alpha = increase_factor_alpha self.num_iter_increase_alpha = num_iter_increase_alpha self.decrease_factor_alpha = decrease_factor_alpha self.num_iter_decrease_alpha = num_iter_decrease_alpha self.win_length = win_length self.hop_length = hop_length self.n_fft = n_fft self.clip_min = clip_min # ignored self.clip_max = clip_max # ignored assert targeted, ( "%s attack only available for targeted outputs" % self.__class__.__name__ ) self.targeted = targeted self.train_mode_for_backward = train_mode_for_backward self._optimizer_arg_1 = optimizer_1 self._optimizer_arg_2 = optimizer_2 self.max_num_decrease_eps = max_num_decrease_eps if max_num_decrease_eps is None: self.max_num_decrease_eps = max_iter_1 def perturb(self, batch): """ Compute an adversarial perturbation Arguments --------- batch : sb.PaddedBatch The input batch to perturb Returns ------- the tensor of the perturbed batch """ if self.train_mode_for_backward: self.asr_brain.module_train() else: self.asr_brain.module_eval() save_device = batch.sig[0].device batch = batch.to(self.asr_brain.device) save_input = batch.sig[0] wav_init = torch.clone(save_input) batch.sig = wav_init, batch.sig[1] # First reset delta global_optimal_delta = torch.zeros(batch.batchsize, self.global_max_length).to( self.asr_brain.device ) self.global_optimal_delta = nn.Parameter(global_optimal_delta) # Next, reset optimizers if self._optimizer_arg_1 is None: self.optimizer_1 = torch.optim.Adam( params=[self.global_optimal_delta], lr=self.learning_rate_1 ) else: self.optimizer_1 = self._optimizer_arg_1( # type: ignore params=[self.global_optimal_delta], lr=self.learning_rate_1 ) if self._optimizer_arg_2 is None: self.optimizer_2 = torch.optim.Adam( params=[self.global_optimal_delta], lr=self.learning_rate_2 ) else: self.optimizer_2 = self._optimizer_arg_2( # type: ignore params=[self.global_optimal_delta], lr=self.learning_rate_2 ) # Then compute the batch adv_wav = self._generate_batch(batch) batch.sig = save_input, batch.sig[1] batch = batch.to(save_device) self.asr_brain.module_eval() return adv_wav def _generate_batch(self, batch): """ Run all attack stages Arguments --------- batch : sb.PaddedBatch The input batch to perturb Returns ------- the tensor of the perturbed batch """ # First stage of attack original_input = torch.clone(batch.sig[0]) successful_adv_input_1st_stage = self._attack_1st_stage(batch) successful_perturbation_1st_stage = ( successful_adv_input_1st_stage - original_input ) if self.max_iter_2 == 0: return successful_adv_input_1st_stage # Compute original masking threshold and maximum psd theta_batch = [] original_max_psd_batch = [] wav_init = batch.sig[0] lengths = (wav_init.size(1) * batch.sig[1]).long() wavs = [wav_init[i, : lengths[i]] for i in range(batch.batchsize)] for _, wav_i in enumerate(wavs): theta, original_max_psd = None, None theta, original_max_psd = self._compute_masking_threshold(wav_i) theta = theta.transpose(1, 0) theta_batch.append(theta) original_max_psd_batch.append(original_max_psd) # Reset delta with new result local_batch_shape = successful_adv_input_1st_stage.shape self.global_optimal_delta.data = torch.zeros( batch.batchsize, self.global_max_length ).to(self.asr_brain.device) self.global_optimal_delta.data[ : local_batch_shape[0], : local_batch_shape[1] ] = successful_perturbation_1st_stage # Second stage of attack successful_adv_input_2nd_stage = self._attack_2nd_stage( batch, theta_batch=theta_batch, original_max_psd_batch=original_max_psd_batch, ) return successful_adv_input_2nd_stage def _attack_1st_stage(self, batch) -> Tuple["torch.Tensor", np.ndarray]: """ The first stage of the attack. """ num_decrease_eps = 0 # Compute local shape local_batch_size = batch.batchsize real_lengths = ( (batch.sig[1] * batch.sig[0].size(1)).long().detach().cpu().numpy() ) local_max_length = np.max(real_lengths) # Initialize rescale rescale = ( np.ones([local_batch_size, local_max_length], dtype=np.float32) * self.initial_rescale ) # Reformat input input_mask = np.zeros( [local_batch_size, local_max_length], dtype=np.float32) original_input = torch.clone(batch.sig[0]) for local_batch_size_idx in range(local_batch_size): input_mask[local_batch_size_idx, : real_lengths[local_batch_size_idx]] = 1 # Optimization loop successful_adv_input: List[Optional["torch.Tensor"]] = [ None] * local_batch_size trans = [None] * local_batch_size for iter_1st_stage_idx in range(self.max_iter_1): # Zero the parameter gradients self.optimizer_1.zero_grad() # Call to forward pass ( loss, local_delta, decoded_output, masked_adv_input, _, ) = self._forward_1st_stage( original_input=original_input, batch=batch, local_batch_size=local_batch_size, local_max_length=local_max_length, rescale=rescale, input_mask=input_mask, real_lengths=real_lengths, ) loss.backward() # Get sign of the gradients self.global_optimal_delta.grad = torch.sign( self.global_optimal_delta.grad) # Do optimization self.optimizer_1.step() # Save the best adversarial example and adjust the rescale # coefficient if successful if iter_1st_stage_idx % self.num_iter_decrease_eps == 0: for local_batch_size_idx in range(local_batch_size): tokens = ( batch.tokens[local_batch_size_idx] .detach() .cpu() .numpy() .reshape(-1) ) pred = np.array( decoded_output[local_batch_size_idx]).reshape(-1) if len(pred) == len(tokens) and (pred == tokens).all(): # print("Found one") # Adjust the rescale coefficient max_local_delta = np.max( np.abs( local_delta[local_batch_size_idx].detach( ).cpu().numpy() ) ) if ( rescale[local_batch_size_idx][0] * self.eps > max_local_delta ): rescale[local_batch_size_idx] = max_local_delta / self.eps if num_decrease_eps < self.max_num_decrease_eps: rescale[local_batch_size_idx] *= self.decrease_factor_eps num_decrease_eps += 1 # Save the best adversarial example successful_adv_input[local_batch_size_idx] = masked_adv_input[ local_batch_size_idx ] trans[local_batch_size_idx] = decoded_output[ local_batch_size_idx ] # If attack is unsuccessful if iter_1st_stage_idx == self.max_iter_1 - 1: for local_batch_size_idx in range(local_batch_size): if successful_adv_input[local_batch_size_idx] is None: successful_adv_input[local_batch_size_idx] = masked_adv_input[ local_batch_size_idx ] trans[local_batch_size_idx] = decoded_output[ local_batch_size_idx ] result = torch.stack(successful_adv_input) # type: ignore batch.sig = original_input, batch.sig[1] return result def _forward_1st_stage( self, original_input: np.ndarray, batch: sb.dataio.batch.PaddedBatch, local_batch_size: int, local_max_length: int, rescale: np.ndarray, input_mask: np.ndarray, real_lengths: np.ndarray, ): # Compute perturbed inputs local_delta = self.global_optimal_delta[: local_batch_size, :local_max_length] local_delta_rescale = torch.clamp(local_delta, -self.eps, self.eps).to( self.asr_brain.device ) local_delta_rescale *= torch.tensor(rescale).to(self.asr_brain.device) adv_input = local_delta_rescale + torch.tensor(original_input).to( self.asr_brain.device ) masked_adv_input = adv_input * torch.tensor(input_mask).to( self.asr_brain.device ) # Compute loss and decoded output batch.sig = masked_adv_input, batch.sig[1] predictions = self.asr_brain.compute_forward(batch, rs.Stage.ATTACK) loss = self.asr_brain.compute_objectives( predictions, batch, rs.Stage.ATTACK) self.asr_brain.module_eval() val_predictions = self.asr_brain.compute_forward(batch, sb.Stage.VALID) decoded_output = self.asr_brain.get_tokens(val_predictions) if self.train_mode_for_backward: self.asr_brain.module_train() return loss, local_delta, decoded_output, masked_adv_input, local_delta_rescale def _attack_2nd_stage( self, batch, theta_batch: List[np.ndarray], original_max_psd_batch: List[np.ndarray], ): # Compute local shape local_batch_size = batch.batchsize real_lengths = ( (batch.sig[1] * batch.sig[0].size(1)).long().detach().cpu().numpy() ) local_max_length = np.max(real_lengths) # Initialize rescale rescale = ( np.ones([local_batch_size, local_max_length], dtype=np.float32) * self.initial_rescale ) # Reformat input input_mask = np.zeros( [local_batch_size, local_max_length], dtype=np.float32) original_input = torch.clone(batch.sig[0]) for local_batch_size_idx in range(local_batch_size): input_mask[local_batch_size_idx, : real_lengths[local_batch_size_idx]] = 1 # Optimization loop successful_adv_input: List[Optional["torch.Tensor"]] = [ None] * local_batch_size trans = [None] * local_batch_size # Initialize alpha and rescale alpha = np.array([self.alpha] * local_batch_size, dtype=np.float32) rescale = ( np.ones([local_batch_size, local_max_length], dtype=np.float32) * self.initial_rescale ) # Reformat input input_mask = np.zeros( [local_batch_size, local_max_length], dtype=np.float32) original_input = torch.clone(batch.sig[0]) for local_batch_size_idx in range(local_batch_size): input_mask[local_batch_size_idx, : real_lengths[local_batch_size_idx]] = 1 # Optimization loop successful_adv_input: List[Optional["torch.Tensor"]] = [ None] * local_batch_size best_loss_2nd_stage = [np.inf] * local_batch_size trans = [None] * local_batch_size for iter_2nd_stage_idx in range(self.max_iter_2): # Zero the parameter gradients self.optimizer_2.zero_grad() # Call to forward pass of the first stage ( loss_1st_stage, _, decoded_output, masked_adv_input, local_delta_rescale, ) = self._forward_1st_stage( original_input=original_input, batch=batch, local_batch_size=local_batch_size, local_max_length=local_max_length, rescale=rescale, input_mask=input_mask, real_lengths=real_lengths, ) # Call to forward pass of the first stage loss_2nd_stage = self._forward_2nd_stage( local_delta_rescale=local_delta_rescale, theta_batch=theta_batch, original_max_psd_batch=original_max_psd_batch, real_lengths=real_lengths, ) # Total loss loss = ( loss_1st_stage.type(torch.float32) + torch.tensor(alpha).to(self.asr_brain.device) * loss_2nd_stage ) loss = torch.mean(loss) loss.backward() # Do optimization self.optimizer_2.step() # Save the best adversarial example and adjust the alpha # coefficient for local_batch_size_idx in range(local_batch_size): tokens = ( batch.tokens[local_batch_size_idx] .detach() .cpu() .numpy() .reshape(-1) ) pred = np.array( decoded_output[local_batch_size_idx]).reshape(-1) if len(pred) == len(tokens) and (pred == tokens).all(): if ( loss_2nd_stage[local_batch_size_idx] < best_loss_2nd_stage[local_batch_size_idx] ): # Update best loss at 2nd stage best_loss_2nd_stage[local_batch_size_idx] = loss_2nd_stage[ local_batch_size_idx ] # Save the best adversarial example successful_adv_input[local_batch_size_idx] = masked_adv_input[ local_batch_size_idx ] trans[local_batch_size_idx] = decoded_output[ local_batch_size_idx ] # Adjust to increase the alpha coefficient if iter_2nd_stage_idx % self.num_iter_increase_alpha == 0: alpha[local_batch_size_idx] *= self.increase_factor_alpha # Adjust to decrease the alpha coefficient elif iter_2nd_stage_idx % self.num_iter_decrease_alpha == 0: alpha[local_batch_size_idx] *= self.decrease_factor_alpha alpha[local_batch_size_idx] = max( alpha[local_batch_size_idx], 0.0005 ) # If attack is unsuccessful if iter_2nd_stage_idx == self.max_iter_2 - 1: for local_batch_size_idx in range(local_batch_size): if successful_adv_input[local_batch_size_idx] is None: successful_adv_input[local_batch_size_idx] = masked_adv_input[ local_batch_size_idx ] trans[local_batch_size_idx] = decoded_output[ local_batch_size_idx ] result = torch.stack(successful_adv_input) # type: ignore return result def _forward_2nd_stage( self, local_delta_rescale: "torch.Tensor", theta_batch: List[np.ndarray], original_max_psd_batch: List[np.ndarray], real_lengths: np.ndarray, ): # Compute loss for masking threshold losses = [] relu = torch.nn.ReLU() for i, _ in enumerate(theta_batch): psd_transform_delta = self._psd_transform( delta=local_delta_rescale[i, : real_lengths[i]], original_max_psd=original_max_psd_batch[i], ) loss = torch.mean( relu(psd_transform_delta - theta_batch[i].to(self.asr_brain.device)) ) losses.append(loss) losses_stack = torch.stack(losses) return losses_stack def _compute_masking_threshold( self, wav: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]: """ Compute the masking threshold and the maximum psd of the original audio. :param wav: Samples of shape (seq_length,). :return: A tuple of the masking threshold and the maximum psd. """ # First compute the psd matrix # Get window for the transformation # window = scipy.signal.get_window("hann", self.win_length, fftbins=True) window = torch.hann_window(self.win_length, periodic=True) # Do transformation # transformed_wav = librosa.core.stft( # y=x, n_fft=self.n_fft, hop_length=self.hop_length, # win_length=self.win_length, window=window, center=False # ) transformed_wav = torch.stft( input=wav.detach().cpu(), n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length, window=window, center=False, return_complex=True, ).numpy() transformed_wav *= np.sqrt(8.0 / 3.0) psd = abs(transformed_wav / self.win_length) original_max_psd = np.max(psd * psd) with np.errstate(divide="ignore"): psd = (20 * np.log10(psd)).clip(min=-200) psd = 96 - np.max(psd) + psd # Compute freqs and barks # freqs = librosa.core.fft_frequencies( # sr=self.asr_brain.hparams.sample_rate, n_fft=self.n_fft) freqs = torch.fft.rfftfreq(n=self.n_fft, d=1.0 / 16000) barks = 13 * np.arctan(0.00076 * freqs) + 3.5 * np.arctan( pow(freqs / 7500.0, 2) ) # Compute quiet threshold ath = np.zeros(len(barks), dtype=np.float32) - np.inf bark_idx = np.argmax(barks > 1) ath[bark_idx:] = ( 3.64 * pow(freqs[bark_idx:] * 0.001, -0.8) - 6.5 * np.exp(-0.6 * pow(0.001 * freqs[bark_idx:] - 3.3, 2)) + 0.001 * pow(0.001 * freqs[bark_idx:], 4) - 12 ) # Compute the global masking threshold theta theta = [] for i in range(psd.shape[1]): # Compute masker index masker_idx = argrelextrema(psd[:, i], np.greater)[0] if 0 in masker_idx: masker_idx = np.delete(masker_idx, 0) if len(psd[:, i]) - 1 in masker_idx: masker_idx = np.delete(masker_idx, len(psd[:, i]) - 1) barks_psd = np.zeros([len(masker_idx), 3], dtype=np.float32) barks_psd[:, 0] = barks[masker_idx] barks_psd[:, 1] = 10 * np.log10( pow(10, psd[:, i][masker_idx - 1] / 10.0) + pow(10, psd[:, i][masker_idx] / 10.0) + pow(10, psd[:, i][masker_idx + 1] / 10.0) ) barks_psd[:, 2] = masker_idx for j in range(len(masker_idx)): if barks_psd.shape[0] <= j + 1: break while barks_psd[j + 1, 0] - barks_psd[j, 0] < 0.5: quiet_threshold = ( 3.64 * pow(freqs[int(barks_psd[j, 2])] * 0.001, -0.8) - 6.5 * np.exp( -0.6 * pow(0.001 * freqs[int(barks_psd[j, 2])] - 3.3, 2) ) + 0.001 * pow(0.001 * freqs[int(barks_psd[j, 2])], 4) - 12 ) if barks_psd[j, 1] < quiet_threshold: barks_psd = np.delete(barks_psd, j, axis=0) if barks_psd.shape[0] == j + 1: break if barks_psd[j, 1] < barks_psd[j + 1, 1]: barks_psd = np.delete(barks_psd, j, axis=0) else: barks_psd = np.delete(barks_psd, j + 1, axis=0) if barks_psd.shape[0] == j + 1: break # Compute the global masking threshold delta = 1 * (-6.025 - 0.275 * barks_psd[:, 0]) t_s = [] for psd_id in range(barks_psd.shape[0]): d_z = barks - barks_psd[psd_id, 0] zero_idx = np.argmax(d_z > 0) s_f = np.zeros(len(d_z), dtype=np.float32) s_f[:zero_idx] = 27 * d_z[:zero_idx] s_f[zero_idx:] = (-27 + 0.37 * max(barks_psd[psd_id, 1] - 40, 0)) * d_z[ zero_idx: ] t_s.append(barks_psd[psd_id, 1] + delta[psd_id] + s_f) t_s_array =
np.array(t_s)
numpy.array
import os, sys from math import sqrt, copysign import numpy as np import helpers as nhp from helpers import rotmat_dict from LatticeModel import LatticeModel from cached_property import cached_property import random import plotly as py import plotly.graph_objs as go from cached_property import cached_property class Lattice(LatticeModel): """Class containing all that pertains to a particular type of lattice (initialization, allowed moves etc.) """ def __init__(self, **kwargs): super().__init__(**kwargs) self.steric_hindrance_penalty = 55 # energy penalty for side chains at adjacent indices pointing the same way, Abeln 2014 self.hb_penalty = -50 # energy bonus for forming an H bond, Abeln 2014 self.ca_dist = 3.8 # Distance in A between CAs at adjacent coordinates self.linker_dist = 20 # Distance tagged CA to dye todo: wild guess based on linker, should MD! self.cacb_dist = 1.53 # Distance between CA and CB self.n1_dist = 1.48 # estimate of distance N to CA self.cm_dist = 4.75 # distance between adjacent centers of mass (deduced from human swissprot dataset) self.tag_dist = 25 self.pairs_mat = kwargs['pairs_mat'] self.pro_penalty = kwargs.get('pro_penalty', 0.0) self.sol_energy_factor = kwargs.get('sol_energy_factor', 1.0) self.p_global = kwargs.get('p_global', 0.1) self.no_anchoring = kwargs.get('no_anchoring', False) self.coords = kwargs.get('coords', None) self.res_coords_mod = kwargs.get('res_coords_mod', None) self.correct_side_chains() self.state = np.ones(self.seq_length, dtype=bool) # start off with all in coil state == 1 @property def rg(self): """ Radius of gyration, based on the implementation for pymol: https://pymolwiki.org/index.php/Radius_of_gyration Uses mass of amino acid, centered at center of mass (actually ca-coords but spaced as if centers of mass) """ coord_mods = self.coords[1:, :3] - self.coords[:-1, :3] cm_list = np.split(coord_mods, axis=0, indices_or_sections=coord_mods.shape[0]) cm_coords = np.zeros_like(self.coords[:, :3], dtype=float) cm_coords[0, :] = self.coords[0, :3] for cmi, cm in enumerate(cm_list): aa1 = nhp.aa_dict[self.aa_sequence[cmi]] aa2 = nhp.aa_dict[self.aa_sequence[cmi + 1]] cm_coords[cmi + 1, :] = cm_coords[cmi, :] + cm * nhp.cm_dist_df.loc[aa1, aa2] # cm_coords = self.coords[:, :3] * self.cm_dist # note: commented, because unit coords are multiplied by modifiers above! res_mass = np.expand_dims([nhp.aa_mass_dict[rn] for rn in self.aa_sequence], -1) cm = cm_coords * res_mass tmass = np.sum(res_mass) rr = np.sum(cm * cm_coords) mm = np.sum(np.power(np.sum(cm, axis=0) / tmass, 2)) rg2 = rr / tmass - mm if rg2 < 0: return 0.0 return sqrt(rg2) @cached_property def start_pos(self): """ Placeholder vector for coordinates """ # mid_point = self.lattice_dims[0] // 2 # return np.tile((mid_point, mid_point, 0, 1), (self.seq_length, 1)) return np.tile((0, 0, 0), (self.seq_length, 1)) @property def individual_energies(self): """ Energy cost function """ e_aa = 0 e_hb = 0 has_neighbor_bool = nhp.inNd(self.res_coords, self.coords) # AA water contact contribution e_sol_vec = np.delete(np.invert(has_neighbor_bool) * self.pairs_mat.loc[self.aa_sequence, 'HOH'].to_numpy(), self.tagged_resi) e_sol_vec[e_sol_vec < 0] *= self.sol_energy_factor e_sol = np.sum(e_sol_vec) # e_sol = np.sum(np.invert(has_neighbor_bool) * self.pairs_mat.loc[aa_seq_noTagged, 'HOH']) * self.sol_energy_factor # Steric hindrance contribution # sh_bool_fwd = np.all(self.res_coords_mod[1:, :] - self.res_coords_mod[:-1, :] == 0, axis=1) # sh_bool_rev = np.all(self.res_coords_mod[:-1, :] - self.res_coords_mod[1:, :] == 0, axis=1) # e_sh = np.sum(np.logical_or(sh_bool_fwd, sh_bool_rev)) * self.steric_hindrance_penalty sh_bool = np.all(self.res_coords_mod[1:, :] - self.res_coords_mod[:-1, :] == 0, axis=1) e_sh = np.sum(sh_bool) * self.steric_hindrance_penalty for ci in range(self.seq_length): cur_aa = self.aa_sequence[ci] neighbor_bool = np.sum(np.abs(self.coords[ci, :] - self.coords), axis=1) == 1 if ci != 0: neighbor_bool[ci - 1] = False # Direct sequential neighbors do NOT count if ci < self.seq_length - 1: neighbor_bool[ci + 1] = False # H-bond contribution if self.state[ci] == 0: resdir_signed_bool = nhp.inNd(self._res_coords_mod, self._res_coords_mod[ci, :]) # check: direction same hbond_disallowed_neighbor_coords = np.vstack((self.coords[ci, :] + self.res_coords_mod[ci, :], self.coords[ci, :] - self.res_coords_mod[ci, :])) hbond_neighbor_bool = np.logical_and(neighbor_bool, np.invert(nhp.inNd(self.coords, hbond_disallowed_neighbor_coords))) # check: neighbor positions, but not in same dimension as side chain extends hbond_bool = np.logical_and(hbond_neighbor_bool, np.logical_and(resdir_signed_bool, np.invert( self.state))) # check: in beta-strand state e_hb += np.sum(hbond_bool) * self.hb_penalty * 0.5 # AA contact contribution if ci in self.tagged_resi: continue # tagged aa's can't form contacts if not np.any(neighbor_bool): continue ni = np.where(neighbor_bool)[0] # neighbor index # case 1: CA--R R--CA res_opposite_bool = nhp.inNd(self._res_coords_mod[ni, :], self._res_coords_mod[ci, :] * -1) res_on_bb_bool = nhp.inNd(self.coords[ni, :], self.res_coords[ci, :]) e_bool1 = np.logical_and(res_on_bb_bool, res_opposite_bool) # case 2 parallel residues: CA^--R CA^--R res_parallel_bool = nhp.inNd(self._res_coords_mod[ni, :], self._res_coords_mod[ci, :]) ca_dim = np.where(self.coords[ni, :3] != self.coords[ci, :3])[1] res_dim = np.array([np.argwhere(self.res_coords[nii, :3] != self.res_coords[ci, :3])[0, 0] for nii in ni]) e_bool2 = np.logical_and(res_parallel_bool, ca_dim != res_dim) e_bool = np.logical_or(e_bool1, e_bool2) neighbor_aas = self.aa_sequence[ni[e_bool]] # res_neighbor_bool = np.sum(np.abs(self.res_coords[ci, :] - self.res_coords), axis=1) == 1 # resmod_unsigned = np.row_stack((self._res_coords_mod[ci, :], self._res_coords_mod[ci, :] * -1)) # resdir_unsigned_bool = nhp.inNd(self._res_coords_mod, resmod_unsigned) # e_bool = np.logical_and(neighbor_bool, np.logical_and(resdir_unsigned_bool, res_neighbor_bool)) # e_bool = np.logical_and(~self.tagged_resi_bool, e_bool) # neighbor_aas = self.aa_sequence[e_bool] e_aa += sum([self.pairs_mat.loc[cur_aa, na] for na in neighbor_aas]) * 0.5 return e_aa, e_hb, e_sol, e_sh @property def base_energy(self): return sum(self.individual_energies) @cached_property def tagged_resi_bool(self): bool_array = np.zeros(self.seq_length, dtype=bool) bool_array[self.tagged_resi] = True return bool_array @staticmethod def stretched_init(seq_length): """ Generate a stretched configuration for a given number of residues """ coords = np.zeros((seq_length, 3), dtype=int) coords[:, 2] += np.arange(seq_length) return coords # --- Global mutations --- @staticmethod def branch_rotation(c, pivot, dim): """ :param c: coordinates to change :param pivot: point around which to rotate :param dim: signed dimension in which to perform rotation (1, 2 or 3), pos for fwd, neg for rev :return: mutated coords """ return np.dot(rotmat_dict[dim], (c - pivot).T).T + pivot @staticmethod def corner_flip(c1, c2, c3): return c2 + ((c1 + c3) - 2 * c2) @staticmethod def crankshaft_move(c, direction): da = c[0, :] != c[3, :] # dim in which hinge points differ db = np.all(c == c[0, :], axis=0) # dim in which all points are same dc = np.logical_and(np.invert(da), np.invert(db)) # dim in which 'swing' differs from hinge points c[(1, 2), dc] = c[(0, 3), dc] c[(1, 2), db] = c[(1, 2), db] + direction return c[1:3, :] @staticmethod def get_neighbors(c, d=1): neighbors = np.tile(c, (6, 1)) neighbors += np.row_stack((np.eye(3, dtype=int) * d, np.eye(3, dtype=int) * -1) * d) return neighbors @property def coords(self): return self._coords @coords.setter def coords(self, new_coords): """ Set coords to newly provided coords if provided, or set with a random walk """ # self._coords = self.start_pos if new_coords is None: nb_attempts = 500 # Allowed types: # - stretched # - serrated # - free_random # - anchored_random if self.starting_structure == 'stretched': self._coords = self.stretched_init(self.seq_length) return # if self.starting_structure == 'free_random': # for attempt_idx in range(nb_attempts): # if self.perform_random_walk([]): return # elif self.starting_structure == 'anchored_random': # anchors = [idx for idx, aa in enumerate(self.aa_sequence) if idx in self.tagged_resi] # for attempt_idx in range(nb_attempts): # if self.perform_random_walk(anchors): return raise ValueError(f'No feasible random start state reached in {nb_attempts} attempts!') else: self._coords = new_coords @property def res_coords(self): """ Residue coords """ return self.coords + self._res_coords_mod @property def res_coords_mod(self): """ Modifier for residue coords, add to CA coords to get residue coords """ return self._res_coords_mod @property def res_coords_plottable(self): """ residue coords, fit for plotting only; shorter distances for untagged, arbitrarily longer for tagged """ coords_mod = self._res_coords_mod * 0.3 coords_mod[self.tagged_resi, :] *= 20 return self.coords + coords_mod def get_distmat(self, coords, anchors): """ return the distances between all lattice points and a number of anchor coordinates """ if anchors.ndim == 1: anchors = np.expand_dims(anchors, 0) return np.column_stack([np.sum(np.abs(coords - an), axis=1) for an in anchors]) def get_free_neighbor_coords(self, c): """ Return free lattice vertices adjacent to given coordinates c, or empty vector if none exist """ neighbors = nhp.get_neighbors(c) neighbor_bool = np.invert(nhp.inNd(neighbors[:, :3], self.coords[:, :3])) return neighbors[neighbor_bool, :] def get_adjacent_bb_coords(self, idx): """ Get coordinates of CAs at positions adjacent to CA at given index idx """ if idx == 0: return self.coords[idx:idx + 2, :] elif idx == self.seq_length - 1: return self.coords[idx - 1:idx, :] else: return self.coords[idx - 1:idx + 2, :] @res_coords_mod.setter def res_coords_mod(self, new_coords): self._res_coords_mod = np.zeros((self.seq_length, 3), dtype=int) if new_coords is None: mod_idx = np.random.randint(3, size=self.seq_length) for i in enumerate(mod_idx): self.res_coords_mod[i] = 1 else: self._res_coords_mod[:] = new_coords # --- Methods to set initial position residue coordinates --- def perform_random_walk(self, anchors): """ Set residue coordinates with a random walk :return: True if random walk was succesful, False if walk ended prematurely n times. """ nb_attempts = 500 prev_anchor = 0 if 0 in anchors: anchors.remove( 0) # No need to set/anchor coords first residue; by default set at one lattice edge first = True anchoring = False if anchoring: for an in anchors: for attempt_idx_1 in range(nb_attempts): anchors_dist = an - prev_anchor # Anchor a tagged position to a lattice edge route_success = self.set_edge_coord(an, anchor=self.coords[prev_anchor, :], dist=anchors_dist, first=first) # Find a route between anchors if route_success: route_success = self.set_new_coords(prev_anchor + 1, an - 1, anchored=True) # If both succeed, continue to next anchor if route_success: first = False break if attempt_idx_1 == nb_attempts - 1: return False prev_anchor = an for attempt_idx_2 in range(nb_attempts): # set route of protein after last anchor route_success = self.set_new_coords(prev_anchor + 1, self.seq_length - 1, anchored=False) if route_success: break if attempt_idx_2 == nb_attempts - 1: return False # todo: test, grow lattice to allow free movement after initial constraint self._lattice_dims = [self.seq_length, self.seq_length, self.seq_length] return True def get_edge_candidates(self, limits_bool, anchor, dist): """ Find an extreme coordinate (i.e. highest/lowest value in any direction) to initially put a tagged residue at. :param limits_bool: 2 x 3 matrix, indicating in which dims (columns) and direction (rows) previous anchor is at edge of current structure (i.e. where new anchor shouldn't be at edge). :param anchor: previous anchor cooordinates :param dist: nb of residues to leave between returned position and previous anchor :return: candidate coordinates at distance dist from anchor, at edge of structure """ # convert limits_bool to index array stating [[direction, dim],...] in which to grow limits_idx = np.vstack(np.where(np.invert(limits_bool))).T # lat_limits = np.array(([0, 0, 0], self.lattice_dims)) # # # Option 1: Get a free lattice edge vertex within range # anchor_bool = np.sum(np.abs(self.free_coords - anchor[:3]), axis=1) <= dist # Check: within dist of anchor # # Check: on lattice edges determined by limits_idx # prev_bool = np.zeros(self.free_coords.shape[0], dtype=bool) # for dir, dim in limits_idx: # temp_bool = self.free_coords[:, dim] >= lat_limits[dir, dim] if dir else \ # self.free_coords[:, dim] <= lat_limits[dir, dim] # prev_bool = np.logical_or(temp_bool, prev_bool) # # return_bool = np.logical_and(prev_bool, anchor_bool) # if np.any(return_bool): # return self.free_coords[return_bool, :3] # Option 2: get free extreme coordinate not on lattice edge but within range # determine new direction to grow in nli = random.randint(0, limits_idx.shape[0] - 1) dir, dim = limits_idx[nli, :] # Generate all valid candidate points mod = np.mgrid[-dist:dist, -dist:dist, -dist:dist].T.reshape(-1, 3) mod = mod[np.sum(np.abs(mod), axis=1) <= dist, :] # at correct distance candidates = anchor[:3] + mod candidates = candidates[(candidates[:, dim] > anchor[dim])] if dir \ else candidates[(candidates[:, dim] < anchor[dim])] # in correct dimension # non-negative # todo kept to simulate a protein being fixed on a slide, but that could be done better I guess candidates = candidates[np.invert(np.any(candidates < 0, axis=1)), :] # # Check if within limits # todo not sure why this was still there... # inlattice_bool = nhp.inNd(candidates, self.free_coords) # return candidates[inlattice_bool, :] return candidates def set_edge_coord(self, idx, anchor, dist, first=False): """ set coordinates for res at idx at a random position at the edge of the lattice. Provide the previous anchor point and the distance between this anchor and this point as restraint. Next edge coord will be set a random limit. """ # Find which limits previous anchor was at if first: limits_bool = np.array([[False, False, True], [False, False, False]], dtype=bool) else: limits = np.percentile(self.coords[:, :3], [0, 100], axis=0) limits_bool = np.vstack([np.equal(lim.squeeze(), anchor[:3]) for lim in np.split(limits, 2, axis=0)]) # Find possible modifiers in allowed directions candidates = self.get_edge_candidates(limits_bool, anchor, dist) # If no options remain (e.g. tags too close to eachother), try the other dim/dir combinations if candidates.size == 0: candidates = self.get_edge_candidates(np.invert(limits_bool), anchor, dist) if candidates.size == 0: return False coords = nhp.pick_random_coords(candidates) self._coords[idx, :] = np.concatenate((coords, [1])) return True def set_new_coords(self, idx_start, idx_end, anchored=False): """ Set valid random positions for a range of indices. Optionally, anchor between the adjacent positions. :return: bool, True if route was set succesfully, False if route ran out of free paths before finishing. """ route_success = True if anchored: try: next_anchor_idx = idx_end + 1 except: pass previous_anchor_idx = idx_start - 1 anchors_dist = next_anchor_idx - previous_anchor_idx - 1 if idx_end < idx_start: # happens when two anchors are adjacent return True idx_list = list(range(idx_start, idx_end + 1)) # Set coordinates for iidx, idx in enumerate(idx_list): candidates = self.get_free_neighbor_coords(self._coords[idx - 1, :]) # ...free (and within lattice) if candidates.size == 0: route_success = False break if anchored: dm = self.get_distmat(candidates, anchors=self._coords[next_anchor_idx, :]) candidates = candidates[dm[:, 0] <= anchors_dist - iidx, :] # ...with enough steps left to reach end if candidates.size == 0: route_success = False break self._coords[idx, :] = nhp.pick_random_coords(candidates) # If ran stuck: reset coordinates to zeros if not route_success: self._coords[idx_list, :] = np.zeros_like(self._coords[idx_list, :]) return False return True # --- Mutations --- def is_valid_candidate_single(self, candidate): """ Check which of given candidates is valid. Last two dims are always considered the number of residues and coordinates per residue respectively. :candidates: m x n ... x seq_length x 4 array :change_idx: list of len m x n x ... with indices of changed residues for this candidate :return: m x n ... np boolean array, True if candidate is valid """ # idx_array = np.meshgrid(*[list(range(0, n)) for n in candidates.shape[:-2]], indexing='ij') # idx_array = np.column_stack([idx.reshape(-1, 1) for idx in idx_array]) # bool_array = np.zeros(candidates.shape[:-2], dtype=bool) # Default validity as 'False' # # for idx in idx_array: # candidate = candidates[tuple(idx)] turn_bool = np.any(np.abs(candidate[:-2, :] - candidate[2:, :]) == 2, axis=1) turn_bool = np.concatenate(([True], turn_bool, [True])) if np.any(np.logical_and(np.invert(self.state), turn_bool)): return False # check: no bends at beta coords, else keep 'False' elif nhp.contains_double_coords(candidate): return False # check: no double coords, else keep 'False' elif not self.is_unobstructed(candidate): return False return True # If all checks passed: valid candidate def is_valid_candidate(self, candidates): """ Check which of given candidates is valid. Last two dims are always considered the number of residues and coordinates per residue respectively. :candidates: m x n ... x seq_length x 4 array :change_idx: list of len m x n x ... with indices of changed residues for this candidate :return: m x n ... np boolean array, True if candidate is valid """ idx_array = np.meshgrid(*[list(range(0, n)) for n in candidates.shape[:-2]], indexing='ij') idx_array = np.column_stack([idx.reshape(-1, 1) for idx in idx_array]) bool_array = np.zeros(candidates.shape[:-2], dtype=bool) # Default validity as 'False' for idx in idx_array: candidate = candidates[tuple(idx)] turn_bool = np.any(np.abs(candidate[:-2, :] - candidate[2:, :]) == 2, axis=1) turn_bool = np.concatenate(([True], turn_bool, [True])) if np.any(np.logical_and(np.invert(self.state), turn_bool)): continue # check: no bends at beta coords, else keep 'False' if nhp.contains_double_coords(candidate): continue # check: no double coords, else keep 'False' if not self.is_unobstructed(candidate): continue # if not self.is_within_lattice(candidate): continue bool_array[tuple(idx)] = True # If all checks passed this loop: valid candidate return bool_array def is_unobstructed(self, coords): """ Check whether tagged residues can reach edge of lattice unobstructed in a given FULL set of coordinates. """ if self.no_anchoring: return True coord_ranges = np.row_stack((np.min(coords, axis=0), np.max(coords, axis=0))) for ti in self.tagged_resi: ray_bool = False ray_list = self.to_end(coords[ti, :], coord_ranges) for ray in ray_list: if not np.any(nhp.inNd(ray, coord_ranges)): ray_bool = True break if not ray_bool: return False return True def to_end(self, coord, ranges): """ get coordinates of all lattice vertices from a point until an edge of the lattice :param d: :return: """ out_list = [] for d in range(3): ray_fw = np.array([]) if coord[d] == ranges[1, d] else np.arange(coord[d] + 1, ranges[1, d] + 1) coord_fw = np.tile(coord, (ray_fw.size, 1)) coord_fw[:, d] = ray_fw out_list.append(coord_fw) ray_rev = np.array([]) if coord[d] == ranges[0, d] else np.arange(ranges[0, d], coord[d]) coord_rev = np.tile(coord, (ray_rev.size, 1)) coord_rev[:, d] = ray_rev out_list.append(coord_rev) return out_list # --- local mutations --- def apply_side_chain_move(self, mut_idx=None): """ Find all valid positions for side chain moves and apply one at random :return: bool, True if mutation was succesful, False otherwise """ # Pick a random AA if mut_idx is None: candidate_idx = np.arange(self.seq_length)[self.state] if not len(candidate_idx): return False mut_idx = random.choice(candidate_idx) if mut_idx in self.tagged_resi and not self.no_anchoring: # Treat tagged residues differently; must always point outward coord_ranges = np.row_stack((np.min(self.coords, axis=0), np.max(self.coords, axis=0))) ray_list = self.to_end(self.coords[mut_idx], coord_ranges) ray_bool = np.ones(len(ray_list), dtype=bool) for ri, ray in enumerate(ray_list): if any(nhp.inNd(ray, self.coords)): ray_bool[ri] = False ray_idx = np.squeeze(np.argwhere(ray_bool), -1) if ray_idx.size == 0: return False cidx = np.random.choice(ray_idx) new_res_mod = np.zeros(3, dtype=int) new_res_mod[cidx // 2] = (-1) ** (cidx % 2) self._res_coords_mod[mut_idx, :] = new_res_mod return True candidate_res_coords = self.get_neighbors(self.coords[mut_idx, :]) np.random.shuffle(candidate_res_coords) bb_coords = np.vstack((self.get_adjacent_bb_coords(mut_idx), self.res_coords[mut_idx, :])) for candidate in candidate_res_coords: if nhp.inNd(candidate, bb_coords)[0]: continue self._res_coords_mod[mut_idx, :] = candidate - self.coords[mut_idx, :] return True return False # res_coord = self.res_coords[mut_idx, :] # forbidden_coords = np.row_stack((res_coord, bb_coords)) # allowed_bool = np.invert(nhp.inNd(candidate_res_coords, forbidden_coords)) # crc = candidate_res_coords[allowed_bool, :] # candidate residue coords # new_res_coord = crc[np.random.randint(crc.shape[0]), :] # self._res_coords_mod[mut_idx, :] = new_res_coord - self.coords[mut_idx, :] # return True def correct_side_chains(self, idx_list=None): """ Check if side chain positions overlap with backbone, if so, correct :param idx_list: optionally, provide list of indices of residues to check. Default: checks all """ if idx_list is None: idx_list = range(self.seq_length) for idx in idx_list: if nhp.inNd(self.res_coords[idx, :], self.get_adjacent_bb_coords(idx))[0]: self.apply_side_chain_move(idx) # For pivot position def apply_state_change(self): """ Find all allowed state changes, apply one """ # prerequisites for flip to strand state: # no turn # if neighbor in strand state, residue must point in opposite direction turn_bool = np.any(np.abs(self.coords[:-2, :] - self.coords[2:, :]) == 2, axis=1) turn_bool = np.concatenate(([True], turn_bool, [True])) left_bool = np.logical_or(self.state[:-1], np.all( np.equal(self._res_coords_mod[:-1, :3], np.invert(self._res_coords_mod[1:, :3])), axis=1)) left_bool = np.concatenate(([True], left_bool)) right_bool = np.logical_or(self.state[1:], np.all( np.equal(self._res_coords_mod[1:, :3], np.invert(self._res_coords_mod[:-1, :3])), axis=1)) right_bool = np.concatenate((right_bool, [True])) valid_beta_idx = np.argwhere(np.logical_and(turn_bool, np.logical_and(left_bool, right_bool))) # valid_beta_idx = np.column_stack((valid_beta_idx, np.repeat('b', valid_beta_idx.size))) # prereq to flip to alpha: must be beta valid_alpha_idx = np.argwhere(np.invert(self.state)) if valid_alpha_idx.size == 0: return False mut_idx = random.choice(np.concatenate((valid_alpha_idx, valid_beta_idx))) self.state[mut_idx] = np.invert(self.state[mut_idx]) return True # --- global mutations --- def apply_branch_rotation(self): """ Find valid positions to apply branch rotation, apply one at random. Changes anywhere between all-1 to 1 position(s). :return: bool, True if mutation was successful, False otherwise """ mutations = list(range(-3, 4)) mutations.remove(0) random.shuffle(mutations) # randomize possible mutations once for entire attempt candidate_found = False idx_list = list(range(self.seq_length - 1)) random.shuffle(idx_list) # randomize positions to check for ci in idx_list: # omit last position, where rotation does not make sense candidate = np.copy( self._coords) # requires new copy each idx, as some non rotated postions might have changed for mi, mut in enumerate(mutations): candidate[ci + 1:, :] = self.branch_rotation(self._coords[ci + 1:, :], self._coords[ci, :], mut) if self.is_valid_candidate_single(candidate): candidate_found = True break if candidate_found: break if not candidate_found: return False # Adapt backbone and residual coords self.coords = candidate self._res_coords_mod[ci + 1:, :] = self.branch_rotation(self._res_coords_mod[ci + 1:, :], self._coords[ci, :], mut) # self.correct_side_chains([ci]) return True # @nb.njit(parallel=True) def apply_corner_flip(self): """ Find valid positions to apply a corner flip and apply one at random. Changes 1 position. :return: bool, True if mutation was successful, False otherwise """ # Find idx of corners: 2 points spaced by 1 point that differ in 2 coordinates corner_bool = np.count_nonzero((self._coords[2:, :] - self._coords[:-2, :]), axis=1) == 2 if not np.any(corner_bool): return False corner_idx = np.squeeze(np.argwhere(corner_bool), axis=1) + 1 # +1 as idx was of left neighbor np.random.shuffle(corner_idx) # Generate candidates # candidates = np.tile(self._coords, (corner_idx.size, 1, 1)) # corner_idx x coords x dims candidate = np.copy(self._coords) candidate_found = False for ci in corner_idx: old_coords = np.copy(candidate[ci, :3]) candidate[ci, :3] = self.corner_flip(self._coords[ci - 1, :3], self._coords[ci, :3], self._coords[ci + 1, :3]) if self.is_valid_candidate_single(candidate): candidate_found = True break else: candidate[ci, :3] = old_coords if not candidate_found: return False self.coords = candidate # self.correct_side_chains(range(ci - 1, ci + 2)) return True def apply_crankshaft_move(self): """ Find valid positions to apply a crank shaft move and apply one at random. Changes 2 positions. :return: bool, True if mutation was successful, False otherwise """ # Find idx where crank shaft is allowed; a u-shaped loop of 4 AAs. diff_4pos = self._coords[3:, :] - self._coords[:-3, :] crank_bool = np.sum(np.absolute(diff_4pos), axis=1) == 1 # if diff is 1 for that postion, it must be a u-loop if not np.any(crank_bool): return False crank_idx = np.squeeze(np.argwhere(crank_bool), axis=1) # index of left-most position of the four points! crank_idx = np.concatenate((crank_idx, crank_idx * -1)) # may swing either way, so double the index np.random.shuffle(crank_idx) # generate candidates candidate = np.copy(self.coords) candidate_found = False for ci in crank_idx: ci_abs = abs(ci) old_coords = np.copy(self.coords[ci_abs + 1:ci_abs + 3, :]) candidate[ci_abs + 1:ci_abs + 3, :] = self.crankshaft_move(np.copy(self.coords[ci_abs:ci_abs + 4, :]), copysign(1, ci)) if self.is_valid_candidate_single(candidate): candidate_found = True break else: candidate[ci_abs + 1:ci_abs + 3, :] = old_coords if not candidate_found: return False self.coords = candidate # self.correct_side_chains(range(ci_abs, ci_abs + 4)) return True def apply_n_steps(self, n): """ Apply n mutations to the structure, chosen at random. :param n: number of mutations to use :return: boolean, False if no mutations can be made anymore, else True """ global_fun_list = [self.apply_crankshaft_move, self.apply_branch_rotation, self.apply_corner_flip] local_fun_list = [self.apply_side_chain_move, self.apply_state_change] for _ in range(n): random.shuffle(global_fun_list) random.shuffle(local_fun_list) if not local_fun_list[0](): _ = local_fun_list[1]() # local mutations cannot fail for now if random.uniform(0, 1) < self.p_global: if global_fun_list[0](): self.correct_side_chains(); continue elif global_fun_list[1](): self.correct_side_chains(); continue elif global_fun_list[2](): self.correct_side_chains(); continue else: return False return True def get_N1(self, real_ca1): """ get position of first N atom in a free lattice direction """ neighbor_coords = nhp.get_neighbors(self.coords[0, :]) neighbor_coords_bool = nhp.inNd(neighbor_coords, self.get_adjacent_bb_coords(0)) neighbor_coords_free = neighbor_coords[np.invert(neighbor_coords_bool), :] # prefer the direction opposite bond with C nc_test = self._coords[0, :] + (self._coords[1, :] - self._coords[0, :]) * -1 if nhp.inNd(np.expand_dims(nc_test, 0), neighbor_coords_free)[0]: nc_out = real_ca1 + ((self._coords[1, :] - self._coords[0, :]) * -1 * self.n1_dist)[:3] return nc_out raise ValueError('position of N-terminus is not free!') # # If not free, pick a random one todo: shouldn't happen # ncf_choice = np.squeeze(random.choice(np.split(neighbor_coords_free, neighbor_coords_free.shape[0], axis=0))) # nc_out = np.copy(real_ca1) + ((ncf_choice - self._coords[0, :]) * self.n1_dist)[:3] # return nc_out @property def dist_fingerprint(self): """ Return distances in A of tagged residues to N-terminus as list of floats """ fingerprint = [] tag_coords = self.coords[self.tagged_resi, :3] * self.ca_dist + self.res_coords_mod[self.tagged_resi, :3] * self.linker_dist for i in range(1, len(self.tagged_resi)): fingerprint.append(float(np.linalg.norm(tag_coords[0, :] - tag_coords[i, :]))) return fingerprint def get_pdb_coords(self): """ Return coordinates in model as PDB-format string (no REMARKS or END) """ # translate and rotate coords_ca = self.coords[:, :3] - self.coords[0, :3] dir = np.argwhere(coords_ca[1]).squeeze()[()] if dir != 2: dir_rot = 2 - dir coords_ca = np.matmul(coords_ca, nhp.get_rotmat(dir_rot)[:3,:3]) coords_ca = coords_ca * self.ca_dist # unit distances to real distances # coords_ca = (self.coords[:, :3] + self.coords[:, :3].min().__abs__()) * self.ca_dist coords_cb = coords_ca + self.res_coords_mod[:, :3] * self.cacb_dist cn = self.get_N1(coords_ca[0, :]) cn_str = nhp.pdb_coord(cn) resn = nhp.aa_dict[self.aa_sequence[0]] txt = f'HETATM 1 N {resn} A 1 {cn_str} 1.00 1.00 N\n' # Add CA of other residues ci = 0 # cip = 1 an = 2 # atom number, start at 2 for first N an_alpha = 1 # tracker of alpha carbon atom number, just for CONECT record resi = 1 conect = "" for ci, (ca, cb) in enumerate(zip(coords_ca, coords_cb)): # --- add alpha carbon CA --- resn_str = nhp.aa_dict[self.aa_sequence[ci]] resi_str = str(resi).rjust(4) ca_str = nhp.pdb_coord(ca) txt += f'HETATM{str(an).rjust(5)} CA {resn_str} A{resi_str} {ca_str} 1.00 1.00 C\n' conect += f"CONECT{str(an_alpha).rjust(5)}{str(an).rjust(5)}\n" an_alpha = an an += 1 if resn_str != 'GLY': # --- add beta carbon CB --- cb_str = nhp.pdb_coord(cb) txt += f'HETATM{str(an).rjust(5)} CB {resn_str} A{resi_str} {cb_str} 1.00 1.00 C\n' conect += f"CONECT{str(an_alpha).rjust(5)}{str(an).rjust(5)}\n" an += 1 if ci in self.tagged_resi: # --- add placeholder atom for tag CT --- ct_str = nhp.pdb_coord(ca + self.res_coords_mod[ci, :3] * self.tag_dist) txt += f'HETATM{str(an).rjust(5)} CT {resn_str} A{resi_str} {ct_str} 1.00 1.00 C\n' conect += f"\nCONECT{str(an-1).rjust(5)}{str(an).rjust(5)}\n" an += 1 resi += 1 # Add terminus an_str = str(an).rjust(5) resn_str = nhp.aa_dict[self.aa_sequence[-1]] resi_str = str(resi - 1).rjust(4) # - 1: still on same residue as last CA txt += f'TER {an_str} {resn_str} A{resi_str}\n' txt += conect return txt def save_pdb(self, fn, rg_list=None): """ write current latice model to a readable pdb format file :param fn: file name :param rg_list: list of radius of gyration values, to store in pdb remarks 0 """ txt = f'REMARK 0 BASE ENERGY {self.base_energy}\n' if rg_list is not None: for rg in rg_list: txt += f'REMARK 1 RG {rg}\n' txt += self.get_pdb_coords() txt += '\n\nEND' with open(fn, 'w') as fh: fh.write(txt) def plot_structure(self, fn=None, auto_open=False): cols = [nhp.aa_to_hp_dict[aa] if resi not in self.tagged_resi else 'purple' for resi, aa in enumerate(self.aa_sequence)] trace_bb = go.Scatter3d(x=self.coords[:, 0], y=self.coords[:, 1], z=self.coords[:, 2], line=dict(color=cols, width=20), # marker=dict(size=5) ) trace_list = [trace_bb] for n in range(self.seq_length): cur_trace = go.Scatter3d( x=(self.coords[n, 0], self.res_coords_plottable[n, 0]), y=(self.coords[n, 1], self.res_coords_plottable[n, 1]), z=(self.coords[n, 2], self.res_coords_plottable[n, 2]), line=dict(color=cols[n], width=20), marker=dict(size=0)) trace_list.append(cur_trace) all_points = np.row_stack((self.coords, self.res_coords_plottable))[:, :3] pmin = np.min(all_points) pmax =
np.max(all_points)
numpy.max
# -*- coding: utf-8 -*- """ Created on Wed Sep 19 09:59:02 2018 @author: <NAME> """ import pytest import pandas as pd import numpy as np import itertools from collections import OrderedDict import numbers import sklearn from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.pipeline import Pipeline from sklearn.base import is_classifier, is_regressor, RegressorMixin, TransformerMixin, BaseEstimator from sklearn.datasets import make_classification, make_regression import sklearn.model_selection from sklearn.model_selection import StratifiedKFold, KFold, TimeSeriesSplit, GroupKFold, cross_val_predict from sklearn.model_selection._validation import _score#, _multimetric_score # TODO : fix test from sklearn.exceptions import NotFittedError from aikit.tools.data_structure_helper import convert_generic from aikit.enums import DataTypes from aikit.transformers.model_wrapper import DebugPassThrough from aikit.pipeline import GraphPipeline from aikit.cross_validation import ( cross_validation, create_scoring, create_cv, score_from_params_clustering, is_clusterer, _score_with_group, _multimetric_score_with_group, IndexTrainTestCv, RandomTrainTestCv, SpecialGroupCV, _check_fit_params ) from aikit.scorer import SCORERS, _GroupProbaScorer, max_proba_group_accuracy # In[] : verification of sklearn behavior def test___check_fit_params(): X= np.zeros((20,2)) train = np.arange(10) fit_params = {"param":"value"} r1 = _check_fit_params(X, fit_params, train) assert r1 == {'param': 'value'} r2 = _check_fit_params(X, {"weight":np.arange(20),"value":"param"}, train) assert r2.keys() == {"weight","value"} assert (r2["weight"] == np.arange(10)).all() assert r2["value"] == "param" def test_is_classifier_is_regressor_is_clusterer(): """ verif behavior of is_classifier and is_regressor """ rf_c = RandomForestClassifier(n_estimators=10, random_state=123) assert is_classifier(rf_c) assert not is_regressor(rf_c) assert not is_clusterer(rf_c) rf_r = RandomForestRegressor() assert not is_classifier(rf_r) assert is_regressor(rf_r) assert not is_clusterer(rf_r) kmeans = KMeans() assert not is_classifier(kmeans) assert not is_regressor(kmeans) assert is_clusterer(kmeans) sc = StandardScaler() assert not is_classifier(sc) assert not is_regressor(sc) assert not is_clusterer(sc) pipe_c = Pipeline([("s", StandardScaler()), ("r", RandomForestClassifier(n_estimators=10, random_state=123))]) assert is_classifier(pipe_c) assert not is_regressor(pipe_c) assert not is_clusterer(pipe_c) pipe_r = Pipeline([("s", StandardScaler()), ("r", RandomForestRegressor(n_estimators=10, random_state=123))]) assert not is_classifier(pipe_r) assert is_regressor(pipe_r) assert not is_clusterer(pipe_r) pipe_t = Pipeline([("s", StandardScaler()), ("r", StandardScaler())]) assert not is_classifier(pipe_t) assert not is_regressor(pipe_t) assert not is_clusterer(pipe_t) pipe_cluster = Pipeline([("s", StandardScaler()), ("r", KMeans())]) assert is_clusterer(pipe_cluster) assert not is_regressor(pipe_cluster) assert not is_classifier(pipe_cluster) def test_fit_and_predict_transfrom(): X, y = make_classification(n_samples=100) X = pd.DataFrame(X, columns=["col_%d" % i for i in range(X.shape[1])]) cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=123) for train, test in cv.split(X, y): pt = DebugPassThrough() predictions, _ = sklearn.model_selection._validation._fit_and_predict( pt, X, y, train, test, verbose=1, fit_params=None, method="transform" ) assert predictions.shape[0] == test.shape[0] assert predictions.shape[1] == X.shape[1] assert type(predictions) == type(X) def test_fit_and_predict_predict(): X, y = make_classification(n_samples=100) X = pd.DataFrame(X, columns=["col_%d" % i for i in range(X.shape[1])]) cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=123) for train, test in cv.split(X, y): logit = LogisticRegression() predictions, _ = sklearn.model_selection._validation._fit_and_predict( logit, X, y, train, test, verbose=1, fit_params=None, method="predict" ) assert predictions.shape[0] == test.shape[0] assert len(predictions.shape) == 1 def test_fit_and_predict_predict_proba(): X, y = make_classification(n_samples=100) X = pd.DataFrame(X, columns=["col_%d" % i for i in range(X.shape[1])]) y = np.array(["CL_%d" % i for i in y]) cv = KFold(n_splits=10, shuffle=False) for train, test in cv.split(X, y): logit = LogisticRegression() predictions, _ = sklearn.model_selection._validation._fit_and_predict( logit, X, y, train, test, verbose=1, fit_params=None, method="predict_proba" ) assert predictions.shape[0] == test.shape[0] assert predictions.shape[1] == 2 @pytest.mark.xfail def test_cross_val_predict(): X, y = make_classification(n_samples=100) X = pd.DataFrame(X, columns=["col_%d" % i for i in range(X.shape[1])]) ii = np.arange(X.shape[0]) np.random.seed(123) np.random.shuffle(ii) pt = DebugPassThrough() cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=123) Xhat = cross_val_predict(pt, X, y, cv=cv, method="transform") assert type(Xhat) == type(X) # Fail : cross_val_predict change the type # In[] cv and scoring def test_create_scoring(): classifier = RandomForestClassifier() regressor = RandomForestRegressor() res = create_scoring(classifier, "accuracy") assert isinstance(res, OrderedDict) assert "accuracy" in res for k, v in res.items(): assert callable(v) res = create_scoring(regressor, "neg_mean_squared_error") assert isinstance(res, OrderedDict) assert "neg_mean_squared_error" in res for k, v in res.items(): assert callable(v) res = create_scoring(regressor, ["neg_mean_squared_error", "neg_median_absolute_error"]) assert isinstance(res, OrderedDict) assert "neg_mean_squared_error" in res assert "neg_median_absolute_error" in res for k, v in res.items(): assert callable(v) res = create_scoring(regressor, res) assert isinstance(res, OrderedDict) assert "neg_mean_squared_error" in res assert "neg_median_absolute_error" in res for k, v in res.items(): assert callable(v) assert type(v) == type(res[k]) res = create_scoring(regressor, {"scorer1": "accuracy"}) assert isinstance(res, OrderedDict) assert "scorer1" in res for k, v in res.items(): assert callable(v) assert type(v) == type(res[k]) res = create_scoring(regressor, {"scorer1": SCORERS["accuracy"]}) assert isinstance(res, OrderedDict) assert "scorer1" in res for k, v in res.items(): assert callable(v) assert type(v) == type(res[k]) res = create_scoring(regressor, SCORERS["accuracy"]) assert isinstance(res, OrderedDict) for k, v in res.items(): assert callable(v) assert type(v) == type(res[k]) res = create_scoring(regressor, None) assert "default_score" in res assert isinstance(res, OrderedDict) for k, v in res.items(): assert callable(v) assert type(v) == type(res[k]) def test_create_cv(): y = np.array([0] * 10 + [1] * 10) X = np.random.randn(20, 3) cv1 = create_cv(cv=10, y=y, classifier=True) assert cv1.__class__.__name__ == "StratifiedKFold" assert len(list(cv1.split(X, y))) == 10 cv1b = create_cv(cv1) assert cv1b is cv1 y2 = np.random.randn(20) cv2 = create_cv(cv=10, y=y2) assert cv2.__class__.__name__ == "KFold" assert len(list(cv2.split(X, y))) == 10 class PersonalizedCV(object): def __init__(self): pass def split(self, X, y, groups=None): pass cv = PersonalizedCV() cv_res = create_cv(cv) assert cv is cv_res @pytest.mark.parametrize("with_groups", [True, False]) def test_cross_validation0(with_groups): np.random.seed(123) X = np.random.randn(100, 10) y = np.random.randn(100) if with_groups: groups = np.array([0] * 25 + [1] * 25 + [2] * 25 + [3] * 25) else: groups = None forest = RandomForestRegressor(n_estimators=10) result = cross_validation(forest, X, y, groups=groups, scoring=["neg_mean_squared_error", "r2"], cv=10) with pytest.raises(sklearn.exceptions.NotFittedError): forest.predict(X) assert isinstance(result, pd.DataFrame) assert list(result.columns) == [ "test_neg_mean_squared_error", "test_r2", "train_neg_mean_squared_error", "train_r2", "fit_time", "score_time", "n_test_samples", "fold_nb", ] assert len(result) == 10 forest = RandomForestRegressor(n_estimators=10, random_state=123) result, yhat = cross_validation( forest, X, y, groups, scoring=["neg_mean_squared_error", "r2"], cv=10, return_predict=True ) with pytest.raises(sklearn.exceptions.NotFittedError): forest.predict(X) assert isinstance(result, pd.DataFrame) assert list(result.columns) == [ "test_neg_mean_squared_error", "test_r2", "train_neg_mean_squared_error", "train_r2", "fit_time", "score_time", "n_test_samples", "fold_nb", ] assert len(result) == 10 assert yhat.shape == (100,) X = np.random.randn(100, 10) y = np.array(["A"] * 33 + ["B"] * 33 + ["C"] * 34) forest = RandomForestClassifier(n_estimators=10, random_state=123) result = cross_validation(forest, X, y, groups, scoring=["accuracy", "neg_log_loss"], cv=10) with pytest.raises(sklearn.exceptions.NotFittedError): forest.predict(X) assert isinstance(result, pd.DataFrame) assert list(result.columns) == [ "test_accuracy", "test_neg_log_loss", "train_accuracy", "train_neg_log_loss", "fit_time", "score_time", "n_test_samples", "fold_nb", ] assert len(result) == 10 forest = RandomForestClassifier(random_state=123, n_estimators=10) result, yhat = cross_validation( forest, X, y, groups, scoring=["accuracy", "neg_log_loss"], cv=10, return_predict=True, method="predict" ) with pytest.raises(sklearn.exceptions.NotFittedError): forest.predict(X) assert yhat.shape == (100,) assert set(np.unique(yhat)) == set(("A", "B", "C")) forest = RandomForestClassifier(random_state=123, n_estimators=10) result, yhat = cross_validation( forest, X, y, groups, scoring=["accuracy", "neg_log_loss"], cv=10, return_predict=True, method="predict_proba" ) with pytest.raises(sklearn.exceptions.NotFittedError): forest.predict(X) assert yhat.shape == (100, 3) assert isinstance(yhat, pd.DataFrame) assert list(yhat.columns) == ["A", "B", "C"] class TransformerFailNoGroups(TransformerMixin, BaseEstimator): def __init__(self): pass def fit(self, X, y, groups=None): if groups is None: raise ValueError("I need a groups") assert X.shape[0] == groups.shape[0] return self def fit_transform(self, X, y, groups): if groups is None: raise ValueError("I need a groups") assert X.shape[0] == groups.shape[0] return X def transform(self, X): return X def test_cross_validation_passing_of_groups(): np.random.seed(123) X = np.random.randn(100, 10) y = np.random.randn(100) groups = np.random.randint(0, 20, size=100) estimator = TransformerFailNoGroups() cv_res, yhat = cross_validation(estimator, X, y, groups, cv=10, no_scoring=True, return_predict=True) # Check that it doesn't fail : meaning the estimator has access to the groups assert cv_res is None assert (yhat == X).all() def test_cross_validation_with_scorer_object_regressor(): np.random.seed(123) X = np.random.randn(100, 10) y = np.random.randn(100) forest = RandomForestRegressor(n_estimators=10, random_state=123) result1 = cross_validation(forest, X, y, scoring=SCORERS["neg_mean_absolute_error"], cv=10) assert result1.shape[0] == 10 assert isinstance(result1, pd.DataFrame) forest = RandomForestRegressor(n_estimators=10, random_state=123) result2 = cross_validation(forest, X, y, scoring="neg_mean_absolute_error", cv=10) assert result2.shape[0] == 10 assert isinstance(result2, pd.DataFrame) assert np.abs(result1.iloc[:, 0] - result2.iloc[:, 0]).max() <= 10 ** (-5) assert np.abs(result1.iloc[:, 1] - result2.iloc[:, 1]).max() <= 10 ** (-5) def test_cross_validation_with_scorer_object_classifier(): X = np.random.randn(100, 10) y = np.array(["A"] * 33 + ["B"] * 33 + ["C"] * 34) forest = RandomForestClassifier(n_estimators=10, random_state=123) result1 = cross_validation(forest, X, y, scoring=SCORERS["accuracy"], cv=10) assert result1.shape[0] == 10 assert isinstance(result1, pd.DataFrame) result2 = cross_validation(forest, X, y, scoring="accuracy", cv=10) assert result2.shape[0] == 10 assert isinstance(result2, pd.DataFrame) assert np.abs(result1.iloc[:, 0] - result2.iloc[:, 0]).max() <= 10 ** (-5) assert np.abs(result1.iloc[:, 1] - result2.iloc[:, 1]).max() <= 10 ** (-5) result1 = cross_validation(forest, X, y, scoring=SCORERS["neg_log_loss"], cv=10) assert result1.shape[0] == 10 assert isinstance(result1, pd.DataFrame) result2 = cross_validation(forest, X, y, scoring="neg_log_loss", cv=10) assert result2.shape[0] == 10 assert isinstance(result2, pd.DataFrame) assert np.abs(result1.iloc[:, 0] - result2.iloc[:, 0]).max() <= 10 ** (-5) assert np.abs(result1.iloc[:, 1] - result2.iloc[:, 1]).max() <= 10 ** (-5) # In[] : verification of approx_cross_validation function @pytest.mark.parametrize( "add_third_class, x_data_type, y_string_class, shuffle, graph_pipeline, with_groups", list( itertools.product( (True, False), (DataTypes.DataFrame, DataTypes.NumpyArray, DataTypes.SparseArray), (True, False), (True, False), (True, False), (True, False), ) ), ) def test_cross_validation(add_third_class, x_data_type, y_string_class, shuffle, graph_pipeline, with_groups): X, y = make_classification(n_samples=100, random_state=123) if with_groups: groups = np.array([0] * 25 + [1] * 25 + [2] * 25 + [3] * 25) else: groups = None X = convert_generic(X, output_type=x_data_type) if x_data_type == DataTypes.DataFrame: X.columns = ["col_%d" % i for i in range(X.shape[1])] if add_third_class: y[0:2] = 2 if shuffle: np.random.seed(123) ii = np.arange(X.shape[0]) np.random.shuffle(ii) y = y[ii] if isinstance(X, pd.DataFrame): X = X.loc[ii, :] else: X = X[ii, :] if y_string_class: y = np.array(["CL_%d" % i for i in y]) if add_third_class: scoring = ["accuracy"] else: scoring = ["accuracy", "neg_log_loss"] if graph_pipeline: estimator = GraphPipeline({"pt": DebugPassThrough(), "lg": LogisticRegression()}, edges=[("pt", "lg")]) else: estimator = LogisticRegression() ################## ### Only score ### ################## cv_res = cross_validation(estimator, X, y, groups, cv=10, scoring=scoring, verbose=0) assert isinstance(cv_res, pd.DataFrame) assert cv_res.shape[0] == 10 for s in scoring: assert ("test_" + s) in set(cv_res.columns) assert ("train_" + s) in set(cv_res.columns) with pytest.raises(NotFittedError): estimator.predict(X) ##################### ### Score + Proba ### ##################### cv_res, yhat_proba = cross_validation( estimator, X, y, groups, cv=10, scoring=scoring, verbose=0, return_predict=True ) assert isinstance(cv_res, pd.DataFrame) assert cv_res.shape[0] == 10 for s in scoring: assert ("test_" + s) in set(cv_res.columns) assert ("train_" + s) in set(cv_res.columns) assert isinstance(yhat_proba, pd.DataFrame) if isinstance(X, pd.DataFrame): assert (yhat_proba.index == X.index).all() assert yhat_proba.shape == (y.shape[0], 2 + 1 * add_third_class) assert yhat_proba.min().min() >= 0 assert yhat_proba.max().max() <= 1 assert list(yhat_proba.columns) == list(np.sort(np.unique(y))) with pytest.raises(NotFittedError): estimator.predict(X) ####################### ### Score + Predict ### ####################### cv_res, yhat = cross_validation( estimator, X, y, groups, cv=10, scoring=scoring, verbose=0, return_predict=True, method="predict" ) assert isinstance(cv_res, pd.DataFrame) assert cv_res.shape[0] == 10 for s in scoring: assert ("test_" + s) in set(cv_res.columns) assert ("train_" + s) in set(cv_res.columns) assert yhat.ndim == 1 assert len(np.setdiff1d(yhat, y)) == 0 assert yhat.shape[0] == y.shape[0] with pytest.raises(NotFittedError): estimator.predict(X) #################### ### Predict only ### #################### cv_res, yhat = cross_validation( estimator, X, y, groups, cv=10, scoring=scoring, verbose=0, return_predict=True, method="predict", no_scoring=True, ) assert yhat.shape[0] == y.shape[0] assert cv_res is None assert yhat.ndim == 1 assert len(np.setdiff1d(yhat, y)) == 0 with pytest.raises(NotFittedError): estimator.predict(X) @pytest.mark.parametrize( "add_third_class, x_data_type, y_string_class, shuffle, graph_pipeline, with_groups", list( itertools.product( (True, False), (DataTypes.DataFrame, DataTypes.NumpyArray, DataTypes.SparseArray), (True, False), (True, False), (True, False), (True, False), ) ), ) def test_approx_cross_validation_early_stop( add_third_class, x_data_type, y_string_class, shuffle, graph_pipeline, with_groups ): X, y = make_classification(n_samples=100, random_state=123) if with_groups: groups = np.array([0] * 25 + [1] * 25 + [2] * 25 + [3] * 25) else: groups = None if add_third_class: y[0:2] = 2 X = convert_generic(X, output_type=x_data_type) if x_data_type == DataTypes.DataFrame: X.columns = ["col_%d" % i for i in range(X.shape[1])] if shuffle: np.random.seed(123) ii = np.arange(X.shape[0]) np.random.shuffle(ii) y = y[ii] if isinstance(X, pd.DataFrame): X = X.loc[ii, :] else: X = X[ii, :] if y_string_class: y = np.array(["CL_%d" % i for i in y]) if add_third_class: scoring = ["accuracy"] else: scoring = ["accuracy", "neg_log_loss"] if graph_pipeline: estimator = GraphPipeline( {"pt": DebugPassThrough(), "lg": LogisticRegression(C=1, random_state=123)}, edges=[("pt", "lg")] ) else: estimator = LogisticRegression(C=1, random_state=123) cv_res, yhat = cross_validation( estimator, X, y, groups, cv=10, scoring=scoring, verbose=0, return_predict=True, method="predict", stopping_round=1, stopping_threshold=1.01, # So that accuracy is sure to be bellow ) assert isinstance(cv_res, pd.DataFrame) assert cv_res.shape[0] == 2 for s in scoring: assert ("test_" + s) in set(cv_res.columns) assert ("train_" + s) in set(cv_res.columns) assert yhat is None cv_res, yhat = cross_validation( estimator, X, y, groups, cv=10, scoring=scoring, verbose=0, return_predict=True, method="predict", stopping_round=1, stopping_threshold=0.0, ) assert isinstance(cv_res, pd.DataFrame) assert cv_res.shape[0] == 10 for s in scoring: assert ("test_" + s) in set(cv_res.columns) assert ("train_" + s) in set(cv_res.columns) assert yhat.ndim == 1 assert len(np.setdiff1d(yhat, y)) == 0 @pytest.mark.parametrize( "x_data_type, shuffle, graph_pipeline, with_groups", list( itertools.product( (DataTypes.DataFrame, DataTypes.NumpyArray, DataTypes.SparseArray), (True, False), (True, False), (True, False), ) ), ) def test_approx_cross_validation_transformer(x_data_type, shuffle, graph_pipeline, with_groups): if graph_pipeline: estimator = GraphPipeline({"ptA": DebugPassThrough(), "ptB": DebugPassThrough()}, edges=[("ptA", "ptB")]) else: estimator = DebugPassThrough() X, y = make_classification(n_samples=100, random_state=123) if with_groups: groups = np.array([0] * 25 + [1] * 25 + [2] * 25 + [3] * 25) else: groups = None X = convert_generic(X, output_type=x_data_type) if x_data_type == DataTypes.DataFrame: X.columns = ["col_%d" % i for i in range(X.shape[1])] if shuffle: np.random.seed(123) ii = np.arange(X.shape[0]) np.random.shuffle(ii) y = y[ii] if isinstance(X, pd.DataFrame): X = X.loc[ii, :] else: X = X[ii, :] scoring = ["accuracy", "neg_log_loss"] ################## ### Score only ### ################## with pytest.raises(Exception): cross_validation(estimator, X, y, groups, cv=10, scoring=scoring, verbose=0) # shouldn't work since DebugPassThrough can't be scored ################# ### Transform ### ################# cv_res, Xhat = cross_validation( estimator, X, y, groups, cv=10, scoring=scoring, verbose=0, return_predict=True, no_scoring=True ) assert type(Xhat) == type(X) assert cv_res is None assert Xhat.shape == X.shape if isinstance(X, pd.DataFrame): assert (Xhat.index == X.index).all() assert (Xhat.columns == X.columns).all() if isinstance(X, pd.DataFrame): assert np.abs(Xhat - X).max().max() <= 10 ** (10 - 10) else: assert np.max(np.abs(Xhat - X)) <= 10 ** (-10) def test_cross_validation_time_serie_split(): X, y = make_classification(n_samples=100, random_state=123) cv = TimeSeriesSplit(n_splits=10) model = RandomForestClassifier(n_estimators=10, random_state=123) cv_res, yhat = cross_validation(model, X, y, cv=cv, return_predict=True) assert yhat is None # because I can't return predictions assert len(cv_res) == 10 assert isinstance(cv_res, pd.DataFrame) def test_score_from_params_clustering(): np.random.seed(123) X = np.random.randn(100, 10) kmeans = KMeans(n_clusters=3, random_state=123) result1 = score_from_params_clustering(kmeans, X, scoring=["silhouette", "davies_bouldin"]) with pytest.raises(sklearn.exceptions.NotFittedError): kmeans.predict(X) assert isinstance(result1, pd.DataFrame) assert list(result1.columns) == ["test_silhouette", "test_davies_bouldin", "fit_time", "score_time"] assert len(result1) == 1 kmeans = KMeans(n_clusters=3, random_state=123) result2, yhat = score_from_params_clustering( kmeans, X, scoring=["silhouette", "davies_bouldin"], return_predict=True ) with pytest.raises(sklearn.exceptions.NotFittedError): kmeans.predict(X) assert isinstance(result2, pd.DataFrame) assert list(result2.columns) == ["test_silhouette", "test_davies_bouldin", "fit_time", "score_time"] assert len(result2) == 1 assert yhat.shape == (100,) assert len(np.unique(yhat)) == 3 assert np.abs(result1.iloc[:, 0] - result2.iloc[:, 0]).max() <= 10 ** (-5) assert np.abs(result1.iloc[:, 1] - result2.iloc[:, 1]).max() <= 10 ** (-5) def test_score_from_params_clustering_with_scorer_object(): X = np.random.randn(100, 10) kmeans = KMeans(n_clusters=3, random_state=123) result1 = score_from_params_clustering(kmeans, X, scoring=SCORERS["silhouette"]) assert result1.shape[0] == 1 assert isinstance(result1, pd.DataFrame) result2 = score_from_params_clustering(kmeans, X, scoring="silhouette") assert result2.shape[0] == 1 assert isinstance(result2, pd.DataFrame) assert np.abs(result1.iloc[:, 0] - result2.iloc[:, 0]).max() <= 10 ** (-5) result1 = score_from_params_clustering(kmeans, X, scoring=SCORERS["calinski_harabaz"]) assert result1.shape[0] == 1 assert isinstance(result1, pd.DataFrame) result2 = score_from_params_clustering(kmeans, X, scoring="calinski_harabaz") assert result2.shape[0] == 1 assert isinstance(result2, pd.DataFrame) assert np.abs(result1.iloc[:, 0] - result2.iloc[:, 0]).max() <= 10 ** (-5) result1 = score_from_params_clustering(kmeans, X, scoring=SCORERS["davies_bouldin"]) assert result1.shape[0] == 1 assert isinstance(result1, pd.DataFrame) result2 = score_from_params_clustering(kmeans, X, scoring="davies_bouldin") assert result2.shape[0] == 1 assert isinstance(result2, pd.DataFrame) assert np.abs(result1.iloc[:, 0] - result2.iloc[:, 0]).max() <= 10 ** (-5) @pytest.mark.parametrize( "x_data_type, shuffle, graph_pipeline", list( itertools.product( (DataTypes.DataFrame, DataTypes.NumpyArray, DataTypes.SparseArray), (True, False), (True, False) ) ), ) def test_score_from_params(x_data_type, shuffle, graph_pipeline): np.random.seed(123) X = np.random.randn(100, 10) X = convert_generic(X, output_type=x_data_type) if x_data_type == DataTypes.DataFrame: X.columns = ["col_%d" % i for i in range(X.shape[1])] if shuffle: ii = np.arange(X.shape[0]) np.random.shuffle(ii) if isinstance(X, pd.DataFrame): X = X.loc[ii, :] else: X = X[ii, :] scoring = ["silhouette", "davies_bouldin", "calinski_harabaz"] if graph_pipeline: estimator = GraphPipeline( {"pt": DebugPassThrough(), "lg": KMeans(n_clusters=3, random_state=123)}, edges=[("pt", "lg")] ) else: estimator = KMeans(n_clusters=3, random_state=123) ################## ### Only score ### ################## res = score_from_params_clustering(estimator, X, scoring=scoring, verbose=0) assert isinstance(res, pd.DataFrame) assert res.shape[0] == 1 for s in scoring: assert ("test_" + s) in set(res.columns) with pytest.raises(NotFittedError): estimator.predict(X) ########################## ### Score + Prediction ### ########################## res, label = score_from_params_clustering(estimator, X, scoring=scoring, verbose=0, return_predict=True) assert isinstance(res, pd.DataFrame) assert res.shape[0] == 1 for s in scoring: assert ("test_" + s) in set(res.columns) assert isinstance(label, np.ndarray) assert len(np.unique(label)) == 3 with pytest.raises(NotFittedError): estimator.predict(X) #################### ### Predict only ### #################### res, label = score_from_params_clustering( estimator, X, scoring=scoring, verbose=0, return_predict=True, no_scoring=True ) assert len(np.unique(label)) == 3 assert res is None with pytest.raises(NotFittedError): estimator.predict(X) class DummyModel(RegressorMixin, BaseEstimator): def __init__(self): pass def fit(self, X, y): return self def predict(self, X): return X[:, 0] class DummyModelCheckFitParams(RegressorMixin, BaseEstimator): def __init__(self): pass def fit(self, X, y, **fit_params): assert "param" in fit_params assert fit_params["param"] == "value" return self def predict(self, X): return X[:, 0] class DummyModelCheckSampleWeight(RegressorMixin, BaseEstimator): def __init__(self): pass def fit(self, X, y, sample_weight=None): if sample_weight is not None: assert X.shape[0] == sample_weight.shape[0] return self def predict(self, X): return X[:, 0] class DummyModelWithApprox(RegressorMixin, BaseEstimator): def __init__(self, check_kwargs=False): self.check_kwargs = check_kwargs def fit(self, X, y): return self def predict(self, X): return X[:, 0] def approx_cross_validation( self, X, y, groups=None, scoring=None, cv=10, verbose=0, fit_params=None, return_predict=False, method="predict", no_scoring=False, stopping_round=None, stopping_threshold=None, **kwargs ): if self.check_kwargs: assert "kwargs_param" in kwargs assert kwargs["kwargs_param"] == "kwargs_value" if no_scoring: cv_res = None else: cv_res = {"scoring": scoring} if return_predict: return cv_res, X[:, 1] else: return cv_res def test_cross_validation_sample_weight(): X, y = make_classification(n_samples=100, random_state=123) sample_weight = np.ones(y.shape[0]) estimator = DummyModelCheckSampleWeight() estimator.fit(X, y, sample_weight=sample_weight) cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict", fit_params={"sample_weight":sample_weight} ) # I just need to check that it works assert yhat.shape[0] == y.shape[0] estimator = DummyModelCheckSampleWeight() estimator.fit(X, y) cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict" ) # I just need to check that it works assert yhat.shape[0] == y.shape[0] @pytest.mark.parametrize("approximate_cv", [True, False]) def test_approx_cross_validation_fit_params(approximate_cv): X, y = make_classification(n_samples=100, random_state=123) estimator = DummyModelCheckFitParams() with pytest.raises(AssertionError): cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict", approximate_cv=approximate_cv, ) cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict", fit_params={"param": "value"}, approximate_cv=approximate_cv, ) def test_approx_cross_validation_pass_kwargs(): X, y = make_classification(n_samples=100, random_state=123) estimator = DummyModelWithApprox(check_kwargs=True) with pytest.raises(AssertionError): cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict", fit_params={"param": "value"}, approximate_cv=True, ) # error because kwargs not passed cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict", fit_params={"param": "value"}, kwargs_param="kwargs_value", approximate_cv=True, ) @pytest.mark.parametrize("approximate_cv", [True, False]) def test_approx_cross_validation_dummy(approximate_cv): X, y = make_classification(n_samples=100, random_state=123) estimator = DummyModel() cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict", approximate_cv=approximate_cv ) assert yhat.ndim == 1 assert np.abs(yhat - X[:, 0]).max() <= 10 ** (-5) estimator = DummyModel() cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=False, return_predict=True, method="predict", approximate_cv=approximate_cv ) assert yhat.ndim == 1 assert np.abs(yhat - X[:, 0]).max() <= 10 ** (-5) @pytest.mark.parametrize("approximate_cv", [True, False]) def test_approx_cross_validation_raise_error(approximate_cv): X, y = make_classification(n_samples=100, random_state=123) estimator = DummyModel() with pytest.raises(ValueError): cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=False, method="predict", approximate_cv=approximate_cv, ) # no_scoring = True AND return_predict = False => Nothing to do ... error estimator = DummyModel() with pytest.raises(AttributeError): cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="transform", approximate_cv=approximate_cv, ) def test_approx_cross_validation_pass_to_method(): X, y = make_classification(n_samples=100, random_state=123) estimator = DummyModelWithApprox() cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=True, return_predict=True, method="predict", approximate_cv=True ) assert cv_res is None assert yhat.ndim == 1 assert np.abs(yhat - X[:, 1]).max() <= 10 ** (-5) estimator = DummyModelWithApprox() cv_res, yhat = cross_validation( estimator, X, y, cv=10, no_scoring=False, return_predict=True, method="predict", approximate_cv=True ) assert cv_res is not None assert "scoring" in cv_res assert yhat.ndim == 1 assert np.abs(yhat - X[:, 1]).max() <= 10 ** (-5) estimator = DummyModelWithApprox() cv_res = cross_validation( estimator, X, y, cv=10, no_scoring=False, return_predict=False, method="predict", approximate_cv=True ) assert cv_res is not None assert "scoring" in cv_res assert yhat.ndim == 1 assert np.abs(yhat - X[:, 1]).max() <= 10 ** (-5) estimator = DummyModelWithApprox() cv_res = cross_validation( estimator, X, y, cv=10, scoring=["neg_mean_squared_error"], no_scoring=False, return_predict=False, method="predict", approximate_cv=True, ) assert cv_res is not None assert "scoring" in cv_res assert cv_res["scoring"] == ["neg_mean_squared_error"] @pytest.mark.parametrize("approximate_cv", [True, False]) def test_approx_cross_validation_cv(approximate_cv): X, y = make_classification() cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=123) estimator = DebugPassThrough() cv_res, yhat = cross_validation( estimator, X, y, groups=None, cv=cv, verbose=1, fit_params={}, return_predict=True, method="transform", no_scoring=True, stopping_round=None, stopping_threshold=None, approximate_cv=approximate_cv, ) assert cv_res is None assert yhat.ndim == 2 assert yhat.shape == X.shape @pytest.mark.skipif(sklearn.__version__ >= "0.21", reason="bug fixed in 0.21") @pytest.mark.xfail def test_cross_val_predict_sklearn_few_sample_per_classes(): np.random.seed(123) X = np.random.randn(100, 2) y = np.array(["AA"] * 33 + ["BB"] * 33 + ["CC"] * 33 + ["DD"]) cv = StratifiedKFold(n_splits=10) logit = LogisticRegression() yhat_proba = cross_val_predict(logit, X, y, cv=cv, method="predict_proba") assert (yhat_proba.max(axis=1) > 0).all() @pytest.mark.parametrize("with_groups", [True, False]) def test_cross_validation_few_sample_per_classes(with_groups): np.random.seed(123) X = np.random.randn(100, 2) y = np.array(["AA"] * 33 + ["BB"] * 33 + ["CC"] * 33 + ["DD"]) if with_groups: groups = np.array([0] * 25 + [1] * 25 + [2] * 25 + [3] * 25) else: groups = None cv = StratifiedKFold(n_splits=10) logit = LogisticRegression() _, yhat_proba = cross_validation(logit, X, y, groups=groups, cv=cv, return_predict=True, no_scoring=True) assert (yhat_proba.max(axis=1) > 0).all() assert yhat_proba.shape == (100, 4) assert list(yhat_proba.columns) == ["AA", "BB", "CC", "DD"] def test_IndexTrainTestCv():
np.random.seed(123)
numpy.random.seed
import numpy as np def calculateInitialMeanAndVariance(m): # Calculate Initial Gradient initialGradient = np.zeros(shape=m.trainingDataCount) for i, content in enumerate(m.trainingData): initialGradient[i] = (m.modelLength - 1) / (content.shape[0] - 1) # Initalize Variables counter =
np.zeros(shape=(m.modelLength, 1))
numpy.zeros
# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. # See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. # Author(s): <NAME> # # Copyright (C) 2018-2019 Inria # # Modification(s): # - YYYY/MM Author: Description of the modification import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler from sklearn.neighbors import DistanceMetric from .preprocessing import DiagramScaler, BirthPersistenceTransform ############################################# # Finite Vectorization methods ############## ############################################# class PersistenceImage(BaseEstimator, TransformerMixin): """ This is a class for computing persistence images from a list of persistence diagrams. A persistence image is a 2D function computed from a persistence diagram by convolving the diagram points with a weighted Gaussian kernel. The plane is then discretized into an image with pixels, which is flattened and returned as a vector. See http://jmlr.org/papers/v18/16-337.html for more details. """ def __init__(self, bandwidth=1., weight=lambda x: 1, resolution=[20,20], im_range=[np.nan, np.nan, np.nan, np.nan]): """ Constructor for the PersistenceImage class. Parameters: bandwidth (double): bandwidth of the Gaussian kernel (default 1.). weight (function): weight function for the persistence diagram points (default constant function, ie lambda x: 1). This function must be defined on 2D points, ie lists or numpy arrays of the form [p_x,p_y]. resolution ([int,int]): size (in pixels) of the persistence image (default [20,20]). im_range ([double,double,double,double]): minimum and maximum of each axis of the persistence image, of the form [x_min, x_max, y_min, y_max] (default [numpy.nan, numpy.nan, numpy.nan, numpyp.nan]). If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method. """ self.bandwidth, self.weight = bandwidth, weight self.resolution, self.im_range = resolution, im_range def fit(self, X, y=None): """ Fit the PersistenceImage class on a list of persistence diagrams: if any of the values in **im_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. y (n x 1 array): persistence diagram labels (unused). """ if np.isnan(np.array(self.im_range)).any(): new_X = BirthPersistenceTransform().fit_transform(X) pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(new_X,y) [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]] self.im_range = np.where(np.isnan(np.array(self.im_range)), np.array([mx, Mx, my, My]), np.array(self.im_range)) return self def transform(self, X): """ Compute the persistence image for each persistence diagram individually and store the results in a single numpy array. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. Returns: numpy array with shape (number of diagrams) x (number of pixels = **resolution[0]** x **resolution[1]**): output persistence images. """ num_diag, Xfit = len(X), [] new_X = BirthPersistenceTransform().fit_transform(X) for i in range(num_diag): diagram, num_pts_in_diag = new_X[i], X[i].shape[0] w = np.empty(num_pts_in_diag) for j in range(num_pts_in_diag): w[j] = self.weight(diagram[j,:]) x_values, y_values = np.linspace(self.im_range[0], self.im_range[1], self.resolution[0]), np.linspace(self.im_range[2], self.im_range[3], self.resolution[1]) Xs, Ys = np.tile((diagram[:,0][:,np.newaxis,np.newaxis]-x_values[np.newaxis,np.newaxis,:]),[1,self.resolution[1],1]), np.tile(diagram[:,1][:,np.newaxis,np.newaxis]-y_values[np.newaxis,:,np.newaxis],[1,1,self.resolution[0]]) image = np.tensordot(w, np.exp((-np.square(Xs)-np.square(Ys))/(2*np.square(self.bandwidth)))/(np.square(self.bandwidth)*2*np.pi), 1) Xfit.append(image.flatten()[np.newaxis,:]) Xfit = np.concatenate(Xfit,0) return Xfit class Landscape(BaseEstimator, TransformerMixin): """ This is a class for computing persistence landscapes from a list of persistence diagrams. A persistence landscape is a collection of 1D piecewise-linear functions computed from the rank function associated to the persistence diagram. These piecewise-linear functions are then sampled evenly on a given range and the corresponding vectors of samples are concatenated and returned. See http://jmlr.org/papers/v16/bubenik15a.html for more details. """ def __init__(self, num_landscapes=5, resolution=100, sample_range=[np.nan, np.nan]): """ Constructor for the Landscape class. Parameters: num_landscapes (int): number of piecewise-linear functions to output (default 5). resolution (int): number of sample for all piecewise-linear functions (default 100). sample_range ([double, double]): minimum and maximum of all piecewise-linear function domains, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn evenly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method. """ self.num_landscapes, self.resolution, self.sample_range = num_landscapes, resolution, sample_range self.nan_in_range = np.isnan(np.array(self.sample_range)) self.new_resolution = self.resolution + self.nan_in_range.sum() def fit(self, X, y=None): """ Fit the Landscape class on a list of persistence diagrams: if any of the values in **sample_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. y (n x 1 array): persistence diagram labels (unused). """ if self.nan_in_range.any(): pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y) [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]] self.sample_range = np.where(self.nan_in_range, np.array([mx, My]), np.array(self.sample_range)) return self def transform(self, X): """ Compute the persistence landscape for each persistence diagram individually and concatenate the results. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. Returns: numpy array with shape (number of diagrams) x (number of samples = **num_landscapes** x **resolution**): output persistence landscapes. """ num_diag, Xfit = len(X), [] x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.new_resolution) step_x = x_values[1] - x_values[0] for i in range(num_diag): diagram, num_pts_in_diag = X[i], X[i].shape[0] ls = np.zeros([self.num_landscapes, self.new_resolution]) events = [] for j in range(self.new_resolution): events.append([]) for j in range(num_pts_in_diag): [px,py] = diagram[j,:2] min_idx = np.clip(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0, self.new_resolution) mid_idx = np.clip(np.ceil((0.5*(py+px) - self.sample_range[0]) / step_x).astype(int), 0, self.new_resolution) max_idx = np.clip(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0, self.new_resolution) if min_idx < self.new_resolution and max_idx > 0: landscape_value = self.sample_range[0] + min_idx * step_x - px for k in range(min_idx, mid_idx): events[k].append(landscape_value) landscape_value += step_x landscape_value = py - self.sample_range[0] - mid_idx * step_x for k in range(mid_idx, max_idx): events[k].append(landscape_value) landscape_value -= step_x for j in range(self.new_resolution): events[j].sort(reverse=True) for k in range( min(self.num_landscapes, len(events[j])) ): ls[k,j] = events[j][k] if self.nan_in_range[0]: ls = ls[:,1:] if self.nan_in_range[1]: ls = ls[:,:-1] ls = np.sqrt(2)*np.reshape(ls,[1,-1]) Xfit.append(ls) Xfit = np.concatenate(Xfit,0) return Xfit class Silhouette(BaseEstimator, TransformerMixin): """ This is a class for computing persistence silhouettes from a list of persistence diagrams. A persistence silhouette is computed by taking a weighted average of the collection of 1D piecewise-linear functions given by the persistence landscapes, and then by evenly sampling this average on a given range. Finally, the corresponding vector of samples is returned. See https://arxiv.org/abs/1312.0308 for more details. """ def __init__(self, weight=lambda x: 1, resolution=100, sample_range=[np.nan, np.nan]): """ Constructor for the Silhouette class. Parameters: weight (function): weight function for the persistence diagram points (default constant function, ie lambda x: 1). This function must be defined on 2D points, ie on lists or numpy arrays of the form [p_x,p_y]. resolution (int): number of samples for the weighted average (default 100). sample_range ([double, double]): minimum and maximum for the weighted average domain, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn evenly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method. """ self.weight, self.resolution, self.sample_range = weight, resolution, sample_range def fit(self, X, y=None): """ Fit the Silhouette class on a list of persistence diagrams: if any of the values in **sample_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. y (n x 1 array): persistence diagram labels (unused). """ if np.isnan(np.array(self.sample_range)).any(): pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y) [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]] self.sample_range = np.where(np.isnan(np.array(self.sample_range)), np.array([mx, My]), np.array(self.sample_range)) return self def transform(self, X): """ Compute the persistence silhouette for each persistence diagram individually and concatenate the results. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. Returns: numpy array with shape (number of diagrams) x (**resolution**): output persistence silhouettes. """ num_diag, Xfit = len(X), [] x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution) step_x = x_values[1] - x_values[0] for i in range(num_diag): diagram, num_pts_in_diag = X[i], X[i].shape[0] sh, weights = np.zeros(self.resolution), np.zeros(num_pts_in_diag) for j in range(num_pts_in_diag): weights[j] = self.weight(diagram[j,:]) total_weight = np.sum(weights) for j in range(num_pts_in_diag): [px,py] = diagram[j,:2] weight = weights[j] / total_weight min_idx = np.clip(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0, self.resolution) mid_idx = np.clip(np.ceil((0.5*(py+px) - self.sample_range[0]) / step_x).astype(int), 0, self.resolution) max_idx = np.clip(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0, self.resolution) if min_idx < self.resolution and max_idx > 0: silhouette_value = self.sample_range[0] + min_idx * step_x - px for k in range(min_idx, mid_idx): sh[k] += weight * silhouette_value silhouette_value += step_x silhouette_value = py - self.sample_range[0] - mid_idx * step_x for k in range(mid_idx, max_idx): sh[k] += weight * silhouette_value silhouette_value -= step_x Xfit.append(np.reshape(np.sqrt(2) * sh, [1,-1])) Xfit = np.concatenate(Xfit, 0) return Xfit class BettiCurve(BaseEstimator, TransformerMixin): """ This is a class for computing Betti curves from a list of persistence diagrams. A Betti curve is a 1D piecewise-constant function obtained from the rank function. It is sampled evenly on a given range and the vector of samples is returned. See https://www.researchgate.net/publication/316604237_Time_Series_Classification_via_Topological_Data_Analysis for more details. """ def __init__(self, resolution=100, sample_range=[np.nan, np.nan]): """ Constructor for the BettiCurve class. Parameters: resolution (int): number of sample for the piecewise-constant function (default 100). sample_range ([double, double]): minimum and maximum of the piecewise-constant function domain, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn evenly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method. """ self.resolution, self.sample_range = resolution, sample_range def fit(self, X, y=None): """ Fit the BettiCurve class on a list of persistence diagrams: if any of the values in **sample_range** is numpy.nan, replace it with the corresponding value computed on the given list of persistence diagrams. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. y (n x 1 array): persistence diagram labels (unused). """ if np.isnan(np.array(self.sample_range)).any(): pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y) [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]] self.sample_range = np.where(np.isnan(np.array(self.sample_range)), np.array([mx, My]), np.array(self.sample_range)) return self def transform(self, X): """ Compute the Betti curve for each persistence diagram individually and concatenate the results. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. Returns: numpy array with shape (number of diagrams) x (**resolution**): output Betti curves. """ num_diag, Xfit = len(X), [] x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution) step_x = x_values[1] - x_values[0] for i in range(num_diag): diagram, num_pts_in_diag = X[i], X[i].shape[0] bc = np.zeros(self.resolution) for j in range(num_pts_in_diag): [px,py] = diagram[j,:2] min_idx = np.clip(np.ceil((px - self.sample_range[0]) / step_x).astype(int), 0, self.resolution) max_idx = np.clip(np.ceil((py - self.sample_range[0]) / step_x).astype(int), 0, self.resolution) for k in range(min_idx, max_idx): bc[k] += 1 Xfit.append(np.reshape(bc,[1,-1])) Xfit = np.concatenate(Xfit, 0) return Xfit class Entropy(BaseEstimator, TransformerMixin): """ This is a class for computing persistence entropy. Persistence entropy is a statistic for persistence diagrams inspired from Shannon entropy. This statistic can also be used to compute a feature vector, called the entropy summary function. See https://arxiv.org/pdf/1803.08304.pdf for more details. Note that a previous implementation was contributed by <NAME>. """ def __init__(self, mode="scalar", normalized=True, resolution=100, sample_range=[np.nan, np.nan]): """ Constructor for the Entropy class. Parameters: mode (string): what entropy to compute: either "scalar" for computing the entropy statistics, or "vector" for computing the entropy summary functions (default "scalar"). normalized (bool): whether to normalize the entropy summary function (default True). Used only if **mode** = "vector". resolution (int): number of sample for the entropy summary function (default 100). Used only if **mode** = "vector". sample_range ([double, double]): minimum and maximum of the entropy summary function domain, of the form [x_min, x_max] (default [numpy.nan, numpy.nan]). It is the interval on which samples will be drawn evenly. If one of the values is numpy.nan, it can be computed from the persistence diagrams with the fit() method. Used only if **mode** = "vector". """ self.mode, self.normalized, self.resolution, self.sample_range = mode, normalized, resolution, sample_range def fit(self, X, y=None): """ Fit the Entropy class on a list of persistence diagrams. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. y (n x 1 array): persistence diagram labels (unused). """ if np.isnan(np.array(self.sample_range)).any(): pre = DiagramScaler(use=True, scalers=[([0], MinMaxScaler()), ([1], MinMaxScaler())]).fit(X,y) [mx,my],[Mx,My] = [pre.scalers[0][1].data_min_[0], pre.scalers[1][1].data_min_[0]], [pre.scalers[0][1].data_max_[0], pre.scalers[1][1].data_max_[0]] self.sample_range = np.where(np.isnan(np.array(self.sample_range)), np.array([mx, My]), np.array(self.sample_range)) return self def transform(self, X): """ Compute the entropy for each persistence diagram individually and concatenate the results. Parameters: X (list of n x 2 numpy arrays): input persistence diagrams. Returns: numpy array with shape (number of diagrams) x (1 if **mode** = "scalar" else **resolution**): output entropy. """ num_diag, Xfit = len(X), [] x_values = np.linspace(self.sample_range[0], self.sample_range[1], self.resolution) step_x = x_values[1] - x_values[0] new_X = BirthPersistenceTransform().fit_transform(X) for i in range(num_diag): orig_diagram, diagram, num_pts_in_diag = X[i], new_X[i], X[i].shape[0] new_diagram = DiagramScaler(use=True, scalers=[([1], MaxAbsScaler())]).fit_transform([diagram])[0] if self.mode == "scalar": ent = - np.sum( np.multiply(new_diagram[:,1], np.log(new_diagram[:,1])) ) Xfit.append(
np.array([[ent]])
numpy.array
import numpy as np from gtfblib import Chen import matplotlib.pyplot as plt from scipy.io import wavfile import pickle from IFModel import generate_impulse_train_multi_channels DEBUG = False folder = './data/full/' # train_x_raw = np.load(folder + 'x_small.npy', allow_pickle=True) train_x_raw =
np.load(folder + 'train_x.npy', allow_pickle=True)
numpy.load
# # PheSEIRModel Class # # This file is part of EPIMODELS # (https://github.com/I-Bouros/multi-epi-model-cross-analysis.git) which is # released under the MIT license. See accompanying LICENSE for copyright # notice and full license details. # """ This script contains code for modelling the extended SEIR model created by Public Health England and Univerity of Cambridge and which is the official model used by the UK government for policy making. It uses an extended version of an SEIR model and contact and region specific matrices. """ from itertools import chain import numpy as np from scipy.stats import nbinom, binom from scipy.integrate import solve_ivp import epimodels as em class PheSEIRModel(object): r"""PheSEIRModel Class: Base class for constructing the ODE model: deterministic SEIR used by the Public Health England to model the Covid-19 epidemic in UK based on region. The population is structured according to their age-group (:math:`i`) and region (:math:`r`) and every individual will belong to one of the compartments of the SEIR model. The general SEIR Model has four compartments - susceptible individuals (:math:`S`), exposed but not yet infectious (:math:`E`), infectious (:math:`I`) and recovered (:math:`R`). In the PHE model framework, the exposed and infectious compartments are split in two: .. math:: :nowrap: \begin{eqnarray} \frac{dS(r, t, i)}{dt} = -\lambda_{r, t, i} S(r, t, i) \\ \frac{dE_1(r, t, i)}{dt} = \lambda_{r, t, i} S( r, t, i) - \kappa E_1(r, t, i) \\ \frac{dE_2(r, t, i)}{dt} = \kappa E_1(r, t, i) - \kappa E_2( r, t, i) \\ \frac{dI_1(r, t, i)}{dt} = \kappa E_2(r, t, i) - \gamma I_1( r, t, i) \\ \frac{dI_2(r, t, i)}{dt} = \gamma I_1(r, t, i) - \gamma I_2( r, t, i) \\ \frac{dR(r, t, i)}{dt} = \gamma I_2(r, t, i) \end{eqnarray} where :math:`S(0) = S_0, E(0) = E_0, I(O) = I_0, R(0) = R_0` are also parameters of the model (evaluation at 0 refers to the compartments' structure at intial time. The parameter :math:`\lambda_{r, t, i}` is the time, age and region-varying rate with which susceptible individuals become infected, which in the context of the PHE model depends on contact and region-specific relative susceptibility matrices. The other two parameters, :math:`\kappa` and :math:`\gamma` are virsus specific and so do not depend with region, age or time: .. math:: :nowrap: \begin{eqnarray} \kappa = \frac{2}{d_L} \\ \gamma = \frac{2}{d_I} \end{eqnarray} where :math:`d_L` refers to mean latent period until disease onset and :math:`d_I` to mean period of infection. """ def __init__(self): super(PheSEIRModel, self).__init__() # Assign default values self._output_names = ['S', 'E1', 'E2', 'I1', 'I2', 'R', 'Incidence'] self._parameter_names = [ 'S0', 'E10', 'E20', 'I10', 'I20', 'R0', 'beta', 'kappa', 'gamma'] # The default number of outputs is 7, # i.e. S, E1, E2, I1, I2, R and Incidence self._n_outputs = len(self._output_names) # The default number of outputs is 7, # i.e. 6 initial conditions and 3 parameters self._n_parameters = len(self._parameter_names) self._output_indices = np.arange(self._n_outputs) def n_outputs(self): """ Returns the number of outputs. """ return self._n_outputs def n_parameters(self): """ Returns the number of parameters. """ return self._n_parameters def output_names(self): """ Returns the (selected) output names. """ names = [self._output_names[x] for x in self._output_indices] return names def parameter_names(self): """ Returns the parameter names. """ return self._parameter_names def set_outputs(self, outputs): """ Checks existence of outputs. """ for output in outputs: if output not in self._output_names: raise ValueError( 'The output names specified must be in correct forms') output_indices = [] for output_id, output in enumerate(self._output_names): if output in outputs: output_indices.append(output_id) # Remember outputs self._output_indices = output_indices self._n_outputs = len(outputs) def _compute_lambda(self, s, i1, i2, b): """ Computes the current time, age and region-varying rate with which susceptible individuals become infected. Parameters ---------- s vector of susceptibles by age group. i1 vector of 1st infective by age group. i2 vector of 2nd infective by age group. b probability matrix of infectivity. """ lam = np.empty_like(s) for i, l in enumerate(lam): prod = 1 for j, _ in enumerate(lam): prod *= (1-b[i, j])**(i1[j]+i2[j]) lam[i] = 1-prod return lam def _compute_evaluation_moments(self, times): """ Returns the points at which we keep the evaluations of the ODE system. """ eval_times = np.around( np.arange( times[0], times[-1]+self._delta_t, self._delta_t, dtype=np.float64), 5) eval_indices = np.where( np.array([(t in times) for t in eval_times]))[0].tolist() ind_in_times = [] j = 0 for i, t in enumerate(eval_times): if i >= eval_indices[j+1]: j += 1 ind_in_times.append(j) return eval_times, ind_in_times def _right_hand_side(self, t, r, y, c, num_a_groups): r""" Constructs the RHS of the equations of the system of ODEs for given a region and time point. The :math:`\lambda` parameter that accompanies the susceptible numbers is dependent on the current number of infectives and is computed using the updated multi-step infectivity matrix of the system according to the following formula .. math:: \lambda_{r, t, i} = 1 - \prod_{j=1}^{n_A}[ (1-b_{r,ij}^{t})^{I1(r,t,j)+I2(r,t,j)}] Parameters ---------- t (float) Time point at which we compute the evaluation. r (int) The index of the region to which the current instance of the ODEs system refers. y (array) Array of all the compartments of the ODE system, segregated by age-group. It assumes y = [S, E1, E2, I1, I2, R] where each letter actually refers to all compartment of that type. (e.g. S refers to the compartments of all ages of susceptibles). c (list) List values used to compute the parameters of the ODEs system. It assumes c = [beta, kappa, gamma], where :math:`beta` encaplsulates temporal fluctuations in transmition for all ages. num_a_groups (int) Number of age groups in which the population is split. It refers to the number of compartments of each type. """ # Read in the number of age-groups a = num_a_groups # Split compartments into their types s, e1, e2, i1, i2, _ = ( y[:a], y[a:(2*a)], y[(2*a):(3*a)], y[(3*a):(4*a)], y[(4*a):(5*a)], y[(5*a):]) # Read parameters of the system beta, dL, dI = c kappa = 2/dL gamma = 2/dI # And identify the appropriate MultiTimesInfectivity matrix for the # ODE system pos = np.where(self._times <= t) ind = pos[-1][-1] b = self.infectivity_timeline.compute_prob_infectivity_matrix( r, t, s, beta[self._region-1][ind]) # Compute the current time, age and region-varying # rate with which susceptible individuals become infected lam = self._compute_lambda(s, i1, i2, b) # Write actual RHS lam_times_s = np.multiply(lam, np.asarray(s)) dydt = np.concatenate(( -lam_times_s, lam_times_s - kappa * np.asarray(e1), kappa * np.asarray(e1) - kappa * np.asarray(e2), kappa * np.asarray(e2) - gamma * np.asarray(i1), gamma * np.asarray(i1) - gamma * np.asarray(i2), gamma * np.asarray(i2))) return dydt def _my_solver(self, times, num_a_groups): """ Computes the values in each compartment of the PHE ODEs system using a 'homemade' solver in the context of the discretised time step version of the model, as suggested in the paper in which it is referenced. Parameters ---------- times (list) List of time points at which we wish to evaluate the ODEs system. num_a_groups (int) Number of age groups in which the population is split. It refers to the number of compartments of each type. """ # Split compartments into their types s, e1, e2, i1, i2, r = np.asarray(self._y_init)[:, self._region-1] # Read parameters of the system beta, dL, dI = self._c kappa = self._delta_t * 2/dL gamma = self._delta_t * 2/dI eval_times, ind_in_times = \ self._compute_evaluation_moments(times) solution = np.ones((len(times), num_a_groups*6)) for ind, t in enumerate(eval_times): # Add present vlaues of the compartments to the solutions if t in times: solution[ind_in_times[ind]] = tuple( chain(s, e1, e2, i1, i2, r)) # And identify the appropriate MultiTimesInfectivity matrix for the # ODE system b = self.infectivity_timeline.compute_prob_infectivity_matrix( self._region, t, s, beta[self._region-1][ind_in_times[ind]]) # Compute the current time, age and region-varying # rate with which susceptible individuals become infected lam = self._compute_lambda(s, i1, i2, b) # Write down ODE system and compute new values for all compartments s_ = np.multiply( np.asarray(s), (np.ones_like(lam) - self._delta_t * lam)) e1_ = (1 - kappa) * np.asarray(e1) + np.multiply( np.asarray(s), self._delta_t * lam) e2_ = (1 - kappa) * np.asarray(e2) + kappa * np.asarray(e1) i1_ = (1 - gamma) * np.asarray(i1) + kappa * np.asarray(e2) i2_ = (1 - gamma) * np.asarray(i2) + gamma * np.asarray(i1) r_ = gamma * np.asarray(i2) + r s, e1, e2, i1, i2, r = ( s_.tolist(), e1_.tolist(), e2_.tolist(), i1_.tolist(), i2_.tolist(), r_.tolist()) return({'y':
np.transpose(solution)
numpy.transpose
import numpy as np import os from .sfr import SFR from .solar_abundance import solar_abundances import time from .data_to_test import likelihood_function, wildcard_likelihood_function, elements_plot, arcturus, sol_norm, plot_processes, save_abundances, cosmic_abundance_standard, ratio_function, star_function, gas_reservoir_metallicity import multiprocessing as mp from .wrapper import initialise_stuff, Chempy, Chempy_all_times try: from scipy.misc import logsumexp except ImportError: from scipy.special import logsumexp ## for scipy version control import numpy.ma as ma from .data_to_test import likelihood_evaluation, read_out_wildcard, likelihood_evaluation_int def gaussian_log(x,x0,xsig): ''' function to calculate the gaussian probability (its normed to Pmax and given in log) INPUT: x = where is the data point or parameter value x0 = mu xsig = sigma ''' return -np.divide((x-x0)*(x-x0),2*xsig*xsig) def lognorm_log(x,mu,factor): ''' this function provides Prior probability distribution where the factor away from the mean behaves like the sigma deviation in normal_log for example if mu = 1 and factor = 2 for 1 it returns 0 for 0,5 and 2 it returns -0.5 for 0.25 and 4 it returns -2.0 and so forth Can be used to specify the prior on the yield factors ''' y = np.log(np.divide(x,mu)) y = np.divide(y,np.log(factor)) y = gaussian_log(y,0.,1.) return y def gaussian(x,x0,xsig): ''' function to calculate the gaussian probability (its normed to Pmax and given in log) INPUT: x = where is the data point or parameter value x0 = mu xsig = sigma ''' factor = 1. / (np.sqrt(xsig * xsig * 2. * np.pi)) exponent = -np.divide((x - x0) * (x - x0),2 * xsig * xsig) return factor * np.exp(exponent) def lognorm(x,mu,factor): ''' this function provides Prior probability distribution where the factor away from the mean behaves like the sigma deviation in normal_log BEWARE: this function is not a properly normalized probability distribution. It only provides relative values. INPUT: x = where to evaluate the function, can be an array mu = peak of the distribution factor = the factor at which the probability decreases to 1 sigma Can be used to specify the prior on the yield factors ''' y = np.log(np.divide(x,mu)) y = np.divide(y,np.log(factor)) y = gaussian(y,0.,1.) return y def shorten_sfr(a,age=None): ''' This function crops the SFR to the length of the age of the star and ensures that enough stars are formed at the stellar birth epoch INPUT: a = Modelparameters OUTPUT: the function will update the modelparameters, such that the simulation will end when the star is born and it will also check whether there is enough sfr left at that epoch ''' if age==None: try: star = np.load('%s.npy' %(a.stellar_identifier)) except Exception as ex: from . import localpath star = np.load(localpath + 'input/stars/' + a.stellar_identifier + '.npy') age_of_star = star['age'][0] else: age_of_star=age assert (age_of_star <= 13.0), "Age of the star must be below 13Gyr" new_timesteps = int((a.time_steps-1)*a.end/(a.end-age_of_star)+1) new_end = (a.end-age_of_star)*(new_timesteps-1)/(a.time_steps-1) ## Compute SFR with the new end-point and timesteps basic_sfr = SFR(a.start,new_end,new_timesteps) ## Also compute old SFR without discretization of final time # This is to ensure we form the correct amount of mass in the simulation old_sfr = SFR(a.start,a.end,a.time_steps) if a.basic_sfr_name == 'gamma_function': getattr(basic_sfr, a.basic_sfr_name)(S0 = a.S_0 * a.mass_factor,a_parameter = a.a_parameter, loc = a.sfr_beginning, scale = a.sfr_scale) getattr(old_sfr, a.basic_sfr_name)(S0 = a.S_0 * a.mass_factor,a_parameter = a.a_parameter, loc = a.sfr_beginning, scale = a.sfr_scale) elif a.basic_sfr_name == 'model_A': basic_sfr.model_A(a.mass_factor*a.S_0,a.t_0,a.t_1) old_sfr.model_A(a.mass_factor*a.S_0,a.t_0,a.t_1) elif a.basic_sfr_name == 'prescribed': basic_sfr.prescribed(a.mass_factor, a.name_of_file) old_sfr.prescribed(a.mass_factor, a.name_of_file) elif a.basic_sfr_name == 'doubly_peaked': basic_sfr.doubly_peaked(S0 = a.mass_factor*a.S_0, peak_ratio = a.peak_ratio, decay = a.sfr_decay, t0 = a.sfr_t0, peak1t0 = a.peak1t0, peak1sigma = a.peak1sigma) old_sfr.prescribed(a.mass_factor, a.name_of_file) # compute a small correction from changing the simulation end time from scipy.stats import gamma basic_gamma = np.sum(gamma.pdf(basic_sfr.t,a.a_parameter,a.sfr_beginning,a.sfr_scale))*basic_sfr.dt old_gamma = np.sum(gamma.pdf(old_sfr.t,a.a_parameter,a.sfr_beginning,a.sfr_scale))*old_sfr.dt correction = basic_gamma/old_gamma a.total_mass*=correction ## NB: normalization doesn't matter here since it will be renormalized later basic_sfr.sfr = a.total_mass * np.divide(basic_sfr.sfr,sum(basic_sfr.sfr)) mass_normalisation = a.total_mass mean_sfr = sum(basic_sfr.sfr) / new_end # at which time in the simulation is the star born star_time = a.end-age_of_star#basic_sfr.t[-1] - age_of_star cut = [np.where(np.abs(basic_sfr.t - star_time) == np.min(np.abs(basic_sfr.t - star_time)))] if len(cut[0][0]) != 1: cut = cut[0][0][0] # updating the end time and the model steps and rescale the total mass time_model = float(basic_sfr.t[tuple(cut)]) a.end = time_model a.time_steps = int(cut[0][0]) + 1 a.total_mass = sum(basic_sfr.sfr[0:a.time_steps]) # check whether the sfr is enough at end to produce reasonable number of stars (which is necessary in order to have a probability to observe a star at all) sfr_at_end = float(basic_sfr.sfr[tuple(cut)] / basic_sfr.dt) fraction_of_mean_sfr = sfr_at_end / mean_sfr a.shortened_sfr_rescaling = a.total_mass / mass_normalisation if fraction_of_mean_sfr<0.05: return np.inf else: return a #assert fraction_of_mean_sfr > 0.05, ('The total SFR of the last age bin is below 5% of the mean SFR', 'stellar identifier = ', a.stellar_identifier, 'star time = ', star_time, 'model time = ', time_model ) def cem(changing_parameter,a): ''' This is the function calculating the chemical evolution for a specific parameter set (changing_parameter) and for a specific observational constraint specified in a (e.g. 'solar_norm' calculates the likelihood of solar abundances coming out of the model). It returns the posterior and a list of blobs. It can be used by an MCMC. This function actually encapsulates the real cem function in order to capture exceptions and in that case return -inf. This makes the MCMC runs much more stable INPUT: changing_parameter = parameter values of the free parameters as an array a = model parameters specified in parameter.py. There are also the names of free parameters specified here OUTPUT: log posterior, array of blobs the blobs contain the prior values, the likelihoods and the actual values of each predicted data point (e.g. elemental abundance value) ''' try: posterior, blobs = cem_real(changing_parameter,a) return posterior, blobs except Exception as ex: import traceback; traceback.print_exc() return -np.inf, [0] def cem_real(changing_parameter,a): ''' real chempy function. description can be found in cem ''' for i,item in enumerate(a.to_optimize): setattr(a, item, changing_parameter[i]) val = getattr(a, item) start_time = time.time() ### PRIOR calculation, values are stored in parameter.py prior_names = [] prior = [] for name in a.to_optimize: (mean, std, functional_form) = a.priors.get(name) val = getattr(a, name) prior_names.append(name) if functional_form == 0: prior.append(gaussian_log(val, mean, std)) elif functional_form == 1: prior.append(lognorm_log(val, mean, std)) a.prior = prior for name in a.to_optimize: (lower, upper) = a.constraints.get(name) val = getattr(a, name) if lower is not None and val<lower: print('%s lower border is violated with %.5f' %(name,val)) return -np.inf, [0] if upper is not None and val>upper: print('%s upper border is violated' %(name)) return -np.inf, [0] if not a.testing_output: print(changing_parameter,mp.current_process()._identity[0])#,a.observational_constraints_index else: print(changing_parameter) ### So that the parameter can be plotted in linear space if 'log10_N_0' in a.to_optimize: a.N_0 = np.power(10,a.log10_N_0) if 'log10_sn1a_time_delay' in a.to_optimize: a.sn1a_time_delay =
np.power(10,a.log10_sn1a_time_delay)
numpy.power
import cv2 import imutils import numpy as np import time # from face_detection import FaceDetection # from scipy import signal import sys from numpy.linalg import inv # import dlib import imutils import time import skin_detector def face_detect_and_thresh(frame): skinM = skin_detector.process(frame) skin = cv2.bitwise_and(frame, frame, mask = skinM) # cv2.imshow("skin2",skin) # cv2.waitKey(1) return skin,skinM def spartialAverage(thresh,frame): a=list(np.argwhere(thresh>0)) # x=[i[0] for i in a] # y=[i[1] for i in a] # p=[x,y] if a: ind_img=(np.vstack((a))) else: return 0,0,0 sig_fin=np.zeros([np.shape(ind_img)[0],3]) test_fin=[] for i in range(
np.shape(ind_img)
numpy.shape
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from scipy.sparse.linalg import LinearOperator, aslinearoperator import numpy as np __all__ = ['DeflationOperator', 'DeflatedOperator'] def vec2mat(x): n = x.shape[0] if x.shape == (n,): return np.reshape(a=x, newshape=(n, 1)) return
np.array(x)
numpy.array
#!/usr/bin/env python # coding: utf-8 # In[1]: import collections import os import numpy as np import tensorflow as tf from scipy.spatial.distance import cdist from sklearn.neighbors import NearestNeighbors from tqdm import tqdm from utils import * # In[2]: trainset = sklearn.datasets.load_files(container_path="data", encoding="UTF-8") trainset.data, trainset.target = separate_dataset(trainset, 1.0) print(trainset.target_names) print(len(trainset.data)) print(len(trainset.target)) # In[3]: def build_dataset(words, n_words, atleast=1): count = [["PAD", 0], ["GO", 1], ["EOS", 2], ["UNK", 3]] counter = collections.Counter(words).most_common(n_words) counter = [i for i in counter if i[1] >= atleast] count.extend(counter) dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary) data = list() for word in words: index = dictionary.get(word, 3) data.append(index) reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return data, dictionary, reversed_dictionary # In[4]: split = (" ".join(trainset.data)).split() vocabulary_size = len(list(set(split))) data, dictionary, rev_dictionary = build_dataset(split, vocabulary_size) # In[5]: len(dictionary) # In[6]: class Vocabulary: def __init__(self, dictionary, rev_dictionary): self._dictionary = dictionary self._rev_dictionary = rev_dictionary @property def start_string(self): return self._dictionary["GO"] @property def end_string(self): return self._dictionary["EOS"] @property def unk(self): return self._dictionary["UNK"] @property def size(self): return len(self._dictionary) def word_to_id(self, word): return self._dictionary.get(word, self.unk) def id_to_word(self, cur_id): return self._rev_dictionary.get(cur_id, self._rev_dictionary[3]) def decode(self, cur_ids): return " ".join([self.id_to_word(cur_id) for cur_id in cur_ids]) def encode(self, sentence, reverse=False, split=True): if split: sentence = sentence.split() word_ids = [self.word_to_id(cur_word) for cur_word in sentence] if reverse: return np.array([self.end_string] + word_ids + [self.start_string], dtype=np.int32) else: return np.array([self.start_string] + word_ids + [self.end_string], dtype=np.int32) class UnicodeCharsVocabulary(Vocabulary): def __init__(self, dictionary, rev_dictionary, max_word_length, **kwargs): super(UnicodeCharsVocabulary, self).__init__(dictionary, rev_dictionary, **kwargs) self._max_word_length = max_word_length self.bos_char = 256 self.eos_char = 257 self.bow_char = 258 self.eow_char = 259 self.pad_char = 260 num_words = self.size self._word_char_ids = np.zeros([num_words, max_word_length], dtype=np.int32) def _make_bos_eos(c): r = np.zeros([self._max_word_length], dtype=np.int32) r[:] = self.pad_char r[0] = self.bow_char r[1] = c r[2] = self.eow_char return r self.bos_chars = _make_bos_eos(self.bos_char) self.eos_chars = _make_bos_eos(self.eos_char) for i, word in enumerate(self._dictionary.keys()): self._word_char_ids[i] = self._convert_word_to_char_ids(word) self._word_char_ids[self.start_string] = self.bos_chars self._word_char_ids[self.end_string] = self.eos_chars @property def word_char_ids(self): return self._word_char_ids @property def max_word_length(self): return self._max_word_length def _convert_word_to_char_ids(self, word): code = np.zeros([self.max_word_length], dtype=np.int32) code[:] = self.pad_char word_encoded = word.encode("utf-8", "ignore")[: (self.max_word_length - 2)] code[0] = self.bow_char for k, chr_id in enumerate(word_encoded, start=1): code[k] = chr_id code[len(word_encoded) + 1] = self.eow_char return code def word_to_char_ids(self, word): if word in self._dictionary: return self._word_char_ids[self._dictionary[word]] else: return self._convert_word_to_char_ids(word) def encode_chars(self, sentence, reverse=False, split=True): if split: sentence = sentence.split() chars_ids = [self.word_to_char_ids(cur_word) for cur_word in sentence] if reverse: return np.vstack([self.eos_chars] + chars_ids + [self.bos_chars]) else: return np.vstack([self.bos_chars] + chars_ids + [self.eos_chars]) def _get_batch(generator, batch_size, num_steps, max_word_length): cur_stream = [None] * batch_size no_more_data = False while True: inputs = np.zeros([batch_size, num_steps], np.int32) if max_word_length is not None: char_inputs = np.zeros([batch_size, num_steps, max_word_length], np.int32) else: char_inputs = None targets =
np.zeros([batch_size, num_steps], np.int32)
numpy.zeros
'''Helper functions ''' import os import re import six import zlib import string import urllib import itertools from dateutil.tz import tzlocal from functools import wraps try: from urllib import unquote except ImportError: from urllib.parse import unquote import numpy as np from cottoncandy import options ############################## # Globals ############################## # S3 AWS #--------- MB = 2**20 MIN_MPU_SIZE = int(options.config.get('upload_settings', 'min_mpu_size'))*MB # 5MB MAX_PUT_SIZE = int(options.config.get('upload_settings', 'max_put_size'))*MB # 5GB MAX_MPU_SIZE = int(options.config.get('upload_settings', 'max_mpu_size_TB'))*MB*MB # 5TB MAX_MPU_PARTS = int(options.config.get('upload_settings', 'max_mpu_parts')) # 10,000 MPU_THRESHOLD = int(options.config.get('upload_settings', 'mpu_use_threshold'))*MB MPU_CHUNKSIZE = int(options.config.get('upload_settings', 'mpu_chunksize'))*MB DASK_CHUNKSIZE = int(options.config.get('upload_settings', 'dask_chunksize'))*MB SEPARATOR = options.config.get('basic', 'path_separator') DEFAULT_ACL = options.config.get('basic', 'default_acl') MANDATORY_BUCKET_PREFIX = options.config.get('basic', 'mandatory_bucket_prefix') ISBOTO_VERBOSE = options.config.get('login', 'verbose_boto') ############################## # misc functions ############################## def sanitize_metadata(metadict): outdict = {} for key,val in metadict.items(): outdict[key.lower()] = val return outdict def pathjoin(a, *p): """Join two or more pathname components, inserting SEPARATOR as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.""" path = a for b in p: if b.startswith(SEPARATOR): path = b elif path == '' or path.endswith(SEPARATOR): path += b else: path += SEPARATOR + b return path def string2bool(mstring): ''' ''' truth_value = False if mstring in ['True','true', 'tru', 't', 'y','yes', '1']: truth_value = True elif mstring == 'None': truth_value = None return truth_value def bytes2human(nbytes): '''Return string representation of bytes. Parameters ---------- nbytes : int Number of bytes Returns ------- human_bytes : str Human readable byte size (e.g. "10.00MB", "1.24GB", etc.). ''' if nbytes == 0: return '0.00B' mapper = {0 : 'B', 10 : 'KB', 20 : 'MB', 30 : 'GB', 40 : 'TB', 50 : 'PB', 60 : 'EB', 70 : 'ZB', } exps = sorted(mapper.keys()) exp_coeff = np.log2(nbytes) exp_closest = int((exps[np.abs(exps - exp_coeff).argmin()])) if
np.log10(nbytes/2.**exp_closest)
numpy.log10
# openSAP32 # Copyright (c) 2014 <NAME> # License: BSD 3-clause # (https://github.com/dukenmarga/openSAP32/blob/master/LICENSE.txt) import numpy as np import openSAP32.solver.mathematic as maths class Truss(): ''' Perform truss structure analysis All index numbering in this class use 2 method: - ArrayIndexing : index number is using numpy indexing start from zero (0) - NormalIndexing : index number is using normal indexing start from one (1), commonly used for numbering for human usage. ''' def __init__(self): self.list = np.array([[]]) pass def solve2d(self, model, rec): '''Solve Truss 2 dimension''' self.INDEX_AREA = 0 self.INDEX_YOUNG_MODULUS = 3 self.INDEX_LENGTH = 3 self.INDEX_SECTION = 2 self.INDEX_MATERIAL = 2 self.INDEX_SIN = 0 self.INDEX_COS = 1 self.INDEX_ANGLE = 2 self.INDEX_SPRING_STIFF = 1 self.INDEX_NODE_1, self.INDEX_NODE_2 = 0, 1 self.INDEX_POSITION_X, self.INDEX_POSITION_Y = 0, 1 self.INDEX_NODE = 0 self.INDEX_FX = 1 self.INDEX_FY = 2 self.INDEX_DX = 1 self.INDEX_DY = 2 self.DOF = 2 # degree of freedom each node self.totalNode = np.size(model.node.list, 0) self.totalMember = np.size(model.structure.list, 0) self.totalDOF = self.totalNode * self.DOF self.assembleTrigonometri(model, rec) self.assembleLocalStiffness(model, rec) self.assembleGlobalStiffness(model, rec) self.assembleLoad(model, rec) self.assembleUnsolvedMatrix(model, rec) self.solveDeformation(model, rec) self.solveInternalForceStress(model, rec) pass def assembleTrigonometri(self, model, rec): '''Stores value of sin and cos of angle that is formed beetween 2 nodes for each element in structure. Example ------- Element 2 in structure is formed beetween node2: (x2=4,y2=3) and node1: (x1=0, y1=0). So, :math:`b = y2-y1 = 3-0 = 3`, :math:`a = x2-x1 = 4-0 = 4`, then using pythagoras :math:`c = 5` :math:`Sin = b/c`, :math:`Cos = a/c`, :math:`Tan = a/b` ''' # ELEMENT structure = model.structure node = model.node restrain = model.restrain for element in structure.list: if self.totalMember == 0: break # NODE_1 & NODE_2 are number of nodes for each element NODE_1, NODE_2 = element[self.INDEX_NODE_1]-1, element[self.INDEX_NODE_2]-1 length_x = node.list[NODE_2][self.INDEX_POSITION_X] - node.list[NODE_1][self.INDEX_POSITION_X] length_y = node.list[NODE_2][self.INDEX_POSITION_Y] - node.list[NODE_1][self.INDEX_POSITION_Y] length_element = maths.hypotenuse(length_y, length_x) # S=sin C=cos T=tan S = length_y/length_element C = length_x/length_element T = 0 # Store trigonometri data of each element if rec.pre.T.size == 0: rec.pre.T = np.array([[S, C, T, length_element]]) else: rec.pre.T = np.append(rec.pre.T, [[S, C, T, length_element]], axis=0) # SPRING for spring in restrain.spring: # S=sin C=cos T=tan S = maths.sin(spring[self.INDEX_ANGLE]) C = maths.cos(spring[self.INDEX_ANGLE]) if C < 1e-10: C = 0 T = 0 length = 0 # Store trigonometri data of each element if rec.pre.T.size == 0: rec.pre.T = np.array([[S, C, T, length]]) else: rec.pre.T = np.append(rec.pre.T, [[S, C, T, length]], axis=0) pass def assembleLocalStiffness(self, model, rec): '''Assemble local stiffness of each element Local stiffness is also known as element stiffness ''' i = 0 # LOCAL STIFFNESS FROM ELEMENT structure = model.structure section = model.section material = model.material restrain = model.restrain Trig = rec.pre.T for element in structure.list: if self.totalMember == 0: break NUM_SECTION = element[self.INDEX_SECTION]-1 A = section.list[NUM_SECTION, self.INDEX_AREA] NUM_MATERIAL = int(section.list[NUM_SECTION, self.INDEX_MATERIAL]-1) E = material.list[NUM_MATERIAL][self.INDEX_YOUNG_MODULUS] L = Trig[i][self.INDEX_LENGTH] K = A * E / L S = Trig[i][self.INDEX_SIN] C = Trig[i][self.INDEX_COS] matrix = [[C*C, C*S, -C*C, -C*S], [C*S, S*S, -C*S, -S*S], [-C*C, -C*S, C*C, C*S], [-C*S, -S*S, C*S, S*S]] matrix = np.dot(matrix, K) if rec.pre.localStiffnessMatrix.size == 0: rec.pre.localStiffnessMatrix = np.array([matrix]) else: rec.pre.localStiffnessMatrix= np.append(rec.pre.localStiffnessMatrix, \ [matrix], axis=0) i = i+1 # LOCAL STIFFNESS FROM SPRING i = self.totalMember for spring in restrain.spring: k = spring[self.INDEX_SPRING_STIFF] S = Trig[i][self.INDEX_SIN] C = Trig[i][self.INDEX_COS] matrix = [[C*C, C*S, -C*C, -C*S], [C*S, S*S, -C*S, -S*S], [-C*C, -C*S, C*C, C*S], [-C*S, -S*S, C*S, S*S]] matrix = np.dot(matrix, k) if rec.pre.localStiffnessMatrix.size == 0: rec.pre.localStiffnessMatrix = np.array([matrix]) else: rec.pre.localStiffnessMatrix= np.append(rec.pre.localStiffnessMatrix, \ [matrix], axis=0) i = i+1 pass def assembleGlobalStiffness(self, model, rec): ''' Assemble global stiffness of structures''' rec.pre.globalStiffnessMatrix = np.array(np.zeros((self.totalDOF, self.totalDOF))) # ELEMENT i = 0 structure = model.structure localStiffnessMatrix = rec.pre.localStiffnessMatrix for element in structure.list: # NODE_1 & NODE_2 are number of nodes for each element NODE_1, NODE_2 = element[self.INDEX_POSITION_X], element[self.INDEX_POSITION_Y] #ArrayIndexing a1 = 2*NODE_1-2 a2 = 2*NODE_1 b1 = 2*NODE_2-2 b2 = 2*NODE_2 rec.pre.globalStiffnessMatrix[a1:a2, a1:a2] += localStiffnessMatrix[i, 0:2, 0:2] rec.pre.globalStiffnessMatrix[a1:a2, b1:b2] += localStiffnessMatrix[i, 0:2, 2:4] rec.pre.globalStiffnessMatrix[b1:b2, a1:a2] += localStiffnessMatrix[i, 2:4, 0:2] rec.pre.globalStiffnessMatrix[b1:b2, b1:b2] += localStiffnessMatrix[i, 2:4, 2:4] i = i+1 pass # SPRING i = self.totalMember restrain = model.restrain for spring in restrain.spring: n = spring[self.INDEX_NODE] #ArrayIndexing a1 = 2*n-2 a2 = 2*n rec.pre.globalStiffnessMatrix[a1:a2, a1:a2] += localStiffnessMatrix[i, 0:2, 0:2] i = i+1 pass def assembleLoad(self, model, rec): '''Assemble load matrix''' rec.pre.loadMatrix = np.array(np.zeros((self.totalDOF,1))) load = model.load for load in load.list: node = load[self.INDEX_NODE] Fx = load[self.INDEX_FX] Fy = load[self.INDEX_FY] rec.pre.loadMatrix[2*node-2:2*node] += [[Fx], [Fy]] pass def assembleUnsolvedMatrix(self, model, rec): '''Construct unsolved matrix. Unsolved matrix is consist of matrix of global stiffness of node which are not restrained and matrix of load at unrestrained node. ''' # construct array number of unrestrained node sequence = np.arange(self.totalDOF) unrestrainedNode=[] restrain = model.restrain for i in sequence: if i not in restrain.list: unrestrainedNode += [i] rec.pre.unrestrainedNode = np.array(unrestrainedNode) unsolvedStiffness = rec.pre.globalStiffnessMatrix[np.ix_(rec.pre.unrestrainedNode, rec.pre.unrestrainedNode)] unsolvedLoad = rec.pre.loadMatrix[np.ix_(rec.pre.unrestrainedNode)] rec.pre.unsolvedGlobalStiffnessMatrix = np.array(unsolvedStiffness) rec.pre.unsolvedLoadMatrix =
np.array(unsolvedLoad)
numpy.array
import numpy as np import pandas as pd import scipy.io from matplotlib import pyplot as plt import pickle from sklearn.model_selection import train_test_split from collections import Counter from tqdm import tqdm import os import torch def preprocess_physionet(): """ download the raw data from https://physionet.org/content/challenge-2017/1.0.0/, and put it in challenge2017/ """ # read label label_df = pd.read_csv('challenge2017/REFERENCE-v3.csv', header=None) label = label_df.iloc[:,1].values print(Counter(label)) # read data all_data = [] filenames = pd.read_csv('challenge2017/training2017/RECORDS', header=None) filenames = filenames.iloc[:,0].values print(filenames) for filename in tqdm(filenames): mat = scipy.io.loadmat('challenge2017/training2017/{0}.mat'.format(filename)) mat = np.array(mat['val'])[0] all_data.append(mat) all_data = np.array(all_data) res = {'data':all_data, 'label':label} with open('challenge2017/challenge2017.pkl', 'wb') as fout: pickle.dump(res, fout) def slide_and_cut(X, Y, window_size, stride, output_pid=False): out_X = [] out_Y = [] out_pid = [] n_sample = X.shape[0] mode = 0 for i in range(n_sample): tmp_ts = X[i] tmp_Y = Y[i] # This aims to 'augment' or 'balance' the data, # You can use according to your dataset or just set 'i_stride = stride' """ if tmp_Y == 0: i_stride = stride elif tmp_Y == 1: i_stride = stride//6 # use 10 for read_data_physionet_2 elif tmp_Y == 2: i_stride = stride//2 elif tmp_Y == 3: i_stride = stride//20 """ i_stride = stride for j in range(0, len(tmp_ts)-window_size, i_stride): out_X.append(tmp_ts[j:j+window_size]) out_Y.append(tmp_Y) out_pid.append(i) if output_pid: return np.array(out_X), np.array(out_Y), np.array(out_pid) else: return np.array(out_X), np.array(out_Y) def read_data_physionet(window_size=2000, stride=1000, is_train=True): # read pkl with open('challenge2017/challenge2017.pkl', 'rb') as fin: res = pickle.load(fin) ## scale data all_data = res['data'] all_label = res['label'] new_data = [] new_label = [] # exclude noise for i in range(len(all_label)): if all_label[i] != '~': new_data.append(all_data[i]) new_label.append(all_label[i]) all_data = np.array(new_data) new_label = np.array(new_label) for i in range(len(all_data)): tmp_data = all_data[i] tmp_std = np.std(tmp_data) tmp_mean = np.mean(tmp_data) all_data[i] = (tmp_data - tmp_mean) / tmp_std ## encode label all_label = [] for i in new_label: if i == 'N': all_label.append(0) elif i == 'A': all_label.append(1) elif i == 'O': all_label.append(2) elif i == '~': all_label.append(3) all_label = np.array(all_label) # slide and cut X, _, Y = slide_and_cut(all_data, all_label, window_size=window_size, stride=stride, output_pid=True) # split train test X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1, random_state=0) # shuffle train if is_train: shuffle_pid = np.random.permutation(Y_train.shape[0]) X_train = X_train[shuffle_pid] Y_train = Y_train[shuffle_pid] X_train =
np.expand_dims(X_train, 1)
numpy.expand_dims
#!/usr/bin/env python # coding: utf-8 # In[1]: import logging import os import sys import argparse import random import numpy as np import tqdm import pickle import pandas as pd from matplotlib import pyplot as plt from keras import backend as K from keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split from sklearn.metrics import fbeta_score, precision_recall_fscore_support, f1_score import torch from torch.utils.data.dataloader import DataLoader import torch.nn.functional as F import torch.nn as nn from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import XLNetTokenizer, XLNetForSequenceClassification, XLNetModel, AdamW # from Dataset import Dataset # sys.path.append(os.path.abspath("../..")) # from skimage.io import imread, imsave device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs!") # In[2]: def logging_storage(logfile_path): logging.basicConfig(filename=logfile_path, filemode='a', level=logging.INFO, format='%(asctime)s => %(message)s') logging.info(torch.__version__) logging.info(device) # ### Global Variables # In[3]: lr = 2e-5 num_epochs = 3 MAX_LEN = 128 batch_size = 128 dataset = 'quora' model = 'xlnet' # In[4]: ending_path = ('%s_%s_%s_%s_%s' %(model, dataset, MAX_LEN, batch_size, str(lr).replace("-", ""))) # In[5]: ending_path # In[6]: save_model_path = "../models/" if not os.path.exists(save_model_path): os.mkdir(save_model_path) logfile_path = "../logs/" + ending_path # In[8]: logging_storage(logfile_path) # ### Data Loading # In[9]: df_train = pd.read_csv('../data/Quora/train.tsv', names = ['Label', 'Q1', 'Q2', 'Id'], sep = "\t") # In[10]: df_dev = pd.read_csv('../data/Quora/dev.tsv', names = ['Label', 'Q1', 'Q2', 'Id'], sep = "\t") # In[11]: df_test = pd.read_csv('../data/Quora/test.tsv', names = ['Label', 'Q1', 'Q2', 'Id'], sep = "\t") # In[12]: print(len(df_train), len(df_test), len(df_dev)) # In[13]: for i, row in df_train.iterrows(): df_train.at[i, 'input'] = " <cls> " + str(row[1]) + " <sep> " + str(row[2]) + " <cls> " if(i % 100000) == 0 and i: print("Completed: %s" %(i)) # In[14]: for i, row in df_dev.iterrows(): df_dev.at[i, 'input'] = " <cls> " + str(row[1]) + " <sep> " + str(row[2]) + " <cls> " if(i % 100000) == 0 and i: print("Completed: %s" %(i)) # In[15]: for i, row in df_test.iterrows(): df_test.at[i, 'input'] = " <cls> " + str(row[1]) + " <sep> " + str(row[2]) + " <cls> " if(i % 100000) == 0 and i: print("Completed: %s" %(i)) # In[16]: tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased', do_lower_case=True, sep_token = '<sep>', cls_token = '<cls>') # In[45]: inp_train = df_train['input'].tolist() labels_train = df_train['Label'].tolist() # In[46]: inp_dev = df_dev['input'].tolist() labels_dev = df_dev['Label'].tolist() # In[47]: inp_test = df_test['input'].tolist() labels_test = df_test['Label'].tolist() # ### Process Dataset # In[48]: tokenized_texts_train = [tokenizer.tokenize(inp) for inp in inp_train] input_ids_train = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts_train] # In[49]: input_ids_train = pad_sequences(input_ids_train, maxlen=MAX_LEN, dtype="long", truncating="post", padding="post") # In[50]: attention_masks_train = [] for seq in input_ids_train: seq_mask = [float(i>0) for i in seq] attention_masks_train.append(seq_mask) # In[51]: train_inputs = torch.tensor(input_ids_train) train_labels = torch.tensor(labels_train) train_masks = torch.tensor(attention_masks_train) # In[52]: train_data = TensorDataset(train_inputs, train_masks, train_labels) train_sampler = RandomSampler(train_data) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size) # ##### Dev # In[53]: tokenized_texts_dev = [tokenizer.tokenize(inp) for inp in inp_dev] input_ids_dev = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts_dev] # In[54]: input_ids_dev = pad_sequences(input_ids_dev, maxlen=MAX_LEN, dtype="long", truncating="post", padding="post") # In[55]: attention_masks_dev = [] for seq in input_ids_dev: seq_mask = [float(i>0) for i in seq] attention_masks_dev.append(seq_mask) # In[56]: dev_inputs = torch.tensor(input_ids_dev) dev_labels = torch.tensor(labels_dev) dev_masks = torch.tensor(attention_masks_dev) # In[57]: dev_data = TensorDataset(dev_inputs, dev_masks, dev_labels) dev_sampler = RandomSampler(dev_data) dev_dataloader = DataLoader(dev_data, sampler=dev_sampler, batch_size=batch_size) # #### Test # In[58]: tokenized_texts_test = [tokenizer.tokenize(inp) for inp in inp_test] input_ids_test = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts_test] # In[59]: input_ids_test = pad_sequences(input_ids_test, maxlen=MAX_LEN, dtype="long", truncating="post", padding="post") # In[60]: attention_masks_test = [] for seq in input_ids_test: seq_mask = [float(i>0) for i in seq] attention_masks_test.append(seq_mask) # In[61]: test_inputs = torch.tensor(input_ids_test) test_labels = torch.tensor(labels_test) test_masks = torch.tensor(attention_masks_test) # In[62]: test_data = TensorDataset(test_inputs, test_masks, test_labels) #test_sampler = RandomSampler(test_data) test_dataloader = DataLoader(test_data, batch_size=batch_size) # ## Models and Parameters # In[63]: model = XLNetForSequenceClassification.from_pretrained("xlnet-base-cased", num_labels=2) model = nn.DataParallel(model) model.to(device) # In[64]: logging.info("Model Loaded!") # In[65]: param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'gamma', 'beta'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.01}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.0} ] # In[66]: optimizer = AdamW(optimizer_grouped_parameters, lr=lr) # In[67]: logging.info("Optimizerlr: %s\tLR1_ML: %s" %(optimizer.param_groups[0]['lr'], lr)) # ## Helper Functions # In[68]: def flat_accuracy(preds, labels): pred_flat = np.argmax(preds, axis=1).flatten() labels_flat = labels.flatten() labels_flat = labels_flat.cpu().detach().numpy() return np.sum(pred_flat == labels_flat), pred_flat # In[69]: def train(i): model.train() total_loss = 0.0 total_predicted_label = np.array([]) total_actual_label = np.array([]) train_len = 0 f_acc = 0 ## adaptive lr optimizer.param_groups[0]['lr'] *= (0.1)**(1/40.) logging.info("LR: %s\tEpoch: %s\t" %(optimizer.param_groups[0]['lr'], i)) for step, batch in enumerate(train_dataloader): batch = tuple(t.to(device) for t in batch) b_input_ids, b_input_mask, b_labels = batch if b_labels.size(0) == 1: continue optimizer.zero_grad() outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels) pred = outputs[1].detach().cpu().numpy() batch_f_acc, pred_flat = flat_accuracy(pred, b_labels) f_acc += batch_f_acc loss = outputs[0] loss.sum().backward() optimizer.step() labels_flat = b_labels.flatten().cpu().detach().numpy() total_actual_label = np.concatenate((total_actual_label, labels_flat)) total_predicted_label = np.concatenate((total_predicted_label, pred_flat)) # print(total_actual_label.shape, total_predicted_label.shape) total_loss += outputs[0].sum() train_len += b_input_ids.size(0) if step%100 == 0 and step: precision, recall, f1_measure, _ = precision_recall_fscore_support(total_actual_label, total_predicted_label, average='macro') logging.info("Train: %5.1f\tEpoch: %d\tIter: %d\tLoss: %5.5f\tAcc= %5.3f\tPrecision= %5.3f\tRecall= %5.3f\tF1_score= %5.3f" % (train_len*100.0/train_inputs.size(0), i, step, total_loss/train_len, f_acc*100.0/train_len, precision*100., recall*100., f1_measure*100.)) if torch.cuda.device_count() > 1: p = 100 path = save_model_path + '/e_' + str(i) + "_" + str(p) + ".ckpt" torch.save(model.module.state_dict(), path) else: torch.save(model.state_dict(), path) precision, recall, f1_measure, _ = precision_recall_fscore_support(total_actual_label, total_predicted_label, average='macro') logging.info("Train: %5.1f\tEpoch: %d\tIter: %d\tLoss: %5.5f\tAcc= %5.3f\tPrecision= %5.3f\tRecall= %5.3f\tF1_score= %5.3f" % (train_len*100.0/train_inputs.size(0), i, step, total_loss/train_len, f_acc*100.0/train_len, precision*100., recall*100., f1_measure*100.)) return total_loss/train_len # In[70]: def dev(i): model.eval() val_len = 0 total_loss = 0 total_predicted_label = np.array([]) total_actual_label =
np.array([])
numpy.array
# The MIT License (MIT) # # Copyright (c) 2016-2018 <NAME> # # 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. """Classes used to define input motions.""" import enum import re import numpy as np import pyrvt # Gravity in m/sec² from scipy.constants import g as GRAVITY class WaveField(enum.Enum): outcrop = 0 within = 1 incoming_only = 2 class Motion(object): def __init__(self, freqs=None): object.__init__(self) self._freqs = np.array([] if freqs is None else freqs) self._pga = None self._pgv = None @property def freqs(self): return self._freqs @property def angular_freqs(self): return 2 * np.pi * self.freqs @property def pgv(self, centimeters=False): """Peak-ground velocity [m/sec].""" if self._pgv is None: # Compute transfer function -- only over non-zero frequencies mask = ~np.isclose(self.angular_freqs, 0) tf = np.zeros_like(mask, dtype=np.complex) tf[mask] = 1 / (self.angular_freqs[mask] * 1j) if centimeters: self._pgv = GRAVITY * 100 * self.calc_peak(tf) else: self._pgv = GRAVITY * self.calc_peak(tf) return self._pgv @property def pga(self): if self._pga is None: self._pga = self.calc_peak() return self._pga class TimeSeriesMotion(Motion): def __init__(self, filename, description, time_step, accels, fa_length=None): Motion.__init__(self) self._filename = filename self._description = description self._time_step = time_step self._accels = np.asarray(accels) self._calc_fourier_spectrum(fa_length) @property def accels(self): return self._accels @property def filename(self): return self._filename @property def description(self): return self._description @property def time_step(self): return self._time_step @property def times(self): return self._time_step *
np.arange(self._accels.size)
numpy.arange
import os from astropy import table import numpy as np from scipy import interpolate def mass_Noyes1984(bv, bv_err=None): """Noyes et al. 1984, ApJ, 279, 763""" # 0.4 < bv < 1.4 bv = np.atleast_1d(bv) f = np.poly1d([-0.42, 0.28]) fdot = np.polyder(f) logtol = 0.01 logmass = f(bv) mass = 10 ** logmass if bv_err is not None: bv_err = np.atleast_1d(bv_err) bv_var = bv_err ** 2 logmass_var = bv_var * fdot(bv) ** 2 + logtol ** 2 mass_var = logmass_var * (np.log(10) * mass) ** 2 mass_err = np.sqrt(mass_var) return mass, mass_err return mass def teff_Noyes1984(bv, bv_err=None): """Noyes et al. 1984, ApJ, 279, 763""" # 0.4 < bv < 1.4 bv = np.atleast_1d(bv) f = np.poly1d([-0.234, 3.908]) fdot = np.polyder(f) logtol = 0.002 logteff = f(bv) teff = 10 ** logteff if bv_err is not None: bv_err = np.atleast_1d(bv_err) bv_var = bv_err ** 2 logteff_var = bv_var * fdot(bv) ** 2 + logtol ** 2 teff_var = logteff_var * (np.log(10) * teff) ** 2 teff_err = np.sqrt(teff_var) return teff, teff_err return teff def bv_Noyes1984(teff, teff_err=None): """Noyes et al. 1984, ApJ, 279, 763""" # 0.4 < bv < 1.4 teff = np.atleast_1d(teff) logteff = np.log10(teff) f = np.poly1d([-1 / 0.234, 3.908 / 0.234]) fdot = np.polyder(f) bv = f(logteff) if teff_err is not None: teff_err = np.atleast_1d(teff_err) teff_var = teff_err ** 2 logteff_var = teff_var / (np.log(10) * teff) ** 2 bv_var = logteff_var * fdot(logteff) ** 2 bv_err = np.sqrt(bv_var) return bv, bv_err return bv def tau_Noyes1984(bv, bv_err=None): """Noyes et al. 1984, ApJ, 279, 763""" bv = np.atleast_1d(bv) x = 1 - bv mask = x < 0 f = np.poly1d([-5.323, 0.025, -0.166, 1.362]) fdot = np.polyder(f) g = np.poly1d([-0.14, 1.362]) gdot = np.polyder(g) logtau = f(x) logtau[mask] = g(x[mask]) tau = 10 ** logtau if bv_err is not None: bv_err = np.atleast_1d(bv_err) bv_var = bv_err ** 2 x_var = bv_var logtau_var = x_var * fdot(x) ** 2 logtau_var[mask] = (x_var * gdot(x) ** 2)[mask] tau_var = logtau_var * (np.log(10) * tau) ** 2 tau_err = np.sqrt(tau_var) return tau, tau_err return tau def Rossby_Noyes1984(prot, bv, prot_err=None, bv_err=None): """Noyes et al. 1984, ApJ, 279, 763""" if bv_err is not None: tau, tau_err = tau_Noyes1984(bv, bv_err) else: tau = tau_Noyes1984(bv) prot = np.atleast_1d(prot) ro = prot / tau if prot_err is not None and bv_err is not None: prot_err = np.atleast_1d(prot_err) ro_err = np.hypot(prot_err / tau, ro * tau_err / tau) return ro, ro_err return ro def tau_Saar1999(bv, bv_err=None): """Saar & Brandenburg 1999, ApJ, 524, 295""" bv = np.atleast_1d(bv) mask = bv >= 1 f = np.poly1d([-3.1466, 12.540, -20.063, 15.382, -3.3300]) fdot = np.polyder(f) logtau = f(bv) logtau[mask] = np.log10(25.0) tau = 10 ** logtau if bv_err is not None: bv_err = np.atleast_1d(bv_err) bv_var = bv_err ** 2 logtau_var = bv_var * fdot(bv) ** 2 logtau_var[mask] = 0.0 tau_var = logtau_var * (np.log(10) * tau) ** 2 tau_err = np.sqrt(tau_var) return tau, tau_err return tau def Rossby_Saar1999(prot, bv, prot_err=None, bv_err=None): """Saar & Brandenburg 1999, ApJ, 524, 295""" if bv_err is not None: tau, tau_err = tau_Saar1999(bv, bv_err) else: tau = tau_Saar1999(bv) prot = np.atleast_1d(prot) ro = prot / (4 * np.pi * tau) if prot_err is not None and bv_err is not None: prot_err = np.atleast_1d(prot_err) ro_err = np.hypot(prot_err / tau, ro * tau_err / tau) / (4 * np.pi) return ro, ro_err return ro def Gyro_Barneslike( n, a, b, c, bv, n_err=0, a_err=0, b_err=0, c_err=0, bv_err=None, age=None, prot=None, age_err=None, prot_err=None, diff_rot=False, ): bv = np.atleast_1d(bv) if age is not None: logprot = n * np.log(age) + b * np.log(bv - c) + np.log(a) prot = np.exp(logprot) if bv_err is not None and age_err is not None: bv_err = np.atleast_1d(bv_err) age_err = np.atleast_1d(age_err) logage_var = (age_err / age) ** 2 bvc_err = np.hypot(bv_err, c_err) logbvc_var = (bvc_err / (bv - c)) ** 2 n_var = n_err ** 2 b_var = b_err ** 2 loga_var = (a_err / a) ** 2 logprot_var = ( n_var * np.log(age) ** 2 + logage_var * n ** 2 + b_var * np.log(bv - c) ** 2 + logbvc_var * b ** 2 + loga_var ) prot_var = logprot_var * prot ** 2 prot_err = np.sqrt(prot_var) return prot, prot_err return prot elif prot is not None: logage = (np.log(prot) - b * np.log(bv - c) -
np.log(a)
numpy.log
""" Example usage ------------- Generate Newton-Cotes quadrature rules:: >>> distribution = chaospy.Uniform(0, 1) >>> for order in range(5): ... abscissas, weights = chaospy.generate_quadrature( ... order, distribution, rule="newton_cotes") ... print(order, abscissas.round(3), weights.round(3)) 0 [[0.5]] [1.] 1 [[0. 1.]] [0.5 0.5] 2 [[0. 0.5 1. ]] [0.167 0.667 0.167] 3 [[0. 0.333 0.667 1. ]] [0.125 0.375 0.375 0.125] 4 [[0. 0.25 0.5 0.75 1. ]] [0.078 0.356 0.133 0.356 0.078] The first few orders with exponential growth rule:: >>> for order in range(4): # doctest: +NORMALIZE_WHITESPACE ... abscissas, weights = chaospy.generate_quadrature( ... order, distribution, rule="newton_cotes", growth=True) ... print(order, abscissas.round(3), weights.round(3)) 0 [[0.5]] [1.] 1 [[0. 0.5 1. ]] [0.167 0.667 0.167] 2 [[0. 0.25 0.5 0.75 1. ]] [0.078 0.356 0.133 0.356 0.078] 3 [[0. 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1. ]] [ 0.035 0.208 -0.033 0.37 -0.16 0.37 -0.033 0.208 0.035] Applying Smolyak sparse grid on Newton-Cotes:: >>> distribution = chaospy.Iid(chaospy.Uniform(0, 1), 2) >>> abscissas, weights = chaospy.generate_quadrature( ... 2, distribution, rule="newton_cotes", ... growth=True, sparse=True) >>> abscissas.round(3) array([[0. , 0. , 0. , 0.25, 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.75, 1. , 1. , 1. ], [0. , 0.5 , 1. , 0.5 , 0. , 0.25, 0.5 , 0.75, 1. , 0.5 , 0. , 0.5 , 1. ]]) >>> weights.round(3) array([ 0.028, 0.022, 0.028, 0.356, 0.022, 0.356, -0.622, 0.356, 0.022, 0.356, 0.028, 0.022, 0.028]) """ from __future__ import division try: from functools import lru_cache except ImportError: # pragma: no cover from functools32 import lru_cache import numpy from scipy import integrate from .hypercube import hypercube_quadrature def newton_cotes(order, domain=(0, 1), growth=False, segments=1): """ Generate the abscissas and weights in Newton-Cotes quadrature. Newton-Cotes quadrature, are a group of formulas for numerical integration based on evaluating the integrand at equally spaced points. Args: order (int, numpy.ndarray:): Quadrature order. domain (:func:`chaospy.Distribution`, ;class:`numpy.ndarray`): Either distribution or bounding of interval to integrate over. growth (bool): If True sets the growth rule for the quadrature rule to only include orders that enhances nested samples. segments (int): Split intervals into N subintervals and create a patched quadrature based on the segmented quadrature. Can not be lower than `order`. If 0 is provided, default to square root of `order`. Nested samples only exist when the number of segments are fixed. Returns: (numpy.ndarray, numpy.ndarray): abscissas: The quadrature points for where to evaluate the model function with ``abscissas.shape == (len(dist), N)`` where ``N`` is the number of samples. weights: The quadrature weights with ``weights.shape == (N,)``. Examples: >>> abscissas, weights = chaospy.quadrature.newton_cotes(4) >>> abscissas.round(4) array([[0. , 0.25, 0.5 , 0.75, 1. ]]) >>> weights.round(4) array([0.0778, 0.3556, 0.1333, 0.3556, 0.0778]) >>> abscissas, weights = chaospy.quadrature.newton_cotes(4, segments=2) >>> abscissas.round(4) array([[0. , 0.25, 0.5 , 0.75, 1. ]]) >>> weights.round(4) array([0.0833, 0.3333, 0.1667, 0.3333, 0.0833]) """ order = numpy.asarray(order) order = numpy.where(growth, numpy.where(order, 2**order, 0), order) return hypercube_quadrature( _newton_cotes, order=order, domain=domain, segments=segments, ) @lru_cache(None) def _newton_cotes(order): """Backend for Newton-Cotes quadrature rule.""" if order == 0: return numpy.full((1, 1), 0.5),
numpy.ones(1)
numpy.ones
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from .pruner import pruner_registry, Pruner from heapq import heappush, heappop from ..utils import logger import re @pruner_registry class GradientSensitivityPruner(Pruner): def __init__(self, model, local_config, global_config): super(GradientSensitivityPruner, self).__init__(model, local_config, global_config) self.parameters = local_config.parameters self.importance = {} self.elementwise_prune = False if local_config.parameters is not None else True def on_epoch_begin(self, epoch): if epoch == self.start_epoch: # register hook for FWK model to get actual input tensor self.model.register_forward_pre_hook() if self.elementwise_prune: self.sparsity = self.update_sparsity(epoch) logger.debug("Start pruning in epoch {} with sparsity {}.". format(str(epoch), str(self.sparsity))) self.is_last_epoch = epoch == self.end_epoch if epoch >= self.start_epoch and epoch <= self.end_epoch: self.compute_mask() def on_batch_begin(self, batch_id): if self.elementwise_prune: for weight_name in self.weights: if weight_name in self.masks: new_weight = self.masks[weight_name].reshape(\ np.array(self.model.get_weight(weight_name).shape)) * \ np.array(self.model.get_weight(weight_name)) self.model.update_weights(weight_name, new_weight) def on_epoch_end(self): if self.elementwise_prune: if self.is_last_epoch: for weight_name in self.weights: if weight_name in self.masks: logger.info( "Set {} sparsity with mask {} {} {}.".format( weight_name, str( self.masks[weight_name].size), str( self.masks[weight_name].sum()), str( 1 - self.masks[weight_name].sum() / self.masks[weight_name].size))) new_weight = self.masks[weight_name].reshape(\ np.array(self.model.get_weight(weight_name).shape)) * \ np.array(self.model.get_weight(weight_name)) self.model.update_weights(weight_name, new_weight) else: for weight_name_raw in self.weights: for weight_name in self.parse_weight_name(weight_name_raw): self.prune_weight(self.model, self.importance, weight_name, self.parameters) if self.is_last_epoch: # remove hooks for FWK model to ensure model saving self.model.remove_hooks() def parse_weight_name(self, weight_name_pattern): # check if asterisk is used to match bert layer indexes if '*' not in weight_name_pattern: yield weight_name_pattern else: weight_all_names = self.model.get_all_weight_names() importance_inputs = self.parameters['importance_inputs'] for single_weight_name in weight_all_names: index_group = re.match( weight_name_pattern.replace('*', '(\d+)'), single_weight_name) if index_group is not None: index = index_group.group(1) if self.parameters.get(index) is None: self.parameters['index'] = int(index) # dynamic change importance_inputs with matched index self.parameters['importance_inputs'] = [ x.replace('*', index) for x in self.parameters['importance_inputs']] yield single_weight_name # change importance_inputs back self.parameters['importance_inputs'] = importance_inputs def on_batch_end(self): if self.elementwise_prune: for weight_name in self.weights: self.update_importance_elementwise(self.model, self.importance, weight_name) else: for weight_name_raw in self.weights: for weight_name in self.parse_weight_name(weight_name_raw): if self.parameters['importance_metric'] == 'abs_gradient': self.update_importance_abs(self.model, self.importance, weight_name, self.parameters) elif self.parameters['importance_metric'] == 'weighted_gradient': self.update_importance_weighted(self.model, self.importance, weight_name, self.parameters) def compute_mask(self): """compute masks according to absolute values""" for weight_name in self.weights: if weight_name in self.importance.keys(): tensor = self.importance[weight_name] if len(tensor.shape) in self.tensor_dims: reduced_tensor = self.pattern.reduce(tensor) if self.method == "per_channel": tensor_flat = reduced_tensor.reshape(list(tensor.shape)[:-2], -1) tensor_flat.sort(axis=-1) threshold = tensor_flat[..., int(self.sparsity * tensor_flat.shape[-1])] threshold = np.expand_dims(np.expand_dims(threshold, -1), -1) threshold = np.repeat(threshold, reduced_tensor.shape[-1], axis=-1) threshold = np.repeat(threshold, reduced_tensor.shape[-2], axis=-2) else: tensor_flat = sorted(np.abs(reduced_tensor.flatten())) threshold = float(tensor_flat[int(len(tensor_flat) * self.sparsity)]) reduced_mask = threshold <
np.abs(reduced_tensor)
numpy.abs
#https://blog.csdn.net/orangefly0214/article/details/81387077 import MultiTemplate from MultiTemplate import TaskTemplate import numpy as np # https://blog.csdn.net/u013812710/article/details/72886491 # https://blog.csdn.net/ismr_m/article/details/53100896 #https://blog.csdn.net/bcfdsagbfcisbg/article/details/78134172 import kubernetes import os import json import influxdb import time import re from sklearn.externals import joblib from sklearn.ensemble import RandomForestRegressor # # from random_job3 import save_job_change_layout # from random_job3 import save_job_change_resource import yaml def load_config(config_file): # # json串是一个字符串 # f = open('product.json', encoding='utf-8') # res = f.read() # product_dic = json.loads(res) # 把json串,变成python的数据类型,只能转换json串内容 # print(product_dic) # print(product_dic['iphone']) # # t = json.load(f) # # print(t) #传一个文件对象,它会帮你直接读json文件,并转换成python数据 # # print(t['iphone']) # f.close() f = open(config_file,encoding='utf-8') res = f.read() config_content = json.loads(res) f.close() return config_content def save_config(config,filename): config_content = {} for key,value in config.items(): # if key != 'job' and key != 'ns': config_content[key] = value # task_content['task_id'] = tasks['task_id'] fw = open(filename, 'w', encoding='utf-8') # ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似\uXXXX的显示数据,设置成False后,就能正常显示 dic_json = json.dumps(config_content, ensure_ascii=False, indent=4) # 字典转成json,字典转成字符串 fw.write(dic_json) fw.close() def deletehelp(delete_job_name,v1): try: v1.delete_namespace(delete_job_name) except Exception as eeeeee: print(eeeeee) command0 = "kubectl get namespace " + delete_job_name + " -o json > /tfdata/tfcnn/deletebuf/" + delete_job_name + ".json" os.system(command0) tmp = load_config("/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json") tmp["spec"]["finalizers"] = [] save_config(tmp, "/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json") try: command1 = 'curl -k -H "Content-Type: application/json" -X PUT --data-binary @/tfdata/tfcnn/deletebuf/' + delete_job_name + '.json http://1172.16.31.10:8081/api/v1/namespaces/'+delete_job_name+'/finalize' os.system(command1) except Exception as helpe: print(helpe) commandopen = 'kubectl proxy --port=8081' os.system(commandopen) os.system(command1) def deletehelp2(delete_job_name,v1): v1.delete_namespace(delete_job_name) command0 = "kubectl get namespace " + delete_job_name + " -o json > /tfdata/tfcnn/deletebuf/" + delete_job_name + ".json" os.system(command0) tmp = load_config("/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json") tmp["spec"]["finalizers"] = [] save_config(tmp, "/tfdata/tfcnn/deletebuf/" + delete_job_name + ".json") try: command1 = 'curl -k -H "Content-Type: application/json" -X PUT --data-binary @/tfdata/tfcnn/deletebuf/' + delete_job_name + '.json http://127.0.0.1:8081/api/v1/namespaces/' + delete_job_name + '/finalize' os.system(command1) except Exception as helpe: print(helpe) commandopen = 'kubectl proxy --port=8081' os.system(commandopen) os.system(command1) def check_path(name): train_dir = os.path.join('/tfdata/k8snfs/', name) print(train_dir) if not os.path.exists(train_dir): os.makedirs(train_dir) return train_dir def save_job_change_layout(job_name,ps_n,worker_n): save_job_path = '/tfdata/k8snfs/%s/%s.json' % (job_name, job_name) job_config = load_config(save_job_path) # 'ps_replicas': job.ps_replicas,'worker_replicas': job.worker_replicas job_config['ps_replicas'] = ps_n job_config['worker_replicas'] = worker_n save_config(job_config, save_job_path) def save_job_change_resource(job_name,cpu_allocate,mem_allocate): save_res_path = '/tfdata/k8snfs/%s/%s_res.json' % (job_name, job_name) job_res_config = load_config(save_res_path) # save_res_path = '/tfdata/k8snfs/%s/%s_res.json' % (job.name, job.name) # save_config(job_config, save_job_path) job_res_config['cpu_source'] = cpu_allocate job_res_config['mem_source'] = mem_allocate save_config(job_res_config, save_res_path) def check_ns(name): kubernetes.config.load_kube_config() v1 = kubernetes.client.CoreV1Api() # v1.create_namespace() exist_ns = v1.list_namespace() exist_ns_name = [] for i in exist_ns.items: exist_ns_name.append(i.metadata.name) if name in exist_ns_name: return True else: return False class clusternode(): def __init__(self,name,total_cpu,total_memory,compute_label,disk_label): self.total_cpu = total_cpu self.total_memory = total_memory self.compute_label = compute_label self.disk_label = disk_label self.name = name class SubTask(): def __init__(self,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag, dbhost='192.168.128.10',mod=-1,retry=0, update_min_step=400, step_update=200, update_start=0.25, update_end=0.75, update_delay=2.0): self.template_id = template_id self.ps_replicas = ps_replicas self.worker_replicas = worker_replicas self.training_step = training_step self.interval = interval self.batch_size = batch_size self.task_id = task_id self.mod = mod self.tag = tag self.rtimes = rtimes self.dbhost = dbhost self.retry = retry kubernetes.config.load_kube_config() self.v1 = kubernetes.client.CoreV1Api() self.v1.list_namespace() self.update_min_step = update_min_step self.step_update = step_update self.update_start = update_start self.update_end = update_end self.update_delay = update_delay self.influx_client = influxdb.InfluxDBClient(host='192.168.128.10',port=8086,username='admin',password='<PASSWORD>',database="NODEMESSAGE") self.node_list = ['k8s-master','k8s-worker0','k8s-worker2','k8s-worker1','k8s-worker3','k8s-worker4', 'k8s-worker5','k8s-worker6','k8s-worker7','k8s-worker8', 'k8s-worker10','k8s-worker11','k8s-worker12','k8s-worker13','k8s-worker14', 'k8s-worker15','k8s-worker16','k8s-worker17','k8s-worker19'] self.node_cpu = {} self.node_compute = {} self.ps_rank = [18,10,2] self.worker_rank = [18,10,4] self.node_compute['k8s-master'] = 1 self.node_compute['k8s-worker0'] = 1 self.node_compute['k8s-worker2'] = 1 self.node_compute['k8s-worker1'] = 1 self.node_compute['k8s-worker3'] = 0 self.node_compute['k8s-worker4'] = 0 self.node_compute['k8s-worker5'] = 1 self.node_compute['k8s-worker6'] = 0 self.node_compute['k8s-worker7'] = 0 self.node_compute['k8s-worker8'] = 0 # self.node_compute['k8s-worker9'] = 0 self.node_compute['k8s-worker10'] = 0 self.node_compute['k8s-worker11'] = 1 self.node_compute['k8s-worker12'] = 1 self.node_compute['k8s-worker13'] = 1 self.node_compute['k8s-worker14'] = 0 self.node_compute['k8s-worker15'] = 1 self.node_compute['k8s-worker16'] = 0 self.node_compute['k8s-worker17'] = 1 # self.node_compute['k8s-worker18'] = 0 self.node_compute['k8s-worker19'] = 0 # self.node_compute['k8s-worker20'] = 0 self.cpu_allocate = 2048 self.memory_allocate = 2048 self.node_cmtype = {} self.node_cmtype['k8s-master'] = 2 self.node_cmtype['k8s-worker0'] = 1 self.node_cmtype['k8s-worker2'] = 1 self.node_cmtype['k8s-worker1'] = 2 self.node_cmtype['k8s-worker3'] = 1 self.node_cmtype['k8s-worker4'] = 2 self.node_cmtype['k8s-worker5'] = 1 self.node_cmtype['k8s-worker6'] = 1 self.node_cmtype['k8s-worker7'] = 1 self.node_cmtype['k8s-worker8'] = 1 # self.node_cmtype['k8s-worker9'] = 1 self.node_cmtype['k8s-worker10'] = 1 self.node_cmtype['k8s-worker11'] = 1 self.node_cmtype['k8s-worker12'] = 1 self.node_cmtype['k8s-worker13'] = 1 self.node_cmtype['k8s-worker14'] = 1 self.node_cmtype['k8s-worker15'] = 1 self.node_cmtype['k8s-worker16'] = 1 self.node_cmtype['k8s-worker17'] = 1 # self.node_cmtype['k8s-worker18'] = 1 self.node_cmtype['k8s-worker19'] = 1 # self.node_cmtype['k8s-worker20'] = 1 self.node_disk = {} self.node_disk['k8s-master'] = 1 self.node_disk['k8s-worker0'] = 1 self.node_disk['k8s-worker2'] = 1 self.node_disk['k8s-worker1'] = 1 self.node_disk['k8s-worker3'] = 0 self.node_disk['k8s-worker4'] = 0 self.node_disk['k8s-worker5'] = 0 self.node_disk['k8s-worker6'] = 0 self.node_disk['k8s-worker7'] = 0 self.node_disk['k8s-worker8'] = 0 # self.node_disk['k8s-worker9'] = 0 self.node_disk['k8s-worker10'] = 0 self.node_disk['k8s-worker11'] = 1 self.node_disk['k8s-worker12'] = 1 self.node_disk['k8s-worker13'] = 1 self.node_disk['k8s-worker14'] = 1 self.node_disk['k8s-worker15'] = 1 self.node_disk['k8s-worker16'] = 0 self.node_disk['k8s-worker17'] = 1 # self.node_disk['k8s-worker18'] = 0 self.node_disk['k8s-worker19'] = 0 # self.node_disk['k8s-worker20'] = 0 self.deadline = 3600 self.starttime = 0 # self.node_cpu['k8s-master'] = 64000 - 2400 # self.node_cpu['k8s-worker0'] = 24000 - 250 # self.node_cpu['k8s-worker2'] = 24000 - 650 # self.node_cpu['k8s-worker1'] = 16000 - 420 # self.node_cpu['k8s-worker3'] = 24000 - 1200 # self.node_cpu['k8s-worker4'] = 24000 - 360 # self.node_cpu['k8s-worker5'] = 32000 - 17000 # self.node_cpu['k8s-worker6'] = 24000 - 160 # self.node_cpu['k8s-worker7'] = 24000 - 160 # self.node_cpu['k8s-worker8'] = 16000 - 160 # self.node_cpu['k8s-worker9'] = 16000 - 160 # self.node_cpu['k8s-worker10'] = 16000 - 160 # self.node_cpu['k8s-worker11'] = 24000 - 200 # self.node_cpu['k8s-worker12'] = 24000 - 170 # self.node_cpu['k8s-worker13'] = 24000 - 210 # self.node_cpu['k8s-worker14'] = 16000 - 210 # self.node_cpu['k8s-worker15'] = 32000 - 210 # self.node_cpu['k8s-worker16'] = 24000 - 210 # self.node_cpu['k8s-worker17'] = 16000 - 210 # # node_cpu['k8s-worker18'] = 16000 - 150 # self.node_cpu['k8s-worker19'] = 32000 - 210 # node_cpu['k8s-worker20'] = 24000 - 150 # self.node_cpu['k8s-master'] = 64000 - 8000 # self.node_cpu['k8s-worker0'] = 24000 - 400 # self.node_cpu['k8s-worker2'] = 24000 - 400 # self.node_cpu['k8s-worker1'] = 16000 - 520 # self.node_cpu['k8s-worker3'] = 24000 - 150 # self.node_cpu['k8s-worker4'] = 24000 - 150 # self.node_cpu['k8s-worker5'] = 24000 - 150 # self.node_cpu['k8s-worker6'] = 16000 - 150 # self.node_cpu['k8s-worker7'] = 16000 - 150 # self.node_cpu['k8s-worker8'] = 16000 - 150 # self.node_cpu['k8s-worker9'] = 16000 - 150 # self.node_cpu['k8s-worker10'] = 16000 - 150 # self.node_cpu['k8s-worker11'] = 24000 - 300 # self.node_cpu['k8s-worker12'] = 16000 - 150 # self.node_cpu['k8s-worker13'] = 16000 - 150 # self.node_cpu['k8s-worker14'] = 16000 - 150 # self.node_cpu['k8s-worker15'] = 16000 - 150 # self.node_cpu['k8s-worker16'] = 16000 - 150 # self.node_cpu['k8s-worker17'] = 24000 - 150 # self.node_cpu['k8s-worker18'] = 16000 - 150 # self.node_cpu['k8s-worker19'] = 32000 - 150 # self.node_cpu['k8s-worker20'] = 24000 - 150 self.node_cpu['k8s-master'] = 64000 - 2500 self.node_cpu['k8s-worker0'] = 24000 - 240 self.node_cpu['k8s-worker2'] = 24000 - 650 self.node_cpu['k8s-worker1'] = 16000 - 300 self.node_cpu['k8s-worker3'] = 24000 - 360 self.node_cpu['k8s-worker4'] = 24000 - 360 self.node_cpu['k8s-worker5'] = 32000 - 320 self.node_cpu['k8s-worker6'] = 24000 - 240 self.node_cpu['k8s-worker7'] = 24000 - 240 self.node_cpu['k8s-worker8'] = 24000 - 240 # self.node_cpu['k8s-worker9'] = 16000 - 240 self.node_cpu['k8s-worker10'] = 24000 - 200 self.node_cpu['k8s-worker11'] = 24000 - 200 self.node_cpu['k8s-worker12'] = 24000 - 240 self.node_cpu['k8s-worker13'] = 24000 - 240 self.node_cpu['k8s-worker14'] = 24000 - 240 self.node_cpu['k8s-worker15'] = 32000 - 220 self.node_cpu['k8s-worker16'] = 24000 - 240 self.node_cpu['k8s-worker17'] = 24000 - 210 # node_cpu['k8s-worker18'] = 16000 - 150 self.node_cpu['k8s-worker19'] = 32000 - 240 self.ps_node_list = ['k8s-worker1','k8s-worker0','k8s-worker10','k8s-worker3'] self.node_memory = {} self.node_memory['k8s-master'] = float(251 * 1024 - 10000) self.node_memory['k8s-worker0'] = float(94 * 1024 - 1400) self.node_memory['k8s-worker2'] = float(94 * 1024 - 3200) self.node_memory['k8s-worker1'] = float(125 * 1024 - 1600) self.node_memory['k8s-worker3'] = float(94 * 1024 - 1200) self.node_memory['k8s-worker4'] = float(188 * 1024 - 1200) self.node_memory['k8s-worker5'] = float(125 * 1024 - 1800) self.node_memory['k8s-worker6'] = float(94 * 1024 - 1200) self.node_memory['k8s-worker7'] = float(94 * 1024 - 1400) self.node_memory['k8s-worker8'] = float(94 * 1024 - 1250) # self.node_memory['k8s-worker9'] = float(62 * 1024 - 1600) self.node_memory['k8s-worker10'] = float(94 * 1024 - 1200) self.node_memory['k8s-worker11'] = float(94 * 1024 - 1400) # node_memory['k8s-worker12'] = float(62 * 1024 - 2000) # node_memory['k8s-worker13'] = float(62 * 1024 - 2000) self.node_memory['k8s-worker12'] = float(94 * 1024 - 1500) self.node_memory['k8s-worker13'] = float(94 * 1024 - 1400) self.node_memory['k8s-worker14'] = float(94 * 1024 - 1800) # node_memory['k8s-worker15'] = float(62 * 1024 - 2000) self.node_memory['k8s-worker15'] = float(125 * 1024 - 1800) # node_memory['k8s-worker16'] = float(62 * 1024 - 2000) self.node_memory['k8s-worker16'] = float(94 * 1024 - 1800) # node_memory['k8s-worker17'] = float(94 * 1024 - 2000) self.node_memory['k8s-worker17'] = float(94 * 1024 - 1400) # node_memory['k8s-worker18'] = float(62 * 1024 - 2000) self.node_memory['k8s-worker19'] = float(125 * 1024 - 1400) # self.node_memory['k8s-master'] = float(251 * 1024 - 9400) # self.node_memory['k8s-worker0'] = float(94 * 1024 - 1000) # self.node_memory['k8s-worker2'] = float(94 * 1024 - 3200) # self.node_memory['k8s-worker1'] = float(125 * 1024 - 1500) # self.node_memory['k8s-worker3'] = float(94 * 1024 - 1100) # self.node_memory['k8s-worker4'] = float(188 * 1024 - 1100) # self.node_memory['k8s-worker5'] = float(125 * 1024 - 4200) # self.node_memory['k8s-worker6'] = float(94 * 1024 - 2000) # self.node_memory['k8s-worker7'] = float(94 * 1024 - 1250) # self.node_memory['k8s-worker8'] = float(62 * 1024 - 1250) # self.node_memory['k8s-worker9'] = float(62 * 1024 - 1250) # self.node_memory['k8s-worker10'] = float(62 * 1024 - 1200) # self.node_memory['k8s-worker11'] = float(94 * 1024 - 1200) # # node_memory['k8s-worker12'] = float(62 * 1024 - 2000) # # node_memory['k8s-worker13'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker12'] = float(94 * 1024 - 2000) # self.node_memory['k8s-worker13'] = float(94 * 1024 - 2000) # self.node_memory['k8s-worker14'] = float(62 * 1024 - 2000) # # node_memory['k8s-worker15'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker15'] = float(125 * 1024 - 2000) # # node_memory['k8s-worker16'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker16'] = float(94 * 1024 - 2000) # # node_memory['k8s-worker17'] = float(94 * 1024 - 2000) # self.node_memory['k8s-worker17'] = float(62 * 1024 - 2000) # # node_memory['k8s-worker18'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker19'] = float(125 * 1024 - 2000) # self.lasttime = # self.node_cpu['k8s-master'] = 64000 - 8000 # self.node_cpu['k8s-worker0'] = 24000 - 400 # self.node_cpu['k8s-worker2'] = 24000 - 400 # self.node_cpu['k8s-worker1'] = 16000 - 520 # self.node_cpu['k8s-worker3'] = 24000 - 150 # self.node_cpu['k8s-worker4'] = 24000 - 150 # self.node_cpu['k8s-worker5'] = 24000 - 150 # self.node_cpu['k8s-worker6'] = 16000 - 150 # self.node_cpu['k8s-worker7'] = 16000 - 150 # self.node_cpu['k8s-worker8'] = 16000 - 150 # self.node_cpu['k8s-worker9'] = 16000 - 150 # self.node_cpu['k8s-worker10'] = 16000 - 150 # self.node_cpu['k8s-worker11'] = 24000 - 300 # self.node_cpu['k8s-worker12'] = 16000 - 150 # self.node_cpu['k8s-worker13'] = 16000 - 150 # self.node_cpu['k8s-worker14'] = 16000 - 150 # self.node_cpu['k8s-worker15'] = 16000 - 150 # self.node_cpu['k8s-worker16'] = 16000 - 150 # self.node_cpu['k8s-worker17'] = 24000 - 150 # self.node_cpu['k8s-worker18'] = 16000 - 150 # self.node_cpu['k8s-worker19'] = 32000 - 150 # self.node_cpu['k8s-worker20'] = 24000 - 150 # self.node_cpu['k8s-master'] = 32000 - 8000 # self.node_cpu['k8s-worker0'] = 24000 - 400 # self.node_cpu['k8s-worker2'] = 24000 - 400 # self.node_cpu['k8s-worker1'] = 16000 - 520 # self.node_cpu['k8s-worker3'] = 24000 - 150 # self.node_cpu['k8s-worker4'] = 16000 - 150 # self.node_cpu['k8s-worker5'] = 24000 - 150 self.total_cpu = 0 self.ps_cpu_base = 0.0 self.ps_mem_base = 0.0 self.ws_cpu_base = 0.0 self.ws_mem_base = 0.0 self.total_mem = 0.0 # self.node_memory = {} # self.node_memory['k8s-master'] = float(251*1024 - 32000) # self.node_memory['k8s-worker0'] = float(94*1024 - 4000) # self.node_memory['k8s-worker2'] = float(94*1024 - 3000) # self.node_memory['k8s-worker1'] = float(125*1024 - 4500) # self.node_memory['k8s-worker3'] = float(94 * 1024 - 2200) # self.node_memory['k8s-worker4'] = float(125 * 1024 - 2200) # self.node_memory['k8s-worker5'] = float(94 * 1024 - 2200) # self.node_memory['k8s-master'] = float(251 * 1024 - 32000) # self.node_memory['k8s-worker0'] = float(94 * 1024 - 4000) # self.node_memory['k8s-worker2'] = float(94 * 1024 - 3000) # self.node_memory['k8sw-orker1'] = float(125 * 1024 - 4500) # self.node_memory['k8s-worker3'] = float(94 * 1024 - 2200) # self.node_memory['k8s-worker4'] = float(188 * 1024 - 2200) # self.node_memory['k8s-worker5'] = float(94 * 1024 - 2200) # self.node_memory['k8s-worker6'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker7'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker8'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker9'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker10'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker11'] = float(94 * 1024 - 2200) # self.node_memory['k8s-worker12'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker13'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker14'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker15'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker16'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker17'] = float(94 * 1024 - 2000) # self.node_memory['k8s-worker18'] = float(62 * 1024 - 2000) # self.node_memory['k8s-worker19'] = float(125 * 1024 - 2000) # self.node_memory['k8s-worker20'] = float(94 * 1024 - 2000) node_keys = self.node_cpu.keys() # print(node_keys) # mem_keys = self.node_memory.keys() # print(mem_keys) for key in node_keys: self.total_cpu = self.total_cpu + self.node_cpu[key] self.total_mem = self.total_mem + self.node_memory[key] self.args = ['--training_step='+str(self.training_step),'--batch_size='+str(self.batch_size),'--interval='+str(self.interval),'--task_id='+str(self.task_id),'--rtimes='+str(self.rtimes),"--tag="+self.tag, '--retry=' + str(self.retry), '--dbhost=' + self.dbhost, '--update_min_step=' + str(self.update_min_step), '--step_update=' + str(self.step_update), '--update_start=' + str(self.update_start), '--update_end=' + str(self.update_end), '--update_delay=' + str(self.update_delay) ] self.measure = "VGG %d" % self.task_id def get_node_list(self): node_list = [i.metadata.name for i in self.v1.list_node().items] return node_list def set_deadline(self,deadline,start_time): self.deadline = deadline self.starttime = start_time def set_mod(self,new_mod): self.mod = new_mod def get_mod(self): return self.mod def set_resource(self,cpu_source,mem_source): self.cpu_allocate = cpu_source self.memory_allocate = mem_source # # def apply_tf(self,cpu_source,mem_source): # self.cpu_allocate = cpu_source # self.memory_allocate = mem_source def update_step(self): step_update_influx = influxdb.InfluxDBClient(host=self.dbhost, port=8086, username='admin', password='<PASSWORD>', database="PREDICT") pre_list = self.measure.split(" ") # measure_s = pre_list[0] + 'S' + pre_list[-1] measure_up = pre_list[0] + 'U' + pre_list[-1] step_items = [ { 'measurement': measure_up, 'tags': { 'task': self.task_id, 'runtimes': self.rtimes, 'retry': self.retry }, 'fields': { 'ps': self.ps_replicas, 'worker':self.worker_replicas, 'training_step': self.training_step } } ] # print(step_to_train) step_update_influx.write_points(step_items, time_precision="ms", database="PREDICT") def schedule_base(self,mode=0): if mode == 0: result = self.influx_client.query( "select * from " + "NODEMESSAGE" + " group by nodes order by desc limit 8") node_list = self.get_node_list() result_keys = result.keys() nodes = [i[-1]['nodes'] for i in result_keys] if 'k8s-worker9' in nodes: nodes.remove('k8s-worker9') # node_mg = [list(result[i]) for i in result_keys] node_mg = [] for i in result_keys: if 'worker9' not in i[-1]['nodes']: node_mg.append(list(result[i])) # print("load node mess sucess!") print("node len is %d" % len(node_mg)) cpu_base = {} memory_base = {} point_base = {} point_base_list = [] # memory_base_list = [] # cpu_base_list = [] node_index = {} # total_cpu = 0 # total_mem = 0 total_cpu_use = 0.0 total_mem_use = 0.0 for i in range(len(node_mg)): cpu_base[nodes[i]] = 0 memory_base[nodes[i]] = 0 point_base[nodes[i]] = 0.0 for j in range(len(node_mg[0])): cpu_base[nodes[i]] += node_mg[i][j]['cpu'] memory_base[nodes[i]] += node_mg[i][j]['memory'] cpu_base[nodes[i]] = (cpu_base[nodes[i]] / len(node_mg[0])) / self.node_cpu[nodes[i]] memory_base[nodes[i]] = (memory_base[nodes[i]] / len(node_mg[0])) / self.node_memory[nodes[i]] total_cpu_use += (cpu_base[nodes[i]] * self.node_cpu[nodes[i]]) total_mem_use += (memory_base[nodes[i]] * self.node_memory[nodes[i]]) tmp = cpu_base[nodes[i]] * 0.72 + memory_base[nodes[i]] * 0.28 # tmp2 = cpu_base[nodes[i]]*self.node_cpu[nodes[i]]* 0.72/self.total_cpu + memory_base[nodes[i]] * self.node_memory[nodes[i]]* 0.28/self.total_mem point_base[nodes[i]] = tmp point_base_list.append(tmp) total_cpu_use = total_cpu_use / self.total_cpu total_mem_use = total_mem_use / self.total_mem list.sort(point_base_list) for key in nodes: # command = 'kubectl label nodes ' + key + ' woksch-' # os.system(command) # command2 = 'kubectl label nodes ' + key + ' wokpro-' # os.system(command2) nod_prori = point_base_list.index(point_base[key]) node_index[key] = nod_prori # priori = ' wokpro=%d' % nod_prori # command3 = 'kubectl label nodes ' + key + priori # os.system(command3) # if cpu_base[key] <= 0.56 and memory_base[key] <= 0.6: # command = 'kubectl label nodes ' + key + ' woksch=true' # os.system(command) # else: # command = 'kubectl label nodes ' + key + ' woksch=false' # os.system(command) return node_index, cpu_base, memory_base, total_cpu_use, total_mem_use else: offset = int(mode) cpu_base_total = [] memory_base_total = [] node_index_total = [] total_cpu_use_total = [] total_mem_use_total = [] for k in range(offset): pianyi = k*8 result = self.influx_client.query( "select * from " + "NODEMESSAGE" + " group by nodes order by desc limit 8 offset "+str(pianyi)) result_keys = result.keys() # nodes = [i[-1]['nodes'] for i in result_keys] # node_mg = [list(result[i]) for i in result_keys] nodes = [i[-1]['nodes'] for i in result_keys] if 'k8s-worker9' in nodes: nodes.remove('k8s-worker9') # node_mg = [list(result[i]) for i in result_keys] node_mg = [] for i in result_keys: if 'worker9' not in i[-1]['nodes']: node_mg.append(list(result[i])) # print("load node mess sucess!") print("node len is %d" % len(node_mg)) cpu_base = {} memory_base = {} point_base = {} point_base_list = [] node_index = {} total_cpu_use = 0.0 total_mem_use = 0.0 for i in range(len(node_mg)): cpu_base[nodes[i]] = 0 memory_base[nodes[i]] = 0 point_base[nodes[i]] = 0.0 for j in range(len(node_mg[0])): cpu_base[nodes[i]] += node_mg[i][j]['cpu'] memory_base[nodes[i]] += node_mg[i][j]['memory'] cpu_base[nodes[i]] = (cpu_base[nodes[i]] / len(node_mg[0])) / self.node_cpu[nodes[i]] memory_base[nodes[i]] = (memory_base[nodes[i]] / len(node_mg[0])) / self.node_memory[nodes[i]] total_cpu_use += (cpu_base[nodes[i]] * self.node_cpu[nodes[i]]) total_mem_use += (memory_base[nodes[i]] * self.node_memory[nodes[i]]) tmp = cpu_base[nodes[i]] * 0.78 + memory_base[nodes[i]] * 0.22 point_base[nodes[i]] = tmp point_base_list.append(tmp) total_cpu_use = total_cpu_use / self.total_cpu total_mem_use = total_mem_use / self.total_mem list.sort(point_base_list) for key in nodes: nod_prori = point_base_list.index(point_base[key]) node_index[key] = nod_prori # return node_index, cpu_base, memory_base, total_cpu_use, total_mem_use node_index_total.append(node_index) cpu_base_total.append(cpu_base) memory_base_total.append(memory_base) total_cpu_use_total.append(total_cpu_use) total_mem_use_total.append(total_mem_use) return node_index_total,cpu_base_total,memory_base_total,total_cpu_use_total,total_mem_use_total def write_retry(self,mode): write_retry_influx = influxdb.InfluxDBClient(host=self.dbhost, port=8086, username='admin', password='<PASSWORD>', database="PREDICT") pre_list = self.measure.split(" ") # measure_s = pre_list[0] + 'S' + pre_list[-1] measure_write = pre_list[0] + 'W' + pre_list[-1] step_items = [ { 'measurement': measure_write, 'tags': { 'task': self.task_id, 'runtimes': self.rtimes, 'retry': self.retry }, 'fields': { 'modulate': int(mode) } } ] # print(step_to_train) write_retry_influx.write_points(step_items, time_precision="ms", database="PREDICT") def schedule_label(self): try: result = self.influx_client.query( "select * from " + "NODEMESSAGE" + " group by nodes order by desc limit 8") except Exception as ee: time.sleep(5) result = self.influx_client.query( "select * from " + "NODEMESSAGE" + " group by nodes order by desc limit 8") node_list = self.get_node_list() # print(node_list) result_keys = result.keys() nodes = [i[-1]['nodes'] for i in result_keys] if 'k8s-worker9' in nodes: nodes.remove('k8s-worker9') # print(nodes) # node_mg = [list(result[i]) for i in result_keys] node_mg = [] for i in result_keys: if 'worker9' not in i[-1]['nodes']: node_mg.append(list(result[i])) # print("load node mess sucess!") print("node len is %d" % len(node_mg)) cpu_base = {} memory_base = {} pcpu_base = {} pmemory_base = {} point_base = {} point_base_list = [] point_base1 = {} point_base_list1 = [] worker_nodes = nodes[:] # print(worker_nodes) # for pk in self.ps_node_list: # worker_nodes.remove(pk) wpoint_base = {} wpoint_base_list = [] wpoint_base1 = {} wpoint_base_list1 = [] ppoint_base = {} ppoint_base_list = [] ppoint_base1 = {} ppoint_base_list1 = [] # memory_base_list = [] # cpu_base_list = [] # node_index = {} # total_cpu = 0 # total_mem = 0 # total_cpu_use = 0.0 # total_mem_use = 0.0 cpu_tmp_base = [] mem_tmp_base = [] cpu_wok_base = [] mem_wok_base = [] for i in range(len(node_mg)): point_base[nodes[i]] = 0.0 cpu_base[nodes[i]] = 0 memory_base[nodes[i]] = 0 for j in range(len(node_mg[0])): cpu_base[nodes[i]] += node_mg[i][j]['cpu'] memory_base[nodes[i]] += node_mg[i][j]['memory'] cpu_base[nodes[i]] = (cpu_base[nodes[i]] / len(node_mg[0])) / self.node_cpu[nodes[i]] memory_base[nodes[i]] = (memory_base[nodes[i]] / len(node_mg[0])) / self.node_memory[nodes[i]] cpu_wok_base.append(cpu_base[nodes[i]]) mem_wok_base.append(memory_base[nodes[i]]) # if nodes[i] in self.ps_node_list: # cpu_base[nodes[i]] = node_mg[i][0]['cpu'] # memory_base[nodes[i]] = node_mg[i][0]['memory'] # for j in range(len(node_mg[0])): # if cpu_base[nodes[i]] < node_mg[i][j]['cpu']: # cpu_base[nodes[i]] = node_mg[i][j]['cpu'] # if memory_base[nodes[i]] < node_mg[i][j]['memory']: # memory_base[nodes[i]] = node_mg[i][j]['memory'] # cpu_base[nodes[i]] = cpu_base[nodes[i]]/self.node_cpu[nodes[i]] # memory_base[nodes[i]] = memory_base[nodes[i]]/self.node_memory[nodes[i]] # cpu_tmp_base.append(cpu_base[nodes[i]]) # mem_tmp_base.append(memory_base[nodes[i]]) # else: # cpu_base[nodes[i]] = 0 # memory_base[nodes[i]] = 0 # for j in range(len(node_mg[0])): # cpu_base[nodes[i]] += node_mg[i][j]['cpu'] # memory_base[nodes[i]] += node_mg[i][j]['memory'] # cpu_base[nodes[i]] = (cpu_base[nodes[i]] / len(node_mg[0])) / self.node_cpu[nodes[i]] # memory_base[nodes[i]] = (memory_base[nodes[i]] / len(node_mg[0])) / self.node_memory[nodes[i]] # # cpu_wok_base.append(cpu_base[nodes[i]]) # mem_wok_base.append(memory_base[nodes[i]]) # pcpu_base[nodes[i]] = node_mg[i][0]['cpu'] # pmemory_base[nodes[i]] = node_mg[i][0]['memory'] # total_cpu_use += (cpu_base[nodes[i]]*self.node_cpu[nodes[i]]) # total_mem_use += (memory_base[nodes[i]]*self.node_memory[nodes[i]]) tmp = cpu_base[nodes[i]] * 0.78 + memory_base[nodes[i]] * 0.22 tmp2 = cpu_base[nodes[i]]*self.node_cpu[nodes[i]]* 0.72/self.total_cpu + memory_base[nodes[i]] * self.node_memory[nodes[i]]* 0.28/self.total_mem tmp3 = tmp*0.6+tmp2*0.4 point_base[nodes[i]] = tmp3 point_base_list.append(tmp3) point_base1[nodes[i]] = tmp point_base_list1.append(tmp) # if nodes[i] in self.ps_node_list: # ppoint_base[nodes[i]] = point_base[nodes[i]] # ppoint_base1[nodes[i]] = tmp # ppoint_base_list.append(point_base[nodes[i]]) # ppoint_base_list1.append(tmp) # else: # wpoint_base[nodes[i]] = point_base[nodes[i]] # wpoint_base1[nodes[i]] = tmp # wpoint_base_list.append(point_base[nodes[i]]) # wpoint_base_list1.append(tmp) # total_cpu_use = total_cpu_use / self.total_cpu # total_mem_use = total_mem_use /self.total_mem list.sort(point_base_list) list.sort(point_base_list1) # list.sort(wpoint_base_list) # list.sort(wpoint_base_list1) # list.sort(ppoint_base_list) # list.sort(ppoint_base_list1) # list.sort(cpu_tmp_base) # list.sort(mem_tmp_base) list.sort(cpu_wok_base) list.sort(mem_wok_base) # self.ps_cpu_base = (cpu_tmp_base[0]+cpu_tmp_base[1])/2 # self.ps_mem_base = (mem_tmp_base[0]+mem_tmp_base[1])/2 self.ws_cpu_base = (cpu_wok_base[0]+cpu_wok_base[1]+cpu_wok_base[2])/3 self.ws_mem_base = (mem_wok_base[0]+mem_wok_base[1]+mem_wok_base[2])/3 # for key in self.ps_node_list: # nod_prori = ppoint_base_list.index(ppoint_base[key]) # try: # command = 'kubectl label nodes ' + key + ' pspro-' # os.system(command) # priori = ' pspro=%d' % nod_prori # command3 = 'kubectl label nodes ' + key + priori # os.system(command3) # except Exception as ep0: # priori = ' pspro=%d' % nod_prori # command3 = 'kubectl label nodes ' + key + priori # os.system(command3) # master_index = wpoint_base_list.index(wpoint_base['k8s-master']) # k8s2_index = wpoint_base_list.index(wpoint_base['k8s-worker2']) master_index = point_base_list.index(point_base['k8s-master']) k8s2_index = point_base_list.index(point_base['k8s-worker2']) limit_max = max(master_index,k8s2_index) limit_min = min(master_index,k8s2_index) # if master_index < 6: # for key in worker_nodes: # # command = 'kubectl label nodes ' + key + ' woksch-' # # os.system(command) # # command = 'kubectl label nodes ' + key + ' pssch-' # # os.system(command) # command2 = 'kubectl label nodes ' + key + ' wokpro-' # os.system(command2) # # nod_prori = wpoint_base_list.index(wpoint_base[key]) # nod_prori = point_base_list.index(point_base[key]) # if 'master' in key: # nod_prori = 6 # if 'k8s-worker2' in key: # nod_prori = 5 # elif nod_prori > limit_min and nod_prori < limit_max: # nod_prori = max(nod_prori - 1,0) # elif nod_prori > limit_max and nod_prori <= 5: # nod_prori = max(nod_prori-2,0) # # # node_index[key] = nod_prori # priori = ' wokpro=%d' % nod_prori # command3 = 'kubectl label nodes ' + key + priori # os.system(command3) # # # master_index = 6 if master_index < 6: for key in worker_nodes: # command = 'kubectl label nodes ' + key + ' woksch-' # os.system(command) # command = 'kubectl label nodes ' + key + ' pssch-' # os.system(command) command2 = 'kubectl label nodes ' + key + ' wokpro-' os.system(command2) # nod_prori = wpoint_base_list.index(wpoint_base[key]) nod_prori = point_base_list.index(point_base[key]) if 'master' in key: nod_prori = 6 # if 'k8s-worker2' in key: # nod_prori = 5 elif nod_prori > master_index and nod_prori <= 6: if 'worker2' not in key: nod_prori = max(nod_prori - 1,0) # node_index[key] = nod_prori priori = ' wokpro=%d' % nod_prori command3 = 'kubectl label nodes ' + key + priori os.system(command3) # elif k8s2_index < 5: # for key in worker_nodes: # # command = 'kubectl label nodes ' + key + ' woksch-' # # os.system(command) # # command = 'kubectl label nodes ' + key + ' pssch-' # # os.system(command) # command2 = 'kubectl label nodes ' + key + ' wokpro-' # os.system(command2) # # nod_prori = wpoint_base_list.index(wpoint_base[key]) # nod_prori = point_base_list.index(point_base[key]) # if 'worker2' in key: # nod_prori = 5 # # if 'k8s-worker2' in key: # # nod_prori = 5 # elif nod_prori > k8s2_index and nod_prori <= 5: # if 'master' not in key: # nod_prori = max(nod_prori - 1,0) # # # node_index[key] = nod_prori # priori = ' wokpro=%d' % nod_prori # command3 = 'kubectl label nodes ' + key + priori # os.system(command3) else: for key in worker_nodes: # command = 'kubectl label nodes ' + key + ' woksch-' # os.system(command) # command = 'kubectl label nodes ' + key + ' pssch-' # os.system(command) command2 = 'kubectl label nodes ' + key + ' wokpro-' os.system(command2) # nod_prori = wpoint_base_list.index(wpoint_base[key]) nod_prori = point_base_list.index(point_base[key]) # if 'master' in key: # nod_prori = 6 # elif nod_prori > master_index and nod_prori <= 6: # nod_prori = nod_prori - 1 # node_index[key] = nod_prori priori = ' wokpro=%d' % nod_prori command3 = 'kubectl label nodes ' + key + priori os.system(command3) # master_index = 6 return point_base.copy(),cpu_base.copy(),memory_base.copy(),point_base_list[:] # if cpu_base[key] <= 0.4 and memory_base[key] <= 0.5: # command = 'kubectl label nodes ' + key + ' woksch=true' # os.system(command) # else: # command = 'kubectl label nodes ' + key + ' woksch=false' # os.system(command) # return node_index,cpu_base,memory_base,total_cpu_use,total_mem_use class VGGTask(SubTask): def __init__(self,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag,channel1,channel2,channel3,channel4,channel5,num_layer1,num_layer2,num_layer3,num_layer4,num_layer5,dbhost='192.168.128.10',mod=-1,retry=0, update_min_step=400, step_update=200, update_start=0.25, update_end=0.8, update_delay=2.0): # def __init__(self,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag, # dbhost='192.168.128.10',mod=-1,retry=0, update_min_step=400, step_update=200, update_start=0.25, # update_end=0.75, update_delay=2.0) SubTask.__init__(self,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag,dbhost,mod,retry,update_min_step,step_update,update_start,update_end,update_delay) # SubTask.__init__(self,template_id,ps_replicas,worker_replicas,training_step,batch_size,interval,task_id,rtimes,tag) self.channel1 = channel1 self.channel2 = channel2 self.channel3 = channel3 self.channel4 = channel4 self.channel5 = channel5 self.num_layer1 = num_layer1 self.num_layer2 = num_layer2 self.num_layer3 = num_layer3 self.num_layer4 = num_layer4 self.num_layer5 = num_layer5 self.num_layers = num_layer1+num_layer2+num_layer3+num_layer4+num_layer5+3 self.template = TaskTemplate.VGG # self.v1 = v1 self.name = 'vgg-'+str(self.task_id)+'-'+str(self.rtimes) self.measure = "VGG %d" % self.task_id self.mod = mod def set_mod(self,new_mod): self.mod = new_mod def get_mod(self): return self.mod def get_node_list(self): node_list = [i.metadata.name for i in self.v1.list_node().items] return node_list def make_args(self): self.args.append('--channel1='+str(self.channel1)) self.args.append('--channel2='+str(self.channel2)) self.args.append('--channel3='+str(self.channel3)) self.args.append('--channel4='+str(self.channel4)) self.args.append('--channel5='+str(self.channel5)) self.args.append('--num_layer1='+str(self.num_layer1)) self.args.append('--num_layer2='+str(self.num_layer2)) self.args.append('--num_layer3='+str(self.num_layer3)) self.args.append('--num_layer4='+str(self.num_layer4)) self.args.append('--num_layer5='+str(self.num_layer5)) self.args.append('--num_layers='+str(self.num_layers)) def get_remain(self, mode=0): try: filepath = '/tfdata/k8snfs/' + self.name + '/worker0/' file_list = os.listdir(filepath) except Exception as ee: # atmp = 0 # step_influx = influxdb.InfluxDBClient(host=self.dbhost, port=8086, username='admin', password='<PASSWORD>', # database="PREDICT") # pre_list = self.measure.split(" ") # measure_s = pre_list[0] + 'S' + pre_list[-1] # measure_t = pre_list[0] + 'T' + pre_list[-1] # result = step_influx.query("select training_step from " + measure_t + " order by desc limit 1") # key = result.keys() # result_inter = result[key[0]] # result_items = list(result_inter) # trains_step = result_items[0]['training_step'] # total_step = int(trains_step) # remain = total_step - atmp + 2 # if remain <= 0: # remain = 0 remain = self.training_step total_step = self.training_step atmp = 0 return remain, total_step, atmp step_influx = influxdb.InfluxDBClient(host=self.dbhost, port=8086, username='admin', password='<PASSWORD>', database="PREDICT") pre_list = self.measure.split(" ") measure_s = pre_list[0] + 'S' + pre_list[-1] measure_t = pre_list[0] + 'T' + pre_list[-1] result = step_influx.query("select training_step from " + measure_t + " order by desc limit 1") key = result.keys() result_inter = result[key[0]] result_items = list(result_inter) trains_step = result_items[0]['training_step'] total_step = int(trains_step) atmp = 0 if mode == 0: step = [] for i in file_list: if 'model.ckpt' in i and 'meta' in i: tmp = re.findall(r'\d+', i) step.append(int(tmp[0])) # tiqv.append(i) if not step: atmp = 0 else: atmp = max(step) else: res = step_influx.query("select * from " + measure_s + " group by nodes,retry order by desc limit 1") res_key = list(res.keys()) # keys = res.keys() if res_key: retry_time = [int(b['retry']) for a, b in res_key] retry_time = set(retry_time) retry = max(retry_time) # node_list = [b['nodes'] for a, b in keys] node_list = [b['nodes'] for a, b in res_key] dic_msg = {} for node in node_list: for i in range(len(res_key)): _, no = res_key[i] if no['nodes'] == node and int(no['retry']) == retry: dic_msg[node] = list(res[res_key[i]]) step_list = [] node_key = list(dic_msg.keys()) for node in node_key: step_list.append(int(dic_msg[node][0]['step'])) if not step_list: atmp = 0 else: atmp = min(step_list) else: atmp = 0 # for node in node_list: # for i in range(len(keys)): # _, no = keys[i] # if no['nodes'] == node: # dic_msg[node] = list(res[keys[i]]) remain = total_step - atmp + 2 if remain <= 0: remain = 0 return remain,total_step,atmp def predict_min(self,rfr): job_path = '/tfdata/k8snfs/%s/%s_res.json' % (self.name,self.name) job_config = load_config(job_path) # "deadline": 14843, # "start_time": 1584816589.613, # "cpu_source": 6046, # "mem_source": 19225, # "cpu_high": 8991, # "memory_base": 8706, # "batch_res": 785, # "flops_res": 127834653, # "params_res": 18273610, # "step_base": 69, batch = job_config['batch_res'] flops = job_config['flops_res'] params = job_config['params_res'] cpu_high = job_config['cpu_high'] mem_base = job_config['memory_base'] cpu_alpha = self.cpu_allocate / cpu_high mem_alpha = self.memory_allocate / mem_base # bfp = list(zip(list(res['batch']),list(res['flops']),list(res['params']),list(res['cpu_alpha']),list(res['mem_alpha']))) data =
np.array([batch, flops, params,cpu_alpha,mem_alpha])
numpy.array
# test_arnoldi_sampling.py import unittest import numpy as np import chaospy as cp from pystatreduce.stochastic_collocation import StochasticCollocation from pystatreduce.quantity_of_interest import QuantityOfInterest from pystatreduce.stochastic_arnoldi.arnoldi_sample import ArnoldiSampling import pystatreduce.examples as examples class ArnoldiSamplingTest(unittest.TestCase): def test_modified_GramSchmidt_fullRank(self): # Generate a random set of vectors and use modGramSchmidt to # orthogonalize them systemsize = 10 # Initialize ArnoldiSampling object alpha = 1.0 num_sample = 4 arnoldi = ArnoldiSampling(alpha, num_sample) # Create arrays for modified_GramSchmidt Z = np.random.rand(systemsize, num_sample) H = np.zeros([num_sample, num_sample-1]) # Populate Z for i in range(-1, num_sample-1): arnoldi.modified_GramSchmidt(i, H, Z) # Check that the vectors are unit normal self.assertAlmostEqual(np.linalg.norm(Z[:,i+1]), 1, places=14) # Check that the vectors are orthogonal for i in range(0, num_sample): for j in range(i+1, num_sample): self.assertAlmostEqual(np.dot(Z[:,i], Z[:,j]), 0, places=14) def test_modified_GramSchmidt_RankDeficient(self): # Generate a random set of vectors, make one of them a linear combination # of the others, and use modGramSchmidt to orthogonalize them systemsize = 10 # Initialize ArnoldiSampling object alpha = 1.0 num_sample = 4 arnoldi = ArnoldiSampling(alpha, num_sample) # Create arrays for modified_GramSchmidt Z = np.random.rand(systemsize, num_sample) Z[:,num_sample-1] = Z[:,0:num_sample-1].dot(np.random.rand(num_sample-1)) H = np.zeros([num_sample, num_sample-1]) for i in range(-1, num_sample-2): arnoldi.modified_GramSchmidt(i, H, Z) # Check that the vectors are unit normal self.assertAlmostEqual(np.linalg.norm(Z[:,i+1]), 1, places=14) # calling now should produce lin_depend flag lin_depend = arnoldi.modified_GramSchmidt(num_sample-2, H, Z) self.assertTrue(lin_depend) def test_arnoldiSample_complete(self): # Compute all of the eigenmodes of an isoprobabilistic Hadamard # quadratic system using Arnoldi sampling and verify against the exact # computation systemsize = 16 eigen_decayrate = 2.0 # Create Hadmard Quadratic object QoI = examples.HadamardQuadratic(systemsize, eigen_decayrate) # Initialize chaospy distribution std_dev = np.random.rand(QoI.systemsize) sqrt_Sigma =
np.diag(std_dev)
numpy.diag
from __future__ import division, print_function, absolute_import import numpy as np import numpy.testing as nt import warnings from dipy.utils.six.moves import xrange from dipy.core.sphere import (Sphere, HemiSphere, unique_edges, unique_sets, faces_from_sphere_vertices, HemiSphere, disperse_charges, _get_forces, unit_octahedron, unit_icosahedron, hemi_icosahedron) from dipy.core.subdivide_octahedron import create_unit_sphere from dipy.core.geometry import cart2sphere, sphere2cart, vector_norm from numpy.testing.decorators import skipif try: from scipy.spatial import Delaunay except ImportError: needs_delaunay = skipif(True, "Need scipy.spatial.Delaunay") else: needs_delaunay = skipif(False) verts = unit_octahedron.vertices edges = unit_octahedron.edges oct_faces = unit_octahedron.faces r, theta, phi = cart2sphere(*verts.T) def test_sphere_construct_args(): nt.assert_raises(ValueError, Sphere) nt.assert_raises(ValueError, Sphere, x=1, theta=1) nt.assert_raises(ValueError, Sphere, xyz=1, theta=1) nt.assert_raises(ValueError, Sphere, xyz=1, theta=1, phi=1) def test_sphere_edges_faces(): nt.assert_raises(ValueError, Sphere, xyz=1, edges=1, faces=None) Sphere(xyz=[0, 0, 1], faces=[0, 0, 0]) Sphere(xyz=[[0, 0, 1], [1, 0, 0], [0, 1, 0]], edges=[[0, 1], [1, 2], [2, 0]], faces=[0, 1, 2]) def test_sphere_not_unit(): with warnings.catch_warnings(): warnings.simplefilter('error') nt.assert_raises(UserWarning, Sphere, xyz=[0, 0, 1.5]) def test_bad_edges_faces(): nt.assert_raises(ValueError, Sphere, xyz=[0, 0, 1.5], edges=[[1, 2]]) def test_sphere_construct(): s0 = Sphere(xyz=verts) s1 = Sphere(theta=theta, phi=phi) s2 = Sphere(*verts.T) nt.assert_array_almost_equal(s0.theta, s1.theta) nt.assert_array_almost_equal(s0.theta, s2.theta) nt.assert_array_almost_equal(s0.theta, theta) nt.assert_array_almost_equal(s0.phi, s1.phi) nt.assert_array_almost_equal(s0.phi, s2.phi) nt.assert_array_almost_equal(s0.phi, phi) def array_to_set(a): return set(frozenset(i) for i in a) def test_unique_edges(): faces = np.array([[0, 1, 2], [1, 2, 0]]) e = array_to_set([[1, 2], [0, 1], [0, 2]]) u = unique_edges(faces) nt.assert_equal(e, array_to_set(u)) u, m = unique_edges(faces, return_mapping=True) nt.assert_equal(e, array_to_set(u)) edges = [[[0, 1], [1, 2], [2, 0]], [[1, 2], [2, 0], [0, 1]]] nt.assert_equal(np.sort(u[m], -1), np.sort(edges, -1)) def test_unique_sets(): sets = np.array([[0, 1, 2], [1, 2, 0], [0, 2, 1], [1, 2, 3]]) e = array_to_set([[0, 1, 2], [1, 2, 3]]) # Run without inverse u = unique_sets(sets) nt.assert_equal(len(u), len(e)) nt.assert_equal(array_to_set(u), e) # Run with inverse u, m = unique_sets(sets, return_inverse=True) nt.assert_equal(len(u), len(e)) nt.assert_equal(array_to_set(u), e) nt.assert_equal(np.sort(u[m], -1), np.sort(sets, -1)) @needs_delaunay def test_faces_from_sphere_vertices(): faces = faces_from_sphere_vertices(verts) faces = array_to_set(faces) expected = array_to_set(oct_faces) nt.assert_equal(faces, expected) def test_sphere_attrs(): s = Sphere(xyz=verts) nt.assert_array_almost_equal(s.vertices, verts) nt.assert_array_almost_equal(s.x, verts[:, 0]) nt.assert_array_almost_equal(s.y, verts[:, 1]) nt.assert_array_almost_equal(s.z, verts[:, 2]) @needs_delaunay def test_edges_faces(): s = Sphere(xyz=verts) faces = oct_faces nt.assert_equal(array_to_set(s.faces), array_to_set(faces)) nt.assert_equal(array_to_set(s.edges), array_to_set(edges)) s = Sphere(xyz=verts, faces=[[0, 1, 2]]) nt.assert_equal(array_to_set(s.faces), array_to_set([[0, 1, 2]])) nt.assert_equal(array_to_set(s.edges), array_to_set([[0, 1], [1, 2], [0, 2]])) s = Sphere(xyz=verts, faces=[[0, 1, 2]], edges=[[0, 1]]) nt.assert_equal(array_to_set(s.faces), array_to_set([[0, 1, 2]])) nt.assert_equal(array_to_set(s.edges), array_to_set([[0, 1]])) @needs_delaunay def test_sphere_subdivide(): sphere1 = unit_octahedron.subdivide(4) sphere2 = Sphere(xyz=sphere1.vertices) nt.assert_equal(sphere1.faces.shape, sphere2.faces.shape) nt.assert_equal(array_to_set(sphere1.faces), array_to_set(sphere2.faces)) sphere1 = unit_icosahedron.subdivide(4) sphere2 = Sphere(xyz=sphere1.vertices) nt.assert_equal(sphere1.faces.shape, sphere2.faces.shape) nt.assert_equal(array_to_set(sphere1.faces), array_to_set(sphere2.faces)) # It might be good to also test the vertices somehow if we can think of a # good test for them. def test_sphere_find_closest(): sphere1 = unit_octahedron.subdivide(4) for ii in range(sphere1.vertices.shape[0]): nt.assert_equal(sphere1.find_closest(sphere1.vertices[ii]), ii) def test_hemisphere_find_closest(): hemisphere1 = hemi_icosahedron.subdivide(4) for ii in range(hemisphere1.vertices.shape[0]): nt.assert_equal(hemisphere1.find_closest(hemisphere1.vertices[ii]), ii) nt.assert_equal(hemisphere1.find_closest(-hemisphere1.vertices[ii]), ii) nt.assert_equal(hemisphere1.find_closest(hemisphere1.vertices[ii] * 2), ii) @needs_delaunay def test_hemisphere_subdivide(): def flip(vertices): x, y, z = vertices.T f = (z < 0) | ((z == 0) & (y < 0)) | ((z == 0) & (y == 0) & (x < 0)) return 1 - 2*f[:, None] decimals = 6 # Test HemiSphere.subdivide # Create a hemisphere by dividing a hemi-icosahedron hemi1 = HemiSphere.from_sphere(unit_icosahedron).subdivide(4) vertices1 = np.round(hemi1.vertices, decimals) vertices1 *= flip(vertices1) order = np.lexsort(vertices1.T) vertices1 = vertices1[order] # Create a hemisphere from a subdivided sphere sphere = unit_icosahedron.subdivide(4) hemi2 = HemiSphere.from_sphere(sphere) vertices2 = np.round(hemi2.vertices, decimals) vertices2 *= flip(vertices2) order = np.lexsort(vertices2.T) vertices2 = vertices2[order] # The two hemispheres should have the same vertices up to their order nt.assert_array_equal(vertices1, vertices2) # Create a hemisphere from vertices hemi3 = HemiSphere(xyz=hemi1.vertices) nt.assert_array_equal(hemi1.faces, hemi3.faces) nt.assert_array_equal(hemi1.edges, hemi3.edges) def test_hemisphere_constructor(): s0 = HemiSphere(xyz=verts) s1 = HemiSphere(theta=theta, phi=phi) s2 = HemiSphere(*verts.T) uniq_verts = verts[::2].T rU, thetaU, phiU = cart2sphere(*uniq_verts) nt.assert_array_almost_equal(s0.theta, s1.theta) nt.assert_array_almost_equal(s0.theta, s2.theta)
nt.assert_array_almost_equal(s0.theta, thetaU)
numpy.testing.assert_array_almost_equal
from constrainedmf.nmf.models import NMF import numpy as np import torch from constrainedmf.utils.plotting import toy_plot torch.manual_seed(1234) np.random.seed(1234) DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def gaussian(x, mu, sig): return np.exp(-
np.power(x - mu, 2.0)
numpy.power
import datetime as dat import numpy as np import os import pandas as pd import scipy as sp import scipy.stats as scat import sys print(os.getcwd()) c_dir = os.path.join(os.getcwd(), 'model_sources/migliore_etal_2018/MiglioreEtAl2018PLOSCompBiol2018') res_dir = os.path.join(os.getcwd(), 'results/Tuning Calcium Model/RXD') os.chdir(c_dir) from mpl_toolkits.mplot3d import Axes3D from itertools import cycle from neuron import h from os.path import join from scipy import integrate as spint from scipy import optimize as spopt import matplotlib.pyplot as plt import bokeh.io as bkio import bokeh.layouts as blay import bokeh.models as bmod import bokeh.plotting as bplt import various_scripts.frequency_analysis as fan from bokeh.palettes import Category20 as palette from bokeh.palettes import Category20b as paletteb from selenium import webdriver colrs = palette[20] + paletteb[20] import plot_results as plt_res # # module_path = os.getcwd() # os.path.abspath(os.path.join('../..')) # if module_path not in sys.path: # sys.path.append(module_path) import migliore_python as mig_py mu = u'\u03BC' delta = u'\u0394' tau = u'\u03C4' # chrome_path = r'/usr/local/bin/chromedriver' # my_opts = webdriver.chrome.options.Options() # my_opts.add_argument('start-maximized') # my_opts.add_argument('disable-infobars') # my_opts.add_argument('--disable-extensions') # my_opts.add_argument('window-size=1200,1000') # my_opts.add_argument('--headless') def single_exponential(x_data, tau): x_data = np.array(x_data) return np.exp(-x_data / tau) def single_exponential_rise(x_data, tau, asym, tshift): return asym * (1.0 - np.exp(-(x_data - tshift) / tau)) def estimate_decay_constant(t_vals, f_vals, change_tol=0.001): max_i = np.argmax(f_vals) plus_i = range(max_i, f_vals.size) pos_i = np.where(f_vals > 0) targ_i = np.intersect1d(plus_i, pos_i) min_val = 0.999 * np.min(f_vals[targ_i]) dec_t = t_vals[targ_i] - t_vals[max_i] dec_norm = (f_vals[targ_i] - min_val) / (f_vals[max_i] - min_val) opt_params, pcov = sp.optimize.curve_fit(single_exponential, dec_t, dec_norm) return opt_params def run_recharge_simulation(param_dict, sim_dur=180000): t_path = join(os.getcwd(), 'morphologies/mpg141209_A_idA.asc') t_steps = np.arange(0, sim_dur, 100) cell = mig_py.MyCell(t_path, True, param_dict) # Calreticulin Parameter Values total_car = param_dict['car_total'] KD_car = param_dict['car_KD'] car_kon = param_dict['car_kon'] car_koff = KD_car * car_kon carca_init = total_car * 0.001 / (KD_car + 0.01) car_init = total_car - carca_init ap_secs = [cell.apical[i] for i in range(10)] t_secs = cell.somatic + ap_secs h.CVode().active(True) h.finitialize(-65.0) for sec in t_secs: cell.ca[cell.er].nodes(sec).concentration = 0.001 cell.carca.nodes(sec).concentration = carca_init cell.car.nodes(sec).concentration = car_init h.CVode().re_init() # Create Numpy Arrays For Storing Data ca_cyt_arr = np.zeros((t_steps.shape[0], 3)) ca_er_arr = np.zeros((t_steps.shape[0], 3)) carca_arr = np.zeros(t_steps.shape) cbdhca_arr = np.zeros(t_steps.shape) cbdlca_arr = np.zeros(t_steps.shape) ogb1ca_arr = np.zeros(t_steps.shape) # dyeca_arr = np.zeros(t_steps.shape) # # e1_arr = np.zeros(t_steps.shape) # e1_2ca_arr = np.zeros(t_steps.shape) # e1_2ca_p_arr = np.zeros(t_steps.shape) # e2_2ca_p_arr = np.zeros(t_steps.shape) # e2_p_arr = np.zeros(t_steps.shape) # e2_arr = np.zeros(t_steps.shape) # # c1_arr = np.zeros(t_steps.shape) # c2_arr = np.zeros(t_steps.shape) # c3_arr = np.zeros(t_steps.shape) # c4_arr = np.zeros(t_steps.shape) # o5_arr = np.zeros(t_steps.shape) # o6_arr = np.zeros(t_steps.shape) for t_i, t_step in enumerate(t_steps): h.continuerun(t_step) ca_cyt_arr[t_i, 0] = cell.ca[cell.cyt].nodes(cell.somatic[0])(0.5)[0].concentration ca_cyt_arr[t_i, 1] = cell.ca[cell.cyt].nodes(cell.apical[0])(0.5)[0].concentration ca_cyt_arr[t_i, 2] = cell.ca[cell.cyt].nodes(cell.apical[9])(0.5)[0].concentration ca_er_arr[t_i, 0] = cell.ca[cell.er].nodes(cell.somatic[0])(0.5)[0].concentration ca_er_arr[t_i, 1] = cell.ca[cell.er].nodes(cell.apical[0])(0.5)[0].concentration ca_er_arr[t_i, 2] = cell.ca[cell.er].nodes(cell.apical[9])(0.5)[0].concentration cbdhca_arr[t_i] = cell.cbdhca[cell.cyt].nodes(cell.somatic[0])(0.5)[0].concentration cbdlca_arr[t_i] = cell.cbdlca[cell.cyt].nodes(cell.somatic[0])(0.5)[0].concentration ogb1ca_arr[t_i] = cell.dyeca[cell.cyt].nodes(cell.somatic[0])(0.5)[0].concentration carca_arr[t_i] = cell.carca[cell.er].nodes(cell.somatic[0])(0.5)[0].concentration # dyeca_arr[t_i] = dyeca.nodes(soma)(0.5)[0].concentration # # e1_arr[t_i] = e1_serca.nodes(soma)(0.5)[0].concentration # e1_2ca_arr[t_i] = e1_2ca_serca.nodes(soma)(0.5)[0].concentration # e1_2ca_p_arr[t_i] = e1_2ca_p_serca.nodes(soma)(0.5)[0].concentration # e2_2ca_p_arr[t_i] = e2_2ca_p_serca.nodes(soma)(0.5)[0].concentration # e2_p_arr[t_i] = e2_p_serca.nodes(soma)(0.5)[0].concentration # e2_arr[t_i] = e2_serca.nodes(soma)(0.5)[0].concentration # # c1_arr[t_i] = c1_ip3r.nodes(soma)(0.5)[0].concentration # c2_arr[t_i] = c2_ip3r.nodes(soma)(0.5)[0].concentration # c3_arr[t_i] = c3_ip3r.nodes(soma)(0.5)[0].concentration # c4_arr[t_i] = c4_ip3r.nodes(soma)(0.5)[0].concentration # o5_arr[t_i] = o5_ip3r.nodes(soma)(0.5)[0].concentration # o6_arr[t_i] = o6_ip3r.nodes(soma)(0.5)[0].concentration print('Final SERCA States') # e1 = cell.e1_serca.nodes(cell.somatic[0])(0.5)[0].concentration # e1_2ca = cell.e1_2ca_serca.nodes(cell.somatic[0])(0.5)[0].concentration # e1_2ca_p = cell.e1_2ca_p_serca.nodes(cell.somatic[0])(0.5)[0].concentration # e2_2ca_p = cell.e2_2ca_p_serca.nodes(cell.somatic[0])(0.5)[0].concentration # e2_p = cell.e2_p_serca.nodes(cell.somatic[0])(0.5)[0].concentration # e2 = cell.e2_serca.nodes(cell.somatic[0])(0.5)[0].concentration # total = e1 + e1_2ca + e1_2ca_p + e2_2ca_p + e2_p + e2 # # print('e1: {}'.format(e1/total)) # print('e1-2ca: {}'.format(e1_2ca / total)) # print('e1-2ca-p: {}'.format(e1_2ca_p / total)) # print('e2-2ca-p: {}'.format(e2_2ca_p / total)) # print('e2-p: {}'.format(e2_p / total)) # print('e2: {}'.format(e2 / total)) result_d = {'t': t_steps, 'sec names': ['Soma', 'Proximal Apical Trunk', 'Distal Apical Trunk'], 'cyt ca': ca_cyt_arr, 'er ca': ca_er_arr, 'carca': carca_arr, 'cbdhca': cbdhca_arr, 'cbdlca': cbdlca_arr, 'ogb1ca': ogb1ca_arr, } return result_d def plot_recharge(result_d): t_steps = result_d['t'] / 1000.0 ret_figs = [] cyt_ca_fig = bplt.figure(title='Cytosol Calcium vs Time') ret_figs.append(cyt_ca_fig) cyt_ca_fig.xaxis.axis_label = 'time (seconds)' cyt_ca_fig.yaxis.axis_label = 'concentration ({}M)'.format(mu) er_ca_fig = bplt.figure(title='Endoplasmic Reticulum Calcium vs Time') ret_figs.append(er_ca_fig) er_ca_fig.xaxis.axis_label = 'time (seconds)' er_ca_fig.yaxis.axis_label = 'concentration ({}M)'.format(mu) carca_fig = bplt.figure(title='Bound Calreticulin vs Time') ret_figs.append(carca_fig) carca_fig.xaxis.axis_label = 'time (seconds)' carca_fig.yaxis.axis_label = 'concentration ({}M)'.format(mu) carca_fig.line(t_steps, 1000.0*result_d['carca'][:], line_width=3, color=colrs[0], legend='Somatic ER') cbd_fig = bplt.figure(title='Bound Calbindin-D28k vs Time') ret_figs.append(cbd_fig) cbd_fig.xaxis.axis_label = 'time (seconds)' cbd_fig.yaxis.axis_label = 'concentration ({}M)'.format(mu) cbd_fig.line(t_steps, 1000.0 * result_d['cbdhca'][:], line_width=3, color=colrs[0], legend='High') cbd_fig.line(t_steps, 1000.0 * result_d['cbdlca'][:], line_width=3, color=colrs[2], legend='Low') ogb1_fig = bplt.figure(title='Bound OGB-1 vs Time') ret_figs.append(ogb1_fig) ogb1_fig.xaxis.axis_label = 'time (seconds)' ogb1_fig.yaxis.axis_label = 'concentration ({}M)'.format(mu) ogb1_fig.line(t_steps, 1000.0 * result_d['ogb1ca'][:], line_width=3, color=colrs[0], legend='High') # for l_i, loc_name in enumerate(result_d['sec names']): # if 'soma' in loc_name: # cyt_ca_fig.line(t_steps, 1000.0*result_d['cyt ca'][:, l_i], line_width=4, color='black', legend='model result') # er_ca_fig.line(t_steps, 1000.0*result_d['er ca'][:, l_i], line_width=4, color='black', legend='model result') for l_i, loc_name in enumerate(result_d['sec names']): cyt_ca_fig.line(t_steps, 1000.0*result_d['cyt ca'][:, l_i], line_width=4, color=colrs[l_i], legend=loc_name) er_ca_fig.line(t_steps, 1000.0*result_d['er ca'][:, l_i], line_width=4, color=colrs[l_i], legend=loc_name) cyt_ca_fig.legend.location = 'bottom_right' return ret_figs def run_current_injection(rxd_sim, param_dict={}, sim_dur=500, c_int=[50, 100], c_amp=1): """ :param cell_type: type of neuron cell to test\n :param conf_obj: configuration dictionary which holds all of the parameters for the neuron cell to be tested\n :param swc_path: location of swc_file, required for CA1PyramidalCell class\n :param sim_dur: simulation duration (msec)\n :param c_int: interval of time current injection pulse is active\n :param c_amp: amplitude of current injection\n :return: t_array, v_array, i_array: t_array\n time array = numpy array of simulation time steps\n v_array = numpy array potentials for soma[0](0.5) of cell\n i_array = numpy array of values for the injected current\n """ t_path = join(os.getcwd(), 'morphologies/mpg141209_A_idA.asc') cell = mig_py.MyCell(t_path, rxd_sim, param_dict) t_curr = h.IClamp(cell.somatic[0](0.5)) t_curr.delay = c_int[0] t_curr.amp = c_amp t_curr.dur = c_int[1] - c_int[0] # apical[9][0.5] distance to soma[0][1.0] = 105.53 um # Record Values i_rec = h.Vector().record(t_curr._ref_i) t = h.Vector().record(h._ref_t) soma_v = h.Vector().record(cell.somatic[0](0.5)._ref_v) apic_v = h.Vector().record(cell.apical[9](0.5)._ref_v) axon_v = h.Vector().record(cell.axonal[0](0.5)._ref_v) s_ica_l = h.Vector().record(cell.somatic[0](0.5)._ref_ica_cal) a_ica_l = h.Vector().record(cell.apical[9](0.5)._ref_ica_cal) s_ica_n = h.Vector().record(cell.somatic[0](0.5)._ref_ica_can) a_ica_n = h.Vector().record(cell.apical[9](0.5)._ref_ica_can) s_ica_t = h.Vector().record(cell.somatic[0](0.5)._ref_ica_cat) a_ica_t = h.Vector().record(cell.apical[9](0.5)._ref_ica_cat) if not rxd_sim: s_ca_cyt = h.Vector().record(cell.somatic[0](0.5)._ref_cai) a_ca_cyt = h.Vector().record(cell.apical[9](0.5)._ref_cai) else: s_ca_cyt = h.Vector().record(cell.ca[cell.cyt].nodes(cell.somatic[0])[0]._ref_concentration) a_ca_cyt = h.Vector().record(cell.ca[cell.cyt].nodes(cell.apical[9])[0]._ref_concentration) ax_ca_cyt = h.Vector().record(cell.ca[cell.cyt].nodes(cell.axonal[0])[0]._ref_concentration) s_ca_er = h.Vector().record(cell.ca[cell.er].nodes(cell.somatic[0])[0]._ref_concentration) a_ca_er = h.Vector().record(cell.ca[cell.er].nodes(cell.apical[9])[0]._ref_concentration) s_dyeca = h.Vector().record(cell.dyeca.nodes(cell.somatic[0])[0]._ref_concentration) a_dyeca = h.Vector().record(cell.dyeca.nodes(cell.apical[9])[0]._ref_concentration) s_cbdhca = h.Vector().record(cell.cbdhca.nodes(cell.somatic[0])[0]._ref_concentration) a_cbdhca = h.Vector().record(cell.cbdhca.nodes(cell.apical[9])[0]._ref_concentration) s_cbdlca = h.Vector().record(cell.cbdlca.nodes(cell.somatic[0])[0]._ref_concentration) a_cbdlca = h.Vector().record(cell.cbdlca.nodes(cell.apical[9])[0]._ref_concentration) s_carca = h.Vector().record(cell.carca.nodes(cell.somatic[0])[0]._ref_concentration) a_carca = h.Vector().record(cell.carca.nodes(cell.apical[9])[0]._ref_concentration) s_ip3r = h.Vector().record(cell.ro_ip3r.nodes(cell.somatic[0])[0]._ref_concentration) a_ip3r = h.Vector().record(cell.ro_ip3r.nodes(cell.apical[9])[0]._ref_concentration) h.cvode.active(1) h.v_init = -69.4 h.tstop = sim_dur h.celsius = 34.0 # h.load_file('negative_init.hoc') # h.init() h.stdinit() print('Running current injection, amplitude = {0} nA'.format(c_amp)) h.continuerun(sim_dur) print('Final IP3R Values') print('r: {0}'.format(cell.r_ip3r.nodes(cell.somatic[0]).concentration)) print('ri: {0}'.format(cell.ri_ip3r.nodes(cell.somatic[0]).concentration)) print('ro: {0}'.format(cell.ro_ip3r.nodes(cell.somatic[0]).concentration)) print('rc: {0}'.format(cell.rc_ip3r.nodes(cell.somatic[0]).concentration)) print('rc2: {0}'.format(cell.rc2_ip3r.nodes(cell.somatic[0]).concentration)) print('rc3: {0}'.format(cell.rc3_ip3r.nodes(cell.somatic[0]).concentration)) print('rc4: {0}'.format(cell.rc4_ip3r.nodes(cell.somatic[0]).concentration)) print('Final IP3 Production Numbers') print('ip3: {0}'.format(cell.ip3.nodes(cell.somatic[0]).concentration)) print('plc: {0}'.format(cell.plc_m1.nodes(cell.somatic[0]).concentration)) print('ga_gtp: {0}'.format(cell.ga_gtp_m1.nodes(cell.somatic[0]).concentration)) print('ga_gtp_plc: {0}'.format(cell.ga_gtp_plc_m1.nodes(cell.somatic[0]).concentration)) print('ip5p: {0}'.format(cell.ip5p.nodes(cell.somatic[0]).concentration)) print('ip5p_ip3: {0}'.format(cell.ip5p_ip3.nodes(cell.somatic[0]).concentration)) print('ip3k: {0}'.format(cell.ip3k.nodes(cell.somatic[0]).concentration)) print('ip3k_2ca: {0}'.format(cell.ip3k_2ca.nodes(cell.somatic[0]).concentration)) print('ip3k_2ca_ip3: {0}'.format(cell.ip3k_2ca_ip3.nodes(cell.somatic[0]).concentration)) res_dict = {'t': np.array(t.as_numpy()), 'i_stim': np.array(i_rec.as_numpy()), 'soma_v': np.array(soma_v), 'soma_cyt': np.array(s_ca_cyt), 'axon_v': np.array(axon_v), 'axon_cyt': np.array(ax_ca_cyt), 'apic9_v': np.array(apic_v), 'apic9_cyt': np.array(a_ca_cyt), 'soma_ica_l': np.array(s_ica_l), 'apic9_ica_l': np.array(a_ica_l), 'soma_ica_n': np.array(s_ica_n), 'apic9_ica_n': np.array(a_ica_n), 'soma_ica_t': np.array(s_ica_t), 'apic9_ica_t': np.array(a_ica_t), } if rxd_sim: res_dict['soma_er'] = np.array(s_ca_er) res_dict['apic9_er'] = np.array(a_ca_er) res_dict['soma_ip3r_open'] = np.array(s_ip3r) res_dict['apic9_ip3r_open'] = np.array(a_ip3r) res_dict['soma_dyeca'] = np.array(s_dyeca) res_dict['apic9_dyeca'] = np.array(a_dyeca) res_dict['soma_cbdhca'] = np.array(s_cbdhca) res_dict['apic9_cbdhca'] = np.array(s_cbdhca) res_dict['soma_cbdlca'] = np.array(s_cbdlca) res_dict['apic9_cbdlca'] = np.array(s_cbdlca) res_dict['soma_carca'] = np.array(s_carca) res_dict['apic9_carca'] = np.array(a_carca) return res_dict def run_current_injection_series(rxd_sim, param_dict={}, sim_dur=500, pulse_times=[50], pulse_amps=[1.0], pulse_length=10): t_path = join(os.getcwd(), 'morphologies/mpg141209_A_idA.asc') cell = mig_py.MyCell(t_path, rxd_sim, param_dict) t_curr = h.IClamp(cell.somatic[0](0.5)) amp_list = [] amp_time = [] for p_time, p_amp in zip(pulse_times, pulse_amps): amp_list += [p_amp, 0.0] amp_time += [p_time, p_time+pulse_length] c_vec = h.Vector().from_python(amp_list) c_time = h.Vector().from_python(amp_time) t_curr.delay = 0 t_curr.dur = 1e9 c_vec.play(t_curr._ref_amp, c_time) # apical[9][0.5] distance to soma[0][1.0] = 105.53 um # Record Values i_rec = h.Vector().record(t_curr._ref_i) t = h.Vector().record(h._ref_t) soma_v = h.Vector().record(cell.somatic[0](0.5)._ref_v) apic_v = h.Vector().record(cell.apical[9](0.5)._ref_v) axon_v = h.Vector().record(cell.axonal[0](0.5)._ref_v) s_ica_l = h.Vector().record(cell.somatic[0](0.5)._ref_ica_cal) a_ica_l = h.Vector().record(cell.apical[9](0.5)._ref_ica_cal) s_ica_n = h.Vector().record(cell.somatic[0](0.5)._ref_ica_can) a_ica_n = h.Vector().record(cell.apical[9](0.5)._ref_ica_can) s_ica_t = h.Vector().record(cell.somatic[0](0.5)._ref_ica_cat) a_ica_t = h.Vector().record(cell.apical[9](0.5)._ref_ica_cat) if not rxd_sim: s_ca_cyt = h.Vector().record(cell.somatic[0](0.5)._ref_cai) a_ca_cyt = h.Vector().record(cell.apical[9](0.5)._ref_cai) else: s_ca_cyt = h.Vector().record(cell.ca[cell.cyt].nodes(cell.somatic[0])[0]._ref_concentration) a_ca_cyt = h.Vector().record(cell.ca[cell.cyt].nodes(cell.apical[9])[0]._ref_concentration) ax_ca_cyt = h.Vector().record(cell.ca[cell.cyt].nodes(cell.axonal[0])[0]._ref_concentration) s_ca_er = h.Vector().record(cell.ca[cell.er].nodes(cell.somatic[0])[0]._ref_concentration) a_ca_er = h.Vector().record(cell.ca[cell.er].nodes(cell.apical[9])[0]._ref_concentration) s_dyeca = h.Vector().record(cell.dyeca.nodes(cell.somatic[0])[0]._ref_concentration) a_dyeca = h.Vector().record(cell.dyeca.nodes(cell.apical[9])[0]._ref_concentration) s_cbdhca = h.Vector().record(cell.cbdhca.nodes(cell.somatic[0])[0]._ref_concentration) a_cbdhca = h.Vector().record(cell.cbdhca.nodes(cell.apical[9])[0]._ref_concentration) s_cbdlca = h.Vector().record(cell.cbdlca.nodes(cell.somatic[0])[0]._ref_concentration) a_cbdlca = h.Vector().record(cell.cbdlca.nodes(cell.apical[9])[0]._ref_concentration) s_carca = h.Vector().record(cell.carca.nodes(cell.somatic[0])[0]._ref_concentration) a_carca = h.Vector().record(cell.carca.nodes(cell.apical[9])[0]._ref_concentration) h.cvode.active(1) h.v_init = -69.4 h.tstop = sim_dur h.celsius = 34.0 # h.load_file('negative_init.hoc') # h.init() h.stdinit() print('Running current injection') h.continuerun(sim_dur) res_dict = {'t': np.array(t.as_numpy()), 'i_stim': np.array(i_rec.as_numpy()), 'soma_v': np.array(soma_v), 'soma_cyt': np.array(s_ca_cyt), 'apic9_v': np.array(apic_v), 'apic9_cyt': np.array(a_ca_cyt), 'axon_v': np.array(axon_v), 'axon_cyt': np.array(ax_ca_cyt), 'soma_ica_l': np.array(s_ica_l), 'apic9_ica_l': np.array(a_ica_l), 'soma_ica_n': np.array(s_ica_n), 'apic9_ica_n': np.array(a_ica_n), 'soma_ica_t': np.array(s_ica_t), 'apic9_ica_t':
np.array(a_ica_t)
numpy.array
#! /usr/bin/env python import numpy as np from collections import OrderedDict import matplotlib.pyplot as plt from selfdrive.car.honda.interface import CarInterface from selfdrive.controls.lib.lateral_mpc import libmpc_py from selfdrive.controls.lib.vehicle_model import VehicleModel # plot lateral MPC trajectory by defining boundary conditions: # lane lines, p_poly and vehicle states. Use this script to tune MPC costs libmpc = libmpc_py.libmpc mpc_solution = libmpc_py.ffi.new("log_t *") points_l = np.array([1.1049711, 1.1053879, 1.1073375, 1.1096942, 1.1124474, 1.1154714, 1.1192677, 1.1245866, 1.1321017, 1.1396152, 1.146443, 1.1555313, 1.1662073, 1.1774249, 1.1888939, 1.2009926, 1.2149779, 1.2300836, 1.2450289, 1.2617753, 1.2785473, 1.2974714, 1.3151019, 1.3331807, 1.3545501, 1.3763691, 1.3983455, 1.4215056, 1.4446729, 1.4691089, 1.4927692, 1.5175346, 1.5429921, 1.568854, 1.5968665, 1.6268958, 1.657122, 1.6853137, 1.7152609, 1.7477539, 1.7793678, 1.8098511, 1.8428392, 1.8746407, 1.9089606, 1.9426043, 1.9775689, 2.0136933, 2.0520134, 2.0891454]) points_r = np.array([-2.4442139, -2.4449506, -2.4448867, -2.44377, -2.4422617, -2.4393811, -2.4374201, -2.4334245, -2.4286852, -2.4238286, -2.4177458, -2.4094386, -2.3994849, -2.3904033, -2.380136, -2.3699453, -2.3594661, -2.3474073, -2.3342307, -2.3194637, -2.3046403, -2.2881098, -2.2706163, -2.2530098, -2.235604, -2.2160542, -2.1967411, -2.1758952, -2.1544619, -2.1325269, -2.1091819, -2.0850561, -2.0621953, -2.0364127, -2.0119917, -1.9851667, -1.9590458, -1.9306552, -1.9024918, -1.8745357, -1.8432863, -1.8131843, -1.7822732, -1.7507075, -1.7180918, -1.6845931, -1.650871, -1.6157099, -1.5787286, -1.5418037]) points_c = (points_l + points_r) / 2.0 def compute_path_pinv(): deg = 3 x = np.arange(50.0) X = np.vstack(tuple(x**n for n in range(deg, -1, -1))).T pinv = np.linalg.pinv(X) return pinv def model_polyfit(points): path_pinv = compute_path_pinv() return np.dot(path_pinv, map(float, points)) xx = [] yy = [] deltas = [] psis = [] times = [] CP = CarInterface.get_params("HONDA CIVIC 2016 TOURING") VM = VehicleModel(CP) v_ref = 32.00 # 45 mph curvature_factor = VM.curvature_factor(v_ref) print(curvature_factor) LANE_WIDTH = 3.9 p_l = map(float, model_polyfit(points_l)) p_r = map(float, model_polyfit(points_r)) p_p = map(float, model_polyfit(points_c)) l_poly = libmpc_py.ffi.new("double[4]", p_l) r_poly = libmpc_py.ffi.new("double[4]", p_r) p_poly = libmpc_py.ffi.new("double[4]", p_p) l_prob = 1.0 r_prob = 1.0 p_prob = 1.0 # This is always 1 mpc_x_points = np.linspace(0., 2.5*v_ref, num=50) points_poly_l = np.polyval(p_l, mpc_x_points) points_poly_r = np.polyval(p_r, mpc_x_points) points_poly_p = np.polyval(p_p, mpc_x_points) print(points_poly_l) lanes_x = np.linspace(0, 49) cur_state = libmpc_py.ffi.new("state_t *") cur_state[0].x = 0.0 cur_state[0].y = 0.5 cur_state[0].psi = 0.0 cur_state[0].delta = 0.0 xs = [] ys = [] deltas = [] titles = [ 'Steer rate cost', 'Heading cost', 'Lane cost', 'Path cost', ] # Steer rate cost sol_x = OrderedDict() sol_y = OrderedDict() delta = OrderedDict() for cost in np.logspace(-1, 1.0, 5): libmpc.init(1.0, 3.0, 1.0, cost) for _ in range(10): libmpc.run_mpc(cur_state, mpc_solution, l_poly, r_poly, p_poly, l_prob, r_prob, curvature_factor, v_ref, LANE_WIDTH) sol_x[cost] = map(float, list(mpc_solution[0].x)) sol_y[cost] = map(float, list(mpc_solution[0].y)) delta[cost] = map(float, list(mpc_solution[0].delta)) xs.append(sol_x) ys.append(sol_y) deltas.append(delta) # Heading cost sol_x = OrderedDict() sol_y = OrderedDict() delta = OrderedDict() for cost in np.logspace(-1, 1.0, 5): libmpc.init(1.0, 3.0, cost, 1.0) for _ in range(10): libmpc.run_mpc(cur_state, mpc_solution, l_poly, r_poly, p_poly, l_prob, r_prob, curvature_factor, v_ref, LANE_WIDTH) sol_x[cost] = map(float, list(mpc_solution[0].x)) sol_y[cost] = map(float, list(mpc_solution[0].y)) delta[cost] = map(float, list(mpc_solution[0].delta)) xs.append(sol_x) ys.append(sol_y) deltas.append(delta) # Lane cost sol_x = OrderedDict() sol_y = OrderedDict() delta = OrderedDict() for cost in np.logspace(-1, 2.0, 5): libmpc.init(1.0, cost, 1.0, 1.0) for _ in range(10): libmpc.run_mpc(cur_state, mpc_solution, l_poly, r_poly, p_poly, l_prob, r_prob, curvature_factor, v_ref, LANE_WIDTH) sol_x[cost] = map(float, list(mpc_solution[0].x)) sol_y[cost] = map(float, list(mpc_solution[0].y)) delta[cost] = map(float, list(mpc_solution[0].delta)) xs.append(sol_x) ys.append(sol_y) deltas.append(delta) # Path cost sol_x = OrderedDict() sol_y = OrderedDict() delta = OrderedDict() for cost in
np.logspace(-1, 1.0, 5)
numpy.logspace
import copy import json import warnings import numpy as np from matrx.actions import GrabObject, RemoveObject, OpenDoorAction, CloseDoorAction from matrx.agents.agent_utils.state import State from matrx.messages import Message class AgentBrain: """ An artificial agent whose behaviour can be programmed to be, for example, (semi-)autonomous. """ def __init__(self, memorize_for_ticks=None): """ Defines the behavior of an agent. This class is the place where all the decision logic of an agent is contained. This class together with the :class:`matrx.objects.agent_body.AgentBody` class represent a full agent. This agent brain simply selects a random action from the possible actions it can do. When you wish to create a new agent, this is the class you need to extend. In specific these are the functions you should override: * :meth:`matrx.agents.agent_brain.initialize` Called before a world starts running. Can be used to initialize variables that can only be initialized after the brain is connected to its body (which is done by the world). * :meth:`matrx.agents.agent_brain.filter_observations` Called before deciding on an action to allow detailed and agent specific filtering of the received world state. * :meth:`matrx.agents.agent_brain.decide_on_action` Called to decide on an action. * :meth:`matrx.agents.agent_brain.get_log_data` Called by data loggers to obtain data that should be logged from this agent internal reasoning. Attributes ---------- action_set: [str, ...] List of actions this agent can perform. agent_id: str The unique identified of this agent's body in the world. agent_name: str The name of this agent. agent_properties: dict A dictionary of this agent's :class:`matrx.objects.agent_body.AgentBody` properties. With as keys the property name, and as value the property's value. These can be adjusted iff they are said to be adjustable (e.g. inside the attribute `keys_of_agent_writable_props`). keys_of_agent_writable_props: [str, ...] List of property names that this agent can adjust. messages_to_send: [Message, ...] List of messages this agent will send. Use the method :meth:`matrx.agents.agent_brain.AgentBrain.send_message` to append to this list. previous_action: str The name of the previous performed or attempted action. previous_action_result: ActionResult The :class:`matrx.actions.action.ActionResult` of the previously performed or attempted action. received_messages: [Message, ...] The list of received messages. rnd_gen: Random The random generator for this agent. rnd_seed: int The random seed with which this agent's `rnd_gen` was initialized. This seed is based on the master random seed given of the :class:`matrx.grid_world.GridWorld`. """ # Class variables for tracking the past action and its result self.previous_action = None self.previous_action_result = None # A list of messages that may be filled by this agent, which is retrieved by the GridWorld and send towards the # appropriate agents. self.messages_to_send = [] self.received_messages = [] # Filled by the WorldFactory during self.factory_initialise() self.agent_id = None self.agent_name = None self.action_set = None # list of action names (strings) self.sense_capability = None self.rnd_gen = None self.rnd_seed = None self.agent_properties = {} self.keys_of_agent_writable_props = [] self.__memorize_for_ticks = memorize_for_ticks # The central state property (an extended dict with unique searching capabilities) self._state = None def initialize(self): """ Method called by any world when it starts. When adding an agent to a :class:`matrx.grid_world.GridWorld`, through a world builer, you only pass the class of your agent brain, not the actual instance. Instead, this instance is made by the builder when a new world is created and ran. At that point this method is called. That makes this method the ideal place for any initialization or reset you want your agent brain to do when starting a world or between worlds. Importantly, this method is called after the builder assigned things to it such as its location, name and object ID. As this method is called afterwards, it allows you to do things related to to those properties. An example is when you run the same world multiple times. In that case the instance of your agent brain will have attributes with values from the previous run. This method can be used to reset them. """ self.previous_action = None self.previous_action_result = None self.messages_to_send = [] self.received_messages = [] self._init_state() def filter_observations(self, state): """ Filters the world state before deciding on an action. In this method you filter the received world state to only those properties and objects the agent is actually supposed to see. Currently the world returns ALL properties of ALL objects within a certain range(s), as specified by :class:`matrx.agents.capabilities.capability.SenseCapability`. But perhaps some objects are obscured because they are behind walls and this agent is not supposed to look through walls, or an agent is not able to see some properties of certain objects (e.g. colour). The adjusted world state that this function returns is directly fed to the agent's decide function. Furthermore, this returned world state is also fed through the MATRX API to any visualisations. Override this method when creating a new AgentBrain and you need to filter the world state further. Parameters ---------- state : State A state description containing all perceived :class:`matrx.objects.env_object.EnvObject` and objects inheriting from this class within a certain range as defined by the :class:`matrx.agents.capabilities.capability.SenseCapability`. The keys are the unique identifiers, as values the properties of an object. See :class:`matrx.objects.env_object.EnvObject` for the kind of properties that are always included. It will also contain all properties for more specific objects that inherit from that class. Also includes a 'world' key that describes common information about the world (e.g. its size). Returns ------- filtered_state : State A dictionary similar to `state` but describing the filtered state this agent perceives of the world. Notes ----- A future version of MATRX will include handy utility function to make state filtering less of a hassle (e.g. to easily remove specific objects or properties, but also ray casting to remove objects behind other objects) """ return state def decide_on_action(self, state): """ Contains the decision logic of the agent. This method determines what action the agent should perform. The :class:`matrx.grid_world.GridWorld` is responsible for deciding when an agent can perform an action, if so this method is called for each agent and fed with the world state from the `filter_observations` method. Two things need to be determined: action name and action arguments. The action is returned simply as the class name (as a string), and the action arguments as a dictionary with the keys the names of the keyword arguments. See the documentation of that action to find out which arguments. An argument that is always possible is that of action_duration, which denotes how many ticks this action should take and overrides the action duration set by the action implementation. Parameters ---------- state : State A state description as given by the agent's :meth:`matrx.agents.agent_brain.AgentBrain.filter_observations` method. Returns ------- action_name : str A string of the class name of an action that is also in the `action_set` class attribute. To ensure backwards compatibility we advise to use Action.__name__ where Action is the intended action. action_args : dict A dictionary with keys any action arguments and as values the actual argument values. If a required argument is missing an exception is raised, if an argument that is not used by that action a warning is printed. The argument applicable to all action is `action_duration`, which sets the number ticks the agent is put on hold by the GridWorld until the action's world mutation is actual performed and the agent can perform a new action (a value of 0 is no wait, 1 means to wait 1 tick, etc.). Notes ----- A future version of MATRX will include handy utility function to make agent decision-making less of a hassle. Think of a Belief-Desire-Intention (BDI) like structure, and perhaps even support for learning agents. """ # send a random message once in a while if self.rnd_gen.random() < 0.1: # Get all agents in our state. # The codeline below can return three things: # - None -> no agents found (impossible as we are in an agent right now) # - an agent object -> only a single agent found # - a list of agent objects -> multiple agents found # Also see for state usage: # https://github.com/matrx-software/matrx/blob/master/matrx/cases/bw4t/bw4t_agents.py agents = state[{"isAgent": True}] # If we found multiple agents, randomly select the ID of one of them or otherwise the ID of the only agent to_id = self.rnd_gen.choice(agents)['obj_id'] if isinstance(agents, list) else agents['obj_id'] self.send_message(Message(content=f"Hello, my name is (agent) {self.agent_name} and I sent this message at " f"tick {state['World']['nr_ticks']}", from_id=self.agent_id, to_id=to_id)) # Select a random action if self.action_set: action = self.rnd_gen.choice(self.action_set) else: action = None action_kwargs = {} if action == RemoveObject.__name__: action_kwargs['object_id'] = None # Get all perceived objects objects = list(state.keys()) # Remove yourself from the object id list objects.remove(self.agent_properties["obj_id"]) # Remove all objects that have 'agent' in the name (so we do not remove those, though agents without agent # in their name can still be removed). objects = [obj for obj in objects if 'agent' not in obj] # Choose a random object id (safety for when it is empty) if objects: object_id = self.rnd_gen.choice(objects) # Assign it action_kwargs['object_id'] = object_id # Select range as just enough to remove that object remove_range = int(np.ceil(np.linalg.norm( np.array(state[object_id]['location']) - np.array( state[self.agent_properties["obj_id"]]['location'])))) # Safety for if object and agent are in the same location remove_range = max(remove_range, 0) # Assign it to the arguments list action_kwargs['remove_range'] = remove_range else: action_kwargs['object_id'] = None action_kwargs['remove_range'] = 0 # if the agent randomly chose a grab action, choose a random object to pickup elif action == GrabObject.__name__: # Set grab range grab_range = 1 # Set max amount of objects max_objects = 3 # Assign it to the arguments list action_kwargs['grab_range'] = grab_range action_kwargs['max_objects'] = max_objects # Get all perceived objects objects = list(state.keys()) # Remove yourself from the object id list objects.remove(self.agent_properties["obj_id"]) # Remove all objects that have 'agent' in the name (so we do not remove those, though agents without agent # in their name can still be removed). objects = [obj for obj in objects if 'agent' not in obj] # Choose a random object id (safety for when it is empty) object_in_range = [] for object_id in objects: # Select range as just enough to grab that object dist = int(np.ceil(np.linalg.norm( np.array(state[object_id]['location']) - np.array( state[self.agent_properties["obj_id"]]['location'])))) if dist <= grab_range and state[object_id]["is_movable"]: object_in_range.append(object_id) if object_in_range: # Select object object_id = self.rnd_gen.choice(object_in_range) # Assign it action_kwargs['object_id'] = object_id else: action_kwargs['object_id'] = None # if we randomly chose to do a open or close door action, find a door to open/close elif action == OpenDoorAction.__name__ or action == CloseDoorAction.__name__: action_kwargs['door_range'] = 1 # np.inf action_kwargs['object_id'] = None # Get all doors from the perceived objects objects = list(state.keys()) doors = [obj for obj in objects if 'class_inheritance' in state[obj] and state[obj]['class_inheritance'][0] == "Door"] # choose a random door if len(doors) > 0: action_kwargs['object_id'] = self.rnd_gen.choice(doors) return action, action_kwargs def get_log_data(self): """ Provides a dictionary of data for any Logger This method functions to relay data from an agent's decision logic (this AgentBrain class) through the GridWorld into a Logger. Here it can be further processed and stored. Returns ------- data : dict A dictionary with keys identifiable names and the data as its value. """ return {} def send_message(self, message): """ Sends a Message from this agent to others Method that allows you to construct a message that will be send to either a specified agent, a team of agents or all agents. Parameters ---------- message : Message A message object that needs to be send. Should be of type Message. It's to_id can contain a single recipient, a list of recipients or None. If None, it is send to all other agents. """ # Check if the message is a true message self.__check_message(message, self.agent_id) # Add the message to our list self.messages_to_send.append(message) def is_action_possible(self, action, action_kwargs): """ Checks if an action would be possible. This method can be called from the AgentBrain to check if a certain action is possible to perform with the current state of the GridWorld. It requires as input an action name and its arguments (if any), same as the decide_on_action method should return. This method does not guarantees that if the action is return by the brain it actually succeeds, as other agents may intervene. Parameters ---------- action : str The name of an Action class. action_kwargs : dict A dictionary with keys any action arguments and as values the actual argument values. Returns ------- succeeded : bool True if the action can be performed, False otherwise. action_results : ActionResult An ActionResult object containing the success or failure of the action, and (if failed) the reason why. """ action_result = self.__callback_is_action_possible(self.agent_id, action, action_kwargs) return action_result.succeeded, action_result @property def state(self): return self._state @state.setter def state(self, new_state): # Check if the return filtered state is a differently created State # object, if so, raise the warning that we are overwriting it. if new_state is not self.state: warnings.warn(f"Overwriting State object of {self.agent_id}. This " f"will cause any stored memory to be gone for good " f"as this was stored in the previous State object.") if isinstance(new_state, dict): raise TypeError(f"The new state should of type State, is of " f"type {new_state.__class__}") self._state = new_state @property def memorize_for_ticks(self): return self.__memorize_for_ticks def create_context_menu_for_other(self, agent_id_who_clicked, clicked_object_id, click_location): """ Generate options for a context menu for a specific object/location that a user NOT controlling this human agent opened. Thus: another human agent selected this agent, opened a context menu by right clicking on an object or location. This function is called. It should return actions, messages, or other info for what this agent can do relevant to that object / location. E.g. pick it up, move to it, display information on it, etc. Example usecase: tasking another agent that is not yourself, e.g. to move to a specific location. For the default MATRX visualization, the context menu is opened by right clicking on an object. This function should generate a list of options (actions, messages, or something else) which relate to that object or location. Each option is in the shape of a text shown in the context menu, and a message which is send to this agent if the user actually clicks that context menu option. Parameters ---------- agent_id_who_clicked : str The ID of the (human) agent that selected this agent and requested for a context menu. clicked_object_id : str A string indicating the ID of an object. Is None if the user clicked on a background tile (which has no ID). click_location : list A list containing the [x,y] coordinates of the object on which the user right clicked. Returns ------- context_menu : list A list containing context menu items. Each context menu item is a dict with a 'OptionText' key, which is the text shown in the menu for the option, and a 'Message' key, which is the message instance that is sent to this agent when the user clicks on the context menu option. """ print("Context menu other") context_menu = [] # Generate a context menu option for every action for action in self.action_set: context_menu.append({ "OptionText": f"Do action: {action}", "Message": Message(content=action, from_id=clicked_object_id, to_id=self.agent_id) }) return context_menu def _factory_initialise(self, agent_name, agent_id, action_set, sense_capability, agent_properties, customizable_properties, rnd_seed, callback_is_action_possible): """ Private MATRX function. Initialization of the brain by the WorldBuilder. Called by the WorldFactory to initialise this agent with all required properties in addition with any custom properties. This also sets the random number generator with a seed generated based on the random seed of the world that is generated. Parameters ---------- agent_name : str The name of the agent. agent_id : str The unique ID given by the world to this agent's avatar. So the agent knows what body is his. action_set : str The list of action names this agent is allowed to perform. sense_capability : SenseCapability The SenseCapability of the agent denoting what it can see withing what range. agent_properties : dict The dictionary of properties containing all mandatory and custom properties. customizable_properties : list A list of keys in agent_properties that this agent is allowed to change. rnd_seed : int The random seed used to set the random number generator self.rng callback_is_action_possible : callable A callback to a GridWorld method that can check if an action is possible. """ # The name of the agent with which it is also known in the world self.agent_name = agent_name # The id of the agent self.agent_id = agent_id # The names of the actions this agent is allowed to perform self.action_set = action_set # Setting the random seed and rng self.rnd_seed = rnd_seed self._set_rnd_seed(seed=rnd_seed) # Initializing the State object self._init_state() # The SenseCapability of the agent; what it can see and within what range self.sense_capability = sense_capability # Contains the agent_properties self.agent_properties = agent_properties # Specifies the keys of properties in self.agent_properties which can be changed by this Agent in this file. If # it is not writable, it can only be updated through performing an action which updates that property (done by # the environment). # NOTE: Changing which properties are writable cannot be done during runtime! Only when adding it to the world. self.keys_of_agent_writable_props = customizable_properties # A callback to the GridWorld instance that can check whether any action (with its arguments) will succeed and # if not why not (in the form of an ActionResult). self.__callback_is_action_possible = callback_is_action_possible def _get_action(self, state, agent_properties, agent_id): """ Private MATRX function The function the environment calls. The environment receives this function object and calls it when it is time for this agent to select an action. Note; This method should NOT be overridden! Parameters ---------- state_dict: dict A state description containing all properties of EnvObject that are within a certain range as defined by self.sense_capability. It is a list of properties in a dictionary agent_properties: dict The properties of the agent, which might have been changed by the environment as a result of actions of this or other agents. agent_id: str the ID of this agent Returns ------- filtered_state : dict The filtered state of this agent agent_properties : dict the agent properties which the agent might have changed, action : str an action string, which is the class name of one of the actions in the Action package. action_kwargs : dict Keyword arguments for the action """ # Process any properties of this agent which were updated in the environment as a result of actions self.agent_properties = agent_properties # Update the state property of an agent with the GridWorld's state dictionary self.state.state_update(state.as_dict()) # Call the filter method to filter the observation self.state = self.filter_observations(self.state) # Call the method that decides on an action action, action_kwargs = self.decide_on_action(self.state) # Store the action so in the next call the agent still knows what it did self.previous_action = action # Return the filtered state, the (updated) properties, the intended actions and any keyword arguments for that # action if needed. return self.state, self.agent_properties, action, action_kwargs def _fetch_state(self, state): self.state.state_update(state.as_dict()) filtered_state = self.filter_observations(self.state) return filtered_state def _get_log_data(self): return self.get_log_data() def _set_action_result(self, action_result): """ A function that the environment calls (similarly as the self.get_action method) to set the action_result of the action this agent decided upon. Note, that the result is given AFTER the action is performed (if possible). Hence it is named the self.previous_action_result, as we can read its contents when we should decide on our NEXT action after the action whose result this is. Note; This method should NOT be overridden! Parameters ---------- action_result : ActionResult An object that inherits from ActionResult, containing a boolean whether the action succeeded and a string denoting the reason why it failed (if it did so). """ self.previous_action_result = action_result def _set_rnd_seed(self, seed): """ The function that seeds this agent's random seed. Note; This method should NOT be overridden! Parameters ---------- seed : int The random seed this agent needs to be seeded with. """ self.rnd_seed = seed self.rnd_gen =
np.random.RandomState(self.rnd_seed)
numpy.random.RandomState
import numpy as np import cv2 import math import copy from opensfm import context from opensfm import pygeometry from opensfm import pymap from opensfm import types from scipy.stats import special_ortho_group from scipy.spatial.transform import Rotation """ Trying to imitate the following structure reconstruction = { "cameras": { "theta": { "projection_type": "equirectangular" } }, "shots" : { 'im1': { "camera": "theta", "rotation": [0.0, 0.0, 0.0], "translation": [0.0, 0.0, 0.0], }, 'im2': { "camera": "theta", "rotation": [0, 0, 0.0], "translation": [-1, 0, 0.0], }, }, "points" : { }, } """ # Define original Pose class Pose(object): """Defines the pose parameters of a camera. The extrinsic parameters are defined by a 3x1 rotation vector which maps the camera rotation respect to the origin frame (rotation) and a 3x1 translation vector which maps the camera translation respect to the origin frame (translation). Attributes: rotation (vector): the rotation vector. translation (vector): the rotation vector. """ def __init__(self, rotation=(0, 0, 0), translation=(0, 0, 0)): self.rotation = rotation self.translation = translation @property def rotation(self): """Rotation in angle-axis format.""" return self._rotation @rotation.setter def rotation(self, value): self._rotation = np.asarray(value, dtype=float) @property def translation(self): """Translation vector.""" return self._translation @translation.setter def translation(self, value): self._translation = np.asarray(value, dtype=float) def transform(self, point): """Transform a point from world to this pose coordinates.""" return self.get_rotation_matrix().dot(point) + self.translation def transform_many(self, points): """Transform points from world coordinates to this pose.""" return points.dot(self.get_rotation_matrix().T) + self.translation def transform_inverse(self, point): """Transform a point from this pose to world coordinates.""" return self.get_rotation_matrix().T.dot(point - self.translation) def transform_inverse_many(self, points): """Transform points from this pose to world coordinates.""" return (points - self.translation).dot(self.get_rotation_matrix()) def get_rotation_matrix(self): """Get rotation as a 3x3 matrix.""" return cv2.Rodrigues(self.rotation)[0] def set_rotation_matrix(self, rotation_matrix, permissive=False): """Set rotation as a 3x3 matrix. >>> pose = Pose() >>> pose.rotation = np.array([0., 1., 2.]) >>> R = pose.get_rotation_matrix() >>> pose.set_rotation_matrix(R) >>> np.allclose(pose.rotation, [0., 1., 2.]) True >>> pose.set_rotation_matrix([[3,-4, 1], [ 5, 3,-7], [-9, 2, 6]]) Traceback (most recent call last): ... ValueError: Not orthogonal >>> pose.set_rotation_matrix([[0, 0, 1], [-1, 0, 0], [0, 1, 0]]) Traceback (most recent call last): ... ValueError: Determinant not 1 """ R = np.array(rotation_matrix, dtype=float) if not permissive: if not np.isclose(np.linalg.det(R), 1): raise ValueError("Determinant not 1") if not np.allclose(np.linalg.inv(R), R.T): raise ValueError("Not orthogonal") self.rotation = cv2.Rodrigues(R)[0].ravel() def get_origin(self): """The origin of the pose in world coordinates.""" return -self.get_rotation_matrix().T.dot(self.translation) def set_origin(self, origin): """Set the origin of the pose in world coordinates. >>> pose = Pose() >>> pose.rotation = np.array([0., 1., 2.]) >>> origin = [1., 2., 3.] >>> pose.set_origin(origin) >>> np.allclose(origin, pose.get_origin()) True """ self.translation = -self.get_rotation_matrix().dot(origin) def get_Rt(self): """Get pose as a 3x4 matrix (R|t).""" Rt = np.empty((3, 4)) Rt[:, :3] = self.get_rotation_matrix() Rt[:, 3] = self.translation return Rt def compose(self, other): """Get the composition of this pose with another. composed = self * other """ selfR = self.get_rotation_matrix() otherR = other.get_rotation_matrix() R = np.dot(selfR, otherR) t = selfR.dot(other.translation) + self.translation res = Pose() res.set_rotation_matrix(R) res.translation = t return res def inverse(self): """Get the inverse of this pose.""" inverse = Pose() R = self.get_rotation_matrix() inverse.set_rotation_matrix(R.T) inverse.translation = -R.T.dot(self.translation) return inverse class Camera(object): """Abstract camera class. A camera is unique defined for its identification description (id), the projection type (projection_type) and its internal calibration parameters, which depend on the particular Camera sub-class. Attributes: id (str): camera description. projection_type (str): projection type. """ pass class PerspectiveCamera(Camera): """Define a perspective camera. Attributes: width (int): image width. height (int): image height. focal (real): estimated focal length. k1 (real): estimated first distortion parameter. k2 (real): estimated second distortion parameter. """ def __init__(self): """Defaut constructor.""" self.id = None self.projection_type = 'perspective' self.width = None self.height = None self.focal = None self.k1 = None self.k2 = None def __repr__(self): return '{}({!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r})'.format( self.__class__.__name__, self.id, self.projection_type, self.width, self.height, self.focal, self.k1, self.k2) def project(self, point): """Project a 3D point in camera coordinates to the image plane.""" # Normalized image coordinates xn = point[0] / point[2] yn = point[1] / point[2] # Radial distortion r2 = xn * xn + yn * yn distortion = 1.0 + r2 * (self.k1 + self.k2 * r2) return np.array([self.focal * distortion * xn, self.focal * distortion * yn]) def project_many(self, points): """Project 3D points in camera coordinates to the image plane.""" distortion = np.array([self.k1, self.k2, 0, 0, 0]) K, R, t = self.get_K(), np.zeros(3),
np.zeros(3)
numpy.zeros
import numpy as np import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, 'utils')) sys.path.append(os.path.join(BASE_DIR, 'nn')) from nn import nn_utils def diameter(obj_points): ''' obj_points: (N, 3) array ''' dist_sq = -np.dot(obj_points, obj_points.T) * 2 + \ np.square(np.linalg.norm(obj_points, axis=-1, keepdims=True)) + \ np.square(np.linalg.norm(obj_points.T, axis=0, keepdims=True)) dist_max = np.max(dist_sq) diameter = np.sqrt(dist_max) return diameter def find_nn_idx(pc_src, pc_target): ''' pc_src: (N1, 3) array pc_target: (N2, 3) array ''' dist_sq = -np.dot(pc_src, pc_target.T) * 2 + \ np.square(np.linalg.norm(pc_src, axis=-1, keepdims=True)) + \ np.square(np.linalg.norm(pc_target.T, axis=0, keepdims=True)) idx_min = np.argmin(dist_sq, axis=0) return idx_min def add_metric(pose_pred, pose_targets, obj_points, diameter, symm=False, percentage=0.1, gpu=True): diam = diameter * percentage model_pred = np.dot(obj_points, pose_pred[:, :3].T) + pose_pred[:, 3] model_targets = np.dot(obj_points, pose_targets[:, :3].T) + pose_targets[:, 3] if symm: if gpu: idxs = nn_utils.find_nearest_point_idx(model_pred, model_targets) else: idxs = find_nn_idx(model_pred, model_targets) mean_dist = np.mean(
np.linalg.norm(model_pred[idxs] - model_targets, 2, 1)
numpy.linalg.norm
import numpy as np from math import sqrt, acos, cos, sin import scipy.sparse as sp import numba from numba import jit def find_adjsacent_faces (faces): """ For every triangle/face in a mesh, it retuns the adjacent triangles/faces """ print ("\nFinding adjacent faces/triangles...") adjacent_faces = [[] for row in range(len(faces))] flist = faces[:,[0, 1, 2]].tolist() for i in range(len(flist)): set1 = set(flist[i]) for j in range(i+1, len(flist)): set2 = set(flist[j]) if(len(set1 & set2)==2): #i.e. if 2 same vertex indices are found between set1 and set2 -> set1 and set2 are adjacent adjacent_faces[i] += [j] adjacent_faces[j] += [i] if(len(adjacent_faces[i])>=3): break return adjacent_faces @jit(nopython=True, parallel=True) def compute_v4 (vertices, faces): v4 = np.zeros((len(faces), 3), dtype = np.float32) for k in numba.prange(len(faces)): cross = np.cross(vertices[faces[k, 1],0:3] - vertices[faces[k, 0],0:3], vertices[faces[k, 2],0:3]-vertices[faces[k, 0],0:3]) v4[k] = vertices[faces[k, 0],0:3] + cross / sqrt(np.linalg.norm(cross)) return v4 @jit(nopython=True, parallel=True) def compute_face_normals(vertices, faces): face_normals = np.zeros((len(faces), 3), dtype = np.float32) for k in numba.prange(len(faces)): cross = np.cross(vertices[faces[k, 1],0:3] - vertices[faces[k, 0],0:3], vertices[faces[k, 2],0:3] - vertices[faces[k, 0],0:3]) face_normals[k] = cross / np.linalg.norm(cross) return face_normals def compute_V_inverse_local (vertices, face, v4): a = np.array([vertices[face[1],0:3] - vertices[face[0],0:3]]) b = np.array([vertices[face[2],0:3] - vertices[face[0],0:3]]) c = np.array([v4 - vertices[face[0],0:3]]) V_inverse_local = np.linalg.solve(np.hstack([a.T, b.T, c.T]), np.identity(3)) return V_inverse_local def compute_V_inverse (vertices, faces, v4): V_inverse = np.zeros((len(faces), 3, 3), dtype = np.float32) # inverse matrix of vertices, including v4 for i in range(len(faces)): V_inverse[i] = compute_V_inverse_local (vertices, faces[i], v4[i]) return V_inverse #make large matrices and vectors def makeEs_ATA_ATc(vertices, faces, Vinv): Adjacent = find_adjsacent_faces(faces) adj_num = 0 for i in range(len(Adjacent)): for j in range(len(Adjacent[i])): adj_num+=1 Es_cVector = sp.csr_matrix((1, adj_num*9), dtype=np.float32) Es_cVector = Es_cVector.T Es_A = sp.lil_matrix((adj_num*9, len(vertices)*3 + len(faces)*3), dtype=np.float32) row = 0 Vinv_list = Vinv.tolist() Faces = faces.tolist() len_vertices = len(vertices) for i in range(len(Adjacent)): for j in Adjacent[i]: e1 =
np.sum(Vinv[i,0:3,0])
numpy.sum
#!/usr/bin/env python3 import sys #sys.path.insert(0, '/home/mike/Dropbox/0_firebird_research/fit_peaks/single_fits/') import numpy as np from seas.waveletFunctions import * import matplotlib.pylab as plt import matplotlib import math from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.gridspec import GridSpec from datetime import datetime from seas.signalanalysis import local_max, linear_regression, abline, gaussian_smooth_2d, lag_n_autocorr #sys.path.insert(0, '/home/mike/Dropbox/0_firebird_research/microburst_characterization/') #from src import remove_dropouts import operator #Adapted from __author__ = '<NAME>' : __init__, waveletTransform, plotPower, lagNAutoCorr #All other functions written by <NAME> ''' To find the global wavelet spectrum run these two scripts: waveletAnalysis.globalWaveletSpectrum() To find events: Need to work on this. Depending on which range of frequencies, you get varying results waveletAnalysis.averageWaveletPower(periodLim =[0.25, 8]) To find signal change: waveletAnalysis.tsSignal() There seems to be very little difference between binned data and full data ''' def waveletCoherence(tc1, tc2, fps=10, siglvl=0.95, sigtest=0): tc1 = np.asarray(np.squeeze(tc1)) tc2 = np.asarray(np.squeeze(tc2)) assert tc1.ndim == 1 and tc2.ndim == 1, 'Timecouses should only be one dimension' assert tc1.shape[0] == tc2.shape[0], 'Timecourses are not the same shape' #run wavelet transform w1 = waveletAnalysis(tc1, fps=fps) w2 = waveletAnalysis(tc2, fps=fps) # cross wavelet transform w1w2 = w1.wave * np.conj( w2.wave) #/ (np.ones([1, tc1.size]) * w1.scale[:, None]) xwt = np.sqrt(w1w2.real**2 + w1w2.imag**2) # calculate phase phase = np.angle(w1w2) # #set up smoothing window # win_s = np.floor(w1.wave.shape[1]/w1.dj)+1 # win_t = 2*np.floor(w1.wave.shape[0]/w1.cadence)+1 # win_s = 10 # win_t = 10 # window2D = np.dot(windowFunc(win_t, win_type = 'ham')[:,np.newaxis] , windowFunc(win_s, win_type = 'ham')[:,np.newaxis].T) #smooth s1 = gaussian_smooth_2d(w1.power, w1.dj, w1.cadence) s2 = gaussian_smooth_2d(w2.power, w2.dj, w2.cadence) s1s2 = gaussian_smooth_2d(w1w2, w1.dj, w1.cadence) #calculate coherency coherency = s1s2 / np.sqrt(s1 * s2) #calculate coherence coherence = (s1s2.real**2 + s1s2.imag**2) / (s1 * s2) # significance? acor1 = 0.5 * (lag_n_autocorr(tc1, 1) + lag_n_autocorr(tc1, 2)) acor2 = 0.5 * (lag_n_autocorr(tc2, 1) + lag_n_autocorr(tc2, 2)) xwt_signif = wave_cohere_signif(([1.0]), ([1.0]), dt=1 / fps, sigtest=sigtest, scale=w1.scale, x_lag1=acor2, y_lag1=acor1, mother=w1.mother, siglvl=siglvl) xwt_signif = xwt_signif[:, np.newaxis].dot(np.ones(w1.n)[np.newaxis, :]) return coherency, coherence, xwt, phase, xwt_signif def wave_cohere_signif(X, Y, dt, scale, sigtest=-1, y_lag1=-1, x_lag1=-1, siglvl=-1, dof=-1, mother=-1, param=-1): ''' Modified from waveletFunctions to take into account two time series in calculating the significance of the cross wavelet transform. ''' n1 = len(np.atleast_1d(Y)) n2 = len(np.atleast_1d(X)) J1 = len(scale) - 1 s0 = np.min(scale) dj = np.log2(scale[1] / scale[0]) if n1 == 1: y_variance = Y else: y_variance = np.std(Y)**2 if n2 == 1: x_variance = X else: x_variance = np.std(X)**2 if sigtest == -1: sigtest = 0 if x_lag1 == -1: x_lag1 = 0.0 if y_lag1 == -1: y_lag1 = 0.0 if siglvl == -1: siglvl = 0.95 if mother == -1: mother = 'MORLET' # get the appropriate parameters [see Table(2)] if mother == 'MORLET': #---------------------------------- Morlet empir = ([2, -1, -1, -1]) if param == -1 or param == 6: param = 6. empir[1:] = ([0.776, 2.39, 0.60]) if param == 4: empir[1:] = ([1.151, 2.5, 0.60]) k0 = param fourier_factor = (4 * np.pi) / (k0 + np.sqrt(2 + k0**2) ) # Scale-->Fourier [Sec.3h] elif mother == 'PAUL': empir = ([2, -1, -1, -1]) if param == -1: param = 4 empir[1:] = ([1.132, 1.17, 1.5]) m = param fourier_factor = (4 * np.pi) / (2 * m + 1) elif mother == 'DOG': #-------------------------------------Paul empir = ([1., -1, -1, -1]) if param == -1 or param == 2: param = 2. empir[1:] = ([3.541, 1.43, 1.4]) elif param == 6: #--------------------------------------DOG empir[1:] = ([1.966, 1.37, 0.97]) m = param fourier_factor = 2 * np.pi * np.sqrt(2. / (2 * m + 1)) else: print('Mother must be one of MORLET, PAUL, DOG') period = scale * fourier_factor dofmin = empir[0] # Degrees of freedom with no smoothing Cdelta = empir[1] # reconstruction factor gamma_fac = empir[2] # time-decorrelation factor dj0 = empir[3] # scale-decorrelation factor freq = dt / period # normalized frequency y_fft_theor = (1 - y_lag1**2) / ( 1 - 2 * y_lag1 * np.cos(freq * 2 * np.pi) + y_lag1**2) # [Eqn(16)] y_fft_theor = y_variance * y_fft_theor # include time-series variance x_fft_theor = (1 - x_lag1**2) / ( 1 - 2 * x_lag1 * np.cos(freq * 2 * np.pi) + x_lag1**2) # [Eqn(16)] x_fft_theor = x_variance * x_fft_theor # include time-series variance fft_theor = np.sqrt(y_fft_theor * x_fft_theor) signif = fft_theor if len(np.atleast_1d(dof)) == 1: if dof == -1: dof = dofmin if sigtest == 0: # no smoothing, DOF=dofmin [Sec.4] dof = dofmin chisquare = chisquare_inv(siglvl, dof) / dof signif = fft_theor * chisquare # [Eqn(18)] elif sigtest == 1: # time-averaged significance if len(np.atleast_1d(dof)) == 1: dof = np.zeros(J1) + dof dof[dof < 1] = 1 dof = dofmin * np.sqrt(1 + (dof * dt / gamma_fac / scale)**2) # [Eqn(23)] dof[dof < dofmin] = dofmin # minimum DOF is dofmin for a1 in range(0, J1 + 1): chisquare = chisquare_inv(siglvl, dof[a1]) / dof[a1] signif[a1] = fft_theor[a1] * chisquare # print("Chi squared: %e " % chisquare) elif sigtest == 2: # time-averaged significance if len(dof) != 2: print( 'ERROR: DOF must be set to [S1,S2], the range of scale-averages' ) if Cdelta == -1: print('ERROR: Cdelta & dj0 not defined for ' + mother + ' with param = ' + str(param)) s1 = dof[0] s2 = dof[1] avg = np.logical_and(scale >= s1, scale < s2) # scales between S1 & S2 navg = np.sum( np.array(np.logical_and(scale >= s1, scale < s2), dtype=int)) if navg == 0: print('ERROR: No valid scales between ' + str(s1) + ' and ' + str(s2)) Savg = 1. / np.sum(1. / scale[avg]) # [Eqn(25)] Smid = np.exp((np.log(s1) + np.log(s2)) / 2.) # power-of-two midpoint dof = (dofmin * navg * Savg / Smid) * np.sqrt( 1 + (navg * dj / dj0)**2) # [Eqn(28)] fft_theor = Savg * np.sum(fft_theor[avg] / scale[avg]) # [Eqn(27)] chisquare = chisquare_inv(siglvl, dof) / dof signif = (dj * dt / Cdelta / Savg) * fft_theor * chisquare # [Eqn(26)] else: print('ERROR: sigtest must be either 0, 1, or 2') return signif def lagWaveletCoherency(tc1, tc2, fps=10, lag=5): for i in np.arange(0, lag + 1): if i == 0: #initialize for proper shape cor, coh, xwt, phase, xwt_sig = waveletCoherence(tc1, tc2) # create ouputs lag_cor = np.zeros( (2 * lag + 1, cor.shape[0], cor.shape[1])) * np.nan lag_coh = np.zeros( (2 * lag + 1, cor.shape[0], cor.shape[1])) * np.nan lag_xwt = np.zeros( (2 * lag + 1, cor.shape[0], cor.shape[1])) * np.nan lag_phase = np.zeros( (2 * lag + 1, cor.shape[0], cor.shape[1])) * np.nan lag_xwt_sig = np.zeros( (2 * lag + 1, cor.shape[0], cor.shape[1])) * np.nan #store in the proper index lag_cor[lag] = cor lag_coh[lag] = coh lag_xwt[lag] = xwt lag_phase[lag] = phase lag_xwt_sig[lag] = xwt_sig else: #finish up the remaining lags (right shifted) lag_cor[lag + i, : , i:], lag_coh[lag + i, : , i:], lag_xwt[lag + i, : , i:],\ lag_phase[lag + i, : , i:], lag_xwt_sig[lag + i, : , i:] = waveletCoherence(tc1[i:],tc2[:-i], fps = fps) #(left shifted) lag_cor[lag - i, : , :-i],lag_coh[lag - i, : , :-i],lag_xwt[lag - i, : , :-i],\ lag_phase[lag - i, : , :-i],lag_xwt_sig[lag - i, : , :-i] = waveletCoherence(tc1[:-i],tc2[i:], fps = fps) return lag_cor, lag_coh, lag_xwt, lag_phase, lag_xwt_sig class waveletAnalysis: def __init__(self, data, fps, **kwargs): """ Initialize the wavelet parameters """ assert data.ndim == 1, 'Time series is the wrong shape. It should be a 1-dim vector' self.dataCopy = data self.data = (data - np.mean(data)) / np.std(data, ddof=1) self.n = len(self.data) self.cadence = 1 / fps self.time = np.arange(self.n) * self.cadence #default parameters #print/ plot statements self.verbose = kwargs.get('verbose', False) self.plot = kwargs.get('plot', False) #wavelet parameters self.mother = kwargs.get('mother', 'MORLET') self.param = kwargs.get('param', 4) self.j1 = kwargs.get('j1', 80) self.pad = kwargs.get('pad', 1) self.dj = kwargs.get('dj', 0.125) self.s0 = kwargs.get('s0', 2 * self.cadence) #noies modeling parameter self.siglvl = kwargs.get('siglvl', 0.95) self.lag1 = 0.5 * (lag_n_autocorr(data, 1) + lag_n_autocorr(data, 2)) # self.lag1 = self.lagNAutoCorr(data, 1) self.waveletTransform() def waveletTransform(self): # Wavelet transform: self.wave, self.period, self.scale, self.coi = \ wavelet(self.data, self.cadence, self.pad, self.dj, self.s0, self.j1, self.mother, self.param) if len(self.time) != len(self.coi): self.coi = self.coi[1:] self.power = (np.abs(self.wave))**2 # compute wavelet power spectrum # Significance levels: (variance=1 for the normalized data) self.signif = wave_signif(([1.0]), dt=self.cadence, sigtest=0, scale=self.scale, \ lag1=self.lag1, mother=self.mother, siglvl = self.siglvl) self.sig95 = self.signif[:, np.newaxis].dot( np.ones(self.n)[np.newaxis, :]) # expand signif --> (J+1)x(N) array self.sig95 = self.power / self.sig95 # where ratio > 1, power is significant return def inverseWaveletTransform(self, waveFlt=None, C_d=1.151, psi0=np.pi**(-0.25) * 0.85): """ Supply own C_d and psi0 if not using a DOG m = 2 wavelet. """ if waveFlt == None: waveFlt = self.waveFlt InvTranform = np.zeros(self.n) tansformConstant = ((self.dj * math.sqrt(self.cadence)) / (C_d * psi0) ) # Reconstruction constant. # For more information, see article: "A Practical Guide to Wavelet Analysis", <NAME> and <NAME>, 1998. for i in range(waveFlt.shape[0]): waveFlt[i, :] /= math.sqrt(self.period[i]) for i in range(self.n): InvTranform[i] = np.sum(np.real(waveFlt[:, i]), axis=0) self.dataFlt = tansformConstant * InvTranform def plotPower(self, ax=None): """ ax is the subplot argument. """ self.levels = [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16] colors = [ 'navy', 'slateblue', 'c', 'g', 'gold', 'orange', 'tomato', 'crimson' ] if ax == None: f = plt.figure() f, ax = plt.subplots(1) else: ax = np.ravel(ax)[0] # Max period is fourier_factor*S0*2^(j1*dj), fourier_factor = 3.97383530632 CS = ax.contourf(self.time, self.period, np.log2(self.power), len(self.levels), colors=colors) im = ax.contourf(CS, levels=np.log2(self.levels), colors=colors) ax.set_xlabel('Time (s)') ax.set_ylabel('Period (s)') ax.set_title('Wavelet Power Spectrum') # 95 significance contour, levels at -99 (fake) and 1 (95# signif) ax.contour(self.time, self.period, self.sig95, [-99, 1], colors='k') # # cone-of-influence, anything "below" is dubious ax.fill_between(self.time, np.max(self.period), self.coi, alpha=0.5, facecolor='white', zorder=3) ax.plot(self.time, self.coi, 'k') # # format y-scale # different matplotlib versions available for python < 3.8. try: ax.set_yscale('log', base=2, subs=None) except ValueError: ax.set_yscale('log', basey=2, subsy=None) ax.set_ylim([np.min(self.period), np.max(self.period)]) axy = ax.yaxis axy.set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.ticklabel_format( axis='y', style='plain') ## causes issues with tkinter mpl canvas ax.invert_yaxis() # set up the size and location of the colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("bottom", size="5%", pad=0.5) plt.colorbar(im, cax=cax, orientation='horizontal') def waveletFilter(self, lowerPeriod=None, upperPeriod=None, movement_vector=None, sigLevel=1): """ NAME: waveletFilter(wave, sig95, l_s = 0, u_s = 29) USE: This does a band pass and power filtering on the wavelet period-frequency domain. Give it the wavelet amplitude array, the power significance array, and the upper and lower scales that will be used for filtering. RETURNS: The filtered wavelet amplitude array. MOD: 2016-04-13 # WAVELET SCALE CALCULATOR ################# # jth scale indicie = ln(S/S0)/(dJ * ln(2)) ################################## """ self.waveFlt = self.wave.copy() # Band pass filter # Proporionally decreases power in specific wavelengths with respect to a 'motion vector' # More motion, more severe the filtration of power in the given frequencies if movement_vector is not None: movement_vector -= movement_vector.min() movement_vector /= movement_vector.max() movement_vector = (1. - movement_vector) if lowerPeriod != None: if lowerPeriod > self.period[0]: lower_ind = np.where(self.period < lowerPeriod)[0][-1] #print('Lower Period: ', self.period[lower_ind], 'Upper Freq: ', 1/self.period[lower_ind]) self.waveFlt[: lower_ind, :] = self.waveFlt[:lower_ind, :] * movement_vector if upperPeriod != None: if upperPeriod < self.period[-1]: upper_ind = np.where(self.period > upperPeriod)[0][0] #print('Upper Period: ', self.period[upper_ind], 'Lower Freq: ', 1/self.period[upper_ind]) self.waveFlt[upper_ind:, :] = self.waveFlt[ upper_ind:, :] * movement_vector # Band pass filter # Zero out parts of the wavlet space that we don't want to reconstruct. else: if lowerPeriod != None: if lowerPeriod > self.period[0]: lower_ind = np.where(self.period < lowerPeriod)[0][-1] #print('Lower Period: ', self.period[lower_ind], 'Lower Freq: ', 1/self.period[lower_ind]) self.waveFlt[:lower_ind, :] = 0 if upperPeriod != None: if upperPeriod < self.period[-1]: upper_ind = np.where(self.period > upperPeriod)[0][0] #print('Upper Period: ', self.period[upper_ind], 'Upper Freq: ', 1/self.period[upper_ind]) self.waveFlt[upper_ind:, :] = 0 # Significance filter notSigInd = np.where( self.sig95 < sigLevel ) # Only pass data that has power of (100% - sigThreshold). Usually sigThreshold is 95%. Was 0.25. self.waveFlt[notSigInd] = 0 ############################################ def nanCOI(self): # get rid of all values outside the cone of influence # wave = np.log2(wave) self.nanCOImat = self.power.copy() for i in range(self.power.shape[1]): cutoff = np.where(self.coi[i] < self.period) self.nanCOImat[cutoff, i] = np.nan def nanSig(self): # get rid of all values that are not significant self.nanSigmat = self.wave self.nanSigmat[np.where(wavelet.sig95 < 1)] = np.nan def sigLost(self, slope, intercept): loss = 1 - (intercept + slope * self.n * self.cadence) / intercept if self.verbose: print('We have lost approximately {0:.2f} % power over the movie'. format(loss[0] * 100)) return loss def binSignal(self, binsz=30): # binsz in seconds binnum = (self.n * self.cadence) // binsz padsz = math.ceil(float(self.n) / binnum) * binnum - self.n binsignal = np.append(self.signal, np.zeros(int(padsz)) * np.nan) binsignal = np.nanmean(binsignal.reshape(int(binnum), -1), axis=1) bintime = np.arange(binsz, self.n * self.cadence + 1, binsz) - binsz / 2 return bintime, binsignal def familySig(self, sigList=[0.9, 0.95, 0.99, 0.999], dof=-1, sigtest=0): # plot a family of significance curves for visualization and analysis if isinstance(sigList, float): if sigtest < 2: fam_signif = np.zeros((1, self.scale.shape[0])) * np.nan if sigtest == 2: fam_signif = np.nan fam_signif = wave_signif([1.0], dt=self.cadence, scale=self.scale, sigtest=sigtest, lag1=self.lag1, siglvl=sigList, dof=dof, mother=self.mother, param=self.param) if isinstance(sigList, list): if sigtest < 2: fam_signif = np.zeros( (len(sigList), self.scale.shape[0])) * np.nan if sigtest == 2: fam_signif = np.zeros((len(sigList), 1)) * np.nan for i, sig in enumerate(sigList): fam_signif[i] = wave_signif([1.0], dt=self.cadence, scale=self.scale, sigtest=sigtest, lag1=self.lag1, siglvl=sig, dof=dof, mother=self.mother, param=self.param) return np.squeeze(fam_signif), np.squeeze(sigList) def sumAcrossPeriod(self, perLim=[0, 100]): #sum wavelet power across select periods if self.verbose: print('Summing across {0} to {1} periods on wavelet run with mother {2} at paramter {3}'.\ format(perLim[0], perLim[1], self.mother, self.param) ) cdelta = None if self.mother == 'MORLET' and self.param == 6: cdelta = 0.776 elif self.mother == 'MORLET' and self.param == 4: cdelta = 1.151 elif self.mother == 'DOG' and self.param == 2: cdelta = 3.541 elif self.mother == 'DOG' and self.param == 6: cdelta = 1.966 else: assert cdelta != None, 'Unknown c value based on wavelet choice' l_per_lim = np.min(np.where(perLim[0] < self.period)) u_per_lim = np.min(np.where(perLim[1] < self.period)) if not hasattr(self, 'nanCOImat'): self.nanCOI() period_sum = (self.dj * self.cadence) / cdelta * np.nansum( (self.nanCOImat[l_per_lim:u_per_lim]**2 / self.period[l_per_lim:u_per_lim, None]), axis=0) return np.squeeze(period_sum) def globalWaveletSpectrum(self): if self.verbose: print('Assessing wavelet mother {0} at paramter {1}'.format( self.mother, self.param)) # calulate the global self spectrum self.nanCOI() # if np.sum(~np.isnan(self.nanCOImat))!=0: self.period_size = np.sum(~np.isnan(self.nanCOImat), axis=1) nan_ind = np.where(self.period_size == 0)[0] self.gws = np.zeros_like(self.period) * np.nan if nan_ind.any(): self.gws[:nan_ind[0]] = np.nanmean(self.nanCOImat[:nan_ind[0], :], axis=1) self.gws[nan_ind] = 0 else: self.gws = np.nanmean(self.nanCOImat, axis=1) if self.period_size.shape[0] != self.period.shape[0]: dif = self.period_size.shape[0] - self.period.shape[0] if dif < 0: self.period_size = np.append(self.period_size, np.zeros(np.abs(dif))) else: self.period_size = self.period_size[:self.period.shape[0]] # calculate the average significance self.gws_sig, self.gws_sigList = self.familySig(sigList=[0.95], dof=self.period_size, sigtest=1) if self.verbose: print('Auto-correlation value: {0:.4g}'.format(self.lag1)) # determine fourier wavelength if self.mother == 'DOG': self.flambda = (2 * np.pi * 1 / self.period) / np.sqrt(self.param + .5) if self.mother == 'MORLET': self.flambda = (4 * np.pi * 1 / self.period) / ( self.param + np.sqrt(2 + np.square(self.param))) mx_wav, mx_gws, mx_sig = local_max(self.period, self.gws, self.gws_sig) fl_wav, mx_gws, mx_sig = local_max(self.flambda, self.gws, self.gws_sig) lwav = [] lgws = [] lfl = [] for i in range(len(mx_wav)): if mx_gws[i] > mx_sig[i]: lwav.append(mx_wav[i]) lgws.append(mx_gws[i]) lfl.append(fl_wav[i]) lwav_inv = [x**(-1) for x in lwav] self.gws_localmax_power = lgws self.gws_localmax_freq = lfl #find the lowest and highest frequencies that are still significant hiwav = np.nan hival = np.nan lowav = np.nan loval = np.nan if np.where(self.gws > self.gws_sig)[0].shape[0] > 0: hival = self.gws[np.where(self.gws > self.gws_sig)][0] hiwav = self.flambda[np.where(self.gws > self.gws_sig)][0] loval = self.gws[np.where(self.gws > self.gws_sig)][-1] lowav = self.flambda[np.where(self.gws > self.gws_sig)][-1] self.gws_lo_high_freq = [(lowav, loval), (hiwav, hival)] if nan_ind.any(): self.gws[nan_ind] = np.nan if self.verbose: print('Low frequency: ', lowav) print('High freqency: ', hiwav) if self.plot: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharey=True) nyq = 0.5 * 1 / self.cadence linetype = ['-', '-.', '--', ':'] fam_signif, sigList = self.familySig(dof=self.period_size, sigtest=1) #self period graph ax1.plot(self.period, self.gws) ax1.plot(lwav, lgws, 'ro') for i in range(len(sigList)): if i >= len(linetype) - 1: j = len(linetype) - 1 else: j = i ax1.plot(self.period, fam_signif[i], label=sigList[i], ls=linetype[j], color='k') if not lgws: ax1.set_ylim([0, 10]) else: ax1.set_ylim([0, np.ceil(max(lgws))]) if not lwav or np.ceil(max(lwav)) < 10: ax1.set_xlim([0, 10]) else: ax1.set_xlim([0, np.ceil(max(lwav))]) # ax1.legend() ax1.set_xlabel(' Wavelet {0} {1} period(s)'.format( self.mother, self.param)) ax1.set_ylabel('normalized power (to variance)') ax1.set_title('Power spectrum by period') # plt.show() # #self frequency graph # plt.plot(1/self.period, gws) # plt.plot(lwav_inv,lgws, 'ro') # for i in range(len(sigList)): # if i >= len(linetype) - 1: # j = len(linetype) - 1 # else: # j = i # plt.plot(1/self.period, fam_signif[i], label = sigList[i], ls = linetype[j], color='k') # if not lgws: # plt.ylim([0,10]) # else: # plt.ylim([0,np.ceil(max(lgws))]) # if not lwav_inv or np.ceil(max(lwav_inv)) < nyq: # plt.xlim([0,nyq]) # else: # plt.xlim([0, np.ceil(max(lwav_inv))]) # plt.xlabel(self.mother + ' frequency') # plt.ylabel('normalized power (to variance)') # plt.legend() # plt.show() #Fourier space lambda ax2.plot(self.flambda, self.gws) for i in range(len(sigList)): if i >= len(linetype) - 1: j = len(linetype) - 1 else: j = i ax2.plot(self.flambda, fam_signif[i], label=sigList[i], ls=linetype[j], color='k') if not lgws: ax2.set_ylim([0, 10]) else: ax2.set_ylim([0, np.ceil(max(lgws))]) if not lfl or np.ceil(max(lfl)) < nyq: ax2.set_xlim([0, nyq]) else: ax2.set_xlim([0, np.ceil(max(lfl))]) ax2.plot(lowav, loval, 'go', label='lowSigFreq') ax2.plot(hiwav, hival, 'bo', label='highSigFreq') ax2.plot(lfl, lgws, 'ro', label='localMax') ax2.legend() ax2.set_xlabel('Fourier frquency') ax2.set_title('Power spectrum by frequency') # ax2.set_ylabel('normalized power (to variance)') plt.tight_layout() plt.show() # return lfl, lgws, [lowav,loval], [hiwav, hival] def averageWaveletPower(self, periodLim=[0.25, 8]): assert len( periodLim) == 2, 'Period limit list must only include 2 values' if self.verbose: print('Creating scaled average of the timeseries, \ created with wavelet mother {0} at paramter {1}'.format( self.mother, self.param)) self.period_sum = self.sumAcrossPeriod(perLim=periodLim) if self.period_sum.shape[0] != self.time.shape[0]: dif = self.period_sum.shape[0] - self.time.shape[0] if dif < 0: self.period_sum = np.append(self.period_sum, np.zeros(np.abs(dif))) else: self.period_sum = self.period_sum[:self.period.shape[0]] # calculate the average significance # sig = wavelet.signif/np.sqrt(1+((self.period_size * wavelet.cadence)/(gamma * wavelet.period))) self.sig_period_sum, _ = self.familySig(sigList=[0.95], dof=periodLim, sigtest=2) #find coordinates of local max values mx_wav, mx_gws = local_max(self.time, self.period_sum) #Return only those above significance threshold ltime = [] lgws = [] for i in range(len(mx_wav)): if mx_gws[i] > self.sig_period_sum: ltime.append(mx_wav[i]) lgws.append(mx_gws[i]) if self.plot: sigline = np.zeros(self.period_sum.shape[0]) + self.sig_period_sum plt.plot(self.time, self.period_sum) plt.plot(self.time, np.squeeze(sigline), 'k--') plt.plot(ltime, lgws, 'ro') # plt.xlim([150, 180]) # plt.ylim([0, 20]) # plt.xlim([0,8]) # plt.ylim([0,1]) plt.show() self.events = ltime self.events_value = lgws def tsSignal(self, binSig=False, periodLim=[0.5, 4]): ''' Using wavelet transforms to assess how the power of signal changes over time ''' self.binSig = binSig assert len(periodLim) == 2, 'Period limits are wrong size' #determine the time and power across neural signal periods self.signal = self.sumAcrossPeriod(perLim=periodLim) self.signal_sig, _ = self.familySig(sigList=[0.95], dof=periodLim, sigtest=2) if self.binSig: bintime, binsignal = self.binSignal() self.slope, self.intercept = linear_regression(bintime, binsignal, verbose=self.verbose) self.signalloss = self.sigLost(self.slope, self.intercept) else: self.slope, self.intercept = linear_regression(self.time, self.signal, verbose=self.verbose) self.signalloss = self.sigLost(self.slope, self.intercept) if self.plot: plt.plot(self.time, self.signal, label='signal power') plt.plot(self.time, np.squeeze(np.ones(self.n) * self.signal_sig), 'k--', label='{0} sign level'.format(self.siglvl)) abline(self.slope, self.intercept, self.n * self.cadence, label='trend', color=None) if self.binSig: plt.scatter(bintime, binsignal, color='r', label='binvalues') plt.xlabel('time(s)') plt.ylabel('summed power (period: {0} - {1})'.format( periodLim[0], periodLim[1])) plt.legend() plt.show() def noiseFilter(self, lowerPeriod=None, upperPeriod=10, movement_vector=None, sigLevel=0.25): if lowerPeriod is None: lowerPeriod = 2 * self.cadence #nyquist sampling rate if movement_vector is not None: movement_vector = np.array(np.squeeze(movement_vector), dtype='float64') assert movement_vector.shape[ 0] == self.n, 'Movement vector is not the same size as the data' self.waveletFilter(lowerPeriod=lowerPeriod, upperPeriod=upperPeriod, movement_vector=movement_vector, sigLevel=sigLevel) self.inverseWaveletTransform() filtData = (self.dataFlt *
np.std(self.dataCopy, ddof=1)
numpy.std
# Copyright 2021 The NetKet Authors - All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import jax.numpy as jnp import pytest import numpy as np import scipy.integrate as sci from netket.experimental.dynamics import Euler, Heun, Midpoint, RK4, RK12, RK23, RK45 from netket.experimental.dynamics._rk_tableau import ( NamedTableau, bt_feuler, bt_heun, bt_midpoint, bt_rk12, bt_rk23, bt_rk4, bt_rk4_dopri, bt_rk4_fehlberg, ) tableaus = { "bt_feuler": bt_feuler, "bt_heun": bt_heun, "bt_midpoint": bt_midpoint, "bt_rk12": bt_rk12, "bt_rk23": bt_rk23, "bt_rk4": bt_rk4, "bt_rk4_dopri": bt_rk4_dopri, "bt_rk4_fehlberg": bt_rk4_fehlberg, } explicit_fixed_step_solvers = { "Euler": Euler, "Heun": Heun, "Midpoint": Midpoint, "RK4": RK4, } explicit_adaptive_solvers = { "RK12": RK12, "RK23": RK23, "RK45": RK45, } @pytest.mark.parametrize("tableau", tableaus) def test_tableau(tableau: str): tableau = tableaus[tableau] # type: NamedTableau assert tableau.name != "" td = tableau.data for x in td.a, td.b, td.c: assert np.all(np.isfinite(x)) assert td.a.ndim == 2 # a should be strictly upper triangular np.testing.assert_array_equal(np.triu(td.a), np.zeros_like(td.a)) # c's should be in [0, 1] assert np.all(td.c >= 0.0) assert np.all(td.c <= 1.0) assert len(td.order) in (1, 2) assert len(td.order) == td.b.ndim assert td.a.shape[0] == td.a.shape[1] assert td.a.shape[0] == td.b.shape[-1] assert td.a.shape[0] == td.c.shape[0] if len(td.order) == 2: assert td.b.shape[0] == 2 @pytest.mark.parametrize("method", explicit_fixed_step_solvers) def test_ode_solver(method): def ode(t, x, **_): return -t * x dt = 0.01 n_steps = 100 solver = explicit_fixed_step_solvers[method](dt=dt) y0 = np.array([1.0]) times = np.linspace(0, n_steps * dt, n_steps, endpoint=False) sol = sci.solve_ivp(ode, (0.0, n_steps * dt), y0, t_eval=times) y_ref = sol.y[0] solv = solver(ode, 0.0, y0) t = [] y_t = [] for _ in range(n_steps): print(solv.t, solv.y) t.append(solv.t) y_t.append(solv.y) solv.step() y_t = np.asarray(y_t) assert np.all(np.isfinite(t)) assert np.all(np.isfinite(y_t)) np.testing.assert_allclose(t, times) # somewhat arbitrary tolerances, that may still help spot # errors introduced later rtol = { "Euler": 1e-2, "RK4": 5e-4, }.get(method, 1e-3) np.testing.assert_allclose(y_t[:, 0], y_ref, rtol=rtol) @pytest.mark.parametrize("solver", explicit_adaptive_solvers) def test_adaptive_solver(solver): solver = explicit_adaptive_solvers[solver] tol = 1e-7 def ode(t, x, **_): return -t * x y0 = np.array([1.0]) solv = solver(dt=0.2, adaptive=True, atol=0.0, rtol=tol)(ode, 0.0, y0) t = [] y_t = [] last_step = -1 while solv.t <= 2.0: print(solv._rkstate) if solv._rkstate.step_no != last_step: last_step = solv._rkstate.step_no t.append(solv.t) y_t.append(solv.y) solv.step() y_t =
np.asarray(y_t)
numpy.asarray
import numpy as np import matplotlib.pyplot as plt import datetime from qutip import Qobj, identity, sigmax, sigmay, sigmaz, sigmam, tensor from qutip.superoperator import liouvillian, sprepost from qutip.qip.operations import cnot, cr import qutip.logging_utils as logging logger = logging.get_logger() #Set this to None or logging.WARN for 'quiet' execution log_level = logging.INFO #QuTiP control modules import qutip.control.pulseoptim as cpo #example_name = 'Lindblad' #The Hamiltoninan model Sx = sigmax() Sy = sigmay() Sz = sigmaz() #Sm = sigmam() Si = identity(2) sm1 = tensor(sigmam(),Si) sm2 = tensor(Si,sigmam()) sz1 = tensor(Sz,Si) sz2 = tensor(Si,Sz) #cnot gate cnot_gate = cnot() U_targ = cr(phi=-np.pi/2) U0 = identity(4) #Hamiltonian parameters #<NAME> w0 = 5. #GHz w1 = 4.844 #GHz del12 = w0-w1 #GHz J = (0.0083)/(2*np.pi) #GHz coup = (J*0.25/del12) t01 = (85.86/1e-3) #ns t02 = (108.53/1e-3) #ns t11 = (113.13/1e-3) #ns t12 = (72.74/1e-3) #ns # Time allowed for the evolution #evo_times = [140,150,160,175,195] evo_times = [1312] #evo_times = [384] #evo_times = [350] # Number of time slots #n_ts = int(float(evo_time/0.222)) #H0 = -(2.22e-1/2.)*tensor(Sz,Si)*0.#toronto #Hc = [(-(2.22e-1/2.)*tensor(Sz,Si)),(0.5*tensor(Si,Sx)),-(0.5*0.01*tensor(Sz,Sx))] #H0 = 0.5*tensor(Sz,Sx)+ 0.5*tensor(Sx,Si) #Hc = [tensor(Si,Sx),tensor(Si,Sy),tensor(Sx,Si),tensor(Sy,Si)] #H0 = w0*tensor(Sz,Si)+w1*tensor(Si,Sz) H0 = -0.5*del12*tensor(Sz,Si) #(-J*0.25/del12)* #Hc = [tensor(Sz,Sx),tensor(Si,Sx),tensor(Si,Sy),tensor(Sy,Si)] #Hc = [tensor(Sz,Sx),tensor(Si,Sx),tensor(Si,Sy),tensor(Si,Sz),tensor(Sz,Si),tensor(Sz,Sy),tensor(Sz,Sz)] #ctrl_term = (tensor(Sz,Si)+tensor(Si,Sx)-tensor(Sz,Sx))#tensor(Sz,Sx)+tensor(Si,Sx)+tensor(Sz,Si) #Hc = [ctrl_term]#,tensor(Sz,Sz),tensor(Si,Sx),tensor(Si,Sy)] Hc = [tensor(Si,Sx), tensor(Si,Sy), tensor(Si,Sz), #tensor(identity(2), sigmax()), #tensor(identity(2), sigmay()), #tensor(identity(2), sigmaz()), tensor(Sz, Sx) + tensor(Sz, Sy) + tensor(Sz, Sz)] #Hc = [tensor(Si,Sx),tensor(Sx,Si),tensor(Sx,Sx),tensor(Sy,Sy)] gamma01 = 1/t01 #ns-1 t1 qubit 1 gamma02 = 1/t02 #ns-1 t1 qubit 2 gamma11 = 1/t11 gamma12 = 1/t12 L0 = liouvillian(H0,[
np.sqrt(gamma01)
numpy.sqrt
# ---------------------------------------------------------------------------- # Copyright 2016 Nervana Systems Inc. # 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. # ---------------------------------------------------------------------------- """ Defines PASCAL_VOC datatset handling """ from __future__ import division from builtins import zip, range import numpy as np import os import xml.etree.ElementTree as ET import tarfile from PIL import Image import abc from generate_anchors import generate_all_anchors from neon.data.datasets import Dataset from neon.util.persist import save_obj, load_obj, get_data_cache_dir from neon import logger as neon_logger # From Caffe: # Pixel mean values (BGR order) as a (1, 1, 3) array # These are the values originally used for training VGG16 # __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) FRCN_PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # the loaded image will be (H, W, C) need to make it (C, H, W) FRCN_IMG_DIM_SWAP = (2, 0, 1) FRCN_EPS = 1.0 BB_XMIN_IDX = 0 BB_YMIN_IDX = 1 BB_XMAX_IDX = 2 BB_YMAX_IDX = 3 NORMALIZE_BBOX_TARGETS = False BBOX_NORMALIZE_TARGETS_PRECOMPUTED = True # True means the values below are used BBOX_NORMALIZE_MEANS = [0.0, 0.0, 0.0, 0.0] # taken from py-faster-rcnn caffe implementation BBOX_NORMALIZE_STDS = [0.1, 0.1, 0.2, 0.2] ASPECT_RATIO_GROUPING = True DEBUG = False dataset_meta = { 'test-2007': dict(size=460032000, file='VOCtest_06-Nov-2007.tar', url='http://host.robots.ox.ac.uk/pascal/VOC/voc2007', subdir='VOCdevkit/VOC2007'), 'trainval-2007': dict(size=451020800, file='VOCtrainval_06-Nov-2007.tar', url='http://host.robots.ox.ac.uk/pascal/VOC/voc2007', subdir='VOCdevkit/VOC2007'), 'trainval-2012': dict(size=2000000000, file='VOCtrainval_11-May-2012.tar', url='http://host.robots.ox.ac.uk/pascal/VOC/voc2012', subdir='VOCdevkit/VOC2012'), } class ObjectLocalization(Dataset): """ Base class for loading object localization data in the PASCAL_VOC format. Data must include: 1. index file of images 2. XML file for each image Args: n_mb (int, optional): how many minibatch to iterate through, can use value smaller than nbatches for debugging path (string, optional): path to the data directory. img_per_batch (int, optional): how many images processed per batch rpn_rois_per_img (int, optional): how many rois to pool from each image to train rpn frcn_rois_per_img (int, optional): how many rois to sample to train frcnn shuffle (boolean, optional): shuffle the image order during training rebuild_cache (boolean, optional): force the cache to be built from scratch subset_pct (float, optional): value between 0 and 100 indicating what percentage of the dataset partition to use. Defaults to 100. """ MAX_SIZE = 1000 MIN_SIZE = 600 FRCNN_ROI_PER_IMAGE = 128 # number of rois to train (needed to initialize global buffers) RPN_ROI_PER_IMAGE = 256 # number of anchors per image IMG_PER_BATCH = 1 # number of images per batch CLASSES = None # list of CLASSES e.g. ['__background__', 'car', 'people',..] SCALE = 1.0 / 16 # scaling factor of the image layers (e.g. VGG) # anchor variables RATIOS = [0.5, 1, 2] # aspect ratios to generate SCALES = [128, 256, 512] # box areas to generate NEGATIVE_OVERLAP = 0.3 # negative anchors have < 0.3 overlap with any gt box POSITIVE_OVERLAP = 0.7 # positive anchors have > 0.7 overlap with at least one gt box FG_FRACTION = 0.5 # at most, positive anchors are 0.5 of the total rois def __init__(self, path='.', n_mb=None, img_per_batch=None, conv_size=None, rpn_rois_per_img=None, frcn_rois_per_img=None, add_flipped=False, shuffle=False, deterministic=False, rebuild_cache=False, subset_pct=100, mock_db=None): self.batch_index = 0 self.path = path self.mock_db = mock_db # how many ROIs per image self.rois_per_img = rpn_rois_per_img if rpn_rois_per_img else self.RPN_ROI_PER_IMAGE self.img_per_batch = img_per_batch if img_per_batch else self.IMG_PER_BATCH self.rois_per_batch = self.rois_per_img * self.img_per_batch # how many ROIs to use to train frcnn self.frcn_rois_per_img = frcn_rois_per_img if frcn_rois_per_img \ else self.FRCNN_ROI_PER_IMAGE assert self.img_per_batch == 1, "Only a minibatch of 1 is supported." self.num_classes = len(self.CLASSES) self._class_to_index = dict(list(zip(self.CLASSES, list(range(self.num_classes))))) # shape of the final conv layer if conv_size: self._conv_size = conv_size else: self._conv_size = int(np.floor(self.MAX_SIZE * self.SCALE)) self._feat_stride = 1 / float(self.SCALE) self._num_scales = len(self.SCALES) * len(self.RATIOS) self._total_anchors = self._conv_size * self._conv_size * self._num_scales self.shuffle = shuffle self.deterministic = deterministic self.add_flipped = add_flipped # load the configure the dataset paths self.config = self.load_data() # annotation metadata self._annotation_file_ext = '.xml' self._annotation_obj_tag = 'object' self._annotation_class_tag = 'name' self._annotation_xmin_tag = 'xmin' self._annotation_xmax_tag = 'xmax' self._annotation_ymin_tag = 'ymin' self._annotation_ymax_tag = 'ymax' # self.rois_per_batch is 128 (2*64) ROIs # But the image path batch size is self.img_per_batch # need to control the batch size here assert self.img_per_batch is 1, "Only a batch size of 1 image is supported" neon_logger.display("Backend batchsize is changed to be {} " "from Object Localization dataset".format( self.img_per_batch)) self.be.bsz = self.img_per_batch # 0. allocate buffers self.allocate() if not self.mock_db: # 1. read image index file assert os.path.exists(self.config['image_path']), \ 'Image index file does not exist: {}'.format(self.config['image_path']) with open(self.config['index_path']) as f: self.image_index = [x.strip() for x in f.readlines()] num_images = len(self.image_index) self.num_image_entries = num_images * 2 if self.add_flipped else num_images self.ndata = self.num_image_entries * self.rois_per_img else: self.num_image_entries = 1 self.ndata = self.num_image_entries * self.rois_per_img assert (subset_pct > 0 and subset_pct <= 100), ('subset_pct must be between 0 and 100') if n_mb is not None: self.nbatches = n_mb else: self.nbatches = int(self.num_image_entries / self.img_per_batch * subset_pct / 100) self.cache_file = self.config['cache_path'] if os.path.exists(self.cache_file) and not rebuild_cache and not self.mock_db: self.roi_db = load_obj(self.cache_file) neon_logger.display('ROI dataset loaded from file {}'.format(self.cache_file)) elif not self.mock_db: # 2. read object Annotations (XML) roi_db = self.load_roi_groundtruth() if(self.add_flipped): roi_db = self.add_flipped_db(roi_db) # 3. construct acnhor targets self.roi_db = self.add_anchors(roi_db) if NORMALIZE_BBOX_TARGETS: # 4. normalize bbox targets by class self.roi_db = self.normalize_bbox_targets(self.roi_db) save_obj(self.roi_db, self.cache_file) neon_logger.display('wrote ROI dataset to {}'.format(self.cache_file)) else: assert self.mock_db is not None roi_db = [self.mock_db] self.roi_db = self.add_anchors(roi_db) # 4. map anchors back to full canvas. # This is neccessary because the network outputs reflect the full canvas. # We cache the files in the unmapped state (above) to save memory. self.roi_db = unmap(self.roi_db) def allocate(self): # 1. allocate backend tensor for the image self.image_shape = (3, self.MAX_SIZE, self.MAX_SIZE) self.img_np = np.zeros( (3, self.MAX_SIZE, self.MAX_SIZE, self.be.bsz), dtype=np.float32) self.dev_X_img = self.be.iobuf(self.image_shape, dtype=np.float32) self.dev_X_img_chw = self.dev_X_img.reshape( 3, self.MAX_SIZE, self.MAX_SIZE, self.be.bsz) self.shape = self.image_shape # For training, the RPN needs: # 1. bounding box target coordinates # 2. bounding box target masks (keep positive anchors only) self.dev_y_bbtargets = self.be.zeros((self._total_anchors * 4, 1)) self.dev_y_bbtargets_mask = self.be.zeros((self._total_anchors * 4, 1)) # 3. anchor labels of objectness # 4. objectness mask (ignore neutral anchors) self.dev_y_labels_flat = self.be.zeros((1, self._total_anchors), dtype=np.int32) self.dev_y_labels_onehot = self.be.zeros((2, self._total_anchors), dtype=np.int32) self.dev_y_labels = self.be.zeros((2 * self._total_anchors, 1), dtype=np.int32) self.dev_y_labels_mask = self.be.zeros((2 * self._total_anchors, 1), dtype=np.int32) # For training, Fast-RCNN needs: # 1. class labels # 2. bbox targets # The above are computed during fprop by the ProposalLayer, # so here we create the buffers to pass that to layer. self.dev_y_frcn_labels = self.be.zeros( (self.num_classes, self.frcn_rois_per_img), dtype=np.int32) self.dev_y_frcn_labels_mask = self.be.zeros( (self.num_classes, self.frcn_rois_per_img), dtype=np.int32) self.dev_y_frcn_bbtargets = self.be.zeros( (self.num_classes * 4, self.frcn_rois_per_img), dtype=np.float32) self.dev_y_frcn_bbmask = self.be.zeros( (self.num_classes * 4, self.frcn_rois_per_img), dtype=np.float32) # we also create some global buffers needed by the ProposalLayer # 1. image_shape # 2. gt_boxes # 3. number of gtboxes # 4. class label for each gt box # 5. image scale # 6. indexes of anchors actually generated for image out of 62x62 possible self.im_shape = self.be.zeros((2, 1), dtype=np.int32) self.gt_boxes = self.be.zeros((64, 4), dtype=np.float32) self.num_gt_boxes = self.be.zeros((1, 1), dtype=np.int32) self.gt_classes = self.be.zeros((64, 1), dtype=np.int32) self.im_scale = self.be.zeros((1, 1), dtype=np.float32) @abc.abstractmethod def load_data(self): """ Abstract class to return a dictionary with data paths. The dictionary must contain: config['root'] # root directory of dataset config['index_path'] # index file with a list of images config['image_path'] # base directory for the images config['annot_path'] # base directory for the XML annotations config['file_ext'] # image file extension (e.g. *.jpg) """ pass def get_global_buffers(self): global_buffers = dict() global_buffers['target_buffers'] = ((self.dev_y_frcn_labels, self.dev_y_frcn_labels_mask), (self.dev_y_frcn_bbtargets, self.dev_y_frcn_bbmask)) global_buffers['img_info'] = (self.im_shape, self.im_scale) global_buffers['gt_boxes'] = (self.gt_boxes, self.gt_classes, self.num_gt_boxes) global_buffers['conv_config'] = (self._conv_size, self.SCALE) return global_buffers def add_anchors(self, roi_db): # adds a database of anchors # 1. for each i in (H,W), generate k=9 anchor boxes centered on i # 2. compute each anchor box against ground truth # 3. assign each anchor to positive (1), negative (0), or ignored (-1) # 4. for positive anchors, store the bbtargets # 1. # generate list of K anchor boxes, where K = # ratios * # scales # anchor boxes are coded as [xmin, ymin, xmax, ymax] all_anchors = generate_all_anchors(self._conv_size, self._conv_size, self.SCALE) # all_anchors are in (CHW) order, matching the CHWN output of the conv layer. assert self._total_anchors == all_anchors.shape[0] # 2. # Iterate through each image, and build list of positive/negative anchors for db in roi_db: im_scale, im_shape = self.calculate_scale_shape(db['img_shape']) # only keep anchors inside image idx_inside = inside_im_bounds(all_anchors, im_shape) if DEBUG: neon_logger.display('im shape', im_shape) neon_logger.display('idx inside', len(idx_inside)) anchors = all_anchors[idx_inside, :] labels = np.empty((len(idx_inside), ), dtype=np.float32) labels.fill(-1) # compute bbox overlaps overlaps = calculate_bb_overlap(np.ascontiguousarray(anchors, dtype=np.float), np.ascontiguousarray(db['gt_bb'] * im_scale, dtype=np.float)) # assign bg labels first bg_idx = overlaps.max(axis=1) < self.NEGATIVE_OVERLAP labels[bg_idx] = 0 # assing fg labels # 1. for each gt box, anchor with higher overlaps [including ties] gt_idx = np.where(overlaps == overlaps.max(axis=0))[0] labels[gt_idx] = 1 # 2. any anchor above the overlap threshold with any gt box fg_idx = overlaps.max(axis=1) >= self.POSITIVE_OVERLAP labels[fg_idx] = 1 if DEBUG: neon_logger.display('max_overlap: {}'.format(overlaps.max())) neon_logger.display('Assigned {} bg labels'.format(bg_idx.sum())) neon_logger.display('Assigned {}+{} fg labels'.format(fg_idx.sum(), len(gt_idx))) neon_logger.display('Total fg labels: {}'.format(np.sum(labels == 1))) neon_logger.display('Total bg labels: {}'.format(np.sum(labels == 0))) # For every anchor, compute the regression target compared # to the gt box that it has the highest overlap with # the indicies of labels should match these targets bbox_targets = np.zeros((len(idx_inside), 4), dtype=np.float32) bbox_targets = _compute_targets(db['gt_bb'][overlaps.argmax(axis=1), :] * im_scale, anchors) # store class label of max_overlap gt to use in normalization gt_max_overlap_classes = overlaps.argmax(axis=1) # store results in database db['labels'] = labels db['bbox_targets'] = bbox_targets db['max_classes'] = gt_max_overlap_classes db['total_anchors'] = self._total_anchors db['idx_inside'] = idx_inside db['im_width'] = im_shape[0] db['im_height'] = im_shape[1] return roi_db def normalize_bbox_targets(self, roi_db): if BBOX_NORMALIZE_TARGETS_PRECOMPUTED: # Use fixed / precomputed "means" and "stds" instead of empirical values means = np.tile( np.array(BBOX_NORMALIZE_MEANS), (self.num_classes, 1)) stds = np.tile( np.array(BBOX_NORMALIZE_STDS), (self.num_classes, 1)) else: # Compute values needed for means and stds # var(x) = E(x^2) - E(x)^2 # Add epsilon for classes with 0 counts class_counts = np.zeros((self.num_classes, 1)) + 1e-14 sums = np.zeros((self.num_classes, 4)) squared_sums = np.zeros((self.num_classes, 4)) for im_i in (self.num_image_entries): targets = roi_db[im_i]['bbox_targets'] for cls in range(1, self.num_classes): cls_inds =
np.where(roi_db[im_i]['gt_classes'] == cls)
numpy.where
import numpy as np from scipy import stats, signal def hanning(x,N): """ Filter a time series x with a Hanning window of length N. If x is 2D, the time series will be filtered along columns. Inputs: x - a numpy array to be filtered N - width of window Output: numpy array of filtered time series """ wts = signal.hann(N) # filter weights xf = _filt(x,wts) return xf def lancz(x=None,dt=1,T=40,return_weights=False): """ Filter a time series x with cosine-Lanczos filter. If x is 2D, the time series will be filtered along columns. The default half amplitude period of 40 hours corresponds to a frequency of 0.6 cpd. A half amplitude period of 34.29h corresponds to 0.7 cpd. The 40 hour half amplitude period is more effective at reducing diurnal-band variability but shifts periods of variability in low passed time series to >2 days. Inputs: x - a numpy array to be filtered dt - sample interval (hours), default = 1 T - half-amplitude period (hours), default = 40 return_weights - Boolean indicating whether to return the filter weights instead of a filtered time series, default = False Output: - numpy array of filtered time series, same size as input with ends NaN values at start and end (default) - numpy array of filter weights (if `return_weights=True` is specified) Reference: <NAME> Thomson, 2004, Data Analysis Methods in Physical Oceanography. 2nd Ed., pp. 539-540. Section 5.10.7.4 - The Hanning window. """ cph = 1./dt # samples per hour nwts = int(np.round(120*cph)) # number of weights # create filter weights wts = signal.firwin(nwts, 1./T, window='hanning', nyq=cph/2.) xf = _filt(x,wts,return_weights) return xf def pl66(x=None,dt=1,T=33,return_weights=False): """ Filter a time series x with the PL66 filter. If x is 2D, the time series will be filtered along columns. Inputs: x - a numpy array to be filtered dt - sample interval (hours), default = 1 T - half-amplitude period (hours), default = 33 return_weights - Boolean indicating whether to return the filter weights instead of a filtered time series, default = False Output: - numpy array of filtered time series, same size as input with ends NaN values at start and end (default) - numpy array of filter weights (if `return_weights=True` is specified) Reference: Rosenfeld (1983), WHOI Technical Report 85-35 Matlab code: http://woodshole.er.usgs.gov/operations/sea-mat/bobstuff-html/pl66tn.html """ Tn=float(T)/dt # normalized cutoff period fqn=1./Tn # normalized cutoff frequency nw = int(np.round(2.*T/dt)) # number of weights on one side # create filter weights j = np.arange(1,nw) tn = np.pi*j den=fqn*fqn*tn**3 wts = (2*np.sin(2*fqn*tn)-np.sin(fqn*tn)-np.sin(3*fqn*tn))/den # make symmetric wts = np.hstack((wts[::-1],2*fqn,wts)) xf = _filt(x,wts,return_weights) return xf def pl64(x=None,dt=1,T=33,return_weights=False): """ Filter a time series x with the PL64 filter. If x is 2D, the time series will be filtered along columns. Inputs: x - a numpy array to be filtered dt - sample interval (hours), default = 1 T - half-amplitude period (hours), default = 33 return_weights - Boolean indicating whether to return the filter weights instead of a filtered time series, default = False Output: - numpy array of filtered time series, same size as input with ends NaN values at start and end (default) - numpy array of filter weights (if `return_weights=True` is specified) Reference: CODE-2: Moored Array and Large-Scale Data Report, WHOI 85-35 """ Tn=float(T)/dt # normalized cutoff period fqn=1./Tn # normalized cutoff frequency nw = int(np.round(64/dt)) # number of weights on one side # create filter weights j = np.arange(1,nw) tn = np.pi*j den=fqn*fqn*tn**3 wts = (2*np.sin(2*fqn*tn)-np.sin(fqn*tn)-np.sin(3*fqn*tn))/den # make symmetric wts = np.hstack((wts[::-1],2*fqn,wts)) xf = _filt(x,wts,return_weights) return xf def _filt(x,wts,return_weights): """ Private function to filter a time series and pad the ends of the filtered time series with NaN values. For N weights, N/2 values are padded at each end of the time series. The filter weights are normalized so that the sum of weights = 1. Inputs: x - the time series (may be 2d, will be filtered along columns) wts - the filter weights return_weights - if True, return the filter weights instead of a filtered time series (default: False) Output: - the filtered time series (default) - filter weights (if `return_weights=True` is specified) """ # convert to 2D array if necessary (general case) ndims = np.ndim(x) if ndims == 1: x = np.expand_dims(x,axis=1) # normalize weights wtsn = wts*sum(wts)**-1 # normalize weights so sum = 1 if return_weights==False: # Convolve using 'direct' method. In older versions of scipy, this has to # be specified because the default 'auto' method could decide to use the # 'fft' method, which does not work for time series with NaNs. In newer # versions, there is no method option. try: xf = signal.convolve(x,wtsn[:,np.newaxis],mode='same',method='direct') except: xf = signal.convolve(x,wtsn[:,np.newaxis],mode='same') # note: np.convolve may be faster # http://scipy.github.io/old-wiki/pages/Cookbook/ApplyFIRFilter # pad ends of time series nwts = len(wts) # number of filter weights npad = int(np.ceil(0.5*nwts)) xf[:npad,:] = np.nan xf[-npad:,:] = np.nan # return array with same number of dimensions as input if ndims == 1: xf = xf.flatten() elif return_weights==True: # return normalized weights instead of filtered time series xf = wtsn else: raise('return_weights must be a Boolean') return xf def princax(u,v=None): ''' Principal axes of a vector time series. Usage: theta,major,minor = princax(u,v) # if u and v are real-valued vector components or theta,major,minor = princax(w) # if w is a complex vector Input: u,v - 1-D arrays of vector components (e.g. u = eastward velocity, v = northward velocity) or w - 1-D array of complex vectors (u + 1j*v) Output: theta - angle of major axis (math notation, e.g. east = 0, north = 90) major - standard deviation along major axis minor - standard deviation along minor axis Reference: <NAME> Thomson, 2001, Data Analysis Methods in Physical Oceanography, 2nd ed., pp. 325-328. Matlab function: http://woodshole.er.usgs.gov/operations/sea-mat/RPSstuff-html/princax.html ''' # if one input only, decompose complex vector if v is None: w = np.copy(u) u = np.real(w) v = np.imag(w) # Make sure inputs are numpy arrays if type(u) is list: u = np.array(u) v = np.array(v) # only use finite values for covariance matrix ii = np.isfinite(u+v) uf = u[ii] vf = v[ii] # compute covariance matrix C = np.cov(uf,vf) # calculate principal axis angle (ET, Equation 4.3.23b) theta = 0.5*np.arctan2(2.*C[0,1],(C[0,0] - C[1,1])) * 180/np.pi # calculate variance along major and minor axes (Equation 4.3.24) term1 = C[0,0] + C[1,1] term2 = ((C[0,0] - C[1,1])**2 + 4*(C[0,1]**2))**0.5 major = np.sqrt(0.5*(term1 + term2)) minor = np.sqrt(0.5*(term1 - term2)) return theta,major,minor def rot(u,v,theta): """ Rotate a vector counter-clockwise OR rotate the coordinate system clockwise. Usage: ur,vr = rot(u,v,theta) Input: u,v - vector components (e.g. u = eastward velocity, v = northward velocity) theta - rotation angle (degrees) Output: ur,vr - rotated vector components Example: rot(1,0,90) returns (0,1) """ # Make sure inputs are numpy arrays if type(u) is list: u = np.array(u) v = np.array(v) w = u + 1j*v # complex vector ang = theta*np.pi/180 # convert angle to radians wr = w*np.exp(1j*ang) # complex vector rotation ur = np.real(wr) # return u and v components vr = np.imag(wr) return ur,vr def fillgapwithnan(x,date): """ Fill in missing data with NaN values. This is intended for a regular time series that has gaps where no data are reported. Although this function is intended for regularly-sampled time series (with gaps), it does allow for some slight irregularity (e.g. 13:00,14:00,15:00,15:59,16:59...) Inputs: x - a numpy array of data (1 or 2 dimensions) date - datetime values that correspond to x Returns: (newx,newdate) newx - new array of data newdate = new datetime values """ xnd = np.ndim(x) # remember original number of dims in x x = np.array(x,ndmin=2) # make array 2D for general use # ensure that x is oriented correctly and has one dimension with same length as date flipdim = False if np.shape(x)[0] != np.shape(date)[0]: x = x.transpose() flipdim = True if np.shape(x)[0] != np.shape(date)[0]: raise Exception('one dimension of x must have same length as date') # find most common timedelta alldeltat = np.diff(date) # stats.mode returns (value, number of occurences) in arrays deltat = stats.mode(alldeltat)[0][0] gapi = np.where(alldeltat > deltat*3/2)[0] # build new arrays newdate = date[0:gapi[0]+1] newx = np.array(x[0:gapi[0]+1,:],ndmin=2) cnt = 0 # counter for looping through the gaps for ii in gapi: tdiff = date[ii+1]-date[ii] # size of gap # number of new values needed to fill gap nstep = int(round((tdiff.total_seconds()/deltat.total_seconds())))-1 for step in np.arange(nstep): t = newdate[-1]+deltat newdate = np.append(newdate,t) gapnans = np.nan*np.ones((nstep,np.shape(x)[1])) newx = np.vstack((newx,gapnans)) if ii!=gapi[-1]: i1 = ii+1 i2 = gapi[cnt+1] newdate = np.append(newdate,date[i1:i2+1]) newx = np.vstack((newx,x[i1:i2+1,:])) else: newdate = np.append(newdate,date[ii+1:]) newx = np.vstack((newx,x[ii+1:,:])) cnt=cnt+1 if flipdim: newx = newx.transpose() if xnd == 1: newx = newx.flatten() # reduce back to 1D array if necessary return (newx,newdate) def depthavg(x,z,h,ssh=None,surface='mixed',bottom='zero'): ''' Compute depth average of each row in 2D array x, with corresponding depths z. Designed to accomodate upward looking ADCP data, with moving sea surface and blank bins with no data near surface. If no sea surface height is specified, it is assumed to be at z=0 for all times. x: variable to be depth-averaged, 2D array with shape N rows, M columns z: measurement depths (z=0 is surface, z=-h is bottom), array of length M h: bottom depth (positive value) ssh: sea surface height (optional, set to zero if None or where value is undefined) surface: boundary condition for surface 'mixed' (default) or 'extrap' bottom: boundary condition for bottom 'zero' (default),'mixed' or 'extrap' ''' # ensure that inputs are arrays of floats x = np.array(x).astype('float') z = np.array(z).astype('float') h = np.array(h).astype('float') if np.ndim(x) == 1: x = x[np.newaxis] ni,nj = np.shape(x) # If SSH not specified, create an array of zeros if ssh is None: ssh = np.zeros(ni) ssh = np.array(ssh) if np.ndim(ssh) == 0: ssh = ssh[np.newaxis] # ssh in 2D column array ssh2 = np.array([ssh]).T # depths in 2D array sorti = np.argsort(z) zs = z[sorti] zs2 = np.tile(zs,[ni,1]) xs2 = x[:,sorti] # sort data in same manner as depths # water depth in 2D column array h2 = np.tile(h,[ni,1]) # new 2D x and z arrays to work with, with bottom and surface included zmat = np.hstack([-h2,zs2,ssh2]) nans2 = np.nan*
np.ones([ni,1])
numpy.ones
import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from tensorflow.keras.datasets import cifar10 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPooling2D from tensorflow.keras.callbacks import LearningRateScheduler, TensorBoard def build_model(): model = Sequential() model.add(Conv2D(6, (5, 5), padding='valid', activation = 'relu', kernel_initializer='he_normal', input_shape=(32,32,3))) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(Conv2D(16, (5, 5), padding='valid', activation = 'relu', kernel_initializer='he_normal')) model.add(MaxPooling2D((2, 2), strides=(2, 2))) model.add(Flatten()) model.add(Dense(120, activation = 'relu', kernel_initializer='he_normal')) model.add(Dense(84, activation = 'relu', kernel_initializer='he_normal')) model.add(Dense(10, activation = 'softmax', kernel_initializer='he_normal')) #sgd = optimizers.SGD(lr=.1, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model def scheduler(epoch): if epoch < 100: return 0.01 if epoch < 150: return 0.005 return 0.001 if __name__ == '__main__': # load data (x_train, y_train), (x_test, y_test) = cifar10.load_data() y_train_categorical = tf.keras.utils.to_categorical(y_train, 10) y_test_categorical = tf.keras.utils.to_categorical(y_test, 10) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255.0 x_test /= 255.0 class_names = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'] fig = plt.figure(figsize=(8,3)) num_classes = 10 for i in range(num_classes): ax = fig.add_subplot(2, 5, 1 + i, xticks=[], yticks=[]) idx =
np.where(y_train[:]==i)
numpy.where
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import xml.etree.ElementTree as ET import os, sys, pdb, math import pickle import numpy as np from PIL import Image, ImageDraw, ImageFont # sys.path.append('/y/dandans/Hand_Object_Detection/faster-rcnn.pytorch/lib/model/utils') # from lib.datasets.viz_hand_obj_debug import * def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.find('truncated').text) obj_struct['difficult'] = int(obj.find('difficult').text) bbox = obj.find('bndbox') obj_struct['bbox'] = [int(bbox.find('xmin').text), int(bbox.find('ymin').text), int(bbox.find('xmax').text), int(bbox.find('ymax').text)] obj_struct['handstate'] = 0 if obj.find('contactstate').text is None else int(obj.find('contactstate').text) obj_struct['leftright'] = 0 if obj.find('handside').text is None else int(obj.find('handside').text) obj_struct['objxmin'] = None if obj.find('objxmin').text in [None, 'None'] else float(obj.find('objxmin').text) obj_struct['objymin'] = None if obj.find('objymin').text in [None, 'None'] else float(obj.find('objymin').text) obj_struct['objxmax'] = None if obj.find('objxmax').text in [None, 'None'] else float(obj.find('objxmax').text) obj_struct['objymax'] = None if obj.find('objymax').text in [None, 'None'] else float(obj.find('objymax').text) if obj_struct['objxmin'] is not None and obj_struct['objymin'] is not None and obj_struct[ 'objxmax'] is not None and obj_struct['objymax'] is not None: obj_struct['objectbbox'] = [obj_struct['objxmin'], obj_struct['objymin'], obj_struct['objxmax'], obj_struct['objymax']] else: obj_struct['objectbbox'] = None objects.append(obj_struct) return objects def voc_ap(rec, prec, use_07_metric=False): """ ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11. else: # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap ''' @description: raw evaluation for fasterrcnn ''' def voc_eval(detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=False): """rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, classname, [ovthresh], [use_07_metric]) Top level function that does the PASCAL VOC evaluation. detpath: Path to detections detpath.format(classname) should produce the detection results file. annopath: Path to annotations annopath.format(imagename) should be the xml annotations file. imagesetfile: Text file containing the list of images, one image per line. classname: Category name (duh) cachedir: Directory for caching the annotations [ovthresh]: Overlap threshold (default = 0.5) [use_07_metric]: Whether to use VOC07's 11 point AP computation (default False) """ # assumes detections are in detpath.format(classname) # assumes annotations are in annopath.format(imagename) # assumes imagesetfile is a text file with each line an image name # cachedir caches the annotations in a pickle file print(f'\n\n thd = {ovthresh}\n\n') # first load gt if not os.path.isdir(cachedir): os.mkdir(cachedir) cachefile = os.path.join(cachedir, '%s_annots.pkl' % imagesetfile) # read list of images with open(imagesetfile, 'r') as f: lines = f.readlines() imagenames = [x.strip() for x in lines] if not os.path.isfile(cachefile): # load annotations recs = {} for i, imagename in enumerate(imagenames): recs[imagename] = parse_rec(annopath.format(imagename)) if i % 100 == 0: print('Reading annotation for {:d}/{:d}'.format( i + 1, len(imagenames))) # save print('Saving cached annotations to {:s}'.format(cachefile)) with open(cachefile, 'wb') as f: pickle.dump(recs, f) else: # load with open(cachefile, 'rb') as f: try: recs = pickle.load(f) except: recs = pickle.load(f, encoding='bytes') # extract gt objects for this class class_recs = {} npos = 0 for imagename in imagenames: R = [obj for obj in recs[imagename] if obj['name'].lower() == classname] bbox = np.array([x['bbox'] for x in R]) difficult = np.array([x['difficult'] for x in R]).astype(np.bool) det = [False] * len(R) npos = npos + sum(~difficult) class_recs[imagename] = {'bbox': bbox, 'difficult': difficult, 'det': det} # read dets detfile = detpath.format(classname) with open(detfile, 'r') as f: lines = f.readlines() splitlines = [x.strip().split(' ') for x in lines] image_ids = [x[0] for x in splitlines] confidence = np.array([float(x[1]) for x in splitlines]) BB = np.array([[float(z) for z in x[2:2 + 4]] for x in splitlines]) nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) if BB.shape[0] > 0: # sort by confidence sorted_ind = np.argsort(-confidence) sorted_scores = np.sort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] # go down dets and mark TPs and FPs for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) if BBGT.size > 0: # compute overlaps # intersection ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin =
np.maximum(BBGT[:, 1], bb[1])
numpy.maximum
# Copyright 2019 Image Analysis Lab, German Center for Neurodegenerative Diseases (DZNE), Bonn # # 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. # IMPORTS import optparse import sys import numpy as np import nibabel as nib import copy HELPTEXT = """ Script to reduce aparc+aseg to aseg by mapping cortex lables back to left/right GM. If --outmask is used, it also creates a brainmask by dilating (5) and eroding (4) the segmentation, and then selecting the largest component. In that case also the segmentation is masked (to remove small components outside the main brain region). USAGE: reduce_to_aseg -i <input_seg> -o <output_seg> Dependencies: Python 3.5 Numpy http://www.numpy.org Nibabel to read and write FreeSurfer data http://nipy.org/nibabel/ skimage for erosion, dilation, connected component https://scikit-image.org/ Original Author: <NAME> Date: Jul-24-2018 """ h_input = 'path to input segmentation' h_output = 'path to ouput segmentation' h_outmask = 'path to ouput mask' def options_parse(): """ Command line option parser for reduce_to_aseg.py """ parser = optparse.OptionParser(version='$Id: reduce_to_aseg.py,v 1.0 2018/06/24 11:34:08 mreuter Exp $', usage=HELPTEXT) parser.add_option('--input', '-i', dest='input_seg', help=h_input) parser.add_option('--output', '-o', dest='output_seg', help=h_output) parser.add_option('--outmask', dest='output_mask', help=h_outmask) (options, args) = parser.parse_args() if options.input_seg is None or options.output_seg is None: sys.exit('ERROR: Please specify input and output segmentations') return options def reduce_to_aseg(data_inseg): print ("Reducing to aseg ...") # replace 2000... with 42 data_inseg[data_inseg >= 2000] = 42 # replace 1000... with 3 data_inseg[data_inseg >= 1000] = 3 return data_inseg def create_mask(aseg_data, dnum, enum): from skimage.morphology import binary_dilation, binary_erosion from skimage.measure import label print ("Creating dilated mask ...") # treat lateral orbital frontal and parsorbitalis special to avoid capturing too much of eye nerve lat_orb_front_mask = np.logical_or(aseg_data == 2012, aseg_data == 1012) parsorbitalis_mask = np.logical_or(aseg_data == 2019, aseg_data == 1019) frontal_mask =
np.logical_or(lat_orb_front_mask, parsorbitalis_mask)
numpy.logical_or
""" Target is in xmin, ymin, xmax, ymax, label coordinates are in range of [0, 1] normlised height and width """ import json, os import torch import pdb, time import torch.utils as tutils import pickle from .transforms import get_clip_list_resized import torch.nn.functional as F import numpy as np from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True from PIL import Image, ImageDraw from modules.tube_helper import make_gt_tube import random as random from modules import utils from random import shuffle logger = utils.get_logger(__name__) def get_box(box, counts): box = box.astype(np.float32) - 1 box[2] += box[0] #convert width to xmax box[3] += box[1] #converst height to ymax for bi in range(4): scale = 320 if bi % 2 == 0 else 240 box[bi] /= scale assert 0<=box[bi]<=1.01, box # if add_one ==0: box[bi] = min(1.0, max(0, box[bi])) if counts is None: box[bi] = box[bi]*682 if bi % 2 == 0 else box[bi]*512 return box, counts def get_frame_level_annos_ucf24(annotations, numf, num_classes, counts=None): frame_level_annos = [ {'labeled':True,'ego_label':0,'boxes':[],'labels':[]} for _ in range(numf)] add_one = 1 # if num_classes == 24: # add_one = 0 for tubeid, tube in enumerate(annotations): # print('numf00', numf, tube['sf'], tube['ef']) for frame_index, frame_num in enumerate(np.arange(tube['sf'], tube['ef'], 1)): # start of the tube to end frame of the tube label = tube['label'] # assert action_id == label, 'Tube label and video label should be same' box, counts = get_box(tube['boxes'][frame_index, :].copy(), counts) # get the box as an array frame_level_annos[frame_num]['boxes'].append(box) box_labels = np.zeros(num_classes) # if add_one == 1: box_labels[0] = 1 box_labels[label+add_one] = 1 frame_level_annos[frame_num]['labels'].append(box_labels) frame_level_annos[frame_num]['ego_label'] = label+1 # frame_level_annos[frame_index]['ego_label'][] = 1 if counts is not None: counts[0,0] += 1 counts[label,1] += 1 return frame_level_annos, counts def get_filtered_tubes_ucf24(annotations): filtered_tubes = [] for tubeid, tube in enumerate(annotations): frames = [] boxes = [] label = tube['label'] count = 0 for frame_index, frame_num in enumerate(np.arange(tube['sf'], tube['ef'], 1)): frames.append(frame_num+1) box, _ = get_box(tube['boxes'][frame_index, :].copy(), None) boxes.append(box) count += 1 assert count == tube['boxes'].shape[0], 'numb: {} count ={}'.format(tube['boxes'].shape[0], count) temp_tube = make_gt_tube(frames, boxes, label) filtered_tubes.append(temp_tube) return filtered_tubes def resize(image, size): image = F.interpolate(image.unsqueeze(0), size=size, mode="nearest").squeeze(0) return image def filter_labels(ids, all_labels, used_labels): """Filter the used ids""" used_ids = [] for id in ids: label = all_labels[id] if label in used_labels: used_ids.append(used_labels.index(label)) return used_ids def get_gt_video_list(anno_file, SUBSETS): """Get video list form ground truth videos used in subset and their ground truth tubes """ with open(anno_file, 'r') as fff: final_annots = json.load(fff) video_list = [] for videoname in final_annots['db']: if is_part_of_subsets(final_annots['db'][videoname]['split_ids'], SUBSETS): video_list.append(videoname) return video_list def get_filtered_tubes(label_key, final_annots, videoname): key_tubes = final_annots['db'][videoname][label_key] all_labels = final_annots['all_'+label_key.replace('tubes','labels')] labels = final_annots[label_key.replace('tubes','labels')] filtered_tubes = [] for _ , tube in key_tubes.items(): label_id = tube['label_id'] label = all_labels[label_id] if label in labels: new_label_id = labels.index(label) # temp_tube = GtTube(new_label_id) frames = [] boxes = [] if 'annos' in tube.keys(): for fn, anno_id in tube['annos'].items(): frames.append(int(fn)) anno = final_annots['db'][videoname]['frames'][fn]['annos'][anno_id] box = anno['box'].copy() for bi in range(4): assert 0<=box[bi]<=1.01, box box[bi] = min(1.0, max(0, box[bi])) box[bi] = box[bi]*682 if bi % 2 == 0 else box[bi]*512 boxes.append(box) else: for fn in tube['frames']: frames.append(int(fn)) temp_tube = make_gt_tube(frames, boxes, new_label_id) filtered_tubes.append(temp_tube) return filtered_tubes def get_filtered_frames(label_key, final_annots, videoname, filtered_gts): frames = final_annots['db'][videoname]['frames'] if label_key == 'agent_ness': all_labels = [] labels = [] else: all_labels = final_annots['all_'+label_key+'_labels'] labels = final_annots[label_key+'_labels'] for frame_id , frame in frames.items(): frame_name = '{:05d}'.format(int(frame_id)) if frame['annotated']>0: all_boxes = [] if 'annos' in frame: frame_annos = frame['annos'] for key in frame_annos: anno = frame_annos[key] box = np.asarray(anno['box'].copy()) for bi in range(4): assert 0<=box[bi]<=1.01, box box[bi] = min(1.0, max(0, box[bi])) box[bi] = box[bi]*682 if bi % 2 == 0 else box[bi]*512 if label_key == 'agent_ness': filtered_ids = [0] else: filtered_ids = filter_labels(anno[label_key+'_ids'], all_labels, labels) if len(filtered_ids)>0: all_boxes.append([box, filtered_ids]) filtered_gts[videoname+frame_name] = all_boxes return filtered_gts def get_av_actions(final_annots, videoname): label_key = 'av_action' frames = final_annots['db'][videoname]['frames'] all_labels = final_annots['all_'+label_key+'_labels'] labels = final_annots[label_key+'_labels'] filtered_gts = {} for frame_id , frame in frames.items(): frame_name = '{:05d}'.format(int(frame_id)) if frame['annotated']>0: gts = filter_labels(frame[label_key+'_ids'], all_labels, labels) filtered_gts[videoname+frame_name] = gts return filtered_gts def get_video_tubes(final_annots, videoname): tubes = {} for key in final_annots['db'][videoname].keys(): if key.endswith('tubes'): filtered_tubes = get_filtered_tubes(key, final_annots, videoname) tubes[key] = filtered_tubes return tubes def is_part_of_subsets(split_ids, SUBSETS): is_it = False for subset in SUBSETS: if subset in split_ids: is_it = True return is_it class VideoDataset(tutils.data.Dataset): """ ROAD Detection dataset class for pytorch dataloader """ def __init__(self, args, train=True, input_type='rgb', transform=None, skip_step=1, full_test=False): self.ANCHOR_TYPE = args.ANCHOR_TYPE self.DATASET = args.DATASET self.SUBSETS = args.SUBSETS self.SEQ_LEN = args.SEQ_LEN self.BATCH_SIZE = args.BATCH_SIZE self.MIN_SEQ_STEP = args.MIN_SEQ_STEP self.MAX_SEQ_STEP = args.MAX_SEQ_STEP # self.MULIT_SCALE = args.MULIT_SCALE self.full_test = full_test self.skip_step = skip_step #max(skip_step, self.SEQ_LEN*self.MIN_SEQ_STEP/2) self.num_steps = max(1, int(self.MAX_SEQ_STEP - self.MIN_SEQ_STEP + 1 )//2) # self.input_type = input_type self.input_type = input_type+'-images' self.train = train self.root = args.DATA_ROOT + args.DATASET + '/' self._imgpath = os.path.join(self.root, self.input_type) # self.image_sets = image_sets self.transform = transform self.ids = list() if self.DATASET == 'road': self._make_lists_road() elif self.DATASET == 'ucf24': self._make_lists_ucf24() self.num_label_types = len(self.label_types) def _make_lists_ucf24(self): self.anno_file = os.path.join(self.root, 'pyannot_with_class_names.pkl') with open(self.anno_file,'rb') as fff: final_annots = pickle.load(fff) database = final_annots['db'] self.trainvideos = final_annots['trainvideos'] ucf_classes = final_annots['classes'] self.label_types = ['action_ness', 'action'] # self.num_classes_list = [1, 24] self.num_classes = 25 # one for action_ness self.ego_classes = ['Non_action'] + ucf_classes self.num_ego_classes = len(self.ego_classes) counts = np.zeros((24, 2), dtype=np.int32) ratios = [1.0, 1.1, 1.1, 0.9, 1.1, 0.8, 0.7, 0.8, 1.1, 1.4, 1.0, 0.8, 0.7, 1.2, 1.0, 0.8, 0.7, 1.2, 1.2, 1.0, 0.9] self.video_list = [] self.numf_list = [] frame_level_list = [] default_ego_label =
np.zeros(self.num_ego_classes)
numpy.zeros
# encoding: UTF-8 # AUTHOR:李来佳 # WeChat/QQ: 28888502 from datetime import datetime import talib as ta import numpy import copy,csv from pykalman import KalmanFilter from vnpy.trader.app.ctaStrategy.ctaBase import * from vnpy.trader.vtConstant import * DEBUGCTALOG = True PERIOD_SECOND = 'second' # 秒级别周期 PERIOD_MINUTE = 'minute' # 分钟级别周期 PERIOD_HOUR = 'hour' # 小时级别周期 PERIOD_DAY = 'day' # 日级别周期 class CtaLineBar(object): """CTA K线""" """ 使用方法: 1、在策略构造函数__init()中初始化 self.lineM = None # 1分钟K线 lineMSetting = {} lineMSetting['name'] = u'M1' lineMSetting['barTimeInterval'] = 60 # 1分钟对应60秒 lineMSetting['inputEma1Len'] = 7 # EMA线1的周期 lineMSetting['inputEma2Len'] = 21 # EMA线2的周期 lineMSetting['inputBollLen'] = 20 # 布林特线周期 lineMSetting['inputBollStdRate'] = 2 # 布林特线标准差 lineMSetting['minDiff'] = self.minDiff # 最小条 lineMSetting['shortSymbol'] = self.shortSymbol #商品短号 self.lineM = CtaLineBar(self, self.onBar, lineMSetting) 2、在onTick()中,需要导入tick数据 self.lineM.onTick(tick) self.lineM5.onTick(tick) # 如果你使用2个周期 3、在onBar事件中,按照k线结束使用;其他任何情况下bar内使用,通过对象使用即可,self.lineM.lineBar[-1].close """ # 区别: # -使用tick模式时,当tick到达后,最新一个lineBar[-1]是当前的正在拟合的bar,不断累积tick,传统按照OnBar来计算的话,是使用LineBar[-2]。 # -使用bar模式时,当一个bar到达时,lineBar[-1]是当前生成出来的Bar,不再更新 TICK_MODE = 'tick' BAR_MODE = 'bar' # 参数列表,保存了参数的名称 paramList = ['vtSymbol'] def __init__(self, strategy, onBarFunc, setting=None,): # OnBar事件回调函数 self.onBarFunc = onBarFunc # 参数列表 self.paramList.append('barTimeInterval') self.paramList.append('period') self.paramList.append('inputPreLen') self.paramList.append('inputEma1Len') self.paramList.append('inputEma2Len') self.paramList.append('inputMa1Len') self.paramList.append('inputMa2Len') self.paramList.append('inputMa3Len') self.paramList.append('inputDmiLen') self.paramList.append('inputDmiMax') self.paramList.append('inputAtr1Len') self.paramList.append('inputAtr2Len') self.paramList.append('inputAtr3Len') self.paramList.append('inputVolLen') self.paramList.append('inputRsi1Len') self.paramList.append('inputRsi2Len') self.paramList.append('inputCmiLen') self.paramList.append('inputBollLen') self.paramList.append('inputBollStdRate') self.paramList.append('inputKdjLen') self.paramList.append('inputCciLen') self.paramList.append('inputMacdFastPeriodLen') self.paramList.append('inputMacdSlowPeriodLen') self.paramList.append('inputMacdSignalPeriodLen') self.paramList.append('inputKF') self.paramList.append('minDiff') self.paramList.append('shortSymbol') self.paramList.append('activeDayJump') self.paramList.append('name') # 输入参数 self.name = u'LineBar' self.mode = self.TICK_MODE # 缺省为tick模式 self.period = PERIOD_SECOND # 缺省为分钟级别周期 self.barTimeInterval = 300 self.barMinuteInterval = self.barTimeInterval / 60 self.inputPreLen = EMPTY_INT #1 self.inputMa1Len = EMPTY_INT # 10 self.inputMa2Len = EMPTY_INT # 20 self.inputMa3Len = EMPTY_INT # 120 self.inputEma1Len = EMPTY_INT # 13 self.inputEma2Len = EMPTY_INT # 21 self.inputDmiLen = EMPTY_INT # 14 # DMI的计算周期 self.inputDmiMax = EMPTY_FLOAT # 30 # Dpi和Mdi的突破阈值 self.inputAtr1Len = EMPTY_INT # 10 # ATR波动率的计算周期(近端) self.inputAtr2Len = EMPTY_INT # 26 # ATR波动率的计算周期(常用) self.inputAtr3Len = EMPTY_INT # 50 # ATR波动率的计算周期(远端) self.inputVolLen = EMPTY_INT # 14 # 平均交易量的计算周期 self.inputRsi1Len = EMPTY_INT # 7 # RSI 相对强弱指数(快曲线) self.inputRsi2Len = EMPTY_INT # 14 # RSI 相对强弱指数(慢曲线) self.shortSymbol = EMPTY_STRING # 商品的短代码 self.minDiff = 1 # 商品的最小价格单位 self.round_n = 4 # round() 小数点的截断数量 self.activeDayJump = False # 隔夜跳空 # 当前的Tick self.curTick = None self.lastTick = None self.curTradingDay = EMPTY_STRING # K 线服务的策略 self.strategy = strategy # K线保存数据 self.bar = None # K线数据对象 self.lineBar = [] # K线缓存数据队列 self.barFirstTick =False # K线的第一条Tick数据 # K 线的相关计算结果数据 self.preHigh = [] # K线的前inputPreLen的的最高 self.preLow = [] # K线的前inputPreLen的的最低 self.lineMa1 = [] # K线的MA1均线,周期是InputMaLen1,不包含当前bar self.lineMa2 = [] # K线的MA2均线,周期是InputMaLen2,不包含当前bar self.lineMa3 = [] # K线的MA2均线,周期是InputMaLen2,不包含当前bar self.lineEma1 = [] # K线的EMA1均线,周期是InputEmaLen1,不包含当前bar self.lineEma1MtmRate = [] # K线的EMA1均线 的momentum(3) 动能 self.lineEma2 = [] # K线的EMA2均线,周期是InputEmaLen2,不包含当前bar self.lineEma2MtmRate = [] # K线的EMA2均线 的momentum(3) 动能 # K线的DMI( Pdi,Mdi,ADX,Adxr) 计算数据 self.barPdi = EMPTY_FLOAT # bar内的升动向指标,即做多的比率 self.barMdi = EMPTY_FLOAT # bar内的下降动向指标,即做空的比率 self.linePdi = [] # 升动向指标,即做多的比率 self.lineMdi = [] # 下降动向指标,即做空的比率 self.lineDx = [] # 趋向指标列表,最大长度为inputM*2 self.barAdx = EMPTY_FLOAT # Bar内计算的平均趋向指标 self.lineAdx = [] # 平均趋向指标 self.barAdxr = EMPTY_FLOAT # 趋向平均值,为当日ADX值与M日前的ADX值的均值 self.lineAdxr = [] # 平均趋向变化指标 # K线的基于DMI、ADX计算的结果 self.barAdxTrend = EMPTY_FLOAT # ADX值持续高于前一周期时,市场行情将维持原趋势 self.barAdxrTrend = EMPTY_FLOAT # ADXR值持续高于前一周期时,波动率比上一周期高 self.buyFilterCond = False # 多过滤器条件,做多趋势的判断,ADX高于前一天,上升动向> inputMM self.sellFilterCond = False # 空过滤器条件,做空趋势的判断,ADXR高于前一天,下降动向> inputMM # K线的ATR技术数据 self.lineAtr1 = [] # K线的ATR1,周期为inputAtr1Len self.lineAtr2 = [] # K线的ATR2,周期为inputAtr2Len self.lineAtr3 = [] # K线的ATR3,周期为inputAtr3Len self.barAtr1 = EMPTY_FLOAT self.barAtr2 = EMPTY_FLOAT self.barAtr3 = EMPTY_FLOAT # K线的交易量平均 self.lineAvgVol = [] # K 线的交易量平均 # K线的RSI计算数据 self.lineRsi1 = [] # 记录K线对应的RSI数值,只保留inputRsi1Len*8 self.lineRsi2 = [] # 记录K线对应的RSI数值,只保留inputRsi2Len*8 self.lowRsi = 30 # RSI的最低线 self.highRsi = 70 # RSI的最高线 self.lineRsiTop = [] # 记录RSI的最高峰,只保留 inputRsiLen个 self.lineRsiButtom = [] # 记录RSI的最低谷,只保留 inputRsiLen个 self.lastRsiTopButtom = {} # 最近的一个波峰/波谷 # K线的CMI计算数据 self.inputCmiLen = EMPTY_INT self.lineCmi = [] # 记录K线对应的Cmi数值,只保留inputCmiLen*8 # K线的布林特计算数据 self.inputBollLen = EMPTY_INT # K线周期 self.inputBollStdRate = 1.5 # 两倍标准差 self.lineBollClose = [] # 用于运算的close价格列表 self.lineUpperBand = [] # 上轨 self.lineMiddleBand = [] # 中线 self.lineLowerBand = [] # 下轨 self.lineBollStd = [] # 标准差 self.lastBollUpper = EMPTY_FLOAT # 最后一根K的Boll上轨数值(与MinDiff取整) self.lastBollMiddle = EMPTY_FLOAT # 最后一根K的Boll中轨数值(与MinDiff取整) self.lastBollLower = EMPTY_FLOAT # 最后一根K的Boll下轨数值(与MinDiff取整+1) # K线的KDJ指标计算数据 self.inputKdjLen = EMPTY_INT # KDJ指标的长度,缺省是9 self.lineK = [] # K为快速指标 self.lineD = [] # D为慢速指标 self.lineJ = [] # self.lineKdjTop = [] # 记录KDJ最高峰,只保留 inputKdjLen个 self.lineKdjButtom = [] # 记录KDJ的最低谷,只保留 inputKdjLen个 self.lastKdjTopButtom = {} # 最近的一个波峰/波谷 self.lastK = EMPTY_FLOAT # bar内计算时,最后一个未关闭的bar的实时K值 self.lastD = EMPTY_FLOAT # bar内计算时,最后一个未关闭的bar的实时值 self.lastJ = EMPTY_FLOAT # bar内计算时,最后一个未关闭的bar的实时J值 # K线的MACD计算数据 self.inputMacdFastPeriodLen = EMPTY_INT self.inputMacdSlowPeriodLen = EMPTY_INT self.inputMacdSignalPeriodLen = EMPTY_INT self.lineDif = [] # DIF = EMA12 - EMA26,即为talib-MACD返回值macd self.lineDea = [] # DEA = (前一日DEA X 8/10 + 今日DIF X 2/10),即为talib-MACD返回值 self.lineMacd = [] # (dif-dea)*2,但是talib中MACD的计算是bar = (dif-dea)*1,国内一般是乘以2 # K 线的CCI计算数据 self.inputCciLen = EMPTY_INT self.lineCci = [] # 卡尔曼过滤器 self.inputKF = False self.kf = None self.lineStateMean = [] self.lineStateCovar = [] if setting: self.setParam(setting) # 修正精度 if self.minDiff < 1: self.round_n = 7 ## 导入卡尔曼过滤器 if self.inputKF: try: self.kf = KalmanFilter(transition_matrices=[1], observation_matrices=[1], initial_state_mean=0, initial_state_covariance=1, observation_covariance=1, transition_covariance=0.01) except : self.writeCtaLog(u'导入卡尔曼过滤器失败,需先安装 pip install pykalman') self.inputKF = False def setParam(self, setting): """设置参数""" d = self.__dict__ for key in self.paramList: if key in setting: d[key] = setting[key] def setMode(self,mode): """Tick/Bar模式""" self.mode = mode def onTick(self, tick): """行情更新 :type tick: object """ # Tick 有效性检查 #if (tick.datetime- datetime.now()).seconds > 10: # self.writeCtaLog(u'无效的tick时间:{0}'.format(tick.datetime)) # return if tick.datetime.hour == 8 or tick.datetime.hour == 20: self.writeCtaLog(u'竞价排名tick时间:{0}'.format(tick.datetime)) return if self.lastTick is None: self.lastTick = tick self.curTick = tick # 3.生成x K线,若形成新Bar,则触发OnBar事件 self.__drawLineBar(tick) self.lastTick = tick # 4.执行 bar内计算 self.__recountKdj(countInBar=True) def addBar(self,bar): """予以外部初始化程序增加bar""" l1 = len(self.lineBar) if l1 == 0: self.lineBar.append(bar) self.curTradingDay = bar.date self.onBar(bar) return # 与最后一个BAR的时间比对,判断是否超过K线的周期 lastBar = self.lineBar[-1] self.curTradingDay = bar.tradingDay is_new_bar = False if self.period == PERIOD_SECOND and (bar.datetime-lastBar.datetime).seconds >= self.barTimeInterval: is_new_bar = True elif self.period == PERIOD_MINUTE and (bar.datetime - lastBar.datetime).seconds >= self.barTimeInterval*60: is_new_bar = True elif self.period == PERIOD_HOUR: if self.barTimeInterval == 1 and bar.datetime.hour != lastBar.datetime.hour : is_new_bar = True elif self.barTimeInterval == 2 and bar.datetime.hour != lastBar.datetime.hour \ and bar.datetime.hour in {1, 9, 11, 13, 15, 21, 23}: is_new_bar = True elif self.barTimeInterval == 4 and bar.datetime.hour != lastBar.datetime.hour \ and bar.datetime.hour in {1, 9, 13, 21}: is_new_bar = True elif self.period == PERIOD_DAY and bar.datetime.date != lastBar.datetime.date : is_new_bar = True if is_new_bar: # 添加新的bar self.lineBar.append(bar) # 将上一个Bar推送至OnBar事件 self.onBar(lastBar) return # 更新最后一个bar # 此段代码,针对一部分短周期生成长周期的k线更新,如3根5分钟k线,合并成1根15分钟k线。 lastBar.close = bar.close lastBar.high = max(lastBar.high, bar.high) lastBar.low = min(lastBar.low, bar.low) lastBar.volume = lastBar.volume + bar.volume lastBar.dayVolume = bar.dayVolume lastBar.mid4 = round((2*lastBar.close + lastBar.high + lastBar.low)/4, self.round_n) lastBar.mid5 = round((2*lastBar.close + lastBar.open + lastBar.high + lastBar.low)/5, self.round_n) def onBar(self, bar): """OnBar事件""" # 计算相关数据 bar.mid4 = round((2*bar.close + bar.high + bar.low)/4, self.round_n) bar.mid5 = round((2*bar.close + bar.open + bar.high + bar.low)/5, self.round_n) self.__recountPreHighLow() self.__recountMa() self.__recountEma() self.__recountDmi() self.__recountAtr() self.__recoundAvgVol() self.__recountRsi() self.__recountCmi() self.__recountKdj() self.__recountBoll() self.__recountMacd() self.__recountCci() self.__recountKF() # 回调上层调用者 self.onBarFunc(bar) def displayLastBar(self): """显示最后一个Bar的信息""" msg = u'['+self.name+u']' if len(self.lineBar) < 2: return msg if self.mode == self.TICK_MODE: displayBar = self.lineBar[-2] else: displayBar = self.lineBar[-1] msg = msg + u'{0} o:{1};h{2};l:{3};c:{4},v:{5}'.\ format(displayBar.date+' '+displayBar.time, displayBar.open, displayBar.high, displayBar.low, displayBar.close, displayBar.volume) if self.inputMa1Len > 0 and len(self.lineMa1) > 0: msg = msg + u',MA({0}):{1}'.format(self.inputMa1Len, self.lineMa1[-1]) if self.inputMa2Len > 0 and len(self.lineMa2) > 0: msg = msg + u',MA({0}):{1}'.format(self.inputMa2Len, self.lineMa2[-1]) if self.inputMa3Len > 0 and len(self.lineMa3) > 0: msg = msg + u',MA({0}):{1}'.format(self.inputMa3Len, self.lineMa3[-1]) if self.inputEma1Len > 0 and len(self.lineEma1) > 0: msg = msg + u',EMA({0}):{1}'.format(self.inputEma1Len, self.lineEma1[-1]) if self.inputEma2Len > 0 and len(self.lineEma2) > 0: msg = msg + u',EMA({0}):{1}'.format(self.inputEma2Len, self.lineEma2[-1]) if self.inputDmiLen > 0 and len(self.linePdi) > 0: msg = msg + u',Pdi:{1};Mdi:{1};Adx:{2}'.format(self.linePdi[-1], self.lineMdi[-1], self.lineAdx[-1]) if self.inputAtr1Len > 0 and len(self.lineAtr1) > 0: msg = msg + u',Atr({0}):{1}'.format(self.inputAtr1Len, self.lineAtr1[-1]) if self.inputAtr2Len > 0 and len(self.lineAtr2) > 0: msg = msg + u',Atr({0}):{1}'.format(self.inputAtr2Len, self.lineAtr2[-1]) if self.inputAtr3Len > 0 and len(self.lineAtr3) > 0: msg = msg + u',Atr({0}):{1}'.format(self.inputAtr3Len, self.lineAtr3[-1]) if self.inputVolLen > 0 and len(self.lineAvgVol) > 0: msg = msg + u',AvgVol({0}):{1}'.format(self.inputVolLen, self.lineAvgVol[-1]) if self.inputRsi1Len > 0 and len(self.lineRsi1) > 0: msg = msg + u',Rsi({0}):{1}'.format(self.inputRsi1Len, self.lineRsi1[-1]) if self.inputRsi2Len > 0 and len(self.lineRsi2) > 0: msg = msg + u',Rsi({0}):{1}'.format(self.inputRsi2Len, self.lineRsi2[-1]) if self.inputKdjLen > 0 and len(self.lineK) > 0: msg = msg + u',KDJ({0}):{1},{2},{3}'.format(self.inputKdjLen, round(self.lineK[-1], self.round_n), round(self.lineD[-1], self.round_n), round(self.lineJ[-1], self.round_n)) if self.inputCciLen > 0 and len(self.lineCci) > 0: msg = msg + u',Cci({0}):{1}'.format(self.inputCciLen, self.lineCci[-1]) if self.inputBollLen > 0 and len(self.lineUpperBand)>0: msg = msg + u',Boll({0}):u:{1},m:{2},l:{3}'.\ format(self.inputBollLen, round(self.lineUpperBand[-1], self.round_n), round(self.lineMiddleBand[-1], self.round_n), round(self.lineLowerBand[-1]), self.round_n) if self.inputMacdFastPeriodLen >0 and len(self.lineDif)>0: msg = msg + u',MACD({0},{1},{2}):Dif:{3},Dea{4},Macd:{5}'.\ format(self.inputMacdFastPeriodLen, self.inputMacdSlowPeriodLen, self.inputMacdSignalPeriodLen, round(self.lineDif[-1], self.round_n), round(self.lineDea[-1], self.round_n), round(self.lineMacd[-1], self.round_n)) if self.inputKF and len(self.lineKfMa) > 0: msg = msg + u',Kalman:{0}'.format( self.lineKfMa[-1]) return msg def __firstTick(self, tick): """ K线的第一个Tick数据""" self.bar = CtaBarData() # 创建新的K线 # 计算K线的整点分钟周期,这里周期最小是1分钟。如果你是采用非整点分钟,例如1.5分钟,请把这段注解掉 if self.barMinuteInterval and self.period == PERIOD_SECOND: self.barMinuteInterval = int(self.barTimeInterval / 60) if self.barMinuteInterval < 1: self.barMinuteInterval = 1 fixedMin = int( tick.datetime.minute /self.barMinuteInterval) * self.barMinuteInterval tick.datetime = tick.datetime.replace(minute=fixedMin) self.bar.vtSymbol = tick.vtSymbol self.bar.symbol = tick.symbol self.bar.exchange = tick.exchange self.bar.openInterest = tick.openInterest self.bar.open = tick.lastPrice # O L H C self.bar.high = tick.lastPrice self.bar.low = tick.lastPrice self.bar.close = tick.lastPrice self.bar.mid4 = tick.lastPrice # 4价均价 self.bar.mid5 = tick.lastPrice # 5价均价 # K线的日期时间 self.bar.tradingDay = tick.tradingDay # K线所在的交易日期 self.bar.date = tick.date # K线的日期,(夜盘的话,与交易日期不同哦) self.bar.datetime = tick.datetime # K线的日期时间(去除秒)设为第一个Tick的时间 self.bar.datetime = self.bar.datetime.replace(second=0, microsecond=0) self.bar.time = self.bar.datetime.strftime('%H:%M:%S') # K线的日总交易量,k线内交易量 self.bar.dayVolume = tick.volume if self.curTradingDay != self.bar.tradingDay or not self.lineBar: # bar的交易日与记录的当前交易日不一致:即该bar为新的交易日,bar的交易量为当前的tick.volume self.bar.volume = tick.volume self.curTradingDay = self.bar.tradingDay else: # bar的交易日与记录的当前交易日一致, 交易量为tick的volume,减去上一根bar的日总交易量 self.bar.volume = tick.volume - self.lineBar[-1].dayVolume self.barFirstTick = True # 标识该Tick属于该Bar的第一个tick数据 self.lineBar.append(self.bar) # 推入到lineBar队列 # ---------------------------------------------------------------------- def __drawLineBar(self, tick): """生成 line Bar """ l1 = len(self.lineBar) # 保存第一个K线数据 if l1 == 0: self.__firstTick(tick) return # 清除480周期前的数据, if l1 > 60 * 8: del self.lineBar[0] # 与最后一个BAR的时间比对,判断是否超过5分钟 lastBar = self.lineBar[-1] # 处理日内的间隔时段最后一个tick,如10:15分,11:30分,15:00 和 2:30分 endtick = False if (tick.datetime.hour == 10 and tick.datetime.minute == 15) \ or (tick.datetime.hour == 11 and tick.datetime.minute == 30) \ or (tick.datetime.hour == 15 and tick.datetime.minute == 00) \ or (tick.datetime.hour == 2 and tick.datetime.minute == 30): endtick = True # 夜盘1:30收盘 if self.shortSymbol in NIGHT_MARKET_SQ2 and tick.datetime.hour == 1 and tick.datetime.minute == 00: endtick = True # 夜盘23:00收盘 if self.shortSymbol in NIGHT_MARKET_SQ3 and tick.datetime.hour == 23 and tick.datetime.minute == 00: endtick = True # 夜盘23:30收盘 if self.shortSymbol in NIGHT_MARKET_ZZ or self.shortSymbol in NIGHT_MARKET_DL: if tick.datetime.hour == 23 and tick.datetime.minute == 30: endtick = True # 满足时间要求 # 1,秒周期,tick的时间,距离最后一个bar的开始时间,已经超出bar的时间周期(barTimeInterval) # 2,分钟、小时周期,取整=0 # 3、日周期,开盘时间 # 4、不是最后一个结束tick is_new_bar = False if ((self.period == PERIOD_SECOND and (tick.datetime-lastBar.datetime).seconds >= self.barTimeInterval) \ or (self.period == PERIOD_MINUTE and tick.datetime.minute % self.barTimeInterval == 0 and tick.datetime.minute != self.lastTick.datetime.minute) or (self.period == PERIOD_HOUR and self.barTimeInterval == 1 and tick.datetime and tick.datetime.hour != self.lastTick.datetime.hour) or (self.period == PERIOD_HOUR and self.barTimeInterval == 2 and tick.datetime and tick.datetime.hour != self.lastTick.datetime.hour and tick.datetime.hour in {1, 9, 11, 13, 21, 23}) or (self.period == PERIOD_HOUR and self.barTimeInterval == 4 and tick.datetime and tick.datetime.hour != self.lastTick.datetime.hour and tick.datetime.hour in {1, 9, 13, 21}) or (self.period == PERIOD_DAY and tick.datetime and (tick.datetime.hour == 21 or tick.datetime.hour == 9) and 14 <= self.lastTick.datetime.hour <= 15) ) and not endtick: # 创建并推入新的Bar self.__firstTick(tick) # 触发OnBar事件 self.onBar(lastBar) else: # 更新当前最后一个bar self.barFirstTick = False # 更新最高价、最低价、收盘价、成交量 lastBar.high = max(lastBar.high, tick.lastPrice) lastBar.low = min(lastBar.low, tick.lastPrice) lastBar.close = tick.lastPrice # 更新日内总交易量,和bar内交易量 lastBar.dayVolume = tick.volume if l1 == 1: # 针对第一个bar的tick volume更新 lastBar.volume = tick.volume else: # 针对新交易日的第一个bar:于上一个bar的时间在14,当前bar的时间不在14点,初始化为tick.volume if self.lineBar[-2].datetime.hour == 14 and tick.datetime.hour != 14 and not endtick: lastBar.volume = tick.volume else: # 其他情况,bar为同一交易日,将tick的volume,减去上一bar的dayVolume lastBar.volume = tick.volume - self.lineBar[-2].dayVolume # 更新Bar的颜色 if lastBar.close > lastBar.open: lastBar.color = COLOR_RED elif lastBar.close < lastBar.open: lastBar.color = COLOR_BLUE else: lastBar.color = COLOR_EQUAL # ---------------------------------------------------------------------- def __recountPreHighLow(self): """计算 K线的前周期最高和最低""" if self.inputPreLen <= 0: # 不计算 return # 1、lineBar满足长度才执行计算 if len(self.lineBar) < self.inputPreLen: self.writeCtaLog(u'数据未充分,当前Bar数据数量:{0},计算High、Low需要:{1}'. format(len(self.lineBar), self.inputPreLen)) return # 2.计算前inputPreLen周期内(不包含当前周期)的Bar高点和低点 preHigh = EMPTY_FLOAT preLow = EMPTY_FLOAT if self.mode == self.TICK_MODE: idx = 2 else: idx = 1 for i in range(len(self.lineBar)-idx, len(self.lineBar)-idx-self.inputPreLen, -1): if self.lineBar[i].high > preHigh or preHigh == EMPTY_FLOAT: preHigh = self.lineBar[i].high # 前InputPreLen周期高点 if self.lineBar[i].low < preLow or preLow == EMPTY_FLOAT: preLow = self.lineBar[i].low # 前InputPreLen周期低点 # 保存 if len(self.preHigh) > self.inputPreLen * 8: del self.preHigh[0] self.preHigh.append(preHigh) # 保存 if len(self.preLow)> self.inputPreLen * 8: del self.preLow[0] self.preLow.append(preLow) #---------------------------------------------------------------------- def __recountMa(self): """计算K线的MA1 和MA2""" l = len(self.lineBar) if not (self.inputMa1Len > 0 or self.inputMa2Len > 0 or self.inputMa3Len > 0): # 不计算 return # 1、lineBar满足长度才执行计算 if len(self.lineBar) < max(7, self.inputMa1Len, self.inputMa2Len, self.inputMa3Len)+2: self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算MA需要:{1}'. format(len(self.lineBar), max(7, self.inputMa1Len, self.inputMa2Len, self.inputMa3Len)+2)) return # 计算第一条MA均线 if self.inputMa1Len > 0: if self.inputMa1Len > l: ma1Len = l else: ma1Len = self.inputMa1Len # 3、获取前InputN周期(不包含当前周期)的K线 if self.mode == self.TICK_MODE: listClose=[x.close for x in self.lineBar[-ma1Len - 1:-1]] else: listClose=[x.close for x in self.lineBar[-ma1Len:]] barMa1 = ta.MA(numpy.array(listClose, dtype=float), ma1Len)[-1] barMa1 = round(float(barMa1), self.round_n) if len(self.lineMa1) > self.inputMa1Len*8: del self.lineMa1[0] self.lineMa1.append(barMa1) # 计算第二条MA均线 if self.inputMa2Len > 0: if self.inputMa2Len > l: ma2Len = l else: ma2Len = self.inputMa2Len # 3、获取前InputN周期(不包含当前周期)的K线 if self.mode == self.TICK_MODE: listClose=[x.close for x in self.lineBar[-ma2Len - 1:-1]] else: listClose=[x.close for x in self.lineBar[-ma2Len:]] barMa2 = ta.MA(
numpy.array(listClose, dtype=float)
numpy.array
import numpy as np from utils.constant import NEGATIVE, POSITIVE from utils.utils import mean_to_canonical import networkx as nx from collections import Counter from sklearn.linear_model import LinearRegression, LogisticRegression import random from utils.utils import numberToBase from utils.utils import multi_index_to_index from utils.utils import sigmoid, outliers_iqr, threshold_matrix from utils.r_pca import R_pca class Ivy: def __init__(self): self.valid_iv = None self.w = None def train(self,IVs,X=None, deps=[], anchor=None, class_balance=None, use_forward=True, use_canonical=True, **kwargs): # determine valid IVs if self.valid_iv == None: self.valid_iv = list(range(IVs.shape[1])) # self._is_valid_iv(IVs) # record use_forward and use_canonical self.use_forward = use_forward self.use_canonical = use_canonical # change the encoding of IVs to {-1,1} IVs = self._convert_iv(IVs) # assign class balance if class_balance is None: # find out class_balance in a heuristic fashion # other class_balance identification methods can also be used class_balance = Counter(IVs.flatten()) class_balance = class_balance[1]/(class_balance[-1]+class_balance[1]) class_balance = [1-class_balance, class_balance] n,p = IVs.shape # sem: second empirical moment matirx sem = np.matmul(IVs.T,IVs)/n # for conditional independent model, # the inverse graph is the complete graph inverse_graph = nx.complete_graph(p) # incidence matrix of the inverse graph M = nx.incidence_matrix(inverse_graph).T.toarray() edge_list_M = np.asarray(inverse_graph.edges()) # make sure deps are in increasing order deps = [[int(x[0]),int(x[1])] for x in deps] # update M and edge_list_M by removing edges in deps selector = [(list(x) not in deps) for x in edge_list_M] M = M[selector,:] edge_list_M = edge_list_M[selector,:] if self.use_forward: # create q exp_q = np.abs(sem[edge_list_M[:,0],edge_list_M[:,1]]) # handle zeros in exp_q eps_zero = 1e-12 exp_q[exp_q==0] = eps_zero # take log of exp_q to get q q = np.log(exp_q) # use only positive entries in sem selector_positive_sem = sem[edge_list_M[:,0],edge_list_M[:,1]]>0 q_positve = q[selector_positive_sem] M_postive = M[selector_positive_sem,:] # make sure that M matrix is full-rank # find the all-zero column selector_non_zero_column_M_positve = np.sum(M_postive,axis=0)>0 # compute l # r_cond = None is for using future default # and silence warning l_subset,_,_,_ = np.linalg.lstsq( M_postive[:,selector_non_zero_column_M_positve], q_positve,rcond=None) l = np.zeros(M.shape[1]) l[:] = np.nan l[selector_non_zero_column_M_positve] = l_subset l[np.isnan(l)] = -100000 self.w = np.exp(l) # get the w which is the mean parameter # the following are in {0,1} encoding self.class_balance = class_balance #[neg, pos] if self.use_canonical: # first empirical moments with {-1,1} encoding fem = np.mean(IVs,axis=0) # second empirical moments with {-1,1} encoding sem = ((IVs.T) @ (IVs))/(n) # augmented with z fem_aug = np.append(fem,self.class_balance[1]-self.class_balance[0]) sem_aug = np.vstack([sem,self.w]) sem_aug = np.hstack([sem_aug,np.append(self.w,0).reshape(-1,1)]) mean_parameter = np.copy(sem_aug) np.fill_diagonal(mean_parameter,fem_aug) self.im, self.theta = mean_to_canonical(deps,mean_parameter,maxiter=100,alpha=0.2) # update class balance self.class_balance_im = self.im.infer.query([str(p)],show_progress=False).normalize(inplace=False).values # use canonical parameters self.im.infer.calibrate() self.im.infer.get_cliques() factor_dict = self.im.infer.get_clique_beliefs() # create prob_dict prob_dict = {} for clique in factor_dict: prob_index = np.array([numberToBase(x,3,len(clique)) for x in range(3**len(clique))]) prob = [] factor = factor_dict[clique].normalize(inplace=False) for assignment in prob_index: # see if assignment is the same dimension of factor absence_selector = (assignment==1) if np.sum(absence_selector) == 0: prob.append(factor.values[tuple((assignment/2).astype(int))]) else: # if not, marginalize: margin_factor = factor.marginalize(np.array(factor.scope())[np.where(absence_selector)],inplace=False) prob.append(margin_factor.values[tuple((assignment[~absence_selector]/2).astype(int))]) # compute condtional probability upon z selector = (prob_index[:,factor.scope().index(str(p))]==0) prob = np.array(prob) prob[selector] = prob[selector]/class_balance[0] selector = (prob_index[:,factor.scope().index(str(p))]==2) prob[selector] = prob[selector]/class_balance[1] prob_dict.update({clique:{"prob_index":np.copy(prob_index),"prob":np.log(prob)}}) self.prob_dict = prob_dict def dependency_validity(self,IVs,lam=None,mu=None,**kwargs): # take symmetric matrix as an argument as well if (IVs.shape[0]==IVs.shape[1]) and np.all(IVs==IVs.T): Sigma = IVs else: Sigma = np.cov(IVs.T) # compute the inverse covariance matrix pinv_Sigma = np.linalg.pinv(Sigma) # set default value of lam and mu lam_default = 1/np.sqrt(np.max(pinv_Sigma.shape)) mu_default = np.prod(pinv_Sigma.shape)/(4*np.sum(np.abs(pinv_Sigma))) if lam == None: lam = lam_default else: lam = lam * lam_default if mu == None: mu = mu_default else: mu = mu * mu_default rpca = R_pca(pinv_Sigma,lmbda=lam,mu=mu) L, S = rpca.fit(max_iter=10000, iter_print=10000) # estimate accuracy u, s, vh = np.linalg.svd(L) l = -u[:,0]*np.sqrt(s[0]) score = (Sigma @ l) return score, S, L def predict_proba(self,IVs,is_ad_hoc=False): # compute soft label IVs = self._convert_iv(IVs) # w = self.w # conditional_accuracy = self.conditional_accuracy n,p = IVs.shape if self.use_canonical: # use canonical parameters pos_posterior = np.zeros(n) neg_posterior = np.zeros(n) for clique in self.prob_dict: iv_index_in_clique = [x for x in range(len(clique)) if list(clique)[x]!= str(p)] iv_index_in_IVs = np.array(list(clique))[iv_index_in_clique].astype(int) assignment = np.zeros([n,len(clique)]).astype(int) assignment[:,iv_index_in_clique] = IVs[:,iv_index_in_IVs]+1 pos_assignment = np.copy(assignment) neg_assignment = np.copy(assignment) pos_assignment[:,list(clique).index(str(p))] = 2 neg_assignment[:,list(clique).index(str(p))] = 0 del assignment # find the index of the assignment pos_assignment_single_index = multi_index_to_index(pos_assignment) neg_assignment_single_index = multi_index_to_index(neg_assignment) # update positve posterior pos_posterior = pos_posterior + self.prob_dict[clique]["prob"][pos_assignment_single_index] # update negative posterior neg_posterior = neg_posterior + self.prob_dict[clique]["prob"][neg_assignment_single_index] Zprob = sigmoid(-(neg_posterior+np.log(self.class_balance_im[0]))+(pos_posterior+np.log(self.class_balance_im[1]))) else: raise NotImplementedError("set use_cannonical=True in training!") return Zprob def predict(self, IVs, b=0.5): Zprob = self.predict_proba(IVs) Z = np.where(Zprob > b, POSITIVE, NEGATIVE) return Z def _convert_iv(self,IVs): IVs = IVs-1 IVs = IVs[:,self.valid_iv] return IVs def get_weights(self): return self.w def get_dependencies(self,S): # threshod deps_mat deps_mat = np.abs(np.copy(S)) np.fill_diagonal(deps_mat,0) # compute thresh thresh_list = np.unique(np.abs(deps_mat[np.triu_indices(deps_mat.shape[0],k=1)])) outlier_index = outliers_iqr(thresh_list)[0] if len(outlier_index)>0: min_outlier = np.min(thresh_list[outlier_index]) thresh = np.max(thresh_list[thresh_list<min_outlier]) short_thresh_list = thresh_list[thresh_list>=thresh] thresh = short_thresh_list[np.argmax(short_thresh_list[1:]/short_thresh_list[0:-1])+1] # get the edges deps = threshold_matrix(deps_mat,thresh) else: deps = [] return deps def get_valid_iv_indx(self,score): # get valid IVs valid_thresh_list = np.sort(np.abs(score)) # exclue the first one valid_thresh = valid_thresh_list[
np.argmax(valid_thresh_list[2:]/valid_thresh_list[1:-1])
numpy.argmax
# -*- mode: python; coding: utf-8 -* # Copyright (c) 2018 Radio Astronomy Software Group # Licensed under the 2-clause BSD License """Tests for BeamFits object. """ from __future__ import absolute_import, division, print_function import nose.tools as nt import os import numpy as np import astropy from astropy.io import fits from pyuvdata import UVBeam import pyuvdata.tests as uvtest from pyuvdata.data import DATA_PATH import pyuvdata.utils as uvutils filenames = ['HERA_NicCST_150MHz.txt', 'HERA_NicCST_123MHz.txt'] cst_files = [os.path.join(DATA_PATH, f) for f in filenames] def test_readCST_writereadFITS(): beam_in = UVBeam() beam_out = UVBeam() beam_in.read_cst_beam(cst_files[0], beam_type='efield', frequency=150e6, telescope_name='TEST', feed_name='bob', feed_version='0.1', feed_pol=['x'], model_name='E-field pattern - Rigging height 4.9m', model_version='1.0') # add optional parameters for testing purposes beam_in.extra_keywords = {'KEY1': 'test_keyword'} beam_in.reference_input_impedance = 340. beam_in.reference_output_impedance = 50. beam_in.receiver_temperature_array = np.random.normal(50.0, 5, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.loss_array = np.random.normal(50.0, 5, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.mismatch_array = np.random.normal(0.0, 1.0, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.s_parameters = np.random.normal(0.0, 0.3, size=(4, beam_in.Nspws, beam_in.Nfreqs)) write_file = os.path.join(DATA_PATH, 'test/outtest_beam.fits') beam_in.write_beamfits(write_file, clobber=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) # redo for power beam del(beam_in) beam_in = UVBeam() # read in efield and convert to power to test cross-pols beam_in.read_cst_beam(cst_files[0], beam_type='efield', frequency=150e6, telescope_name='TEST', feed_name='bob', feed_version='0.1', feed_pol=['x'], model_name='E-field pattern - Rigging height 4.9m', model_version='1.0') beam_in.efield_to_power() # add optional parameters for testing purposes beam_in.extra_keywords = {'KEY1': 'test_keyword'} beam_in.reference_input_impedance = 340. beam_in.reference_output_impedance = 50. beam_in.receiver_temperature_array = np.random.normal(50.0, 5, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.loss_array = np.random.normal(50.0, 5, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.mismatch_array = np.random.normal(0.0, 1.0, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.s_parameters = np.random.normal(0.0, 0.3, size=(4, beam_in.Nspws, beam_in.Nfreqs)) beam_in.write_beamfits(write_file, clobber=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) # now replace 'power' with 'intensity' for btype F = fits.open(write_file) data = F[0].data primary_hdr = F[0].header primary_hdr['BTYPE'] = 'Intensity' hdunames = uvutils._fits_indexhdus(F) bandpass_hdu = F[hdunames['BANDPARM']] prihdu = fits.PrimaryHDU(data=data, header=primary_hdr) hdulist = fits.HDUList([prihdu, bandpass_hdu]) if float(astropy.__version__[0:3]) < 1.3: hdulist.writeto(write_file, clobber=True) else: hdulist.writeto(write_file, overwrite=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) # now remove coordsys but leave ctypes 1 & 2 F = fits.open(write_file) data = F[0].data primary_hdr = F[0].header primary_hdr.pop('COORDSYS') hdunames = uvutils._fits_indexhdus(F) bandpass_hdu = F[hdunames['BANDPARM']] prihdu = fits.PrimaryHDU(data=data, header=primary_hdr) hdulist = fits.HDUList([prihdu, bandpass_hdu]) if float(astropy.__version__[0:3]) < 1.3: hdulist.writeto(write_file, clobber=True) else: hdulist.writeto(write_file, overwrite=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) # now change frequency units F = fits.open(write_file) data = F[0].data primary_hdr = F[0].header primary_hdr['CUNIT3'] = 'MHz' primary_hdr['CRVAL3'] = primary_hdr['CRVAL3'] / 1e6 primary_hdr['CDELT3'] = primary_hdr['CRVAL3'] / 1e6 hdunames = uvutils._fits_indexhdus(F) bandpass_hdu = F[hdunames['BANDPARM']] prihdu = fits.PrimaryHDU(data=data, header=primary_hdr) hdulist = fits.HDUList([prihdu, bandpass_hdu]) if float(astropy.__version__[0:3]) < 1.3: hdulist.writeto(write_file, clobber=True) else: hdulist.writeto(write_file, overwrite=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) def test_writeread_healpix(): beam_in = UVBeam() beam_out = UVBeam() # fill UVBeam object with dummy data for now for testing purposes beam_in.read_cst_beam(cst_files[0], beam_type='efield', frequency=150e6, telescope_name='TEST', feed_name='bob', feed_version='0.1', feed_pol=['x'], model_name='E-field pattern - Rigging height 4.9m', model_version='1.0') beam_in.interpolation_function = 'az_za_simple' beam_in.to_healpix() write_file = os.path.join(DATA_PATH, 'test/outtest_beam_hpx.fits') beam_in.write_beamfits(write_file, clobber=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) # redo for power beam del(beam_in) beam_in = UVBeam() # read in efield and convert to power to test cross-pols beam_in.read_cst_beam(cst_files[0], beam_type='efield', frequency=150e6, telescope_name='TEST', feed_name='bob', feed_version='0.1', feed_pol=['x'], model_name='E-field pattern - Rigging height 4.9m', model_version='1.0') beam_in.efield_to_power() # add optional parameters for testing purposes beam_in.extra_keywords = {'KEY1': 'test_keyword'} beam_in.reference_input_impedance = 340. beam_in.reference_output_impedance = 50. beam_in.receiver_temperature_array = np.random.normal(50.0, 5, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.loss_array = np.random.normal(50.0, 5, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.mismatch_array = np.random.normal(0.0, 1.0, size=(beam_in.Nspws, beam_in.Nfreqs)) beam_in.s_parameters = np.random.normal(0.0, 0.3, size=(4, beam_in.Nspws, beam_in.Nfreqs)) # check that data_array is complex nt.assert_true(np.iscomplexobj(np.real_if_close(beam_in.data_array, tol=10))) beam_in.interpolation_function = 'az_za_simple' beam_in.to_healpix() # check that data_array is complex after interpolation nt.assert_true(np.iscomplexobj(np.real_if_close(beam_in.data_array, tol=10))) beam_in.write_beamfits(write_file, clobber=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) # now remove coordsys but leave ctype 1 F = fits.open(write_file) data = F[0].data primary_hdr = F[0].header primary_hdr.pop('COORDSYS') hdunames = uvutils._fits_indexhdus(F) hpx_hdu = F[hdunames['HPX_INDS']] bandpass_hdu = F[hdunames['BANDPARM']] prihdu = fits.PrimaryHDU(data=data, header=primary_hdr) hdulist = fits.HDUList([prihdu, hpx_hdu, bandpass_hdu]) if float(astropy.__version__[0:3]) < 1.3: hdulist.writeto(write_file, clobber=True) else: hdulist.writeto(write_file, overwrite=True) beam_out.read_beamfits(write_file) nt.assert_equal(beam_in, beam_out) def test_errors(): beam_in = UVBeam() beam_out = UVBeam() beam_in.read_cst_beam(cst_files[0], beam_type='efield', frequency=150e6, telescope_name='TEST', feed_name='bob', feed_version='0.1', feed_pol=['x'], model_name='E-field pattern - Rigging height 4.9m', model_version='1.0') beam_in.beam_type = 'foo' write_file = os.path.join(DATA_PATH, 'test/outtest_beam.fits') nt.assert_raises(ValueError, beam_in.write_beamfits, write_file, clobber=True) nt.assert_raises(ValueError, beam_in.write_beamfits, write_file, clobber=True, run_check=False) beam_in.beam_type = 'efield' beam_in.antenna_type = 'phased_array' write_file = os.path.join(DATA_PATH, 'test/outtest_beam.fits') nt.assert_raises(ValueError, beam_in.write_beamfits, write_file, clobber=True) # now change values for various items in primary hdu to test errors beam_in.antenna_type = 'simple' header_vals_to_change = [{'BTYPE': 'foo'}, {'COORDSYS': 'orthoslant_zenith'}, {'NAXIS': ''}, {'CUNIT1': 'foo'}, {'CUNIT2': 'foo'}, {'CUNIT3': 'foo'}] for i, hdr_dict in enumerate(header_vals_to_change): beam_in.write_beamfits(write_file, clobber=True) keyword = list(hdr_dict.keys())[0] new_val = hdr_dict[keyword] F = fits.open(write_file) data = F[0].data primary_hdr = F[0].header hdunames = uvutils._fits_indexhdus(F) basisvec_hdu = F[hdunames['BASISVEC']] bandpass_hdu = F[hdunames['BANDPARM']] if 'NAXIS' in keyword: ax_num = keyword.split('NAXIS')[1] if ax_num != '': ax_num = int(ax_num) ax_use = len(data.shape) - ax_num new_arrays = np.split(data, primary_hdr[keyword], axis=ax_use) data = new_arrays[0] else: data = np.squeeze(np.split(data, primary_hdr['NAXIS1'], axis=len(data.shape) - 1)[0]) else: primary_hdr[keyword] = new_val prihdu = fits.PrimaryHDU(data=data, header=primary_hdr) hdulist = fits.HDUList([prihdu, basisvec_hdu, bandpass_hdu]) if float(astropy.__version__[0:3]) < 1.3: hdulist.writeto(write_file, clobber=True) else: hdulist.writeto(write_file, overwrite=True) nt.assert_raises(ValueError, beam_out.read_beamfits, write_file) # now change values for various items in basisvec hdu to not match primary hdu header_vals_to_change = [{'COORDSYS': 'foo'}, {'CTYPE1': 'foo'}, {'CTYPE2': 'foo'}, {'CDELT1': np.diff(beam_in.axis1_array)[0] * 2}, {'CDELT2':
np.diff(beam_in.axis2_array)
numpy.diff
"""ResNet50 model for Keras. Adapted from tf.keras.applications.resnet50.ResNet50(). This is ResNet model version 1.5. Related papers/blogs: - https://arxiv.org/abs/1512.03385 - https://arxiv.org/pdf/1603.05027v2.pdf - http://torch.ch/blog/2016/02/04/resnets.html """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.python.keras import backend from tensorflow.python.keras import initializers from tensorflow.python.keras import models from tensorflow.python.keras import regularizers layers = tf.keras.layers def _gen_l2_regularizer(use_l2_regularizer=True, l2_weight_decay=1e-4): return regularizers.l2(l2_weight_decay) if use_l2_regularizer else None def fixed_padding(inputs, kernel_size, data_format='channels_last'): """Pads the input along the spatial dimensions independently of input size. Args: inputs: `Tensor` of size `[batch, channels, height, width]` or `[batch, height, width, channels]` depending on `data_format`. kernel_size: `int` kernel size to be used for `conv2d` or max_pool2d` operations. Should be a positive integer. data_format: `str` either "channels_first" for `[batch, channels, height, width]` or "channels_last for `[batch, height, width, channels]`. Returns: A padded `Tensor` of the same `data_format` with size either intact (if `kernel_size == 1`) or padded (if `kernel_size > 1`). """ pad_total = kernel_size - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg if data_format == 'channels_first': padded_inputs = tf.pad(inputs, [[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]]) else: padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]]) return padded_inputs def identity_block(input_tensor, kernel_size, filters, stage, block, use_l2_regularizer=True, batch_norm_decay=0.9, batch_norm_epsilon=1e-5, batch_norm_trainable=True): """The identity block is the block that has no conv layer at shortcut. Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names use_l2_regularizer: whether to use L2 regularizer on Conv layer. batch_norm_decay: Moment of batch norm layers. batch_norm_epsilon: Epsilon of batch borm layers. Returns: Output tensor for the block. """ filters1, filters2, filters3 = filters if backend.image_data_format() == 'channels_last': bn_axis = 3 else: bn_axis = 1 conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' # Kernel: 1 # Strides: 1 x = layers.Conv2D( filters1, kernel_size=(1, 1), strides=(1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2a')( input_tensor) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name=bn_name_base + '2a')( x) x = layers.Activation('relu')(x) # Kernel: 3 # Strides: 1 x = layers.Conv2D( filters2, kernel_size=kernel_size, strides=(1,1), padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2b')(x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name=bn_name_base + '2b')(x) x = layers.Activation('relu')(x) # Kernel: 1 # Strides: 1 x = layers.Conv2D( filters3, kernel_size=(1, 1), strides=(1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2c')(x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name=bn_name_base + '2c')(x) x = layers.add([x, input_tensor]) x = layers.Activation('relu')(x) return x def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), use_l2_regularizer=True, batch_norm_decay=0.9, batch_norm_epsilon=1e-5, batch_norm_trainable=True): """A block that has a conv layer at shortcut. Note that from stage 3, the second conv layer at main path is with strides=(2, 2) And the shortcut should have strides=(2, 2) as well Args: input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names strides: Strides for the second conv layer in the block. use_l2_regularizer: whether to use L2 regularizer on Conv layer. batch_norm_decay: Moment of batch norm layers. batch_norm_epsilon: Epsilon of batch borm layers. Returns: Output tensor for the block. """ filters1, filters2, filters3 = filters if backend.image_data_format() == 'channels_last': bn_axis = 3 else: bn_axis = 1 conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' # Kernel: 1 # Stride: Dynamic shortcut = layers.Conv2D( filters3, kernel_size=(1, 1), strides=strides, use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '1')(input_tensor) shortcut = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name=bn_name_base + '1')(shortcut) # Kernel: 1 # Stride: 1 x = layers.Conv2D( filters1, kernel_size=(1, 1), strides=(1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2a')(input_tensor) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name=bn_name_base + '2a')(x) x = layers.Activation('relu')(x) # Kernel: 3 # Strides: Dynamic if strides[0] > 1: x = fixed_padding(x, kernel_size, data_format=backend.image_data_format()) padding = 'valid' else: padding = 'same' x = layers.Conv2D( filters2, kernel_size=kernel_size, strides=strides, padding=padding, use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2b')(x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name=bn_name_base + '2b')(x) x = layers.Activation('relu')(x) # Kernel: 1 # Stride: 1 x = layers.Conv2D( filters3, kernel_size=(1, 1), strides=(1, 1), use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name=conv_name_base + '2c')(x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name=bn_name_base + '2c')(x) x = layers.add([x, shortcut]) x = layers.Activation('relu')(x) return x def resnet50( include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, batch_size=None, use_l2_regularizer=True, rescale_inputs=False, batch_norm_decay=0.9, batch_norm_epsilon=1e-5, batch_norm_trainable=True, width_multiplier=1): """Instantiates the ResNet50 architecture. Args: num_classes: `int` number of classes for image classification. batch_size: Size of the batches for each step. use_l2_regularizer: whether to use L2 regularizer on Conv/Dense layer. rescale_inputs: whether to rescale inputs from 0 to 1. batch_norm_decay: Moment of batch norm layers. batch_norm_epsilon: Epsilon of batch borm layers. Returns: A Keras model instance. """ if input_tensor is None: img_input = layers.Input(shape=input_shape, batch_size=batch_size) else: if not tf.keras.backend.is_keras_tensor(input_tensor): img_input = layers.Input(tensor=input_tensor, shape=input_shape) else: img_input = input_tensor x = img_input if backend.image_data_format() == 'channels_first': x = layers.Permute((3, 1, 2))(x) bn_axis = 1 else: # channels_last bn_axis = 3 block_config = dict( use_l2_regularizer=use_l2_regularizer, batch_norm_decay=batch_norm_decay, batch_norm_epsilon=batch_norm_epsilon, batch_norm_trainable=batch_norm_trainable) #x = layers.ZeroPadding2D(padding=(3, 3), name='conv1_pad')(x) x = fixed_padding(x, 7, backend.image_data_format()) x = layers.Conv2D( 64 * width_multiplier, kernel_size=(7, 7), strides=(2, 2), padding='valid', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=_gen_l2_regularizer(use_l2_regularizer), name='conv1')(x) x = layers.BatchNormalization( axis=bn_axis, momentum=batch_norm_decay, epsilon=batch_norm_epsilon, trainable=batch_norm_trainable, name='bn_conv1')(x) x = layers.Activation('relu')(x) x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x) x = conv_block(x, 3, np.array([64, 64, 256]) * width_multiplier, stage=2, block='a', strides=(1, 1), **block_config) x = identity_block(x, 3, np.array([64, 64, 256]) * width_multiplier, stage=2, block='b', **block_config) x = identity_block(x, 3, np.array([64, 64, 256]) * width_multiplier, stage=2, block='c', **block_config) x = conv_block(x, 3, np.array([128, 128, 512]) * width_multiplier, stage=3, block='a', **block_config) x = identity_block(x, 3, np.array([128, 128, 512]) * width_multiplier, stage=3, block='b', **block_config) x = identity_block(x, 3, np.array([128, 128, 512]) * width_multiplier, stage=3, block='c', **block_config) x = identity_block(x, 3, np.array([128, 128, 512]) * width_multiplier, stage=3, block='d', **block_config) x = conv_block(x, 3, np.array([256, 256, 1024]) * width_multiplier, stage=4, block='a', **block_config) x = identity_block(x, 3, np.array([256, 256, 1024]) * width_multiplier, stage=4, block='b', **block_config) x = identity_block(x, 3, np.array([256, 256, 1024]) * width_multiplier, stage=4, block='c', **block_config) x = identity_block(x, 3, np.array([256, 256, 1024]) * width_multiplier, stage=4, block='d', **block_config) x = identity_block(x, 3, np.array([256, 256, 1024]) * width_multiplier, stage=4, block='e', **block_config) x = identity_block(x, 3, np.array([256, 256, 1024]) * width_multiplier, stage=4, block='f', **block_config) x = conv_block(x, 3, np.array([512, 512, 2048]) * width_multiplier, stage=5, block='a', **block_config) x = identity_block(x, 3,
np.array([512, 512, 2048])
numpy.array
#!/bin/env python from matplotlib import pyplot as plt import numpy as np import argparse import os, sys import regex as re import pickle as pkl class Chip: def __init__(self, file_name_str): self.file_name = file_name_str basename = file_name_str.split("/")[-1] #remove parent dirs basename = basename.split(".")[0] #remove filetype self.basename = basename pattern = re.compile("dtc(\d+)isBarrel(\d+)layer(\d+)disk(\d+)module(\d+)chip(\d+)") result = pattern.match(basename) if not result: raise ValueError("{} is not a valid input filename.".format(file_name_str)) values = result.groups() self.dtc_id = int(values[0]) self.is_barrel = True if int(values[1])==0: self.is_barrel = False self.layer = int(values[2]) self.disk = int(values[3]) self.module = int(values[4]) self.chip_id = int(values[5]) def read_nevents_from_dirname(data_dir): pattern = re.compile(".*output_(\d+k?)evt.*") result = pattern.match(data_dir) if not result: raise ValueError("Error: input dir doesn't indicate number of events, should be in format like input_10kevt...") value = result.groups()[0] value = value.replace("k","000") return int(value) def load_data(data_dir, cache_file_name=""): # if there is cache file, load it if cache_file_name and os.path.exists(cache_file_name): with open(cache_file_name,'rb') as cache_file: data = pkl.load(cache_file) print("Loaded cheched data from file {}".format(cache_file_name)) return data # otherwise we load data as normal data = {} # read the ordered input file names, so that we can match to the physical location of each chip with open("{}/ordered_file_names.txt".format(data_dir)) as ordered_file_names_txt: data['chip'] = [Chip(line.replace("\n","")) for line in ordered_file_names_txt.readlines()] nchips = len(data['chip']) # read the event length from input file nevents = read_nevents_from_dirname(data_dir) data["event_size"] = np.zeros(shape=(nchips, nevents),dtype=np.int32) print("Reading event length...") for ichip in range(nchips): ievent = 0 with open("../"+data["chip"][ichip].file_name, "rb") as chip_binary_input: byte = chip_binary_input.read(8) mask = (1 << 63) len_counting = 0 while (byte): int_from_byte = int(byte[::-1].hex(),16) if ( (mask & int_from_byte) == mask ): # new event if len_counting == 0: len_counting += 1 else: data["event_size"][ichip][ievent]=len_counting ievent += 1 len_counting = 1 else: len_counting += 1 byte = chip_binary_input.read(8) if len_counting > 0: data["event_size"][ichip][ievent]=len_counting # read the buffer ocupancy from output file # estimating nticks assuming maximum 1000 ticks per event nticks = 1000 * nevents data["buffer_over_time"] = np.zeros(shape=(nchips, nticks),dtype=np.int32) input_fn = "{}/output_fifo_data_sizes.txt".format(data_dir) print("reading buffer occupancies...") with open(input_fn) as f: for iline,line in enumerate(f.readlines()): if iline >= nticks: nticks = nticks * 2 data["buffer_over_time"].resize( (nchips, nticks) ) numbers = line.replace("\n","").split(",") assert(nchips == len(numbers)) #print(numbers) for ichip in range(nchips): #print(int(numbers[i])) data["buffer_over_time"][ichip][iline]=int(numbers[ichip]) # Save data into cache file if cache_file_name: with open(cache_file_name,'wb') as cache_file: pkl.dump(data, cache_file) print("Saved data into cache file {}".format(cache_file_name)) return data def find_local_maximum(a): ret = np.zeros(int(len(a)/2),dtype=np.int32) jentry = 0 for ientry in range(1, len(a)-1): if (a[ientry] > a[ientry+1]) & (a[ientry] >= a[ientry-1]) & (a[ientry] > 1): ret[jentry] = a[ientry] jentry+=1 ret.resize(jentry) return ret def get_perchip_tag(data, ichip): perchip_tag = "DTC={}, ".format(data["chip"][ichip].dtc_id) if data["chip"][ichip].is_barrel: perchip_tag += "Barrel" else: perchip_tag += "Endcap/Forward" perchip_tag += "\n Layer={}".format(data["chip"][ichip].layer) perchip_tag += ", Disk={}".format(data["chip"][ichip].disk) perchip_tag += ", Module={}".format(data["chip"][ichip].module) perchip_tag += ", Chip_ID={}".format(data["chip"][ichip].chip_id) return perchip_tag def plot_buffer_over_time(data, outdir, args): buffer_over_time_outdir = "{}/buffer-over-time_plots".format(outdir) if not os.path.exists(buffer_over_time_outdir): os.makedirs(buffer_over_time_outdir) fig,ax = plt.subplots(1,1) total_buffer_over_time = np.zeros(len(data["buffer_over_time"][0]),dtype=np.int32) # Plot for inidvidual FIFO for ichip,buffer_over_time in enumerate(data["buffer_over_time"]): total_buffer_over_time += buffer_over_time if args.total_only: continue x = np.arange(len(buffer_over_time)) ax.plot(x,buffer_over_time*64/1024) plot_file_name = "{}/{}.png".format(buffer_over_time_outdir, data["chip"][ichip].basename) ax.set_xlabel("clock tick") ax.set_ylabel("buffer occupancy (kb)") perchip_tag = get_perchip_tag(data, ichip) ax.text(0.5, 0.7, perchip_tag, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) fig.savefig(plot_file_name) print("{} saved.".format(plot_file_name)) ax.clear() # Plot for total x = np.arange(len(total_buffer_over_time)) ax.plot(x,total_buffer_over_time*64/1024) plot_file_name = "{}/DTC11Total.png".format(buffer_over_time_outdir) ax.set_xlabel("clock tick") ax.set_ylabel("buffer occupancy (kb)") ax.text(0.5, 0.7, "Sum of FIFO occupancies", horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) fig.savefig(plot_file_name) print("{} saved.".format(plot_file_name)) ax.clear() return def plot_buffer_distribution(data, outdir, args, data_to_compare=None, labels_for_comparison=("ver1", "ver2")): buffer_dist_outdir = "{}/buffer_distribution_plots".format(outdir) if args.add_buffer_all_tick: buffer_dist_outdir += "_hasAllTick" if args.no_buffer_peak: buffer_dist_outdir += "_noPeakDist" if args.no_event_length: buffer_dist_outdir += "_noEvtLength" if args.cumulative_use_all: buffer_dist_outdir += "_cumulativeAllTick" if args.no_cumulative: buffer_dist_outdir += "_noCumulative" if not os.path.exists(buffer_dist_outdir): os.makedirs(buffer_dist_outdir) fig, ax = plt.subplots() # Plot for individual fifos max_single_chip_buffer = np.max(data["buffer_over_time"]) max_single_chip_evtsize = np.max(data["event_size"]) binning_buffer = np.arange(0,4+max_single_chip_buffer,2) binning_evtsize = np.arange(0,4+max_single_chip_evtsize,2) max_xlim = 300 for ichip in range(len(data["chip"])): if args.total_only: continue ax.clear() output_filename = "{}/bufferplot_ichip{}.png".format(outdir, data["chip"][ichip].basename) h_event_length,_ = np.histogram(data["event_size"][ichip], bins=binning_evtsize, density=True) if not args.no_event_length: ax.plot(binning_evtsize[:-1]/16, h_event_length, label="event length") max_xlim = max(max_xlim, max(binning_evtsize)) h_buffering_size,_ = np.histogram(data["buffer_over_time"][ichip], bins=binning_buffer, density=True) if args.add_buffer_all_tick: ax.plot(binning_buffer[:-1]/16 , h_buffering_size, label="fifo capacity") max_xlim = max(max_xlim, max(binning_buffer)) h_buffering_local_maximum,_ = np.histogram(find_local_maximum(data["buffer_over_time"][ichip]), bins=binning_buffer, density=True) if not args.no_buffer_peak: ax.plot(binning_buffer[:-1]/16, h_buffering_local_maximum, label="fifo capacity at local maximum") max_xlim = max(max_xlim, max(binning_buffer)) # Plot cumulative if not args.no_cumulative: h_cumulative = np.zeros(len(h_buffering_size),dtype=np.float32) if args.cumulative_use_all: h_normed = (binning_buffer[1:] - binning_buffer[:-1]) * h_buffering_size else: h_normed = (binning_buffer[1:] - binning_buffer[:-1]) * h_buffering_local_maximum for ibin in range(len(h_cumulative)): h_cumulative[ibin] = sum(h_normed[ibin:]) ax.plot(binning_buffer[:-1]/16, h_cumulative, label="comprehensive cumulative") max_xlim = max(max_xlim, max(binning_buffer)) ax.legend() ax.set_xlim(0,max_xlim/16) ax.set_yscale('log') ax.set_xlabel("buffer occupancy (kb)") ax.set_ylabel("counts") perchip_tag = get_perchip_tag(data, ichip) ax.text(0.5, 0.7, perchip_tag, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) output_filename = "{}/{}.png".format(buffer_dist_outdir, data["chip"][ichip].basename) fig.savefig(output_filename) print("{} saved.".format(output_filename)) # Plot for combination of fifos: fifo_sizes_combined = np.zeros(len(data["buffer_over_time"][0]),dtype=np.int32) event_length_combined = np.zeros(len(data["event_size"][0]),dtype=np.int32) for ichip in range(len(data["buffer_over_time"])): fifo_sizes_combined += np.array(data["buffer_over_time"][ichip]) event_length_combined +=
np.array(data["event_size"][ichip])
numpy.array
import os import numpy as np import pytest import autoarray as aa from autoarray import exc class TestRegion1D: def test__sanity_check__first_pixel_or_column_equal_too_or_bigger_than_second__raise_errors( self ): with pytest.raises(exc.RegionException): aa.Region1D(region=(2, 2)) with pytest.raises(exc.RegionException): aa.Region1D(region=(2, 1)) def test__sanity_check__negative_coordinates_raise_errors(self): with pytest.raises(exc.RegionException): aa.Region1D(region=(-1, 0)) with pytest.raises(exc.RegionException): aa.Region1D(region=(0, -1)) def test__extraction_via_slice(self): arr_1d = aa.Array1D.manual_native( array=np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), pixel_scales=1.0 ) region = aa.Region1D(region=(0, 2)) new_arr_1d = arr_1d[region.slice] assert (new_arr_1d == np.array([1.0, 2.0])).all() region = aa.Region1D(region=(1, 3)) new_arr_1d = arr_1d[region.slice] assert (new_arr_1d == np.array([2.0, 3.0])).all() def test__add_region_to_arr_1d_via_slice(self): arr_1d = aa.Array1D.manual_native( array=np.array([1.0, 2.0, 3.0, 4.0]), pixel_scales=1.0 ) image = aa.Array1D.full(fill_value=1.0, shape_native=6, pixel_scales=1.0) region = aa.Region1D(region=(0, 1)) arr_1d[region.slice] += image[region.slice] assert (arr_1d == np.array([2.0, 2.0, 3.0, 4.0])).all() arr_1d = aa.Array1D.manual_native( array=np.array([1.0, 2.0, 3.0, 4.0]), pixel_scales=1.0 ) region = aa.Region1D(region=(2, 4)) arr_1d[region.slice] += image[region.slice] assert (arr_1d == np.array([1.0, 2.0, 4.0, 5.0])).all() def test__set_region_to_zero_via_slice(self): arr_1d = aa.Array1D.manual_native( array=np.array([1.0, 2.0, 3.0, 4.0]), pixel_scales=1.0 ) region = aa.Region1D(region=(0, 1)) arr_1d[region.slice] = 0 assert (arr_1d == np.array([0.0, 2.0, 3.0, 4.0])).all() arr_1d = aa.Array1D.manual_native( array=np.array([1.0, 2.0, 3.0, 4.0]), pixel_scales=1.0 ) region = aa.Region1D(region=(2, 4)) arr_1d[region.slice] = 0 assert (arr_1d ==
np.array([1.0, 2.0, 0.0, 0.0])
numpy.array
# (C) <NAME> and Carnegie Mellon University, 2016 import sys import re import math import os.path import collections import scipy.sparse as SS import scipy.io as SIO import numpy as NP import numpy.random as NR import logging from tensorlog import config from tensorlog import mutil from tensorlog import matrixdb from tensorlog import declare from tensorlog import util conf = config.Config() conf.normalize_outputs = True; conf.help.normalize_outputs = "In .exam files, l1-normalize the weights of valid outputs" # # dealing with labeled training data # class Dataset(object): def __init__(self,xDict,yDict): # dict which maps mode declaration to X matrices for training self.xDict = xDict # likewise for Y matrices self.yDict = yDict def isSinglePredicate(self): """Returns true if all the examples are for a single predicate.""" return len(list(self.xDict.keys()))==1 def extractMode(self,mode): """Return a new Dataset that just contains this mode.""" assert mode in self.xDict, 'dataset does not contain mode %s' % str(mode) return Dataset({mode:self.xDict[mode]}, {mode:self.yDict[mode]}) def modesToLearn(self): """Return list of modes associated with the data.""" return list(self.xDict.keys()) def hasMode(self,mode): """True if there are examples of the mode in the dataset.""" return (mode in self.yDict and mode in self.xDict) def getX(self,mode): """Get a matrix of all inputs for the mode.""" return self.xDict[mode] def getY(self,mode): """Get a matrix of all desired outputs for the mode.""" return self.yDict[mode] def size(self): return sum([m.nnz for m in list(self.xDict.values())]) + sum([m.nnz for m in list(self.yDict.values())]) def shuffle(self): for mode in self.xDict: shuffledRowNums = NP.arange(mutil.numRows(self.xDict[mode])) NR.shuffle(shuffledRowNums) self.xDict[mode] = mutil.shuffleRows(self.xDict[mode],shuffledRowNums) self.yDict[mode] = mutil.shuffleRows(self.yDict[mode],shuffledRowNums) def minibatchIterator(self,batchSize=100,shuffleFirst=True): """Iterate over triples (mode,X',Y') where X' and Y' are sets of batchSize rows from the full data for mode, randomly selected (without replacement) from the dataset.""" # randomize the order of the examples if shuffleFirst: self.shuffle() # then sample an ordering of the modes modeList = self.modesToLearn() modeSampleDict = {} for modeIndex,mode in enumerate(modeList): numBatches = int(math.ceil( mutil.numRows(self.getX(mode)) / float(batchSize) )) modeSampleDict[mode] =
NP.ones(numBatches,dtype='int')
numpy.ones
# Copyright 2019 Graphcore Ltd. import tensorflow as tf import numpy as np import os # Data file settings USER_PART = 0 # user id goes first in the data file ITEM_PART = 1 # item id goes second in the data file RATING_PART = 2 # rating goes third in the data file DELIMITER = '\t' # Dataset generation parameters SHUFFLE_BUFFER = 10000 class AutoencoderData: def __init__(self, data_file_name, training_data=None): self.data_file_name = data_file_name # When doing validation, we use training data to feed into the model and generate predicted ratings. # The predictions are then compared to the ground truth in validation # data. if training_data is None: self.user_xlat_map, self.item_xlat_map = {}, {} do_build_maps = True user_index, item_index = 0, 0 else: self.training_dict = training_data.ratings_dict self.user_xlat_map, self.item_xlat_map = training_data.user_xlat_map, training_data.item_xlat_map do_build_maps = False self.ratings_dict = {} with open(self.data_file_name) as data_file: for user_item_rating in data_file: parts = user_item_rating.split(DELIMITER) if len(parts) != 3: raise ValueError( 'Line "{}" is invalid in {}'.format( user_item_rating, self.data_file_name)) user_id_external = int(parts[USER_PART]) item_id_external = int(parts[ITEM_PART]) rating = float(parts[RATING_PART]) # Build dense maps to keep only users or items that have # training data if do_build_maps: if user_id_external not in self.user_xlat_map: self.user_xlat_map[user_id_external] = user_index user_index += 1 if item_id_external not in self.item_xlat_map: self.item_xlat_map[item_id_external] = item_index item_index += 1 # Mapped user and item ids user_id_internal = self.user_xlat_map[user_id_external] item_id_internal = self.item_xlat_map[item_id_external] if user_id_internal not in self.ratings_dict: self.ratings_dict[user_id_internal] = [] self.ratings_dict[user_id_internal].append( (item_id_internal, rating)) self.user_id_list = list(self.ratings_dict.keys()) self._input_size = len(self.item_xlat_map) # Generate one data sample during training def generate_sample(self): index = 0 while index < len(self.user_id_list): sample = np.zeros(self._input_size, dtype=np.int8) for (item_number, rating) in self.ratings_dict[self.user_id_list[index]]: sample[item_number] = rating index += 1 yield sample # Generate a pair of observed and ground truth data samples during # evaluation def generate_pair(self): index = 0 while index < len(self.user_id_list): # sample ground truth sample_gt = np.zeros(self._input_size, dtype=np.int8) for (item_number, rating) in self.ratings_dict[self.user_id_list[index]]: sample_gt[item_number] = rating # sample observed sample_observed = np.zeros(self._input_size, dtype=np.int8) for (item_number, rating) in self.training_dict[self.user_id_list[index]]: sample_observed[item_number] = rating index += 1 yield np.concatenate((sample_observed, sample_gt), axis=None) @property def size(self): return len(self.user_id_list) @property def input_size(self): return self._input_size # Create a tf Dataset with buffering, stats, etc. def get_dataset(self, opts, is_training): batch_size = opts.batch_size if is_training else opts.validation_batch_size dtypes = opts.precision.split('.') datatype = tf.float16 if dtypes[0] == '16' else tf.float32 # Create a tf Dataset using a binary file or from generator if is_training: # We use a binary file to store the preprocessed dataset. # This way the throughput is more stable. def generate_entire_dataset_in_numpy(): index = 0 samples =
np.zeros((self.size, self._input_size), dtype=np.int8)
numpy.zeros
# MIT License # # Copyright (c) 2019 <NAME> # # 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 __future__ import absolute_import from __future__ import division from __future__ import print_function from builtins import input import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix import joblib def calc_avg_emb(): # a function to create a vector of n average embeddings for each # tinder profile # get the embeddings per profile labels = np.load('labels.npy', allow_pickle=True) # label_strings = np.load('label_strings.npy', allow_pickle=True) embeddings = np.load('embeddings.npy', allow_pickle=True) image_list = np.load('image_list.npy', allow_pickle=True) # determine the n dimension of embeddings n_emb = embeddings.shape[1] # find the maximum number of images in a profile split_image_list = [] profile_list = [] for i in image_list: split_image_list.append(i.split('.')[1]) # split_image_list.append(i.replace('/', '.').split('.')) profile_list.append(i.split('.')[0]) # convert profile list to pandas index pl = pd.Index(profile_list) pl_unique = pl.value_counts() # get the summar statics of pl pl_describe = pl_unique.describe() print('Summary statistics of profiles with at least one detectable face') print(pl_describe) number_of_profiles = int(pl_describe[0]) # number_of_images = int(pl_describe[-1]) # convert the embeddings to a data frame eb = pd.DataFrame(embeddings, index=pl) dislike = pd.Series(labels, index=pl) # if dislike == 1 it means I disliked the person! # create a blank numpy array for embeddings new_embeddings = np.zeros((number_of_profiles, n_emb)) new_labels = np.zeros(number_of_profiles) for i, j in enumerate(pl_unique.index): temp = eb.loc[j] # if a profile has more than one face it will be a DataFrame # else the profile will be a Series if isinstance(temp, pd.DataFrame): # get the average of each column temp_embeddings = np.mean(temp.values, axis=0) else: temp_embeddings = temp.values # save the new embeddings new_embeddings[i] = temp_embeddings # Save the profile label, 1 for dislike, 0 for like new_labels[i] = dislike[j].max() # save the files np.save('embeddings_avg_profile.npy', new_embeddings) np.save('labels_avg_profile.npy', new_labels) return new_embeddings, new_labels def calc_avg_emb_temp(embeddings): # a function to create a vector of n average embeddings for each # in the temp_images_aligned folder # embeddings = np.load('temp_embeddings.npy', allow_pickle=True) # determine the n dimension of embeddings n_emb = embeddings.shape[1] # calculate the average embeddings new_embeddings =
np.zeros((1, n_emb))
numpy.zeros
import geopandas as gpd import numpy as np import os from typing import Union from netCDF4 import Dataset import rasterio from rasterio.warp import calculate_default_transform, reproject, Resampling def read_grid(raster_file: str, nan_threshold: Union[float, int] = 100, window: Union[str, list, tuple, np.ndarray] = None, buffer: Union[float, int] = 100, return_meta: bool = False): """ Read :param raster_file: file to read :param nan_threshold: numbers with an absolute value greater than this are set to NaN :param window: :param buffer: :return: """ assert os.path.exists(raster_file) raster = rasterio.open(raster_file) no_data = raster.nodata if window is not None: if isinstance(window, str): assert os.path.exists(window) shp = gpd.GeoDataFrame.from_file(window) x1, y1, x2, y2 = np.array(shp.bounds)[0] else: assert len(window) == 4 x1, y1, x2, y2 = window[:] assert all([x2 > x1, y2 > y1]) buffer_value = 0 if buffer is None else buffer if x1 < raster.bounds.left: x1 = np.round(raster.bounds.left + 1) lowest = min([raster.bounds.bottom, raster.bounds.top]) if y1 < lowest: y1 = np.round(lowest + -1) if raster.bounds.top < raster.bounds.bottom: window_object = rasterio.windows.from_bounds(x1 - buffer_value, y2 + buffer_value, x2 + buffer_value, y1 - buffer_value, transform=raster.transform) else: window_object = rasterio.windows.from_bounds(x1 - buffer_value, y1 - buffer_value, x2 + buffer_value, y2 + buffer_value, transform=raster.transform) z = raster.read(1, window=window_object) geo_transform = raster.window_transform(window_object) else: z = raster.read(1) # Get affine transform from raster geo_transform = raster.transform if return_meta: geo_meta = raster.meta.copy() geo_meta.update({"width": z.shape[1], "height": z.shape[0], "transform": geo_transform}) else: geo_meta = None # extract origin, pixel width and pixel height from affine transform origin_x = geo_transform[2] origin_y = geo_transform[5] pixel_width = geo_transform[0] pixel_height = geo_transform[4] # Width and height of raster in pixels cols = z.shape[1] rows = z.shape[0] # Turn into X and Y coordinates x = origin_x + pixel_width * np.arange(cols) y = origin_y + pixel_height * np.arange(rows) # Set values above threshold to NaN if no_data != np.nan: z[z < -nan_threshold] = np.NaN z[z > nan_threshold] = np.NaN # Close raster raster.close() if return_meta: return x, y, z, geo_meta else: return x, y, z def read_tiff(tiff: str, x_correct: float = None, y_correct: float = None, nan_threshold: Union[float, int] = 9000, make_y_ascending: bool = False, window: Union[str, list, tuple, np.ndarray] = None, buffer: Union[float, int]=100, return_meta: bool = False): """ Read geotiff, rather than generic raster. Uses read_grid. :param tiff: Filename :param x_correct: Offset to get back to GMT convention :param y_correct: Generally same as x_correct :param make_y_ascending: flips y and z along y axis so that y[-1] > y[0] :return: """ assert os.path.exists(tiff) # Read grid into x, y ,z if return_meta: x, y, z, geo_meta = read_grid(tiff, nan_threshold=nan_threshold, window=window, buffer=buffer, return_meta=return_meta) else: x, y, z = read_grid(tiff, nan_threshold=nan_threshold, window=window, buffer=buffer) geo_meta = None if make_y_ascending and y[0] > y[-1]: y = y[::-1] z = z[::-1, :] # If necessary, sort out problems with pixel vs. gridline registration (need to supply values) if x_correct is not None: x += x_correct print("Adjusting for GMT-Tiff difference") if y_correct is not None: y += y_correct if return_meta: return x, y, z, geo_meta else: return x, y, z def read_gmt_grid(grd_file: str): """ function to read in a netcdf4 format file. Rasterio is really slow to do it. :param grd_file: :return: """ assert os.path.exists(grd_file) # Open dataset and check that x,y,z are variable names fid = Dataset(grd_file, "r") assert all([a in fid.variables for a in ("x", "y", "z")]) xm, ym, zm = [fid.variables[a][:] for a in ("x", "y", "z")] fid.close() # Check arrays are either numpy arrays or masked arrays for a in (xm, ym, zm): assert any([isinstance(a, b) for b in (np.ma.MaskedArray, np.ndarray)]) x = xm if isinstance(xm, np.ndarray) else xm.filled(fill_value=np.nan) y = ym if isinstance(ym, np.ndarray) else ym.filled(fill_value=np.nan) z = zm if isinstance(zm, np.ndarray) else zm.filled(fill_value=np.nan) return
np.array(x)
numpy.array
import re import pandas as pd import numpy as np from sciparse import string_to_dict, dict_to_string, ureg from datetime import datetime as dt def parse_default( filename, data=None, metadata=None, read_write='r'): """ Default parser for data. Assumes there is a single line of metadata at the top line in the form of a dictionary and the remainder is tabular and can be imported as a pandas DataFrame :param filename: Name of the file to be written :param data: Data to write to file :param metadata: Metadata to write to file :param read_write: "r" or "w". Read or write. """ if read_write == 'r': with open(filename) as fh: string_metadata = fh.readline().rstrip('\n') metadata = string_to_dict(string_metadata) data = pd.read_csv(fh) return data, metadata elif read_write == 'w': with open(filename, 'w') as fh: metadata_line = dict_to_string(metadata) + '\n' fh.write(metadata_line) if isinstance(data, pd.DataFrame): data.to_csv(fh, mode='a', index=False) elif data is None: pass else: raise ValueError(f'This method only implemented for type of pd.DataFrame, you attempted to pass in type {type(data)}.') def parse_xrd(filename): """ Loads XRD data from a given filename :param filename: The filename to open :returns (data, metadata): set of data and metadata from XRD file """ with open(filename) as file_handle: count = 0 reg_pattern = re.compile(r'\w+=\S*\w+') metadata = {} while True: line = file_handle.readline() if line == '[Data]\n' or not line: break line = line.rstrip('\n') if reg_pattern.match(line): split_string = line.split('=') name = split_string[0].lower() val = split_string[1].lower() interesting_names = [ 'drivename', 'startposition', 'date', 'time', 'increment', 'scantype','start', 'steps'] if name in interesting_names: if name == 'drivename': current_drive = val elif name == 'startposition': metadata[current_drive] = float(val) else: try: metadata[name] = int(val) except: try: metadata[name] = float(val) except: metadata[name] = val data = pd.read_csv(file_handle) data = data.loc[:, ~data.columns.str.contains('^Unnamed')] data = data.rename(columns=lambda x: x.strip()) # Strip whitespace data = data.rename(columns={'Angle': 'Angle (deg)', 'Det1Disc1': 'Counts'}) return data, metadata def parse_lcr(filename): metadata = parse_lcr_header(filename) data_start_line = find_lcr_dataline(filename) with open(filename, 'r') as dataFile: lines = dataFile.readlines() header_line = lines[data_start_line-1] header_line = header_line.replace("\n", "") data_types = header_line.split("\t") data_types = [x for x in data_types if x != ""] data = pd.DataFrame({}) for dtype in data_types: data[dtype] = np.array([]) lines = lines[data_start_line:-4] if len(lines) != metadata['n_samples']: raise ValueError("number lines not equal to data lines. Issue with parsing.") for line in lines: line = line.replace("\n", "") line_data = line.split("\t") line_data = [float(x) for x in line_data if x != ''] new_data_row = pd.DataFrame({}) for i, dtype in enumerate(data_types): new_data_row[dtype] = [line_data[i]] data = data.append(new_data_row) return data, metadata def parse_lcr_header(filename): metadata = {} currentID = '' with open(filename, 'r') as dataFile: lines = dataFile.readlines() for line in lines: line = line.replace(":", " ") line = line.replace("\n", "") line = line.replace("\t", "") lineData = line.split(" ") if lineData[0] == 'ID': currentID = lineData[-1] if lineData[0] == 'MODE': if currentID == 'A': mode = lineData[-1] elif lineData[0] == 'START': start_voltage = float(lineData[-1]) elif lineData[0] == 'STOP': stop_voltage = float(lineData[-1]) elif lineData[0] == 'STEP': step_voltage = float(lineData[-1]) elif lineData[0] == 'DATE': recorded_date = dt.strptime(lineData[-1], "%m/%d/%Y") elif lineData[0] == 'TIME': timeData = lineData[-3] + " " + lineData[-2] + " " + lineData[-1] recorded_time = dt.strptime(timeData, "%H %M %S") elif lineData[0] == 'PNTS': n_samples = int(lineData[-1]) metadata = { 'start_voltage': start_voltage, 'stop_voltage': stop_voltage, 'step_voltage': step_voltage, 'date': recorded_date, 'time': recorded_time, 'n_samples': n_samples, 'mode': mode, } return metadata def find_lcr_dataline(filename): with open(filename, 'r') as dataFile: lines = dataFile.readlines() currentLine = 0 dataLines = [] for line in lines: lineData = line.split(" ") if lineData[0] == "DATA:": # begin reading data data_start_line = currentLine + 3 return data_start_line currentLine += 1 def convert_lcr_to_standard(data, metadata): """ Converts an LCR dataset into standard form (Z, theta). :param data: Pandas DataFrame containing LCR data in a potentially non-standard form (Cp/Q, Cp/D, Cp/Rp for example) """ columns = data.columns.values if 'frequency' not in metadata and 'f' not in metadata: raise ValueError(f'Frequency not in metadata. Metadata contains {metadata}') f = metadata['frequency'] w = 2*np.pi*f new_data = data.copy() if 'Z' in columns and 'THETA' in columns: Z = data['Z'] theta = data['THETA'] del new_data['Z'], new_data['THETA'] elif 'C' in columns and 'Q' in columns:# C assumed to be Cp Q = new_data['Q'] Cp = new_data['C'] Z = 1 / (w*Cp) * 1 / np.sqrt(1 + 1/(Q**2)) theta = -np.arctan(Q) del new_data['Q'], new_data['C'] elif 'C' in columns and 'D' in columns: # D = 1/Q. C assumed Cp D = data['D'] Cp = data['C'] Z = 1 / (w*Cp) * 1 /
np.sqrt(1 + (D**2))
numpy.sqrt
""" Graphics module for erdorbit. """ # third party imports import numpy as np from shapely.geometry import LineString def resize_3d_drawing_to_fit_canvas(input_coords, canvas_height, margins): """ This function resizes the drawing to fit the canvas size Input: input_coords np array of floats shape (:, 3) x, y, z, position in km canvas_height float margins (int, int, int, int) left, top, right, bottom canvas margins Output: np array of floats shape (:, 3) x, y, z, position in canvas dimension """ # assuming size of object to draw is 2 times largest value in positions array drawing_size = np.max(np.abs(input_coords)) * 2 return input_coords * (canvas_height - margins[1] - margins[3]) / drawing_size def resize_2d_drawing_to_fit_canvas(input_coords, canvas_width, canvas_height, margins): """ This function resizes the drawing to fit the canvas size Input: input_coords np array of floats shape (:, 2) x, y position in km canvas_width float canvas_height float margins (int, int, int, int) left, top, right, bottom canvas margins Output: np array of floats shape (:, 2) x, y position in canvas dimension """ # find out if portrait or landscape mode portrait_mode = False if canvas_height >= canvas_width: portrait_mode = True # find out largest dimension of drawing xdim = np.max(input_coords[:, 0]) - np.min(input_coords[:, 0]) ydim = np.max(input_coords[:, 1]) - np.min(input_coords[:, 1]) # adapt to portrait or landscape mode if necessary if xdim > ydim and portrait_mode or xdim < ydim and not portrait_mode: output_coords = np.zeros(input_coords.shape) output_coords[:, 0] = input_coords[:, 1] output_coords[:, 1] = input_coords[:, 0] else: output_coords = input_coords # find out along which dimension to scale drawing to constrain proportions x_scaling = (canvas_width - margins[2] - margins[0]) / ( np.max(output_coords[:, 0]) - np.min(output_coords[:, 0]) ) y_scaling = (canvas_height - margins[1] - margins[3]) / ( np.max(output_coords[:, 1]) - np.min(output_coords[:, 1]) ) if x_scaling < y_scaling: # scale drawing by x dimension and contrain proportions scaling_factor = x_scaling # along x: apply standard translation output_coords[:, 0] = ( margins[0] + (output_coords[:, 0] - np.min(output_coords[:, 0])) * scaling_factor ) # along y: use x scaling factor and replace to center output_coords[:, 1] = ( (output_coords[:, 1] - np.min(output_coords[:, 1])) * scaling_factor + margins[1] - (np.max(output_coords[:, 1]) - np.min(output_coords[:, 1])) * scaling_factor / 2 + (canvas_height - margins[1] - margins[3]) / 2 ) else: # scale drawing by y dimension and contrain proportions scaling_factor = y_scaling # along y: apply standard translation output_coords[:, 1] = ( margins[1] + (output_coords[:, 1] -
np.min(output_coords[:, 1])
numpy.min
from __future__ import print_function import matplotlib import numpy as np import copy import re import warnings from astropy import log from astropy import units as u from six.moves import xrange from six import string_types from ..config import mycfg from ..config import ConfigDescriptor as cfgdec from . import units from . import models from ..specwarnings import warn from . import interactive from . import history from . import widgets class Registry(object): """ This class is a simple wrapper to prevent fitter properties from being globals """ def __init__(self): self.npars = {} self.multifitters = {} #to delete self.peakbgfitters = {} self.fitkeys = {} self.associatedkeys = {} self._interactive_help_message_root = """ '?' will print this help message again. The keys denoted by surrounding / / are mnemonics. 1. Left-click or hit 'p' (/p/ick) with the cursor over the plot at both of the two desired X-values to select a fitting range. You can e/x/clude parts of the spectrum by hitting 'x' at two positions. 2. Then /m/iddle-click or hit 'm' twice to select (/m/ark) a peak and width - the first mark should be on the peak of the line, the second should be at the approximate half-max point on the curve. 3. When you're done, right-click or hit 'd' to perform the fit and disconnect the mouse and keyboard (/d/isconnect because you're /d/one). Any time before you're /d/one, you can select a different fitter (see below). To /c/ancel or /c/lear all connections, press 'c' '?' : get help (this message) 'c' : cancel / clear 'p','1' : pick / selection region for fitting 'm','2' : mark / identify a peak 'd','3' : done / do the fit, then disconnect the fitter 'i' : individual components / show each fitted component You can select different fitters to use with the interactive fitting routine. The default is gaussian ('g'), all options are listed below: """ self._make_interactive_help_message() def __copy__(self): # http://stackoverflow.com/questions/1500718/what-is-the-right-way-to-override-the-copy-deepcopy-operations-on-an-object-in-p cls = self.__class__ result = cls.__new__(cls) result.__dict__.update(self.__dict__) return result def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): setattr(result, k, copy.deepcopy(v, memo)) return result def add_fitter(self, name, function, npars, override=False, key=None, multisingle=None): ''' Register a fitter function. Parameters ---------- name: string The fit function name. function: function The fitter function. Single-fitters should take npars + 1 input parameters, where the +1 is for a 0th order baseline fit. They should accept an X-axis and data and standard fitting-function inputs (see, e.g., gaussfitter). Multi-fitters should take N * npars, but should also operate on X-axis and data arguments. npars: int How many parameters does the function being fit accept? Other Parameters ---------------- override: True | False Whether to override any existing type if already present. key: char Key to select the fitter in interactive mode ''' if multisingle is not None: warn("The 'multisingle' keyword is no longer required.", DeprecationWarning) if not name in self.peakbgfitters or override: self.peakbgfitters[name] = function if not name in self.multifitters or override: self.multifitters[name] = function if key is not None: self.fitkeys[key] = name self._make_interactive_help_message() self.npars[name] = npars self.associated_keys = dict(zip(self.fitkeys.values(),self.fitkeys.keys())) def _make_interactive_help_message(self): """ Generate the interactive help message from the fitkeys """ self.interactive_help_message = ( self._interactive_help_message_root + "\n" + "\n".join(["'%s' - select fitter %s" % (key,name) for key,name in self.fitkeys.items()]) + "\n" # trailing \n so that users' input is on a fresh line ) # Declare default registry built in for all spectra default_Registry = Registry() default_Registry.add_fitter('ammonia',models.ammonia_model(),6,key='a') default_Registry.add_fitter('cold_ammonia',models.ammonia.cold_ammonia_model(),6) default_Registry.add_fitter('ammonia_tau',models.ammonia_model_vtau(),6) # not implemented default_Registry.add_fitter(Registry,'ammonia',models.ammonia_model( ),6, ,key='A') default_Registry.add_fitter('formaldehyde',models.formaldehyde_fitter,3,key='F') # CAN'T USE f! reserved for fitting # do'nt override default_Registry.add_fitter('formaldehyde',models.formaldehyde_vheight_fitter,3) default_Registry.add_fitter('gaussian',models.gaussian_fitter(),3,key='g') default_Registry.add_fitter('vheightgaussian',models.gaussian_vheight_fitter(),4) default_Registry.add_fitter('voigt',models.voigt_fitter(),4,key='v') default_Registry.add_fitter('lorentzian',models.lorentzian_fitter(),3,key='L') #default_Registry.add_fitter('hill5',models.hill5infall.hill5_fitter,5) #default_Registry.add_fitter('hcn',models.hcn.hcn_vtau_fitter,4) class Specfit(interactive.Interactive): def __init__(self, Spectrum, Registry=None): super(Specfit, self).__init__(Spectrum, interactive_help_message=Registry.interactive_help_message) self.model = None self.parinfo = None self.modelpars = None self.modelerrs = None self.modelplot = [] self.modelcomponents = None self._plotted_components = [] self.npeaks = 0 #self.nclicks_b1 = 0 #self.nclicks_b2 = 0 #self.xmin = 0 #self.xmax = Spectrum.data.shape[0] self.button2action = self.guesspeakwidth self.guesses = [] self.click = 0 self.fitkwargs = {} self.auto = False self.fitleg=None self.residuals=None self.setfitspec() self.fittype = 'gaussian' self.measurements = None self.vheight=False # vheight must be a boolean, can't be none self._component_kwargs = {} self.Registry = Registry self.autoannotate = mycfg['autoannotate'] self.EQW_plots = [] #self.seterrspec() @property def fitter(self): if hasattr(self, '_fitter'): return self._fitter else: raise AttributeError("The 'specfit' object has no 'fitter' yet. " "This means you haven't yet run a fit. The " "fitter is not accessible until after a fit " "has been run.") @fitter.setter def fitter(self, value): self._fitter = value @cfgdec def __call__(self, interactive=False, usemoments=True, fittype=None, clear_all_connections=True, debug=False, guesses='moments', parinfo=None, save=True, annotate=None, show_components=None, use_lmfit=False, verbose=True, clear=True, reset_selection=True, fit_plotted_area=True, use_window_limits=None, vheight=None, exclude=None, **kwargs): """ Fit model functions to a spectrum Parameters ---------- interactive : boolean The plotter window will go into interactive mode. See self.interactive_help_message for details on how to use the interactive fitter. fittype : str [passed to fitting codes; defaults to gaussian] The model to use. Model must be registered in self.Registry. gaussian, lorentzian, and voigt profiles are registered by default guesses : list or 'moments' A list of guesses. Guesses must have length = n*number of parameters in model. Guesses are *required* for multifit fits (there is no automated guessing for most models) EXAMPLE: for single-fit gaussian guesses = [height,amplitude,center,width] for multi-fit gaussian, it is [amplitude, center, width] You can also pass the keyword string 'moments' to have the moments be used to automatically determine the guesses for a *single* peak parinfo : `pyspeckit.spectrum.parinfo.ParinfoList` An alternative way to specify guesses. Supercedes guesses. use_lmfit : boolean If lmfit-py (https://github.com/newville/lmfit-py) is installed, you can use it instead of the pure-python (but slow) mpfit. reset_selection : boolean Override any selections previously made using `fit_plotted_area` or other keywords? fit_plotted_area : boolean If no other limits are specified, the plotter's xmin/xmax will be used to define the fit region. Only respects the x-axis limits, not the y-axis limits. use_window_limits : boolean If ``fit_plotted_area==True`` and no other limits are specified, will use the displayed window area (as set by the zoom tools) as the fitting range. Only respects the x-axis limits, not the y-axis limits. exclude : None or list Passed to selectregion; specifies regions to exclude in xarr units Plotter-related Parameters -------------------------- annotate : None or boolean If None, will use the default stored in self.annotate, otherwise overwrites. Annotations will appear on the plot if a plotter exists. show_components : boolean Show the individual components of a multi-component fit (defaults to blue) clear : boolean Clear previous fitter plots before overplotting the fit? Advanced Parameters ------------------- clear_all_connections : boolean Clear all of the interactive connections from a previous interactive session (e.g., a baseline fitting session) before continuing? usemoments : boolean Use the moments of the spectrum as input guesses. Only works for gaussian and gaussian-like models. Only works for single-fit mode (not multifit) DEPRECATED debug : boolean Print debug statements? save : boolean Save best fits in the FITS header as keywords? ONLY IMPLEMENTED FOR GAUSSIANS verbose : boolean Print out extra stuff vheight : None or boolean if None, defaults to self.vheight, otherwise overrides Determines whether a 0th order baseline will be fit along with the line """ if clear: self.clear() if reset_selection: self.selectregion(verbose=verbose, debug=debug, fit_plotted_area=fit_plotted_area, exclude=exclude, use_window_limits=use_window_limits, **kwargs) for arg in ['xmin','xmax','xtype','reset']: if arg in kwargs: kwargs.pop(arg) if fittype is not None: self.fittype = fittype self.fitter = self.Registry.multifitters[self.fittype] if 'multifit' in kwargs: kwargs.pop('multifit') log.warning("The multifit keyword is no longer required. All fits " "allow for multiple components.", DeprecationWarning) if 'guess' in kwargs: if guesses is None: guesses = kwargs.pop('guess') log.warning("The keyword 'guess' is nonstandard; please use 'guesses'") else: raise ValueError("Received keywords 'guess' and 'guesses'. " "Please only use 'guesses'") self.npeaks = 0 self.fitkwargs = kwargs log.debug("Additional keyword arguments passed to fitter are: {0}" .format(kwargs)) if interactive: if self.Spectrum.plotter.axis is None: raise Exception("Interactive fitting requires a plotter.") # reset button count & guesses on every __call__ self.nclicks_b1 = 0 self.nclicks_b2 = 0 self.guesses = [] self.start_interactive(clear_all_connections=clear_all_connections, reset_selection=True, debug=debug, **kwargs) elif (self.fittype in self.Registry.multifitters or guesses is not None or parinfo is not None): if guesses is None and parinfo is None: raise ValueError("You must input guesses when using multifit." " Also, baseline (continuum fit) first!") elif parinfo is not None: self.guesses = parinfo.values self.parinfo = parinfo self.multifit(show_components=show_components, verbose=verbose, debug=debug, use_lmfit=use_lmfit, annotate=annotate, parinfo=parinfo, guesses=None, **kwargs) elif guesses is not None: if isinstance(guesses, tuple): guesses = list(guesses) self.guesses = guesses self.multifit(show_components=show_components, verbose=verbose, debug=debug, use_lmfit=use_lmfit, fittype=fittype, guesses=guesses, annotate=annotate, **kwargs) else: raise ValueError("Guess and parinfo were somehow invalid.") else: raise ValueError("Can't fit with given fittype {0}:" " it is not Registered as a fitter.".format(self.fittype)) if save: self.savefit() def EQW(self, plot=False, plotcolor='g', fitted=True, continuum=None, components=False, annotate=False, alpha=0.5, loc='lower left', xmin=None, xmax=None, xunits=None, continuum_as_baseline=False, xunit='pixel', midpt_location='plot-center'): """ Returns the equivalent width (integral of "baseline" or "continuum" minus the spectrum) over the selected range (the selected range defaults to self.xmin:self.xmax, so it may include multiple lines!) Parameters ---------- plot : bool Plots a box indicating the EQW if plot==True (i.e., it will have a width equal to the equivalent width, and a height equal to the measured continuum) fitted : bool Use the fitted model? If false, uses the data continuum : None or float Can specify a fixed continuum with this keyword, otherwise will use the fitted baseline. WARNING: continuum=0 will still "work", but will give numerically invalid results. Similarly, a negative continuum will work, but will yield results with questionable physical meaning. continuum_as_baseline : bool Replace the baseline with the specified continuum when computing the absorption depth of the line components : bool If your fit is multi-component, will attempt to acquire centroids for each component and print out individual EQWs xmin : float xmax : float The range over which to compute the EQW xunit : str The units of xmin/xmax midpt_location : 'fitted', 'plot-center' If 'plot' is set, this determines where the EQW will be drawn. It can be the fitted centroid or the plot-center, i.e. (xmin+xmax)/2 Returns ------- Equivalent Width, or widths if components=True """ if continuum is not None: # if continuum is specified, don't bother with checks if np.median(self.Spectrum.baseline.basespec) == 0: raise ValueError("Baseline / continuum is zero: equivalent width is undefined.") elif np.median(self.Spectrum.baseline.basespec) < 0: if mycfg.WARN: warn( "WARNING: Baseline / continuum is negative: equivalent width is poorly defined." ) if xunits is not None and xunit=='pixel': # todo: deprecation warning xunit = xunits # determine range to use if xmin is None: xmin = self.xmin #self.Spectrum.xarr.x_to_pix(self.xmin) else: xmin = self.Spectrum.xarr.x_to_pix(xmin, xval_units=xunit) if xmax is None: xmax = self.xmax #self.Spectrum.xarr.x_to_pix(self.xmax) else: xmax = self.Spectrum.xarr.x_to_pix(xmax, xval_units=xunit) dx = np.abs(self.Spectrum.xarr[xmin:xmax].cdelt(approx=True).value) log.debug("xmin={0} xmax={1} dx={2} continuum={3}" .format(xmin, xmax, dx, continuum)) if components: centroids = self.fitter.analytic_centroids() integrals = self.fitter.component_integrals(self.Spectrum.xarr[xmin:xmax],dx=dx) eqw = [] for cen,integ in zip(centroids,integrals): center_pix = self.Spectrum.xarr.x_to_pix(cen) if continuum is None: continuum = self.Spectrum.baseline.basespec[center_pix] elif continuum_as_baseline: integrals[-1] += -(self.Spectrum.baseline.basespec[xmin:xmax] - continuum).sum() * dx eqw.append(-integ / continuum) if plot: plot = False if mycfg.WARN: warn("Cannot plot multiple Equivalent Widths") elif fitted: model = self.get_model(self.Spectrum.xarr[xmin:xmax], add_baseline=False) # EQW is positive for absorption lines # fitted components are assume to be continuum-subtracted integral = (-model).sum() * dx if continuum is None: # centroid in data units # (may fail if model has pos + neg values) center = (model*self.Spectrum.xarr[xmin:xmax]).sum()/model.sum() center_pix = self.Spectrum.xarr.x_to_pix(center) continuum = self.Spectrum.baseline.basespec[center_pix] elif continuum_as_baseline: integral += -(self.Spectrum.baseline.basespec[xmin:xmax] - continuum).sum() * dx eqw = integral / continuum else: if continuum_as_baseline: diffspec = (continuum - self.Spectrum.data) elif self.Spectrum.baseline.subtracted is False: diffspec = (self.Spectrum.baseline.basespec - self.Spectrum.data) else: diffspec = -self.Spectrum.data sumofspec = diffspec[xmin:xmax].sum() * dx if continuum is None: continuum = np.median(self.Spectrum.baseline.basespec) eqw = sumofspec / continuum if plot and self.Spectrum.plotter.axis: if midpt_location == 'plot-center': midpt_pixel = int(np.round((xmin+xmax)/2.0)) midpt = self.Spectrum.xarr[midpt_pixel].value elif midpt_location == 'fitted': try: shifts = np.array([self.Spectrum.specfit.parinfo[x].value for x in self.Spectrum.specfit.parinfo.keys() if 'SHIFT' in x]) except AttributeError: raise AttributeError("Can only specify midpt_location=" "fitted if there is a SHIFT parameter" "for the fitted model") # We choose to display the eqw fit at the center of the fitted # line set, closest to the passed window. # Note that this has the potential to show a eqw "rectangle" # centered on a fitted line other than the one measured for the # eqw call, if there are more than one fitted lines within the # window. midpt_pixel = int((xmin+xmax)/2) midval = self.Spectrum.xarr[midpt_pixel].value midpt_index = np.argmin(np.abs(shifts-midval)) midpt = shifts[midpt_index] midpt_pixel = self.Spectrum.xarr.x_to_pix(midpt) else: raise ValueError("midpt_location must be 'plot-center' or " "fitted") if continuum_as_baseline: midpt_level = continuum else: midpt_level = self.Spectrum.baseline.basespec[midpt_pixel] log.debug("EQW plotting: midpt={0}, midpt_pixel={1}, " "midpt_level={2}, eqw={3}".format(midpt, midpt_pixel, midpt_level, eqw)) self.EQW_plots.append(self.Spectrum.plotter.axis.fill_between( [midpt-eqw/2.0,midpt+eqw/2.0], [0,0], [midpt_level,midpt_level], color=plotcolor, alpha=alpha, label='EQW: %0.3g' % eqw)) if annotate: self.Spectrum.plotter.axis.legend( [(matplotlib.collections.CircleCollection([0],facecolors=[plotcolor],edgecolors=[plotcolor]))], [('EQW: %0.3g' % eqw)], markerscale=0.01, borderpad=0.1, handlelength=0.1, handletextpad=0.1, loc=loc) if self.Spectrum.plotter.autorefresh: self.Spectrum.plotter.refresh() if hasattr(self.Spectrum,'header'): history.write_history(self.Spectrum.header, "EQW for %s: %s" % (self.fittype,eqw)) return eqw def register_fitter(self,*args,**kwargs): """ Register a model fitter """ self.Registry.add_fitter(*args,**kwargs) register_fitter.__doc__ += Registry.add_fitter.__doc__ def seterrspec(self, usestd=None, useresiduals=True): """ Simple wrapper function to set the error spectrum; will either use the input spectrum or determine the error using the RMS of the residuals, depending on whether the residuals exist. """ if (self.Spectrum.error is not None) and not usestd: if (self.Spectrum.error == 0).all(): if self.residuals is not None and useresiduals: residuals_std = self.residuals.std() if residuals_std == 0: self.errspec = np.ones(self.spectofit.shape[0]) warnings.warn("Residuals have 0 standard deviation. " "That's probably too good to be true.") else: self.errspec = np.ones(self.spectofit.shape[0]) * residuals_std elif type(self.Spectrum.error) is np.ma.masked_array: # force errspec to be a non-masked array of ones self.errspec = self.Spectrum.error.data + 1 else: self.errspec = self.Spectrum.error + 1 else: # this is the default behavior if spectrum.error is set self.errspec = self.Spectrum.error.copy() elif self.residuals is not None and useresiduals: self.errspec = np.ones(self.spectofit.shape[0]) * self.residuals.std() else: self.errspec = np.ones(self.spectofit.shape[0]) * self.spectofit.std() def setfitspec(self): """ Set the spectrum that will be fit. This is primarily to remove NANs from consideration: if you simply remove the data from both the X-axis and the Y-axis, it will not be considered for the fit, and a linear X-axis is not needed for fitting. However, it may be possible to do this using masked arrays instead of setting errors to be 1e10.... """ if self.Spectrum.data.sum() is np.ma.masked: self.spectofit = np.zeros_like(self.Spectrum.data) self.errspec = np.zeros_like(self.Spectrum.data) self._valid = False return # see https://github.com/numpy/numpy/issues/3474 self.spectofit = np.ma.copy(self.Spectrum.data) if hasattr(self.Spectrum.data, 'mask') and hasattr(self.spectofit, 'mask'): assert np.all(self.Spectrum.data.mask == self.spectofit.mask) self._valid = True if hasattr(self.Spectrum,'baseline'): if ((not self.Spectrum.baseline.subtracted and self.Spectrum.baseline.basespec is not None and len(self.spectofit) == len(self.Spectrum.baseline.basespec))): self.spectofit -= self.Spectrum.baseline.basespec OKmask = np.isfinite(self.spectofit) with warnings.catch_warnings(): # catch a specific np1.7 futurewarning relating to masks warnings.simplefilter("ignore") self.spectofit[~OKmask] = 0 self.seterrspec() # the "OK" mask is just checking that the values are finite self.errspec[~OKmask] = 1e10 # if an includemask is set *and* there are some included values, "mask out" the rest # otherwise, if *all* data are excluded, we should assume that means the includemask # simply hasn't been initialized if self.includemask is not None and (self.includemask.shape == self.errspec.shape) and any(self.includemask): self.errspec[~self.includemask] = 1e10*self.errspec.max() @property def mask(self): """ Mask: True means "exclude" """ if ((hasattr(self.spectofit, 'mask') and self.spectofit.shape==self.spectofit.mask.shape)): mask = self.spectofit.mask else: mask = np.zeros_like(self.spectofit, dtype='bool') return mask @property def dof(self): """ degrees of freedom in fit """ if not hasattr(self, 'npix_fitted'): raise AttributeError('No fit has been run, so npix_fitted is not ' 'defined and dof cannot be computed.') return (self.npix_fitted - self.vheight - self.npeaks * self.Registry.npars[self.fittype] + np.sum(self.parinfo.fixed) + np.sum([x != '' for x in self.parinfo.tied])) #self.dof = self.includemask.sum()-self.npeaks*self.Registry.npars[self.fittype]-vheight+np.sum(self.parinfo.fixed) @property def mask_sliced(self): """ Sliced (subset) Mask: True means "exclude" """ return self.mask[self.xmin:self.xmax] def multifit(self, fittype=None, renormalize='auto', annotate=None, show_components=None, verbose=True, color=None, guesses=None, parinfo=None, reset_fitspec=True, use_window_limits=None, use_lmfit=False, plot=True, **kwargs): """ Fit multiple gaussians (or other profiles) Parameters ---------- fittype : str What function will be fit? fittype must have been Registryed in the peakbgfitters dict. Uses default ('gaussian') if not specified renormalize : 'auto' or bool if 'auto' or True, will attempt to rescale small data (<1e-9) to be closer to 1 (scales by the median) so that the fit converges better parinfo : `~parinfo` structure Guess structure; supercedes ``guesses`` guesses : list or 'moments' Either a list of guesses matching the number of parameters * the number of peaks for the model, or 'moments' to fit a single spectrum with the moments as guesses """ if reset_fitspec: self.setfitspec() if not self._valid: raise ValueError("Data are invalid; cannot be fit.") #if self.fitkwargs.has_key('negamp'): self.fitkwargs.pop('negamp') # We now do this in gaussfitter.py if fittype is not None: self.fittype = fittype bad_kws = ['fittype','plot'] for kw in bad_kws: if kw in self.fitkwargs: del self.fitkwargs[kw] if guesses is not None and parinfo is not None: raise ValueError("Both guesses and parinfo were specified, " "but only one of these is allowed.") if guesses is None: if parinfo is not None: guesses = list(parinfo.values) else: guesses = list(self.guesses) elif isinstance(guesses, string_types) and guesses in ('moment', 'moments'): guesses = self.moments(vheight=False, **kwargs) else: guesses = list(guesses) # needs to be mutable, but needs to be a copy!! if len(guesses) < self.Registry.npars[self.fittype]: raise ValueError("Too few parameters input. Need at least %i for %s models" % (self.Registry.npars[self.fittype],self.fittype)) self.npeaks = len(guesses)/self.Registry.npars[self.fittype] self.fitter = self.Registry.multifitters[self.fittype] self.vheight = False if self.fitter.vheight: # Need to reset the parinfo if vheight has previously been set, # otherwise npars will disagree, which causes problems if # renormalization happens self.fitter.vheight = False self.fitter.npeaks = self.npeaks self.fitter._make_parinfo(npeaks=self.npeaks) # add kwargs to fitkwargs self.fitkwargs.update(kwargs) if 'renormalize' in self.fitkwargs: del self.fitkwargs['renormalize'] # if parinfo was specified, we use it and ignore guesses otherwise, we # make a parinfo so we can test 'scaleable' below if parinfo is not None: pinf_for_scaling = parinfo else: pinf_for_scaling, _ = self.fitter._make_parinfo(parvalues=guesses, npeaks=self.npeaks, **self.fitkwargs) scalefactor = 1.0 if renormalize in ('auto',True): datarange = np.nanmax(self.spectofit[self.xmin:self.xmax]) - np.nanmin(self.spectofit[self.xmin:self.xmax]) if abs(datarange) < 1e-9: scalefactor = np.nanmedian(np.abs(self.spectofit)) if not np.isfinite(scalefactor): raise ValueError("non-finite scalefactor = {0} encountered.".format(scalefactor)) elif scalefactor == 0: raise ValueError("scalefactor = {0} encountered, which will result " "in divide-by-zero errors".format(scalefactor)) log.info("Renormalizing data by factor %e to improve fitting procedure" % scalefactor) self.spectofit /= scalefactor self.errspec /= scalefactor # this error should be unreachable, but is included as a sanity check if self.fitter.npeaks * self.fitter.npars != len(pinf_for_scaling): raise ValueError("Length of parinfo doesn't agree with " " npeaks * npars = {0}" .format(self.fitter.npeaks * self.fitter.npars)) if len(guesses) != len(pinf_for_scaling): raise ValueError("Length of parinfo doens't match length of guesses") # zip guesses with parinfo: truncates parinfo if len(parinfo) > len(guesses) # actually not sure how/when/if this should happen; this might be a bad hack # revisit with tests!! for jj,(guess,par) in enumerate(zip(guesses,pinf_for_scaling)): if par.scaleable: guesses[jj] /= scalefactor # if parinfo was passed in, this will change it # if it was not, it will change only the placeholder # (becuase we are passing by reference above) par.value /= scalefactor par.limits = [lim / scalefactor for lim in par.limits] log.debug("Rescaled guesses to {0}".format(guesses)) # all fit data must be float64, otherwise the optimizers may take steps # less than the precision of the data and get stuck xtofit = self.Spectrum.xarr[self.xmin:self.xmax][~self.mask_sliced].astype('float64') spectofit = self.spectofit[self.xmin:self.xmax][~self.mask_sliced].astype('float64') err = self.errspec[self.xmin:self.xmax][~self.mask_sliced].astype('float64') if np.all(err == 0): raise ValueError("Errors are all zero. This should not occur and " "is a bug. (if you set the errors to all zero, " "they should be overridden and set to 1)") if parinfo is not None: self._validate_parinfo(parinfo, mode='fix') else: pinf, _ = self.fitter._make_parinfo(parvalues=guesses, npeaks=self.npeaks, **self.fitkwargs) new_guesses = self._validate_parinfo(pinf, 'guesses') if any((x!=y) for x,y in zip(guesses, new_guesses)): warn("Guesses have been changed from {0} to {1}" .format(guesses, new_guesses)) guesses = new_guesses mpp,model,mpperr,chi2 = self.fitter(xtofit, spectofit, err=err, npeaks=self.npeaks, parinfo=parinfo, # the user MUST be allowed to override parinfo. params=guesses, use_lmfit=use_lmfit, **self.fitkwargs) any_out_of_range = self._validate_parinfo(self.fitter.parinfo, mode='check') if any(any_out_of_range): warn("The fitter returned values that are outside the " "parameter limits. DEBUG INFO: {0}".format(any_out_of_range)) self.spectofit *= scalefactor self.errspec *= scalefactor if hasattr(self.fitter.mp,'status'): self.mpfit_status = models.mpfit_messages[self.fitter.mp.status] if model is None: raise ValueError("Model was not set by fitter. Examine your fitter.") self.chi2 = chi2 self.model = model * scalefactor self.parinfo = self.fitter.parinfo # rescale any scaleable parameters for par in self.parinfo: if par.scaleable: par.value *= scalefactor if par.error is not None: par.error *= scalefactor if par.limits is not None: par.limits = [lim*scalefactor for lim in par.limits] self.modelpars = self.parinfo.values self.modelerrs = self.parinfo.errors self.residuals = spectofit - self.model if self.Spectrum.plotter.axis is not None and plot: if color is not None: kwargs.update({'composite_fit_color':color}) self.plot_fit(annotate=annotate, show_components=show_components, use_window_limits=use_window_limits, **kwargs) # Re-organize modelerrs so that any parameters that are tied to others inherit the errors of the params they are tied to if 'tied' in self.fitkwargs: for ii, element in enumerate(self.fitkwargs['tied']): if not element.strip(): continue if '[' in element and ']' in element: i1 = element.index('[') + 1 i2 = element.index(']') loc = int(element[i1:i2]) else: # assume lmfit version varnames = re.compile('([a-zA-Z][a-zA-Z_0-9]*)').search(element).groups() if not varnames: continue elif len(varnames) > 1: warn("The 'tied' parameter {0} is not simple enough for error propagation".format(element)) continue else: varname = varnames[0] loc = self.parinfo.names.index(varname) self.modelerrs[ii] = self.modelerrs[loc] # make sure the full model is populated self._full_model() # calculate the number of pixels included in the fit. This should # *only* be done when fitting, not when selecting data. # (see self.dof) self.npix_fitted = self.includemask.sum() - self.mask.sum() self.history_fitpars() def refit(self, use_lmfit=False): """ Redo a fit using the current parinfo as input """ return self.multifit(parinfo=self.parinfo, use_lmfit=use_lmfit, reset_fitspec=False) def history_fitpars(self): if hasattr(self.Spectrum,'header'): history.write_history(self.Spectrum.header, "SPECFIT: Fitted " "profile of type %s" % (self.fittype)) history.write_history(self.Spectrum.header, "Chi^2: %g DOF: %i" % (self.chi2, self.dof)) for par in self.parinfo: history.write_history(self.Spectrum.header, str(par)) def peakbgfit(self, usemoments=True, annotate=None, vheight=True, height=0, negamp=None, fittype=None, renormalize='auto', color=None, use_lmfit=False, show_components=None, debug=False, use_window_limits=True, guesses=None, nsigcut_moments=None, plot=True, parinfo=None, **kwargs): """ Fit a single peak (plus a background) Parameters ---------- usemoments : bool The initial guess will be set by the fitter's 'moments' function (this overrides 'guesses') annotate : bool Make a legend? vheight : bool Fit a (constant) background as well as a peak? height : float initial guess for background negamp : bool If True, assumes amplitude is negative. If False, assumes positive. If None, can be either. fittype : bool What function will be fit? fittype must have been Registryed in the peakbgfitters dict renormalize : 'auto' or bool if 'auto' or True, will attempt to rescale small data (<1e-9) to be closer to 1 (scales by the median) so that the fit converges better nsigcut_moments : bool pass to moment guesser; can do a sigma cut for moment guessing """ self.npeaks = 1 self.auto = True self.setfitspec() if fittype is not None: self.fittype=fittype NP = self.Registry.peakbgfitters[self.fittype].default_npars if guesses is not None: log.debug("Using user-specified guesses.") self.guesses = guesses if len(guesses) != NP + vheight: raise ValueError("Invalid guesses specified for single-fitter." "Expected {0}, got {1}. Perhaps you should " "use the multifitter (multifit=True)?" .format(NP+vheight, len(guesses))) elif usemoments: # this can be done within gaussfit but I want to save them # use this INDEPENDENT of fittype for now (voigt and gauss get same guesses) log.debug("Using moment-based guesses.") moments_f = self.Registry.peakbgfitters[self.fittype].moments self.guesses = moments_f(self.Spectrum.xarr[self.xmin:self.xmax], self.spectofit[self.xmin:self.xmax], vheight=vheight, negamp=negamp, nsigcut=nsigcut_moments, **kwargs) else: if negamp: self.guesses = [height,-1,0,1] else: self.guesses = [height,1,0,1] # If we're fitting anything but a simple Gaussian, we need the length # of guesses to be right so we pad with appended zeros # BUT, if the guesses from the moments have the right number of # parameters, we don't need to do this. if NP > len(self.guesses): for ii in xrange(len(self.guesses),NP): self.guesses += [0.0] self.fitter = self.Registry.peakbgfitters[self.fittype] log.debug("n(guesses): %s Guesses: %s vheight: %s " % (len(self.guesses),self.guesses,vheight)) scalefactor = 1.0 if renormalize in ('auto',True): datarange = self.spectofit[self.xmin:self.xmax].max() - self.spectofit[self.xmin:self.xmax].min() if abs(datarange) < 1e-9: scalefactor = np.median(np.abs(self.spectofit)) log.info("Renormalizing data by factor %e to improve fitting procedure" % scalefactor) self.spectofit /= scalefactor self.errspec /= scalefactor self.guesses[0] /= scalefactor if vheight: self.guesses[1] /= scalefactor log.debug("Guesses before fit: {0}".format(self.guesses)) if 'debug' in self.fitkwargs: debug = self.fitkwargs['debug'] del self.fitkwargs['debug'] mpp,model,mpperr,chi2 = self.fitter( self.Spectrum.xarr[self.xmin:self.xmax], self.spectofit[self.xmin:self.xmax], err=self.errspec[self.xmin:self.xmax], vheight=vheight, params=self.guesses, parinfo=parinfo, debug=debug, use_lmfit=use_lmfit, **self.fitkwargs) log.debug("1. Guesses, fits after: {0}, {1}".format(self.guesses, mpp)) self.spectofit *= scalefactor self.errspec *= scalefactor if hasattr(self.fitter.mp,'status'): self.mpfit_status = models.mpfit_messages[self.fitter.mp.status] self.parinfo = self.fitter.parinfo if model is None: raise ValueError("Model was not set by fitter. Examine your fitter.") self.chi2 = chi2 self.vheight=vheight if vheight: self.Spectrum.baseline.order = 0 self.Spectrum.baseline.baselinepars = [mpp[0]*scalefactor] # first item in list form self.Spectrum.baseline.basespec = self.Spectrum.data*0 + mpp[0]*scalefactor self.model = model*scalefactor - mpp[0]*scalefactor # I removed this recently for some reason, but more code depends on it being in place # Need to figure out *WHY* anything would want an extra parameter if len(mpp) == self.fitter.npars+1: mpp = mpp[1:] else: self.model = model*scalefactor self.residuals = self.spectofit[self.xmin:self.xmax] - self.model*scalefactor self.modelpars = mpp self.modelerrs = mpperr # rescale any scaleable parameters for par in self.parinfo: if par.scaleable: par.value = par.value * scalefactor if par.error is not None: par.error = par.error * scalefactor if self.Spectrum.plotter.axis is not None and plot: if color is not None: kwargs.update({'composite_fit_color':color}) self.plot_fit(annotate=annotate, use_window_limits=use_window_limits, show_components=show_components, **kwargs) # make sure the full model is populated self._full_model(debug=debug) self.npix_fitted = self.includemask.sum() - self.mask.sum() log.debug("2. Guesses, fits after vheight removal: {0},{1}" .format(self.guesses, mpp)) self.history_fitpars() def _full_model(self, debug=False, **kwargs): """ Compute the model for the whole spectrum """ self.fullmodel = self.get_full_model(debug=debug,**kwargs) self.fullresiduals = self.Spectrum.data - self.fullmodel def get_full_model(self, debug=False,**kwargs): """ compute the model over the full axis """ return self.get_model(self.Spectrum.xarr, debug=debug,**kwargs) def get_model(self, xarr, pars=None, debug=False, add_baseline=None): """ Compute the model over a given axis """ if pars is None: return self.get_model_frompars(xarr=xarr, pars=self.parinfo, add_baseline=add_baseline, debug=debug) else: return self.get_model_frompars(xarr=xarr, pars=pars, add_baseline=add_baseline, debug=debug) def get_model_frompars(self, xarr, pars, debug=False, add_baseline=None): """ Compute the model over a given axis """ if ((add_baseline is None and (self.Spectrum.baseline.subtracted or self.vheight)) or add_baseline is False): return self.fitter.n_modelfunc(pars,**self.fitter.modelfunc_kwargs)(xarr) else: return (self.fitter.n_modelfunc(pars, **self.fitter.modelfunc_kwargs)(xarr) + self.Spectrum.baseline.get_model(np.arange(xarr.size))) def plot_model(self, pars, offset=0.0, annotate=False, clear=False, **kwargs): """ Plot a model from specified input parameters (see plot_fit for kwarg specification) annotate is set to "false" because arbitrary annotations are not yet implemented """ # really, plot_fit should be thin on top of plot_model, but that's # not how I wrote it, so it will have to wait for a refactor if clear: self.clear() return self.plot_fit(pars=pars, offset=offset, annotate=False, **kwargs) #def assess_npeaks(self): # """ # Attempt to determine whether any of the peaks are unnecessary # """ # if self.npeaks <= 1: # return # npars = self.fitter.npars # perpeakpars = [self.parinfo.values[ii*npars:(ii+1)*npars] for ii in # range(self.npeaks)] # parsets = [((x[0][0],x[1][0]),x[0][1]+x[1][1]) for x in # itertools.combinations(perpeakpars, self.npeaks-1)] # parsets = [x # for y in itertools.combinations(perpeakpars, self.npeaks-1) # for x in y] # chi2_without = [(self.spectofit[self.xmin:self.xmax] - # self.get_model_frompars(self.xarr, self.pars[ii*npars: def plot_fit(self, xarr=None, annotate=None, show_components=None, composite_fit_color='red', lw=0.5, composite_lw=0.75, pars=None, offset=None, use_window_limits=None, show_hyperfine_components=None, plotkwargs={}, **kwargs): """ Plot the fit. Must have fitted something before calling this! It will be automatically called whenever a spectrum is fit (assuming an axis for plotting exists) kwargs are passed to the fitter's components attribute Parameters ---------- xarr : None If none, will use the spectrum's xarr. Otherwise, plot the specified xarr. This is useful if you want to plot a well-sampled model when the input spectrum is undersampled annotate : None or bool Annotate the plot? If not specified, defaults to self.autoannotate show_components : None or bool show_hyperfine_components : None or bool Show the individual gaussian components overlaid on the composite fit use_window_limits : None or bool If False, will reset the window to include the whole spectrum. If True, leaves the window as is. Defaults to self.use_window_limits if None. pars : parinfo A parinfo structure or list of model parameters. If none, uses best-fit offset : None or float Y-offset. If none, uses the default self.Spectrum.plotter offset, otherwise, uses the specified float. """ #if self.Spectrum.baseline.subtracted is False and self.Spectrum.baseline.basespec is not None: # # don't display baseline if it's included in the fit # plot_offset = self.Spectrum.plotter.offset+(self.Spectrum.baseline.basespec * (~self.vheight)) #else: if offset is None: plot_offset = self.Spectrum.plotter.offset else: plot_offset = offset if xarr is None: xarr = self.Spectrum.xarr if pars is not None: model = self.get_model_frompars(xarr, pars) else: self._full_model() model = self.fullmodel self.modelplot += self.Spectrum.plotter.axis.plot(xarr, model + plot_offset, color=composite_fit_color, linewidth=lw, **plotkwargs) # Plot components if show_components or show_hyperfine_components: self.plot_components(xarr=xarr, show_hyperfine_components=show_hyperfine_components, pars=pars, plotkwargs=plotkwargs) uwl = use_window_limits if use_window_limits is not None else self.use_window_limits # plotter kwargs are kwargs for the Spectrum.plotter, # whereas plotkwargs are for the matplotlib plot command plotterkwargs = {} plotterkwargs.update(self.Spectrum.plotter.plotkwargs) plotterkwargs['use_window_limits'] = uwl self.Spectrum.plotter.reset_limits(**plotterkwargs) if self.Spectrum.plotter.autorefresh: self.Spectrum.plotter.refresh() if annotate or ((annotate is None) and self.autoannotate): self.annotate() if self.vheight: self.Spectrum.baseline.annotate() def plot_components(self, xarr=None, show_hyperfine_components=None, component_yoffset=0.0, component_lw=0.75, pars=None, component_fit_color='blue', component_kwargs={}, add_baseline=False, plotkwargs={}, **kwargs): """ Overplot the individual components of a fit Parameters ---------- xarr : None If none, will use the spectrum's xarr. Otherwise, plot the specified xarr. This is useful if you want to plot a well-sampled model when the input spectrum is undersampled show_hyperfine_components : None | bool Keyword argument to pass to component codes; determines whether to return individual (e.g., hyperfine) components of a composite model component_yoffset : float Vertical (y-direction) offset to add to the components when plotting component_lw : float Line width of component lines component_fitcolor : color Color of component lines component_kwargs : dict Keyword arguments to pass to the fitter.components method add_baseline : bool Add the fit to the components before plotting. Makes sense to use if self.Spectrum.baseline.subtracted == False pars : parinfo A parinfo structure or list of model parameters. If none, uses best-fit """ plot_offset = self.Spectrum.plotter.offset if xarr is None: xarr = self.Spectrum.xarr if show_hyperfine_components is not None: component_kwargs['return_hyperfine_components'] = show_hyperfine_components self._component_kwargs = component_kwargs if pars is None: pars = self.modelpars self.modelcomponents = self.fitter.components(xarr=xarr, pars=pars, **component_kwargs) yoffset = plot_offset + component_yoffset if add_baseline: yoffset += self.Spectrum.baseline.basespec for data in self.modelcomponents: # can have multidimensional components if len(data.shape) > 1: for d in data: self._plotted_components += self.Spectrum.plotter.axis.plot(xarr, d + yoffset, color=component_fit_color, linewidth=component_lw, **plotkwargs) else: self._plotted_components += self.Spectrum.plotter.axis.plot(xarr, data + yoffset, color=component_fit_color, linewidth=component_lw, **plotkwargs) def fullsizemodel(self): """ If the model was fit to a sub-region of the spectrum, expand it (with zeros wherever the model was not defined) to fill the spectrum. Examples -------- >>> noise = np.random.randn(100) >>> xarr = np.linspace(-50,50,100) >>> signal = np.exp(-(xarr-5)**2/(2*3.**2)) >>> sp = pyspeckit.Spectrum(data=noise + signal, xarr=xarr, xarrkwargs={'units':'km/s'}) >>> sp.specfit(xmin=-25,xmax=25) >>> sp.specfit.model.shape (48,) >>> sp.specfit.fullsizemodel() >>> sp.specfit.model.shape (100,) """ if self.model.shape != self.Spectrum.data.shape: temp = np.zeros(self.Spectrum.data.shape) temp[self.xmin:self.xmax] = self.model self.model = temp self.residuals = self.spectofit - self.model self.selectregion(reset=True) def plotresiduals(self, fig=2, axis=None, clear=True, color='k', linewidth=0.5, drawstyle='steps-mid', yoffset=0.0, label=True, pars=None, zeroline=None, set_limits=True, **kwargs): """ Plot residuals of the fit. Specify a figure or axis; defaults to figure(2). Parameters ---------- fig : int Figure number. Overridden by axis axis : axis The axis to plot on pars : None or parlist If set, the residuals will be computed for the input parameters zeroline : bool or None Plot the "zero" line through the center of the residuals. If None, defaults to "True if yoffset!=0, False otherwise" kwargs are passed to matplotlib plot """ self._full_model(pars=pars) if axis is None: if isinstance(fig,int): fig=matplotlib.pyplot.figure(fig) self.residualaxis = matplotlib.pyplot.gca() if clear: self.residualaxis.clear() else: self.residualaxis = axis if clear: self.residualaxis.clear() self.residualplot = self.residualaxis.plot(self.Spectrum.xarr, self.fullresiduals+yoffset, drawstyle=drawstyle, linewidth=linewidth, color=color, **kwargs) if zeroline or (zeroline is None and yoffset != 0): self.residualplot += self.residualaxis.plot(self.Spectrum.xarr, (np.zeros_like(self.Spectrum.xarr.value)+yoffset), linestyle='--', color='k', alpha=0.5) if set_limits: if ((self.Spectrum.plotter.xmin is not None) and (self.Spectrum.plotter.xmax is not None)): self.residualaxis.set_xlim(self.Spectrum.plotter.xmin.value, self.Spectrum.plotter.xmax.value) if ((self.Spectrum.plotter.ymin is not None) and (self.Spectrum.plotter.ymax is not None)): self.residualaxis.set_ylim(self.Spectrum.plotter.ymin, self.Spectrum.plotter.ymax) if label: self.residualaxis.set_xlabel(self.Spectrum.plotter.xlabel) self.residualaxis.set_ylabel(self.Spectrum.plotter.ylabel) self.residualaxis.set_title("Residuals") if self.Spectrum.plotter.autorefresh: self.residualaxis.figure.canvas.draw() def annotate(self,loc='upper right',labelspacing=0.25, markerscale=0.01, borderpad=0.1, handlelength=0.1, handletextpad=0.1, fontsize=10, frameon=False, chi2=None, optimal_chi2_kwargs={}, **kwargs): """ Add a legend to the plot showing the fitted parameters _clearlegend() will remove the legend chi2 : {True or 'reduced' or 'optimal' or 'allthree'} kwargs passed to legend """ self._clearlegend() pl = matplotlib.collections.CircleCollection([0],edgecolors=['k']) if hasattr(self.fitter,'annotations'): self._annotation_labels = self.fitter.annotations() else: raise Exception("Fitter %s has no annotations." % self.fitter) #xtypename = units.unit_type_dict[self.Spectrum.xarr.xtype] xcharconv = units.SmartCaseNoSpaceDict({u.Hz.physical_type:'\\nu', u.m.physical_type:'\\lambda', (u.km/u.s).physical_type:'v', 'pixels':'x', u.dimensionless_unscaled:'x', 'dimensionless':'x', }) try: xchar = xcharconv[self.Spectrum.xarr.unit.physical_type] except AttributeError: unit_key = self.Spectrum.xarr.unit xchar = xcharconv[u.Unit(unit_key).physical_type] self._annotation_labels = [L.replace('x',xchar) if L[1]=='x' else L for L in self._annotation_labels] if chi2 is not None: chi2n_label = '$\\chi^2/\\nu = %0.2g$' % (self.chi2/self.dof) chi2opt_label = '$\\chi^2_o/\\nu = %0.2g$' % self.optimal_chi2(**optimal_chi2_kwargs) chi2_label = '$\\chi^2 = %0.2g$' % self.chi2 if chi2 == 'allthree': self._annotation_labels.append("\n".join([chi2n_label, chi2_label, chi2opt_label])) elif chi2 == 'reduced': self._annotation_labels.append(chi2n_label) elif chi2 == 'optimal': self._annotation_labels.append(chi2opt_label) else: self._annotation_labels.append(chi2_label) if self.Spectrum.plotter.axis: try: self.fitleg = self.Spectrum.plotter.axis.legend( tuple([pl]*len(self._annotation_labels)), self._annotation_labels, loc=loc, markerscale=markerscale, borderpad=borderpad, handlelength=handlelength, handletextpad=handletextpad, labelspacing=labelspacing, frameon=frameon, fontsize=fontsize, **kwargs) self.Spectrum.plotter.axis.add_artist(self.fitleg) except TypeError as ex: print("Error {0} was raised, which may indicate an outdated mpl version".format(ex)) try: self.fitleg.set_draggable(True) except AttributeError: # wrong version and/or non-interactive backend pass if self.Spectrum.plotter.autorefresh: self.Spectrum.plotter.refresh() def print_fit(self, print_baseline=True, **kwargs): """ Print the best-fit parameters to the command line """ if self.Spectrum.baseline.baselinepars is not None and print_baseline: print("Baseline: " + " + ".join(["%12g x^%i" % (x,i) for i,x in enumerate(self.Spectrum.baseline.baselinepars[::-1])])) for i,p in enumerate(self.parinfo): print("%15s: %12g +/- %12g" % (p['parname'],p['value'],p['error'])) def clear(self, legend=True, components=True): """ Remove the fitted model from the plot Also removes the legend by default """ if self.Spectrum.plotter.axis is not None: for p in self.modelplot: p.set_visible(False) if legend: self._clearlegend() if components: self._clearcomponents() if self.Spectrum.plotter.autorefresh: self.Spectrum.plotter.refresh() # Empty the modelplot array to free memory self.modelplot = [] # remove residuals from self if they're there. if hasattr(self,'residualplot'): for L in self.residualplot: if L in self.Spectrum.plotter.axis.lines: self.Spectrum.plotter.axis.lines.remove(L) def _clearcomponents(self): for pc in self._plotted_components: pc.set_visible(False) if pc in self.Spectrum.plotter.axis.lines: self.Spectrum.plotter.axis.lines.remove(pc) if self.Spectrum.plotter.autorefresh: self.Spectrum.plotter.refresh() # Empty the plotted components array to free memory self._plotted_components = [] def _clearlegend(self): """ Remove the legend from the plot window """ axis = self.Spectrum.plotter.axis if axis and axis.legend_ == self.fitleg: axis.legend_ = None if axis and self.fitleg is not None: # don't remove fitleg unless it's in the current axis # self.fitleg.set_visible(False) if self.fitleg in axis.artists: axis.artists.remove(self.fitleg) if self.Spectrum.plotter.autorefresh: self.Spectrum.plotter.refresh() def savefit(self): """ Save the fit parameters from a Gaussian fit to the FITS header .. todo:: THESE SHOULD BE WRITTEN FOR EACH TYPE OF MODEL TO BE FIT """ if self.modelpars is not None and hasattr(self.Spectrum,'header'): for ii,p in enumerate(self.modelpars): try: if ii % 3 == 0: self.Spectrum.header['AMP%1i' % (ii/3)] = (p,"Gaussian best fit amplitude #%i" % (ii/3)) elif ii % 3 == 1: self.Spectrum.header['CEN%1i' % (ii/3)] = (p,"Gaussian best fit center #%i" % (ii/3)) elif ii % 3 == 2: self.Spectrum.header['WID%1i' % (ii/3)] = (p,"Gaussian best fit width #%i" % (ii/3)) except ValueError as ex: log.info("Failed to save fit to header: {0}".format(ex)) def downsample(self,factor): """ Downsample the model spectrum (and the spectofit spectra) This should only be done when Spectrum.smooth is called """ if self.model is not None: self.model = self.model[::factor] if self.residuals is not None: self.residuals = self.residuals[::factor] self.spectofit = self.spectofit[::factor] self.errspec = self.errspec[::factor] self.includemask = self.includemask[::factor] def crop(self,x1pix,x2pix): """ When spectrum.crop is called, this must be too """ if self.model is not None: self.model = self.model[x1pix:x2pix] if hasattr(self,'fullmodel'): self.fullmodel = self.fullmodel[x1pix:x2pix] self.includemask = self.includemask[x1pix:x2pix] self.setfitspec() def integral(self, analytic=False, direct=False, threshold='auto', integration_limits=None, integration_limit_units='pixels', return_error=False, **kwargs): """ Return the integral of the fitted spectrum Parameters ---------- analytic : bool Return the analytic integral of the fitted function? .. WARNING:: This approach is only implemented for some models .. todo:: Implement error propagation for this approach direct : bool Return the integral of the *spectrum* (as opposed to the *fit*) over a range defined by the `integration_limits` if specified or `threshold` otherwise threshold : 'auto' or 'error' or float Determines what data to be included in the integral based off of where the model is greater than this number If 'auto', the threshold will be set to peak_fraction * the peak model value. If 'error', uses the error spectrum as the threshold See `self.get_model_xlimits` for details integration_limits : None or 2-tuple Manually specify the limits in `integration_limit_units` units return_error : bool Return the error on the integral if set. The error computed by sigma = sqrt(sum(sigma_i^2)) * dx kwargs : passed to `self.fitter.integral` if ``not(direct)`` Returns ------- np.scalar or np.ndarray with the integral or integral & error """ if analytic: return self.fitter.analytic_integral(modelpars=self.parinfo.values) xmin,xmax = self.get_model_xlimits(units='pixels', threshold=threshold) if integration_limits is None: integration_limits = [xmin,xmax] integration_limits = [ self.Spectrum.xarr.x_to_pix(x,xval_units=integration_limit_units) for x in integration_limits] if xmax - xmin > 1: # can only get cdelt if there's more than 1 pixel dx = self.Spectrum.xarr[xmin:xmax].cdelt().value else: dx = None if dx is None: #dx = np.abs(np.concatenate([np.diff(self.Spectrum.xarr),[0]])) #warn("Irregular X-axis. The last pixel is ignored.") self.Spectrum.xarr.make_dxarr() dx = self.Spectrum.xarr.dxarr.value else: # shouldn't shape be a 'property'? dx = np.repeat(np.abs(dx), self.Spectrum.shape) if direct: integrand = self.Spectrum.data[xmin:xmax] if not self.Spectrum.baseline.subtracted: integrand -= self.Spectrum.baseline.basespec[xmin:xmax] integ = (integrand * dx[xmin:xmax]).sum() if return_error: # compute error assuming a "known mean" (not a sample mean). If sample mean, multiply # by sqrt(len(dx)/(len(dx)-1)) (which should be very near 1) error = np.sqrt((dx[xmin:xmax] * self.Spectrum.error[xmin:xmax]**2).sum() / dx[xmin:xmax].sum()) return np.array([integ,error]) else: return integ #OK = np.abs( fullmodel ) > threshold #integ = (self.spectofit[OK] * dx[OK]).sum() #error = np.sqrt((self.errspec[OK]**2 * dx[OK]).sum()/dx[OK].sum()) else: if not hasattr(self.fitter,'integral'): raise AttributeError("The fitter %s does not have an integral implemented" % self.fittype) # the model considered here must NOT include the baseline! # if it does, you'll get the integral of the continuum #fullmodel = self.get_full_model(add_baseline=False) if self.Spectrum.xarr.cdelt() is not None: dx = np.median(dx) integ = self.fitter.integral(self.modelpars, dx=dx, **kwargs) if return_error: if mycfg.WARN: warn("WARNING: The computation of the error " "on the integral is not obviously " "correct or robust... it's just a guess.") OK = self.model_mask(threshold=threshold, add_baseline=False) error = np.sqrt((self.errspec[OK]**2).sum()) * dx #raise NotImplementedError("We haven't written up correct error estimation for integrals of fits") else: integ = 0 error = 0 warn("An analytic integal could not be computed because the X-axis is irregular. Try direct=True when integrating, or find a way to linearize the X-axis") if return_error: return integ,error else: return integ def model_mask(self, **kwargs): """ Get a mask (boolean array) of the region where the fitted model is significant Parameters ---------- threshold : 'auto' or 'error' or float The threshold to compare the model values to for selecting the mask region. * auto: uses `peak_fraction` times the model peak * error: use the spectrum error * float: any floating point number as an absolute threshold peak_fraction : float Parameter used if ``threshold=='auto'`` to determine fraction of model peak to set threshold at add_baseline : bool Add the fitted baseline to the model before comparing to threshold? Returns ------- mask : `~numpy.ndarray` A boolean mask array with the same size as the spectrum, set to ``True`` where the fitted model has values above a specified threshold """ return self._compare_to_threshold(**kwargs) def _compare_to_threshold(self, threshold='auto', peak_fraction=0.01, add_baseline=False): """ Identify pixels that are above some threshold """ model = self.get_full_model(add_baseline=add_baseline) # auto-set threshold from some fraction of the model peak if threshold=='auto': threshold = peak_fraction * np.abs(model).max() elif threshold=='error': threshold = self.errspec OK = np.abs(model) > threshold return OK def get_model_xlimits(self, threshold='auto', peak_fraction=0.01, add_baseline=False, unit='pixels', units=None): """ Return the x positions of the first and last points at which the model is above some threshold Parameters ---------- threshold : 'auto' or 'error' or float If 'auto', the threshold will be set to peak_fraction * the peak model value. If 'error', uses the error spectrum as the threshold peak_fraction : float ignored unless threshold == 'auto' add_baseline : bool Include the baseline when computing whether the model is above the threshold? default FALSE. Passed to get_full_model. units : str A valid unit type, e.g. 'pixels' or 'angstroms' """ OK = self._compare_to_threshold(threshold=threshold, peak_fraction=peak_fraction, add_baseline=add_baseline) # find the first & last "True" values xpixmin = OK.argmax() xpixmax = len(OK) - OK[::-1].argmax() - 1 if units is not None and unit =='pixels': # todo: deprecate unit = units if unit == 'pixels': return [xpixmin,xpixmax] else: return self.Spectrum.xarr[[xpixmin,xpixmax]].as_unit(units) def shift_pars(self, frame=None): """ Shift the velocity / wavelength / frequency of the fitted parameters into a different frame Right now this only takes care of redshift and only if redshift is defined. It should be extended to do other things later """ for ii,pi in enumerate(self.parinfo): for partype in ('shift','offset','velo'): if partype in str.lower(pi['parname']): if frame is not None: self.modelpars[ii] = self.Spectrum.xarr.x_in_frame(self.modelpars[ii], frame) def moments(self, fittype=None, **kwargs): """ Return the moments see the :mod:`~pyspeckit.spectrum.moments` module Parameters ---------- fittype : None or str The registered fit type to use for moment computation """ if fittype is None: fittype = self.fittype return list(self.Registry.multifitters[fittype].moments( self.Spectrum.xarr[self.xmin:self.xmax], self.spectofit[self.xmin:self.xmax], **kwargs)) def button3action(self, event, debug=False, nwidths=1): """ Disconnect the interactiveness Perform the fit (or die trying) Hide the guesses """ if self.nclicks_b1 == 0: # there has been no selection # therefore, we assume *everything* is selected self.includemask[:] = True self.Spectrum.plotter.figure.canvas.mpl_disconnect(self.click) self.Spectrum.plotter.figure.canvas.mpl_disconnect(self.keyclick) if self.npeaks > 0: if hasattr(self, 'fitter'): self.guesses = self.fitter.parse_3par_guesses(self.guesses) else: # default fitter is a Gaussian, which has 3 parameters if len(self.guesses) % 3 != 0: log.error("Default fitter is Gaussian, and there were " "{0} guess parameters, which is not a " "multiple of 3.".format(len(self.guesses))) log.info("{0} Guesses : {1} X channel range: {2}-{3}" .format(len(self.guesses), self.guesses, self.xmin, self.xmax)) self.multifit(use_window_limits=True) for p in self.button2plot + self.button1plot: p.set_visible(False) # disconnect interactive window (and more importantly, reconnect to # original interactive cmds) self.clear_all_connections() def copy(self, parent=None, registry=None): """ Create a copy of the spectral fit - includes copies of the _full_model, the registry, the fitter, parinfo, modelpars, modelerrs, model, npeaks Parameters ---------- parent : `pyspeckit.classes.Spectrum` A `~Spectrum` instance that is the parent of the specfit instance. This needs to be specified at some point, but defaults to None to prevent overwriting a previous plot. """ if registry is None: if hasattr(parent, 'Registry'): registry = parent.Registry else: # only make a copy if we're not already given a specific registry # to inherit copy.deepcopy(self.Registry) newspecfit = Specfit(parent, Registry=registry) newspecfit.parinfo = copy.deepcopy(self.parinfo) if newspecfit.parinfo is None: newspecfit.modelpars = None newspecfit.modelerrs = None else: newspecfit.modelpars = newspecfit.parinfo.values newspecfit.modelerrs = newspecfit.parinfo.errors newspecfit.includemask = self.includemask.copy() newspecfit.model = copy.copy(self.model) newspecfit.npeaks = self.npeaks if hasattr(self,'fitter'): newspecfit.fitter = copy.deepcopy(self.fitter) newspecfit.fitter.parinfo = newspecfit.parinfo if hasattr(self,'fullmodel'): newspecfit._full_model() # this is ridiculous, absurd, and infuriating... newspecfit.button2action = newspecfit.guesspeakwidth if parent is not None: newspecfit.Spectrum.plotter = parent.plotter else: newspecfit.Spectrum.plotter = None return newspecfit def __copy__(self): return self.copy(parent=self.Spectrum) def add_sliders(self, parlimitdict=None, **kwargs): """ Add a Sliders window in a new figure appropriately titled Parameters ---------- parlimitdict: dict Each parameter needs to have displayed limits; these are set in min-max pairs. If this is left empty, the widget will try to guess at reasonable limits, but the guessing is not very sophisticated yet. .. todo:: Add a button in the navbar that makes this window pop up http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib """ if parlimitdict is None: # try to create a reasonable parlimit dict parlimitdict = {} for param in self.parinfo: if not param.parname in parlimitdict: if any( (x in param['parname'].lower() for x in ('shift','xoff')) ): lower, upper = (self.Spectrum.xarr[self.includemask].min().value, self.Spectrum.xarr[self.includemask].max().value) elif any( (x in param['parname'].lower() for x in ('width','fwhm')) ): xvalrange = (self.Spectrum.xarr[self.includemask].max().value - self.Spectrum.xarr[self.includemask].min().value) lower,upper = (0,xvalrange) elif any( (x in param['parname'].lower() for x in ('amp','peak','height')) ): datarange = self.spectofit.max() - self.spectofit.min() lower,upper = (param['value']-datarange, param['value']+datarange) else: lower = param['value'] * 0.1 upper = param['value'] * 10 # override guesses with limits if param.limited[0]: # nextafter -> next representable float lower = np.nextafter(param.limits[0], param.limits[0]+1) if param.limited[1]: upper = np.nextafter(param.limits[1], param.limits[1]-1) parlimitdict[param.parname] = (lower,upper) if hasattr(self,'fitter'): self.SliderWidget = widgets.FitterSliders(self, self.Spectrum.plotter.figure, npars=self.fitter.npars, parlimitdict=parlimitdict, **kwargs) else: log.error("Must have a fitter instantiated before creating sliders") def optimal_chi2(self, reduced=True, threshold='error', **kwargs): """ Compute an "optimal" :math:`\chi^2` statistic, i.e. one in which only pixels in which the model is statistically significant are included Parameters ---------- reduced : bool Return the reduced :math:`\chi^2` threshold : 'auto' or 'error' or float If 'auto', the threshold will be set to peak_fraction * the peak model value, where peak_fraction is a kwarg passed to get_model_xlimits reflecting the fraction of the model peak to consider significant If 'error', uses the error spectrum as the threshold kwargs : dict passed to :meth:`get_model_xlimits` Returns ------- chi2 : float :math:`\chi^2` statistic or reduced :math:`\chi^2` statistic (:math:`\chi^2/n`) .. math:: \chi^2 = \sum( (d_i - m_i)^2 / e_i^2 ) """ modelmask = self._compare_to_threshold(threshold=threshold, **kwargs) chi2 = np.sum((self.fullresiduals[modelmask]/self.errspec[modelmask])**2) if reduced: # vheight included here or not? assuming it should be... return chi2/self.dof else: return chi2 def get_pymc(self, **kwargs): """ Create a pymc MCMC sampler from the current fitter. Defaults to 'uninformative' priors `kwargs` are passed to the fitter's get_pymc method, with parameters defined below. Parameters ---------- data : np.ndarray error : np.ndarray use_fitted_values : bool Each parameter with a measured error will have a prior defined by the Normal distribution with sigma = par.error and mean = par.value Examples -------- >>> x = pyspeckit.units.SpectroscopicAxis(np.linspace(-10,10,50), unit='km/s') >>> e = np.random.randn(50) >>> d = np.exp(-np.asarray(x)**2/2.)*5 + e >>> sp = pyspeckit.Spectrum(data=d, xarr=x, error=np.ones(50)*e.std()) >>> sp.specfit(fittype='gaussian') >>> MCuninformed = sp.specfit.get_pymc() >>> MCwithpriors = sp.specfit.get_pymc(use_fitted_values=True) >>> MCuninformed.sample(1000) >>> MCuninformed.stats()['AMPLITUDE0'] >>> # WARNING: This will fail because width cannot be set <0, but it may randomly reach that... >>> # How do you define a likelihood distribution with a lower limit?! >>> MCwithpriors.sample(1000) >>> MCwithpriors.stats()['AMPLITUDE0'] """ if hasattr(self.fitter,'get_pymc'): return self.fitter.get_pymc(self.Spectrum.xarr, self.spectofit, self.errspec, **kwargs) else: raise AttributeError("Fitter %r does not have pymc implemented." % self.fitter) def get_emcee(self, nwalkers=None, **kwargs): """ Get an emcee walker ensemble for the data & model using the current model type Parameters ---------- data : np.ndarray error : np.ndarray nwalkers : int Number of walkers to use. Defaults to 2 * self.fitters.npars Examples -------- >>> import pyspeckit >>> x = pyspeckit.units.SpectroscopicAxis(np.linspace(-10,10,50), unit='km/s') >>> e = np.random.randn(50) >>> d = np.exp(-np.asarray(x)**2/2.)*5 + e >>> sp = pyspeckit.Spectrum(data=d, xarr=x, error=np.ones(50)*e.std()) >>> sp.specfit(fittype='gaussian') >>> emcee_ensemble = sp.specfit.get_emcee() >>> p0 = emcee_ensemble.p0 * (np.random.randn(*emcee_ensemble.p0.shape) / 10. + 1.0) >>> pos,logprob,state = emcee_ensemble.run_mcmc(p0,100) """ import emcee if hasattr(self.fitter,'get_emcee_ensemblesampler'): nwalkers = (self.fitter.npars * self.fitter.npeaks + self.fitter.vheight) * 2 emc = self.fitter.get_emcee_ensemblesampler(self.Spectrum.xarr, self.spectofit, self.errspec, nwalkers) emc.nwalkers = nwalkers emc.p0 = np.array([self.parinfo.values] * emc.nwalkers) return emc def get_components(self, **kwargs): """ If a model has been fitted, return the components of the model Parameters ---------- kwargs are passed to self.fitter.components """ if self.modelpars is not None: self.modelcomponents = self.fitter.components(self.Spectrum.xarr, self.modelpars, **kwargs) return self.modelcomponents def measure_approximate_fwhm(self, threshold='error', emission=True, interpolate_factor=1, plot=False, grow_threshold=2, **kwargs): """ Measure the FWHM of a fitted line This procedure is designed for multi-component *blended* lines; if the true FWHM is known (i.e., the line is well-represented by a single gauss/voigt/lorentz profile), use that instead. Do not use this for multiple independently peaked profiles. This MUST be run AFTER a fit has been performed! Parameters ---------- threshold : 'error' | float The threshold above which the spectrum will be interpreted as part of the line. This threshold is applied to the *model*. If it is 'noise', self.error will be used. emission : bool Is the line absorption or emission? interpolate_factor : integer Magnification factor for determining sub-pixel FWHM. If used, "zooms-in" by using linear interpolation within the line region plot : bool Overplot a line at the FWHM indicating the FWHM. kwargs are passed to matplotlib.plot grow_threshold : int Minimum number of valid points. If the total # of points above the threshold is <= to this number, it will be grown by 1 pixel on each side Returns ------- The approximated FWHM, if it can be computed If there are <= 2 valid pixels, a fwhm cannot be computed """ if threshold == 'error': threshold = self.Spectrum.error if np.all(self.Spectrum.error==0): threshold = 1e-3*self.Spectrum.data.max() if self.Spectrum.baseline.subtracted is False: data = self.Spectrum.data - self.Spectrum.baseline.basespec else: data = self.Spectrum.data * 1 model = self.get_full_model(add_baseline=False) if np.count_nonzero(model) == 0: raise ValueError("The model is all zeros. No FWHM can be " "computed.") # can modify inplace because data is a copy of self.Spectrum.data if not emission: data *= -1 model *= -1 line_region = model > threshold if line_region.sum() == 0: raise ValueError("No valid data included in FWHM computation") if line_region.sum() <= grow_threshold: line_region[line_region.argmax()-1:line_region.argmax()+1] = True reverse_argmax = len(line_region) - line_region.argmax() - 1 line_region[reverse_argmax-1:reverse_argmax+1] = True log.warning("Fewer than {0} pixels were identified as part of the fit." " To enable statistical measurements, the range has been" " expanded by 2 pixels including some regions below the" " threshold.".format(grow_threshold)) # determine peak (because data is neg if absorption, always use max) peak = data[line_region].max() xarr = self.Spectrum.xarr[line_region] xarr.make_dxarr() cd = xarr.dxarr.min() if interpolate_factor > 1: newxarr = units.SpectroscopicAxis(np.arange(xarr.min().value-cd.value, xarr.max().value+cd.value, cd.value / float(interpolate_factor) ), unit=xarr.unit, equivalencies=xarr.equivalencies ) # load the metadata from xarr # newxarr._update_from(xarr) data = np.interp(newxarr,xarr,data[line_region]) xarr = newxarr else: data = data[line_region] # need the peak location so we can find left/right half-max locations peakloc = data.argmax() hm_left = np.argmin(np.abs(data[:peakloc]-peak/2.)) hm_right = np.argmin(np.abs(data[peakloc:]-peak/2.)) + peakloc deltax = xarr[hm_right]-xarr[hm_left] if plot: # for plotting, use a negative if absorption sign = 1 if emission else -1 # shift with baseline if baseline is plotted if not self.Spectrum.baseline.subtracted: basespec = self.Spectrum.baseline.get_model(xarr) yoffleft = self.Spectrum.plotter.offset + basespec[hm_left] yoffright = self.Spectrum.plotter.offset + basespec[hm_right] else: yoffleft = yoffright = self.Spectrum.plotter.offset log.debug("peak={2} yoffleft={0} yoffright={1}".format(yoffleft, yoffright, peak)) log.debug("hm_left={0} hm_right={1} xarr[hm_left]={2} xarr[hm_right]={3}".format(hm_left, hm_right, xarr[hm_left], xarr[hm_right])) self.Spectrum.plotter.axis.plot([xarr[hm_right].value, xarr[hm_left].value], np.array([sign*peak/2.+yoffleft, sign*peak/2.+yoffright]), **kwargs) self.Spectrum.plotter.refresh() # debug print hm_left,hm_right,"FWHM: ",deltax # debug self.Spectrum.plotter.axis.plot(xarr,data,color='magenta') # debug self.Spectrum.plotter.refresh() # debug raise TheDead return deltax def _validate_parinfo(self, parinfo, mode='fix'): assert mode in ('fix','raise','check','guesses') any_out_of_range = [] for param in parinfo: if (param.limited[0] and (param.value < param.limits[0])): if (
np.allclose(param.value, param.limits[0])
numpy.allclose
import matplotlib.pyplot as plt import numpy as np def full(resolution): i = 0 indexes_array = np.zeros((resolution * resolution, 2)) for j in range(resolution): for k in range(resolution): indexes_array[i] =
np.array([j, k])
numpy.array
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' GOAL Fig. 5: Plot Arctic sea-ice area (10^6 km^2), computed via compute_area.py Fig. 6: Plot Arctic sea-ice volume (10^3 km^3), computed via compute_volume.py PROGRAMMER <NAME> LAST UPDATE 17/11/2020 ''' # Standard libraries import numpy as np import matplotlib.pyplot as plt from scipy import stats # Options save_fig = True save_var = False # Working directories dir_input = '/nobackup/rossby24/proj/rossby/joint_exp/oseaice/' dir_D000 = dir_input + 'post-proc/D000/' dir_D012 = dir_input + 'post-proc/D012/' dir_D013 = dir_input + 'post-proc/D013/' dir_D014 = dir_input + 'post-proc/D014/' dir_D015 = dir_input + 'post-proc/D015/' dir_D016 = dir_input + 'post-proc/D016/' dir_D017 = dir_input + 'post-proc/D017/' dir_D018 = dir_input + 'post-proc/D018/' dir_D019 = dir_input + 'post-proc/D019/' dir_D020 = dir_input + 'post-proc/D020/' dir_D021 = dir_input + 'post-proc/D021/' dir_D022 = dir_input + 'post-proc/D022/' dir_D023 = dir_input + 'post-proc/D023/' dir_D024 = dir_input + 'post-proc/D024/' dir_D025 = dir_input + 'post-proc/D025/' dir_D027 = dir_input + 'post-proc/D027/' dir_D028 = dir_input + 'post-proc/D028/' dir_D029 = dir_input + 'post-proc/D029/' dir_D030 = dir_input + 'post-proc/D030/' dir_piomas = dir_input + 'obs/' dir_fig = dir_input + 'OSeaIce_Paper/' # Function to retrieve monthly mean and compute seasonal cycle def compute_monthly(nm,nmy,var): nyears = int(nm / nmy) var_mon = np.zeros((nmy,nyears)) var_ym = np.zeros(nmy) sd_var = np.zeros(nmy) for i in np.arange(nmy): for k in np.arange(nyears): if np.isnan(var[i+k*nmy]) == False: var_mon[i,k] = var[i+k*nmy] var_ym[i] = var_ym[i] + var[i+k*nmy] var_ym[i] = var_ym[i] / nyears for i in np.arange(nmy): for k in np.arange(nyears): if np.isnan(var[i+k*nmy]) == False: sd_var[i] = sd_var[i] + (var[i+k*nmy] - var_ym[i])**2. sd_var[i] = np.sqrt(sd_var[i] / nyears) return var_mon,var_ym,sd_var # Function to compute trend + SD of trend def compute_trend(nyears,var): ndecades = nyears / 10 year = np.arange(nyears) + 1 idx = np.isfinite(year) & np.isfinite(var) a,b = np.polyfit(year[idx],var[idx],1) lreg = a * year + b trend_decade = a * nyears / ndecades trend_percent = 100 * trend_decade / lreg[0] n_freedom = nm-2 s_yx = np.sum((var[idx]-lreg[idx])**2)/n_freedom SS_xx = np.sum((year-np.mean(year))**2) s_a = np.sqrt(s_yx/SS_xx) sd_trend = s_a * nyears / ndecades t_a = a / s_a alpha = 0.05 t_crit = stats.t.ppf(1-alpha/2,n_freedom) sig_a = 0 if np.abs(t_a) > t_crit: sig_a = 1 return trend_decade,sd_trend,trend_percent,sig_a # Function to compute significativity of difference between two means def compute_sig(n,var1,var2): mean_var1 = np.nanmean(var1) mean_var2 = np.nanmean(var2) diff = mean_var1 - mean_var2 reldiff = diff / mean_var2 sum_var1 = 0. sum_var2 = 0. for i in np.arange(n): if np.isnan(var1[i]) == False: sum_var1 = sum_var1 + (var1[i] - mean_var1)**2. if np.isnan(var2[i]) == False: sum_var2 = sum_var2 + (var2[i] - mean_var2)**2. sd = np.sqrt((sum_var1 + sum_var2) / (2. * n - 2.)) es = sd * np.sqrt(2. / n) t = diff / es alpha = 0.05 t_crit = stats.t.ppf(1-alpha/2,(2.*n-2.)) sig = 0 if np.abs(t) > t_crit: sig = 1 return sig # Load sea-ice area EC-Earth D000 filename = dir_D000 + 'SIarea_D000.npy' area_D000,area_barents_D000,area_greenland_D000,area_labrador_D000,area_laptev_D000,area_chukchi_D000,area_beaufort_D000,area_central_D000 = np.load(filename) # Load sea-ice area EC-Earth D012 filename = dir_D012 + 'SIarea_D012.npy' area_D012a,area_barents_D012a,area_greenland_D012a,area_labrador_D012a,area_laptev_D012a,area_chukchi_D012a,area_beaufort_D012a,area_central_D012a = np.load(filename) # Load sea-ice area EC-Earth D012 from 2180-2229 filename = dir_D012 + 'SIarea_D012_2180.npy' area_D012b,area_barents_D012b,area_greenland_D012b,area_labrador_D012b,area_laptev_D012b,area_chukchi_D012b,area_beaufort_D012b,area_central_D012b = np.load(filename) area_D012 = np.concatenate((area_D012a,area_D012b),axis=0) # Load sea-ice area EC-Earth D013 filename = dir_D013 + 'SIarea_D013.npy' area_D013,area_barents_D013,area_greenland_D013,area_labrador_D013,area_laptev_D013,area_chukchi_D013,area_beaufort_D013,area_central_D013 = np.load(filename) # Load sea-ice area EC-Earth D014 filename = dir_D014 + 'SIarea_D014.npy' area_D014,area_barents_D014,area_greenland_D014,area_labrador_D014,area_laptev_D014,area_chukchi_D014,area_beaufort_D014,area_central_D014 = np.load(filename) # Load sea-ice area EC-Earth D015 filename = dir_D015 + 'SIarea_D015.npy' area_D015,area_barents_D015,area_greenland_D015,area_labrador_D015,area_laptev_D015,area_chukchi_D015,area_beaufort_D015,area_central_D015 = np.load(filename) # Load sea-ice area EC-Earth D016 filename = dir_D016 + 'SIarea_D016.npy' area_D016,area_barents_D016,area_greenland_D016,area_labrador_D016,area_laptev_D016,area_chukchi_D016,area_beaufort_D016,area_central_D016 = np.load(filename) # Load sea-ice area EC-Earth D017 filename = dir_D017 + 'SIarea_D017.npy' area_D017,area_barents_D017,area_greenland_D017,area_labrador_D017,area_laptev_D017,area_chukchi_D017,area_beaufort_D017,area_central_D017 = np.load(filename) # Load sea-ice area EC-Earth D018 filename = dir_D018 + 'SIarea_D018.npy' area_D018,area_barents_D018,area_greenland_D018,area_labrador_D018,area_laptev_D018,area_chukchi_D018,area_beaufort_D018,area_central_D018 = np.load(filename) # Load sea-ice area EC-Earth D019 filename = dir_D019 + 'SIarea_D019.npy' area_D019,area_barents_D019,area_greenland_D019,area_labrador_D019,area_laptev_D019,area_chukchi_D019,area_beaufort_D019,area_central_D019 = np.load(filename) # Load sea-ice area EC-Earth D020 filename = dir_D020 + 'SIarea_D020.npy' area_D020,area_barents_D020,area_greenland_D020,area_labrador_D020,area_laptev_D020,area_chukchi_D020,area_beaufort_D020,area_central_D020 = np.load(filename) # Load sea-ice area EC-Earth D021 filename = dir_D021 + 'SIarea_D021.npy' area_D021a,area_barents_D021a,area_greenland_D021a,area_labrador_D021a,area_laptev_D021a,area_chukchi_D021a,area_beaufort_D021a,area_central_D021a = np.load(filename) # Load sea-ice area EC-Earth D021 from 2180-2229 filename = dir_D021 + 'SIarea_D021_2180.npy' area_D021b,area_barents_D021b,area_greenland_D021b,area_labrador_D021b,area_laptev_D021b,area_chukchi_D021b,area_beaufort_D021b,area_central_D021b = np.load(filename) area_D021 = np.concatenate((area_D021a,area_D021b),axis=0) # Load sea-ice area EC-Earth D022 filename = dir_D022 + 'SIarea_D022.npy' area_D022,area_barents_D022,area_greenland_D022,area_labrador_D022,area_laptev_D022,area_chukchi_D022,area_beaufort_D022,area_central_D022 = np.load(filename) # Load sea-ice area EC-Earth D023 filename = dir_D023 + 'SIarea_D023.npy' area_D023,area_barents_D023,area_greenland_D023,area_labrador_D023,area_laptev_D023,area_chukchi_D023,area_beaufort_D023,area_central_D023 = np.load(filename) # Load sea-ice area EC-Earth D024 filename = dir_D024 + 'SIarea_D024.npy' area_D024,area_barents_D024,area_greenland_D024,area_labrador_D024,area_laptev_D024,area_chukchi_D024,area_beaufort_D024,area_central_D024 = np.load(filename) # Load sea-ice area EC-Earth D025 filename = dir_D025 + 'SIarea_D025.npy' area_D025,area_barents_D025,area_greenland_D025,area_labrador_D025,area_laptev_D025,area_chukchi_D025,area_beaufort_D025,area_central_D025 = np.load(filename) # Load sea-ice area EC-Earth D027 filename = dir_D027 + 'SIarea_D027.npy' area_D027,area_barents_D027,area_greenland_D027,area_labrador_D027,area_laptev_D027,area_chukchi_D027,area_beaufort_D027,area_central_D027 = np.load(filename) # Load sea-ice area EC-Earth D028 filename = dir_D028 + 'SIarea_D028.npy' area_D028,area_barents_D028,area_greenland_D028,area_labrador_D028,area_laptev_D028,area_chukchi_D028,area_beaufort_D028,area_central_D028 = np.load(filename) # Load sea-ice area EC-Earth D029 filename = dir_D029 + 'SIarea_D029.npy' area_D029,area_barents_D029,area_greenland_D029,area_labrador_D029,area_laptev_D029,area_chukchi_D029,area_beaufort_D029,area_central_D029 = np.load(filename) # Load sea-ice area EC-Earth D030 filename = dir_D030 + 'SIarea_D030.npy' area_D030,area_barents_D030,area_greenland_D030,area_labrador_D030,area_laptev_D030,area_chukchi_D030,area_beaufort_D030,area_central_D030 = np.load(filename) # Load sea-ice area OSI SAF (OSI-450) 1979-2015 filename = dir_t613 + 'SIarea_OSI-450_1979-2015.npy' area_obs,area_barents_obs,area_greenland_obs,area_labrador_obs,area_laptev_obs,area_chukchi_obs,area_beaufort_obs,area_central_obs = np.load(filename) # Load sea-ice volume EC-Earth D000 filename = dir_D000 + 'SIvolume_D000.npy' volume_D000,volume_barents_D000,volume_greenland_D000,volume_labrador_D000,volume_laptev_D000,volume_chukchi_D000,volume_beaufort_D000,volume_central_D000 = np.load(filename) # Load sea-ice volume EC-Earth D012 filename = dir_D012 + 'SIvolume_D012.npy' volume_D012a,volume_barents_D012a,volume_greenland_D012a,volume_labrador_D012a,volume_laptev_D012a,volume_chukchi_D012a,volume_beaufort_D012a,volume_central_D012a = np.load(filename) # Load sea-ice volume EC-Earth D012 from 2180-2229 filename = dir_D012 + 'SIvolume_D012_2180.npy' volume_D012b,volume_barents_D012b,volume_greenland_D012b,volume_labrador_D012b,volume_laptev_D012b,volume_chukchi_D012b,volume_beaufort_D012b,volume_central_D012b = np.load(filename) volume_D012 = np.concatenate((volume_D012a,volume_D012b),axis=0) # Load sea-ice volume EC-Earth D013 filename = dir_D013 + 'SIvolume_D013.npy' volume_D013,volume_barents_D013,volume_greenland_D013,volume_labrador_D013,volume_laptev_D013,volume_chukchi_D013,volume_beaufort_D013,volume_central_D013 = np.load(filename) # Load sea-ice volume EC-Earth D014 filename = dir_D014 + 'SIvolume_D014.npy' volume_D014,volume_barents_D014,volume_greenland_D014,volume_labrador_D014,volume_laptev_D014,volume_chukchi_D014,volume_beaufort_D014,volume_central_D014 = np.load(filename) # Load sea-ice volume EC-Earth D015 filename = dir_D015 + 'SIvolume_D015.npy' volume_D015,volume_barents_D015,volume_greenland_D015,volume_labrador_D015,volume_laptev_D015,volume_chukchi_D015,volume_beaufort_D015,volume_central_D015 = np.load(filename) # Load sea-ice volume EC-Earth D016 filename = dir_D016 + 'SIvolume_D016.npy' volume_D016,volume_barents_D016,volume_greenland_D016,volume_labrador_D016,volume_laptev_D016,volume_chukchi_D016,volume_beaufort_D016,volume_central_D016 = np.load(filename) # Load sea-ice volume EC-Earth D017 filename = dir_D017 + 'SIvolume_D017.npy' volume_D017,volume_barents_D017,volume_greenland_D017,volume_labrador_D017,volume_laptev_D017,volume_chukchi_D017,volume_beaufort_D017,volume_central_D017 = np.load(filename) # Load sea-ice volume EC-Earth D018 filename = dir_D018 + 'SIvolume_D018.npy' volume_D018,volume_barents_D018,volume_greenland_D018,volume_labrador_D018,volume_laptev_D018,volume_chukchi_D018,volume_beaufort_D018,volume_central_D018 = np.load(filename) # Load sea-ice volume EC-Earth D019 filename = dir_D019 + 'SIvolume_D019.npy' volume_D019,volume_barents_D019,volume_greenland_D019,volume_labrador_D019,volume_laptev_D019,volume_chukchi_D019,volume_beaufort_D019,volume_central_D019 = np.load(filename) # Load sea-ice volume EC-Earth D020 filename = dir_D020 + 'SIvolume_D020.npy' volume_D020,volume_barents_D020,volume_greenland_D020,volume_labrador_D020,volume_laptev_D020,volume_chukchi_D020,volume_beaufort_D020,volume_central_D020 = np.load(filename) # Load sea-ice volume EC-Earth D021 filename = dir_D021 + 'SIvolume_D021.npy' volume_D021a,volume_barents_D021a,volume_greenland_D021a,volume_labrador_D021a,volume_laptev_D021a,volume_chukchi_D021a,volume_beaufort_D021a,volume_central_D021a = np.load(filename) # Load sea-ice volume EC-Earth D021 from 2180-2229 filename = dir_D021 + 'SIvolume_D021_2180.npy' volume_D021b,volume_barents_D021b,volume_greenland_D021b,volume_labrador_D021b,volume_laptev_D021b,volume_chukchi_D021b,volume_beaufort_D021b,volume_central_D021b = np.load(filename) volume_D021 = np.concatenate((volume_D021a,volume_D021b),axis=0) # Load sea-ice volume EC-Earth D022 filename = dir_D022 + 'SIvolume_D022.npy' volume_D022,volume_barents_D022,volume_greenland_D022,volume_labrador_D022,volume_laptev_D022,volume_chukchi_D022,volume_beaufort_D022,volume_central_D022 = np.load(filename) # Load sea-ice volume EC-Earth D023 filename = dir_D023 + 'SIvolume_D023.npy' volume_D023,volume_barents_D023,volume_greenland_D023,volume_labrador_D023,volume_laptev_D023,volume_chukchi_D023,volume_beaufort_D023,volume_central_D023 = np.load(filename) # Load sea-ice volume EC-Earth D024 filename = dir_D024 + 'SIvolume_D024.npy' volume_D024,volume_barents_D024,volume_greenland_D024,volume_labrador_D024,volume_laptev_D024,volume_chukchi_D024,volume_beaufort_D024,volume_central_D024 = np.load(filename) # Load sea-ice volume EC-Earth D025 filename = dir_D025 + 'SIvolume_D025.npy' volume_D025,volume_barents_D025,volume_greenland_D025,volume_labrador_D025,volume_laptev_D025,volume_chukchi_D025,volume_beaufort_D025,volume_central_D025 = np.load(filename) # Load sea-ice volume EC-Earth D027 filename = dir_D027 + 'SIvolume_D027.npy' volume_D027,volume_barents_D027,volume_greenland_D027,volume_labrador_D027,volume_laptev_D027,volume_chukchi_D027,volume_beaufort_D027,volume_central_D027 = np.load(filename) # Load sea-ice volume EC-Earth D028 filename = dir_D028 + 'SIvolume_D028.npy' volume_D028,volume_barents_D028,volume_greenland_D028,volume_labrador_D028,volume_laptev_D028,volume_chukchi_D028,volume_beaufort_D028,volume_central_D028 = np.load(filename) # Load sea-ice volume EC-Earth D029 filename = dir_D029 + 'SIvolume_D029.npy' volume_D029,volume_barents_D029,volume_greenland_D029,volume_labrador_D029,volume_laptev_D029,volume_chukchi_D029,volume_beaufort_D029,volume_central_D029 = np.load(filename) # Load sea-ice volume EC-Earth D030 filename = dir_D030 + 'SIvolume_D030.npy' volume_D030,volume_barents_D030,volume_greenland_D030,volume_labrador_D030,volume_laptev_D030,volume_chukchi_D030,volume_beaufort_D030,volume_central_D030 = np.load(filename) # Time parameters nmy = 12 nm = np.size(area) nm_D000 = np.size(area_D000) nm_D012 = np.size(area_D012) nm_D013 = np.size(area_D013) nm_obs = np.size(area_obs) nyears = int(nm / nmy) nyears_D000 = int(nm_D000 / nmy) nyears_D012 = int(nm_D012 / nmy) nyears_D013 = int(nm_D013 / nmy) nyears_obs = int(nm_obs / nmy) # Load sea-ice volume PIOMAS 1979-2019 (2 last months missing at the time of writing) year,vol1,vol2,vol3,vol4,vol5,vol6,vol7,vol8,vol9,vol10,vol11,vol12 = np.loadtxt(dir_piomas+'PIOMAS.2sst.monthly.Current.v2.1.txt',unpack=True) nyears_piomas = np.size(year) nm_piomas = nyears_piomas*nmy volume_piomas = np.zeros(nm_piomas) k = 0 for j in np.arange(nyears_piomas): volume_piomas[k] = vol1[j] volume_piomas[k+1] = vol2[j] volume_piomas[k+2] = vol3[j] volume_piomas[k+3] = vol4[j] volume_piomas[k+4] = vol5[j] volume_piomas[k+5] = vol6[j] volume_piomas[k+6] = vol7[j] volume_piomas[k+7] = vol8[j] volume_piomas[k+8] = vol9[j] volume_piomas[k+9] = vol10[j] volume_piomas[k+10] = vol11[j] volume_piomas[k+11] = vol12[j] k = k + nmy volume_piomas[-1] = np.nan volume_piomas[-2] = np.nan # Retrieve monthly mean SIA EC-Earth area_mon,area_ym,sd_area = compute_monthly(nm,nmy,area) # t613 1950-2014 nm_reduced = int((2014-1979+1)*12) begin_reduced = int((1979-1950)*12) notused,area_ym2,sd_area2 = compute_monthly(nm_reduced,nmy,area[begin_reduced::]) # t613 1979-2014 area_mon_D000,notused,notused = compute_monthly(nm_D000,nmy,area_D000) # 2014-2213 begin_reduced_D000 = int((2130-2014)*12) area_mon_D000b,area_ym_D000,sd_area_D000 = compute_monthly(nm_D013,nmy,area_D000[begin_reduced_D000:begin_reduced_D000+nm_D013]) # 2130-2179 area_mon_D012,notused,notused = compute_monthly(nm_D012,nmy,area_D012) area_mon_D012b,area_ym_D012,sd_area_D012 = compute_monthly(nm_D013,nmy,area_D012a) area_mon_D013,area_ym_D013,sd_area_D013 = compute_monthly(nm_D013,nmy,area_D013) area_mon_D014,area_ym_D014,sd_area_D014 = compute_monthly(nm_D013,nmy,area_D014) area_mon_D015,area_ym_D015,sd_area_D015 = compute_monthly(nm_D013,nmy,area_D015) area_mon_D016,area_ym_D016,sd_area_D016 = compute_monthly(nm_D013,nmy,area_D016) area_mon_D017,area_ym_D017,sd_area_D017 = compute_monthly(nm_D013,nmy,area_D017) area_mon_D018,area_ym_D018,sd_area_D018 = compute_monthly(nm_D013,nmy,area_D018) area_mon_D019,area_ym_D019,sd_area_D019 = compute_monthly(nm_D013,nmy,area_D019) area_mon_D020,area_ym_D020,sd_area_D020 = compute_monthly(nm_D013,nmy,area_D020) area_mon_D021,notused,notused = compute_monthly(nm_D012,nmy,area_D021) area_mon_D021b,area_ym_D021,sd_area_D021 = compute_monthly(nm_D013,nmy,area_D021a) area_mon_D022,area_ym_D022,sd_area_D022 = compute_monthly(nm_D013,nmy,area_D022) area_mon_D023,area_ym_D023,sd_area_D023 = compute_monthly(nm_D013,nmy,area_D023) area_mon_D024,area_ym_D024,sd_area_D024 = compute_monthly(nm_D013,nmy,area_D024) area_mon_D025,area_ym_D025,sd_area_D025 = compute_monthly(nm_D013,nmy,area_D025) area_mon_D027,area_ym_D027,sd_area_D027 = compute_monthly(nm_D013,nmy,area_D027) area_mon_D028,area_ym_D028,sd_area_D028 = compute_monthly(nm_D013,nmy,area_D028) area_mon_D029,area_ym_D029,sd_area_D029 = compute_monthly(nm_D013,nmy,area_D029) area_mon_D030,area_ym_D030,sd_area_D030 = compute_monthly(nm_D013,nmy,area_D030) # Retrieve monthly mean SIV EC-Earth volume_mon,volume_ym,sd_volume = compute_monthly(nm,nmy,volume) # 1950-2014 notused,volume_ym2,sd_volume2 = compute_monthly(nm_reduced,nmy,volume[begin_reduced::]) # 1979-2014 volume_mon_D000,notused,notused = compute_monthly(nm_D000,nmy,volume_D000) # 2014-2213 volume_mon_D000b,volume_ym_D000,sd_volume_D000 = compute_monthly(nm_D013,nmy,volume_D000[begin_reduced_D000:begin_reduced_D000+nm_D013]) # 2130-2179 volume_mon_D012,notused,notused = compute_monthly(nm_D012,nmy,volume_D012) volume_mon_D012b,volume_ym_D012,sd_volume_D012 = compute_monthly(nm_D013,nmy,volume_D012a) volume_mon_D013,volume_ym_D013,sd_volume_D013 = compute_monthly(nm_D013,nmy,volume_D013) volume_mon_D014,volume_ym_D014,sd_volume_D014 = compute_monthly(nm_D013,nmy,volume_D014) volume_mon_D015,volume_ym_D015,sd_volume_D015 = compute_monthly(nm_D013,nmy,volume_D015) volume_mon_D016,volume_ym_D016,sd_volume_D016 = compute_monthly(nm_D013,nmy,volume_D016) volume_mon_D017,volume_ym_D017,sd_volume_D017 = compute_monthly(nm_D013,nmy,volume_D017) volume_mon_D018,volume_ym_D018,sd_volume_D018 = compute_monthly(nm_D013,nmy,volume_D018) volume_mon_D019,volume_ym_D019,sd_volume_D019 = compute_monthly(nm_D013,nmy,volume_D019) volume_mon_D020,volume_ym_D020,sd_volume_D020 = compute_monthly(nm_D013,nmy,volume_D020) volume_mon_D021,notused,notused = compute_monthly(nm_D012,nmy,volume_D021) volume_mon_D021b,volume_ym_D021,sd_volume_D021 = compute_monthly(nm_D013,nmy,volume_D021a) volume_mon_D022,volume_ym_D022,sd_volume_D022 = compute_monthly(nm_D013,nmy,volume_D022) volume_mon_D023,volume_ym_D023,sd_volume_D023 = compute_monthly(nm_D013,nmy,volume_D023) volume_mon_D024,volume_ym_D024,sd_volume_D024 = compute_monthly(nm_D013,nmy,volume_D024) volume_mon_D025,volume_ym_D025,sd_volume_D025 = compute_monthly(nm_D013,nmy,volume_D025) volume_mon_D027,volume_ym_D027,sd_volume_D027 = compute_monthly(nm_D013,nmy,volume_D027) volume_mon_D028,volume_ym_D028,sd_volume_D028 = compute_monthly(nm_D013,nmy,volume_D028) volume_mon_D029,volume_ym_D029,sd_volume_D029 = compute_monthly(nm_D013,nmy,volume_D029) volume_mon_D030,volume_ym_D030,sd_volume_D030 = compute_monthly(nm_D013,nmy,volume_D030) # Retrieve monthly mean SIA Barents/Kara Sea area_mon_barents_D000,notused,notused = compute_monthly(nm_D000,nmy,area_barents_D000) area_mon_barents_D012,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D012a) area_mon_barents_D013,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D013) area_mon_barents_D014,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D014) area_mon_barents_D015,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D015) area_mon_barents_D016,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D016) area_mon_barents_D017,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D017) area_mon_barents_D018,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D018) area_mon_barents_D019,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D019) area_mon_barents_D020,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D020) area_mon_barents_D021,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D021a) area_mon_barents_D022,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D022) area_mon_barents_D023,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D023) area_mon_barents_D024,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D024) area_mon_barents_D025,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D025) area_mon_barents_D027,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D027) area_mon_barents_D028,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D028) area_mon_barents_D029,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D029) area_mon_barents_D030,notused,notused = compute_monthly(nm_D013,nmy,area_barents_D030) # Retrieve monthly mean SIA OSI SAF area_obs_mon,area_obs_ym,sd_area_obs = compute_monthly(nm_obs,nmy,area_obs) # 1979-2015 nm_obs_reduced = int((2014-1979+1)*12) notused,area_obs_ym2,sd_area_obs2 = compute_monthly(nm_obs_reduced,nmy,area_obs[0:nm_obs_reduced]) # 1979-2014 # Retrieve monthly mean SIV PIOMAS volume_piomas_mon,volume_piomas_ym,sd_volume_piomas = compute_monthly(nm_piomas,nmy,volume_piomas) # 1979-2019 (missing 11 and 12/2019) notused,volume_piomas_ym2,sd_volume_piomas2 = compute_monthly(nm_obs_reduced,nmy,volume_piomas[0:nm_obs_reduced]) # 1979-2014 # Save March/September SIA and SIV if save_var == True: filename = dir_fig + 'SIA_March.npy' np.save(filename,[area_mon_D000b[2,:],area_mon_D012b[2,:],area_mon_D013[2,:],area_mon_D014[2,:],area_mon_D015[2,:],area_mon_D016[2,:],area_mon_D017[2,:],area_mon_D018[2,:],area_mon_D019[2,:],area_mon_D020[2,:],area_mon_D021b[2,:],area_mon_D022[2,:],area_mon_D023[2,:],area_mon_D024[2,:],area_mon_D025[2,:],area_mon_D027[2,:],area_mon_D028[2,:],area_mon_D029[2,:],area_mon_D030[2,:]]) filename = dir_fig + 'SIV_March.npy' np.save(filename,[volume_mon_D000b[2,:],volume_mon_D012b[2,:],volume_mon_D013[2,:],volume_mon_D014[2,:],volume_mon_D015[2,:],volume_mon_D016[2,:],volume_mon_D017[2,:],volume_mon_D018[2,:],volume_mon_D019[2,:],volume_mon_D020[2,:],volume_mon_D021b[2,:],volume_mon_D022[2,:],volume_mon_D023[2,:],volume_mon_D024[2,:],volume_mon_D025[2,:],volume_mon_D027[2,:],volume_mon_D028[2,:],volume_mon_D029[2,:],volume_mon_D030[2,:]]) filename = dir_fig + 'SIA_September.npy' np.save(filename,[area_mon_D000b[8,:],area_mon_D012b[8,:],area_mon_D013[8,:],area_mon_D014[8,:],area_mon_D015[8,:],area_mon_D016[8,:],area_mon_D017[8,:],area_mon_D018[8,:],area_mon_D019[8,:],area_mon_D020[8,:],area_mon_D021b[8,:],area_mon_D022[8,:],area_mon_D023[8,:],area_mon_D024[8,:],area_mon_D025[8,:],area_mon_D027[8,:],area_mon_D028[8,:],area_mon_D029[8,:],area_mon_D030[8,:]]) filename = dir_fig + 'SIV_September.npy' np.save(filename,[volume_mon_D000b[8,:],volume_mon_D012b[8,:],volume_mon_D013[8,:],volume_mon_D014[8,:],volume_mon_D015[8,:],volume_mon_D016[8,:],volume_mon_D017[8,:],volume_mon_D018[8,:],volume_mon_D019[8,:],volume_mon_D020[8,:],volume_mon_D021b[8,:],volume_mon_D022[8,:],volume_mon_D023[8,:],volume_mon_D024[8,:],volume_mon_D025[8,:],volume_mon_D027[8,:],volume_mon_D028[8,:],volume_mon_D029[8,:],volume_mon_D030[8,:]]) ########### # Table 2 # ########### # Print mean numbers - March Arctic SIA month = 2 begin_reduced = int(2130-2014) print('March Arctic SIA (10^6 km^2)') print('CTRL =',np.round(area_ym_D000[month],1),'+/-',np.round(sd_area_D000[month],1)) print('Obs =',np.round(area_obs_ym[month],1),'+/-',np.round(sd_area_obs[month],1)) print('ATL1+1K =',np.round(area_ym_D013[month],1),'+/-',np.round(sd_area_D013[month],1),compute_sig(nyears_D013,area_mon_D013[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+3K =',np.round(area_ym_D012[month],1),'+/-',np.round(sd_area_D012[month],1),compute_sig(nyears_D013,area_mon_D012[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+5K =',np.round(area_ym_D014[month],1),'+/-',np.round(sd_area_D014[month],1),compute_sig(nyears_D013,area_mon_D014[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+1K =',np.round(area_ym_D016[month],1),'+/-',np.round(sd_area_D016[month],1),compute_sig(nyears_D013,area_mon_D016[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+3K =',np.round(area_ym_D015[month],1),'+/-',np.round(sd_area_D015[month],1),compute_sig(nyears_D013,area_mon_D015[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+5K =',np.round(area_ym_D017[month],1),'+/-',np.round(sd_area_D017[month],1),compute_sig(nyears_D013,area_mon_D017[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+1K =',np.round(area_ym_D019[month],1),'+/-',np.round(sd_area_D019[month],1),compute_sig(nyears_D013,area_mon_D019[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+3K =',np.round(area_ym_D018[month],1),'+/-',np.round(sd_area_D018[month],1),compute_sig(nyears_D013,area_mon_D018[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+5K =',np.round(area_ym_D020[month],1),'+/-',np.round(sd_area_D020[month],1),compute_sig(nyears_D013,area_mon_D020[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+1K =',np.round(area_ym_D027[month],1),'+/-',np.round(sd_area_D027[month],1),compute_sig(nyears_D013,area_mon_D027[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+3K =',np.round(area_ym_D021[month],1),'+/-',np.round(sd_area_D021[month],1),compute_sig(nyears_D013,area_mon_D021[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+5K =',np.round(area_ym_D028[month],1),'+/-',np.round(sd_area_D028[month],1),compute_sig(nyears_D013,area_mon_D028[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+1K =',np.round(area_ym_D029[month],1),'+/-',np.round(sd_area_D029[month],1),compute_sig(nyears_D013,area_mon_D029[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+3K =',np.round(area_ym_D022[month],1),'+/-',np.round(sd_area_D022[month],1),compute_sig(nyears_D013,area_mon_D022[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+5K =',np.round(area_ym_D030[month],1),'+/-',np.round(sd_area_D030[month],1),compute_sig(nyears_D013,area_mon_D030[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+1K =',np.round(area_ym_D024[month],1),'+/-',np.round(sd_area_D024[month],1),compute_sig(nyears_D013,area_mon_D024[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+3K =',np.round(area_ym_D023[month],1),'+/-',np.round(sd_area_D023[month],1),compute_sig(nyears_D013,area_mon_D023[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+5K =',np.round(area_ym_D025[month],1),'+/-',np.round(sd_area_D025[month],1),compute_sig(nyears_D013,area_mon_D025[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+3K - PAC3+3K =',compute_sig(nyears_D013,area_mon_D022[month,:],area_mon_D023[month,:])) print('ATL2+3K - ATL2+1K =',compute_sig(nyears_D013,area_mon_D015[month,:],area_mon_D016[month,:])) print('ATL3+3K - ATL3+1K =',compute_sig(nyears_D013,area_mon_D018[month,:],area_mon_D019[month,:])) print('PAC3+3K - PAC3+5K =',compute_sig(nyears_D013,area_mon_D023[month,:],area_mon_D025[month,:])) print('------------') # Print mean numbers - September Arctic SIA month = 8 print('September Arctic SIA (10^6 km^2)') print('CTRL =',np.round(area_ym_D000[month],1),'+/-',np.round(sd_area_D000[month],1)) print('Obs =',np.round(area_obs_ym[month],1),'+/-',np.round(sd_area_obs[month],1)) print('ATL1+1K =',np.round(area_ym_D013[month],1),'+/-',np.round(sd_area_D013[month],1),compute_sig(nyears_D013,area_mon_D013[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+3K =',np.round(area_ym_D012[month],1),'+/-',np.round(sd_area_D012[month],1),compute_sig(nyears_D013,area_mon_D012[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+5K =',np.round(area_ym_D014[month],1),'+/-',np.round(sd_area_D014[month],1),compute_sig(nyears_D013,area_mon_D014[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+1K =',np.round(area_ym_D016[month],1),'+/-',np.round(sd_area_D016[month],1),compute_sig(nyears_D013,area_mon_D016[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+3K =',np.round(area_ym_D015[month],1),'+/-',np.round(sd_area_D015[month],1),compute_sig(nyears_D013,area_mon_D015[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+5K =',np.round(area_ym_D017[month],1),'+/-',np.round(sd_area_D017[month],1),compute_sig(nyears_D013,area_mon_D017[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+1K =',np.round(area_ym_D019[month],1),'+/-',np.round(sd_area_D019[month],1),compute_sig(nyears_D013,area_mon_D019[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+3K =',np.round(area_ym_D018[month],1),'+/-',np.round(sd_area_D018[month],1),compute_sig(nyears_D013,area_mon_D018[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+5K =',np.round(area_ym_D020[month],1),'+/-',np.round(sd_area_D020[month],1),compute_sig(nyears_D013,area_mon_D020[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+1K =',np.round(area_ym_D027[month],1),'+/-',np.round(sd_area_D027[month],1),compute_sig(nyears_D013,area_mon_D027[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+3K =',np.round(area_ym_D021[month],1),'+/-',np.round(sd_area_D021[month],1),compute_sig(nyears_D013,area_mon_D021[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+5K =',np.round(area_ym_D028[month],1),'+/-',np.round(sd_area_D028[month],1),compute_sig(nyears_D013,area_mon_D028[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+1K =',np.round(area_ym_D029[month],1),'+/-',np.round(sd_area_D029[month],1),compute_sig(nyears_D013,area_mon_D029[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+3K =',np.round(area_ym_D022[month],1),'+/-',np.round(sd_area_D022[month],1),compute_sig(nyears_D013,area_mon_D022[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+5K =',np.round(area_ym_D030[month],1),'+/-',np.round(sd_area_D030[month],1),compute_sig(nyears_D013,area_mon_D030[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+1K =',np.round(area_ym_D024[month],1),'+/-',np.round(sd_area_D024[month],1),compute_sig(nyears_D013,area_mon_D024[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+3K =',np.round(area_ym_D023[month],1),'+/-',np.round(sd_area_D023[month],1),compute_sig(nyears_D013,area_mon_D023[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+5K =',np.round(area_ym_D025[month],1),'+/-',np.round(sd_area_D025[month],1),compute_sig(nyears_D013,area_mon_D025[month,:],area_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+3K - PAC3+3K =',compute_sig(nyears_D013,area_mon_D022[month,:],area_mon_D023[month,:])) print('ATL2+3K - ATL2+1K =',compute_sig(nyears_D013,area_mon_D015[month,:],area_mon_D016[month,:])) print('ATL3+3K - ATL3+1K =',compute_sig(nyears_D013,area_mon_D018[month,:],area_mon_D019[month,:])) print('PAC3+3K - PAC3+5K =',compute_sig(nyears_D013,area_mon_D023[month,:],area_mon_D025[month,:])) print('------------') # Print mean numbers - March Arctic SIV month = 2 print('March Arctic SIV (10^3 km^3)') print('CTRL =',np.round(volume_ym_D000[month],1),'+/-',np.round(sd_volume_D000[month],1)) print('PIOMAS =',np.round(volume_piomas_ym[month],1),'+/-',np.round(sd_volume_piomas[month],1)) print('ATL1+1K =',np.round(volume_ym_D013[month],1),'+/-',np.round(sd_volume_D013[month],1),compute_sig(nyears_D013,volume_mon_D013[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+3K =',np.round(volume_ym_D012[month],1),'+/-',np.round(sd_volume_D012[month],1),compute_sig(nyears_D013,volume_mon_D012[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+5K =',np.round(volume_ym_D014[month],1),'+/-',np.round(sd_volume_D014[month],1),compute_sig(nyears_D013,volume_mon_D014[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+1K =',np.round(volume_ym_D016[month],1),'+/-',np.round(sd_volume_D016[month],1),compute_sig(nyears_D013,volume_mon_D016[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+3K =',np.round(volume_ym_D015[month],1),'+/-',np.round(sd_volume_D015[month],1),compute_sig(nyears_D013,volume_mon_D015[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+5K =',np.round(volume_ym_D017[month],1),'+/-',np.round(sd_volume_D017[month],1),compute_sig(nyears_D013,volume_mon_D017[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+1K =',np.round(volume_ym_D019[month],1),'+/-',np.round(sd_volume_D019[month],1),compute_sig(nyears_D013,volume_mon_D019[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+3K =',np.round(volume_ym_D018[month],1),'+/-',np.round(sd_volume_D018[month],1),compute_sig(nyears_D013,volume_mon_D018[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL3+5K =',np.round(volume_ym_D020[month],1),'+/-',np.round(sd_volume_D020[month],1),compute_sig(nyears_D013,volume_mon_D020[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+1K =',np.round(volume_ym_D027[month],1),'+/-',np.round(sd_volume_D027[month],1),compute_sig(nyears_D013,volume_mon_D027[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+3K =',np.round(volume_ym_D021[month],1),'+/-',np.round(sd_volume_D021[month],1),compute_sig(nyears_D013,volume_mon_D021[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC1+5K =',np.round(volume_ym_D028[month],1),'+/-',np.round(sd_volume_D028[month],1),compute_sig(nyears_D013,volume_mon_D028[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+1K =',np.round(volume_ym_D029[month],1),'+/-',np.round(sd_volume_D029[month],1),compute_sig(nyears_D013,volume_mon_D029[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+3K =',np.round(volume_ym_D022[month],1),'+/-',np.round(sd_volume_D022[month],1),compute_sig(nyears_D013,volume_mon_D022[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+5K =',np.round(volume_ym_D030[month],1),'+/-',np.round(sd_volume_D030[month],1),compute_sig(nyears_D013,volume_mon_D030[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+1K =',np.round(volume_ym_D024[month],1),'+/-',np.round(sd_volume_D024[month],1),compute_sig(nyears_D013,volume_mon_D024[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+3K =',np.round(volume_ym_D023[month],1),'+/-',np.round(sd_volume_D023[month],1),compute_sig(nyears_D013,volume_mon_D023[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC3+5K =',np.round(volume_ym_D025[month],1),'+/-',np.round(sd_volume_D025[month],1),compute_sig(nyears_D013,volume_mon_D025[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('PAC2+3K - PAC3+3K =',compute_sig(nyears_D013,volume_mon_D022[month,:],volume_mon_D023[month,:])) print('ATL2+3K - ATL2+1K =',compute_sig(nyears_D013,volume_mon_D015[month,:],volume_mon_D016[month,:])) print('ATL3+3K - ATL3+1K =',compute_sig(nyears_D013,volume_mon_D018[month,:],volume_mon_D019[month,:])) print('PAC3+3K - PAC3+5K =',compute_sig(nyears_D013,volume_mon_D023[month,:],volume_mon_D025[month,:])) print('------------') # Print mean numbers - September Arctic SIV month = 8 print('September Arctic SIV (10^3 km^3)') print('CTRL =',np.round(volume_ym_D000[month],1),'+/-',np.round(sd_volume_D000[month],1)) print('PIOMAS =',np.round(volume_piomas_ym[month],1),'+/-',np.round(sd_volume_piomas[month],1)) print('ATL1+1K =',np.round(volume_ym_D013[month],1),'+/-',np.round(sd_volume_D013[month],1),compute_sig(nyears_D013,volume_mon_D013[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+3K =',np.round(volume_ym_D012[month],1),'+/-',np.round(sd_volume_D012[month],1),compute_sig(nyears_D013,volume_mon_D012[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL1+5K =',np.round(volume_ym_D014[month],1),'+/-',np.round(sd_volume_D014[month],1),compute_sig(nyears_D013,volume_mon_D014[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+1K =',np.round(volume_ym_D016[month],1),'+/-',np.round(sd_volume_D016[month],1),compute_sig(nyears_D013,volume_mon_D016[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+3K =',np.round(volume_ym_D015[month],1),'+/-',np.round(sd_volume_D015[month],1),compute_sig(nyears_D013,volume_mon_D015[month,:],volume_mon_D000[month,begin_reduced:begin_reduced+nyears_D013])) print('ATL2+5K =',
np.round(volume_ym_D017[month],1)
numpy.round
# Ohter import import sys import os # Matplotlib import matplotlib.pyplot # Tensorflow import tensorflow import datetime # Numpy and Pandas import numpy import pandas import math import scipy # Csv file manipulatons import csv #import time from sklearn.preprocessing import StandardScaler from joblib import dump from sklearn.model_selection import train_test_split from data_utils import normalize_data, denormalize_data, init_data, split_data, shuffle_data from datetime import date, time, timedelta from manage_stocks import add_indicator, add_indicators_to_predict from stockstats import StockDataFrame EPOCHS = 35 NB_INDICATORS = 15 TIME_BY_INTERVAL = numpy.array([ ('1m', timedelta(minutes=1)), ('2m', timedelta(minutes=2)), ('5m', timedelta(minutes=5)), ('15m', timedelta(minutes=15)), ('30m', timedelta(minutes=30)), ('60m', timedelta(minutes=60)), ('90m', timedelta(minutes=90)), ('1h', timedelta(hours=1)), ('1d', timedelta(days=1)), ('5d', timedelta(days=5)), ('1wk', timedelta(weeks=1)), ('1mo', timedelta(weeks=4)), ('3mo', timedelta(weeks=12)) ]) def custom_loss_function(y_actual, y_predicted): #print('y_actual:', y_actual) #print('y_predicted', y_predicted) #tensorflow.print('y_actual', y_actual) #tensorflow.print('y_predicted', y_predicted) #time.sleep(1) custom_loss_value=tensorflow.keras.backend.mean(tensorflow.keras.backend.sum(tensorflow.keras.backend.square((y_actual - y_predicted)/10))) return custom_loss_value def create_model(model_path): model = tensorflow.keras.models.Sequential() model.add(tensorflow.keras.layers.Dense(256)) model.add(tensorflow.keras.layers.Dense(128)) model.add(tensorflow.keras.layers.Dense(64)) model.add(tensorflow.keras.layers.Dense(6)) model.compile( loss=tensorflow.keras.losses.MeanSquaredError(), optimizer=tensorflow.keras.optimizers.Adam(lr=1e-3, decay=1e-4), ) #Checkpoint model checkpoint_callback = tensorflow.keras.callbacks.ModelCheckpoint( model_path, monitor='val_loss', mode='min', save_best_only=True, verbose=1, save_weights_only=False, save_freq='epoch' ) return (model, checkpoint_callback) def print_predict(predict, real, interval): """printing predict""" matplotlib.pyplot.plot(predict, 'r') matplotlib.pyplot.plot(real, 'b') matplotlib.pyplot.title('Predict') matplotlib.pyplot.xlabel(f'interval {interval}') matplotlib.pyplot.ylabel('Close Price') matplotlib.pyplot.show() def test_model(model, x_test, y_test, scaler, interval): predicted_data = model.predict(x_test) predicted_data, real_data = denormalize_data(predicted_data, y_test, scaler) print_predict(predicted_data, real_data, interval) def predict_one_interval(model, open_data, scaler): open_data = numpy.reshape(open_data, (-1, NB_INDICATORS)) close_data = model.predict(open_data) close_data = scaler.inverse_transform(close_data) return close_data def get_time_to_add(nb_calls, interval, stock_path): data = numpy.genfromtxt(stock_path, delimiter=',', dtype=str) now = datetime.datetime.strptime(str(data[len(data) - 1][0]), "%Y-%m-%d") for elem in TIME_BY_INTERVAL: if (elem[0] == interval): time_to_add = elem[1] return (now + time_to_add) def write_predict(stock_path, close_data, interval): write_predict.nb_calls += 1 time_to_add = get_time_to_add(write_predict.nb_calls, interval, stock_path) with open(stock_path, 'a+') as file: writer = csv.DictWriter(file, fieldnames=['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume']) data_to_write = { 'Date' : time_to_add.strftime("%Y-%m-%d"), 'Open' : close_data[0], 'High' : close_data[1], 'Low' : close_data[2], 'Close' : close_data[3], 'Adj Close' : close_data[4], 'Volume' : close_data[5] } writer.writerow(data_to_write) write_predict.nb_calls = 0 def predict_multiple_intervals(model, open_data, scaler, stock_path, interval, nb_intervals): if nb_intervals == 0: return open_data = numpy.reshape(open_data, (-1, NB_INDICATORS)) close_data = model.predict(open_data) data_to_write = scaler.inverse_transform(close_data) data_to_write =
numpy.ndarray.flatten(data_to_write)
numpy.ndarray.flatten
import numpy as np import matplotlib.pyplot as plt class PCA(object): """ Principal component analysis (PCA) PCA is defined as an orthogonal linear transformation that transforms the data to a new coordinate system which ıs used for feature reduction. It provides via eigen-decomposition of the covariance/correlation matrix on the contrary of sckit-learn which does via SVD. Parameters: ---------- corr: bool, default: True if True, the eigen-decomposition will be calculated using correlation matrix. Attributes: ---------- p_: int Number of variables n_: int Number of observations eig_vals: array Eigen values of the matrix eig_vecs: matrix Eigen vector-matrix of the matrix explained_variance_ratio_: array The amount of variance explained by each of components Examples: --------- from eigpca import PCA X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) pca = PCA() pca.fit(X) pca.transform(X, n_components=1) """ def __init__(self, corr=True): self.corr = corr def fit_transform(self, X, n_components=None): """ Fit and apply dimensionality reduction """ self.fit(X) return self.transform(X, n_components) def transform(self, X, n_components=None): """ Apply dimensionality reduction Parameters ---------- X: array-like, shape (n_observations(n), n_variables(p)) The data n_components: int, default: None Number of components If it's None, then it will be set number of eigen values that are greater than 1. Reason: Those with eigenvalues less than 1.00 are not considered to be stable. They account for less variability than does a single variable and are not retained in the analysis. In this sense, you end up with fewer factors than original number of variables. (Girden, 2001) reference: https://stats.stackexchange.com/a/80318 Returns ------- X_new: array-like, shape (n_observations, n_components) Transformed values """ X = self._check_shape(X) if X.shape[1] != self.p_: raise ValueError(f"X must have {self.p_} variables. ") if n_components and (n_components > self.p_ or n_components < 1): ValueError("Components cannot be greater than number of variables or less than 1") if not n_components: return np.dot(X, self.eig_vecs[:, self.eig_vals > 1]) else: return np.dot(X, self.eig_vecs[:, :n_components]) def fit(self, X): """ Eigen-decomposition of X Parameters ---------- X: array-like, shape (n_observations(n), n_variables(p)) The data """ X = self._check_shape(X) self.p_ = X.shape[1] # variables self.n_ = X.shape[0] # observations xs = X - X.mean(axis=0) # standardised S = np.dot(xs.T, xs) / (self.n_ - 1) # variance-covariance matrix if self.corr: # calculate correlation with matrix multiplication d = S.diagonal().T * np.identity(self.p_) d_sqrt_inv = (1 / np.sqrt(d).diagonal()).T * np.identity(self.p_) corr = np.dot(np.dot(d_sqrt_inv, S), d_sqrt_inv) eig_vals, eig_vecs =
np.linalg.eig(corr)
numpy.linalg.eig
from functools import reduce import numpy as np from dataset.pose_dataset import PoseDataset, Batch def merge_batch(batches): """ Merges n=len(batches) batches of size 1 into one batch of size n """ res = {} for key, tensor in batches[0].items(): elements = [batch[key] for batch in batches] if type(tensor) is np.ndarray: elements = reduce(lambda x, y:
np.concatenate((x, y), axis=0)
numpy.concatenate
""" This file contains the implementation of the main class object: anaRDPacct --- an analytical moment accountant that keeps track the effects of a hetereogeneous sequence of randomized algorithms using the RDP technique. In particular it supports amplification of RDP by subsampling without replacement and the amplification of RDP by poisson sampling, but unfortunately not (yet) together. """ import numpy as np from scipy.optimize import minimize_scalar import sys sys.path.append('..') import autodp from autodp import utils, rdp_bank from autodp.privacy_calibrator import subsample_epsdelta import scipy import math def general_upperbound(func, mm, prob): """ :param func: :param mm: alpha in RDP :param prob: sample probability :return: the upperbound in theorem 1 in 2019 ICML,could be applied for general case(including poisson distribution) k_approx = 100 k approximation is applied here """ def cgf(x): return (x - 1) * func(x) if np.isinf(func(mm)): return np.inf if mm == 1 or mm == 0: return 0 cur_k = np.minimum(50, mm - 1) # choose small k-approx for general upperbound (here is 50) in case of scipy-accuracy log_term_1 = mm * np.log(1 - prob) #logBin = utils.get_binom_coeffs(mm) log_term_2 = np.log(3) - func(mm) + mm * utils.stable_logsumexp_two(np.log(1 - prob), np.log(prob) + func(mm)) neg_term_3 = [np.log(scipy.special.comb(mm,l)) + np.log(3) + (mm - l) * np.log(1 - prob) + l * np.log(prob) + utils.stable_log_diff_exp((l - 1) * func(mm), cgf(l))[1] for l in range(3, cur_k + 1)] neg_term_4 = np.log(mm*(mm - 1)/2) + 2 * np.log(prob) + (mm - 2) * np.log( 1 - prob) + utils.stable_log_diff_exp(np.log(3) + func(mm), func(2))[1] neg_term_5 = np.log(2) + np.log(prob) + np.log(mm) + (mm - 1) * np.log(1 - prob) neg_term_6 = mm * np.log(1 - prob) + np.log(3) - func(mm) pos_term = utils.stable_logsumexp([log_term_1, log_term_2]) neg_term_3.append(neg_term_4) neg_term_3.append(neg_term_5) neg_term_3.append(neg_term_6) neg_term = utils.stable_logsumexp(neg_term_3) bound = utils.stable_log_diff_exp(pos_term, neg_term)[1] return bound def fast_subsampled_cgf_upperbound(func, mm, prob, deltas_local): # evaulate the fast CGF bound for the subsampled mechanism # func evaluates the RDP of the base mechanism # mm is alpha. NOT lambda. return np.inf if np.isinf(func(mm)): return np.inf if mm == 1: return 0 secondterm = np.minimum(np.minimum((2) * np.log(np.exp(func(np.inf)) - 1) + np.minimum(func(2), np.log(4)), np.log(2) + func(2)), np.log(4) + 0.5 * deltas_local[int(2 * np.floor(2 / 2.0)) - 1] + 0.5 * deltas_local[int(2 * np.ceil(2 / 2.0)) - 1] ) + 2 * np.log(prob) + np.log(mm) + np.log(mm - 1) - np.log(2) if mm == 2: return utils.stable_logsumexp([0, secondterm]) # approximate the remaining terms using a geometric series logratio1 = np.log(prob) + np.log(mm) + func(mm) logratio2 = logratio1 + np.log(np.exp(func(np.inf)) - 1) logratio = np.minimum(logratio1, logratio2) if logratio1 > logratio2: coeff = 1 else: coeff = 2 if mm == 3: return utils.stable_logsumexp([0, secondterm, np.log(coeff) + 3 * logratio]) # Calculate the sum of the geometric series starting from the third term. This is a total of mm-2 terms. if logratio < 0: geometric_series_bound = np.log(coeff) + 3 * logratio - np.log(1 - np.exp(logratio)) \ + np.log(1 - np.exp((mm - 2) * logratio)) elif logratio > 0: geometric_series_bound = np.log(coeff) + 3 * logratio + (mm-2) * logratio - np.log(np.exp(logratio) - 1) else: geometric_series_bound = np.log(coeff) + np.log(mm - 2) # we will approximate using (1+h)^mm logh1 = np.log(prob) + func(mm - 1) logh2 = logh1 + np.log(np.exp(func(np.inf)) - 1) binomial_series_bound1 = np.log(2) + mm * utils.stable_logsumexp_two(0, logh1) binomial_series_bound2 = mm * utils.stable_logsumexp_two(0, logh2) tmpsign, binomial_series_bound1 \ = utils.stable_sum_signed(True, binomial_series_bound1, False, np.log(2) + utils.stable_logsumexp([0, logh1 + np.log(mm), 2 * logh1 + np.log(mm) + np.log(mm - 1) - np.log(2)])) tmpsign, binomial_series_bound2 \ = utils.stable_sum_signed(True, binomial_series_bound2, False, utils.stable_logsumexp([0, logh2 + np.log(mm), 2 * logh2 + np.log(mm) + np.log(mm - 1) - np.log(2)])) remainder = np.min([geometric_series_bound, binomial_series_bound1, binomial_series_bound2]) return utils.stable_logsumexp([0, secondterm, remainder]) def fast_poission_subsampled_cgf_upperbound(func, mm, prob): # evaulate the fast CGF bound for the subsampled mechanism # func evaluates the RDP of the base mechanism # mm is alpha. NOT lambda. if np.isinf(func(mm)): return np.inf if mm == 1: return 0 # Bound #1: log [ (1-\gamma + \gamma e^{func(mm)})^mm ] bound1 = mm * utils.stable_logsumexp_two(np.log(1-prob), np.log(prob) + func(mm)) # Bound #2: log [ (1-gamma)^alpha E [ 1 + gamma/(1-gamma) E[p/q]]^mm ] # log[ (1-gamma)^\alpha { 1 + alpha gamma / (1-gamma) + gamma^2 /(1-gamma)^2 * alpha(alpha-1) /2 e^eps(2)) # + alpha \choose 3 * gamma^3 / (1-gamma)^3 / e^(-2 eps(alpha)) * (1 + gamma /(1-gamma) e^{eps(alpha)}) ^ (alpha - 3) } # ] if mm >= 3: bound2 = utils.stable_logsumexp([mm * np.log(1-prob), (mm-1) * np.log(1-prob) + np.log(mm) + np.log(prob), (mm-2)*np.log(1-prob) + 2 * np.log(prob) + np.log(mm) + np.log(mm-1) + func(2), np.log(mm) + np.log(mm-1) + np.log(mm-2) - np.log(3*2) + 3 * np.log(prob) + (mm-3)*np.log(1-prob) + 2 * func(mm) + (mm-3) * utils.stable_logsumexp_two(0, np.log(prob) - np.log(1-prob) + func(mm))]) else: bound2 = bound1 #print('www={} func={} mm={}'.format(np.exp(func(mm))-1),func, mm) #print('bound1 ={} bound2 ={}'.format(bound1,bound2)) return np.minimum(bound1,bound2) def fast_k_subsample_upperbound(func, mm, prob, k): """ :param func: :param mm: :param prob: sample probability :param k: approximate term :return: k-term approximate upper bound in therorem 11 in ICML-19 """ def cgf(x): return (x - 1) * func(x) if np.isinf(func(mm)): return np.inf if mm == 1: return 0 #logBin = utils.get_binom_coeffs(mm) cur_k = np.minimum(k, mm - 1) if (2 * cur_k) >= mm: exact_term_1 = (mm - 1) * np.log(1 - prob) + np.log(mm * prob - prob + 1) exact_term_2 = [np.log(scipy.special.comb(mm,l)) + (mm - l) * np.log(1 - prob) + l * np.log(prob) + cgf(l) for l in range(2, mm + 1)] exact_term_2.append(exact_term_1) bound = utils.stable_logsumexp(exact_term_2) return bound s, mag1 = utils.stable_log_diff_exp(0, -func(mm - cur_k)) new_log_term_1 = np.log(1 - prob) * mm + mag1 new_log_term_2 = -func(mm - cur_k) + mm * utils.stable_logsumexp_two(np.log(1 - prob), np.log(prob) + func(mm - cur_k)) new_log_term_3 = [np.log(scipy.special.comb(mm,l)) + (mm - l) * np.log(1 - prob) + l * np.log(prob) + utils.stable_log_diff_exp((l - 1) * func(mm - cur_k), cgf(l))[1] for l in range(2, cur_k + 1)] if len(new_log_term_3) > 0: new_log_term_3 = utils.stable_logsumexp(new_log_term_3) else: return utils.stable_logsumexp_two(new_log_term_1, new_log_term_2) new_log_term_4 = [np.log(scipy.special.comb(mm,mm-l)) + (mm - l) * np.log(1 - prob) + l * np.log(prob) + utils.stable_log_diff_exp(cgf(l), (l - 1) * func(mm - cur_k))[1] for l in range(mm - cur_k + 1, mm + 1)] new_log_term_4.append(new_log_term_1) new_log_term_4.append(new_log_term_2) new_log_term_4 = utils.stable_logsumexp(new_log_term_4) s, new_log_term_5 = utils.stable_log_diff_exp(new_log_term_4, new_log_term_3) new_bound = new_log_term_5 return new_bound class anaRDPacct: """A class that keeps track of the analytical expression of the RDP --- 1/(alpha-1)*CGF of the privacy loss R.V.""" def __init__(self, m=100, tol=0.1, m_max=500, m_lin_max=10000, approx = False, verbose=False): # m_max indicates the number that we calculate binomial coefficients exactly up to. # beyond that we use Stirling approximation. # ------ Class Attributes ----------- self.m = m # default number of binomial coefficients to precompute self.m_max = m_max # An upper bound of the quadratic dependence self.m_lin_max = m_lin_max # An upper bound of the linear dependence. self.verbose = verbose self.approx = approx self.lambs = np.linspace(1, self.m, self.m).astype(int) # Corresponds to \alpha = 2,3,4,5,.... for RDP self.alphas = np.linspace(1, self.m, self.m).astype(int) self.RDPs_int = np.zeros_like(self.alphas, float) self.n=0 self.RDPs = [] # analytical CGFs self.coeffs = [] self.RDP_inf = .0 # This is effectively for pure DP. self.logBinomC = utils.get_binom_coeffs(self.m + 1) # The logBinomC is only needed for subsampling mechanisms. self.idxhash = {} # save the index of previously used algorithms self.cache = {} # dictionary to save results from previously seen algorithms self.deltas_cache = {} # dictionary to save results of all discrete derivative path self.evalRDP = lambda x: 0 self.flag = True # a flag indicating whether evalCGF is out of date self.flag_subsample = False # a flag to indicate whether we need to expand the logBinomC. self.tol = tol # ---------- Methods ------------ def build_zeroth_oracle(self): self.evalRDP = lambda x: sum([c * item(x) for (c, item) in zip(self.coeffs, self.RDPs)]) def plot_rdp(self): if not self.flag: self.build_zeroth_oracle() self.flag = True import matplotlib.pyplot as plt plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k') x = range(0,self.m,1) y = [self.evalRDP(item) for item in x] plt.loglog(x, y) plt.show() def plot_cgf_int(self): import matplotlib.pyplot as plt plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k') plt.plot(self.alphas, self.RDPs_int) plt.xlabel(r'$\lambda$') plt.ylabel('CGF') plt.show() def plot_rdp_int(self): import matplotlib.pyplot as plt plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k') plt.loglog(self.alphas, self.RDPs_int) if not self.flag: self.build_zeroth_oracle() self.flag = True x = range(1,self.m_lin_max,1) y = [self.evalRDP(item) for item in x] plt.loglog(x, y) plt.xlabel(r'$\alpha$') plt.ylabel(r'RDP $\epsilon$') plt.show() def get_rdp(self,alphas): # alphas is a numpy array or a list of numbers # we will return a numpy array of the corresponding RDP if not self.flag: self.build_zeroth_oracle() self.flag = True alphas = np.array(alphas) assert(np.all(alphas >= 1)) rdp_list = [] for alpha in alphas: rdp_list.append(self.evalRDP(alpha)) return np.array(rdp_list) def get_eps(self, delta): # minimize over \lambda if not self.flag: self.build_zeroth_oracle() self.flag = True if delta<0 or delta > 1: print("Error! delta is a probability and must be between 0 and 1") if delta == 0: return self.RDP_inf else: def fun(x): # the input the RDP's \alpha if x <= 1: return np.inf else: return np.log(1 / delta)/(x-1) + self.evalRDP(x) def fun_int(i): # the input is RDP's \alpha in integer if i <= 1 | i >= len(self.RDPs_int): return np.inf else: return np.log(1 / delta) / (i-1) + self.RDPs_int[i - 1] # When do we have computational constraints? # Only when we have subsampled items. # First check if the forward difference is positive at self.m, or if it is infinite while (self.m<self.m_max) and (not np.isposinf(fun(self.m))) and (fun_int(self.m-1)-fun_int(self.m-2) < 0): # If so, double m, expand logBimomC until the forward difference is positive if self.flag_subsample: # The following line is m^2 time. self.logBinomC = utils.get_binom_coeffs(self.m*2+1) # Update deltas_caches for key, val in self.deltas_cache.items(): if type(key) is tuple: func_tmp = key[0] else: func_tmp = key cgf = lambda x: x*func_tmp(x+1) deltas,signs_deltas = utils.get_forward_diffs(cgf,self.m*2) self.deltas_cache[key] = [deltas, signs_deltas] new_alphas = range(self.m + 1, self.m * 2 + 1, 1) self.alphas = np.concatenate((self.alphas, np.array(new_alphas))) # array of integers self.m = self.m * 2 mm = np.max(self.alphas) rdp_int_new = np.zeros_like(self.alphas, float) for key,val in self.cache.items(): idx = self.idxhash[key] rdp = self.RDPs[idx] newarray = np.zeros_like(self.alphas, float) for j in range(2,mm+1,1): newarray[j-1] = rdp(1.0*j) newarray[0]=newarray[1] coeff = self.coeffs[idx] rdp_int_new += newarray * coeff self.cache[key] = newarray self.RDPs_int = rdp_int_new # # update the integer CGF and the cache for each function # rdp_int_new = np.zeros_like(self.RDPs_int) # for key,val in self.cache.items(): # idx = self.idxhash[key] # rdp = self.RDPs[idx] # newarray = np.zeros_like(self.RDPs_int) # for j in range(self.m): # newarray[j] = rdp(1.0*(j+self.m+1)) # # coeff = self.coeffs[idx] # rdp_int_new += newarray * coeff # self.cache[key] = np.concatenate((val, newarray)) # # # update the corresponding quantities # self.RDPs_int = np.concatenate((self.RDPs_int, rdp_int_new)) #self.m = self.m*2 bestint = np.argmin(np.log(1 / delta)/(self.alphas[1:]-1) + self.RDPs_int[1:]) + 1 if bestint == self.m-1: if self.verbose: print('Warning: Reach quadratic upper bound: m_max.') # In this case, we matches the maximum qudaratic upper bound # Fix it by calling O(1) upper bounds and do logarithmic search cur = fun(bestint) while (not np.isposinf(cur)) and fun(bestint-1)-fun(bestint-2) < -1e-8: bestint = bestint*2 cur = fun(bestint) if bestint > self.m_lin_max and self.approx ==True: print('Warning: Reach linear upper bound: m_lin_max.') return cur results = minimize_scalar(fun, method='Bounded', bounds=[self.m-1, bestint + 2], options={'disp': False}) if results.success: return results.fun else: return None #return fun(bestint) if bestint == 0: if self.verbose: print('Warning: Smallest alpha = 1.') # find the best integer alpha. bestalpha = self.alphas[bestint] results = minimize_scalar(fun, method='Bounded',bounds=[bestalpha-1, bestalpha+1], options={'disp':False}) # the while loop above ensures that bestint+2 is at most m, and also bestint is at least 0. if results.success: return results.fun else: # There are cases when certain \delta is not feasible. # For example, let p and q be uniform the privacy R.V. is either 0 or \infty and unless all \infty # events are taken cared of by \delta, \epsilon cannot be < \infty return -1 def compose_mechanism(self, func, coeff=1.0): self.flag = False if func in self.idxhash: self.coeffs[self.idxhash[func]] += coeff # also update the integer CGFs self.RDPs_int += self.cache[func] * coeff else: # book keeping self.idxhash[func] = self.n self.n += 1 self.coeffs.append(coeff) # update the analytical self.RDPs.append(func) # also update the integer results if func in self.cache: tmp = self.cache[func] else: tmp = np.zeros_like(self.RDPs_int, float) for i in range(self.m): tmp[i] = func(i+1) self.cache[func] = tmp # save in cache self.RDPs_int += tmp * coeff self.RDP_inf += func(np.inf) * coeff #795010 #imple 100 def compose_subsampled_mechanism(self, func, prob, coeff=1.0): # This function is for subsample without replacements. self.flag = False self.flag_subsample = True if (func, prob) in self.idxhash: idx = self.idxhash[(func, prob)] # update the coefficients of each function self.coeffs[idx] += coeff # also update the integer CGFs self.RDPs_int += self.cache[(func, prob)] * coeff else: def cgf(x): return x * func(x+1) # we need forward differences of thpe exp(cgf) # The following line is the numericall y stable way of implementing it. # The output is in polar form with logarithmic magnitude deltas, signs_deltas = utils.get_forward_diffs(cgf,self.m) #deltas1, signs_deltas1 = get_forward_diffs_direct(func, self.m) #tmp = deltas-deltas1 self.deltas_cache[(func,prob)] = [deltas,signs_deltas] def subsample_func_int(x): # This function evaluates teh CGF at alpha = x, i.e., lamb = x- 1 deltas_local, signs_deltas_local = self.deltas_cache[(func,prob)] if np.isinf(func(x)): return np.inf mm = int(x) fastupperbound = fast_subsampled_cgf_upperbound(func, mm, prob, deltas_local) fastupperbound2 = general_upperbound(func, mm, prob) if self.approx ==True: if fastupperbound2 <0: print('general rdp is negative',x) return fastupperbound2 if mm <= self.alphas[-1]: # compute the bound exactly. Requires book keeping of O(x^2) moments = [ np.minimum(np.minimum((j)*np.log(np.exp(func(np.inf))-1) + np.minimum(cgf(j-1),np.log(4)), np.log(2) + cgf(j-1)), np.log(4) + 0.5*deltas_local[int(2*np.floor(j/2.0))-1] + 0.5*deltas_local[int(2*np.ceil(j/2.0))-1]) + j*np.log(prob) +self.logBinomC[int(mm), j] for j in range(2,int(mm+1),1)] return np.minimum(fastupperbound, utils.stable_logsumexp([0]+moments)) elif mm <= self.m_lin_max: # compute the bound with stirling approximation. Everything is O(x) now. moment_bound = lambda j: np.minimum(j * np.log(np.exp(func(np.inf)) - 1) + np.minimum(cgf(j - 1), np.log(4)), np.log(2) + cgf(j - 1)) + j * np.log(prob) + utils.logcomb(mm, j) moments = [moment_bound(j) for j in range(2,mm+1,1)] return np.minimum(fastupperbound, utils.stable_logsumexp([0]+ moments)) else: # Compute the O(1) upper bound return fastupperbound def subsample_func(x): # This function returns the RDP at alpha = x # RDP with the linear interpolation upper bound of the CGF epsinf, tmp = subsample_epsdelta(func(np.inf),0,prob) if np.isinf(x): return epsinf if prob == 1.0: return func(x) if (x >= 1.0) and (x <= 2.0): return np.minimum(epsinf, subsample_func_int(2.0) / (2.0-1)) if np.equal(np.mod(x, 1), 0): return np.minimum(epsinf, subsample_func_int(x) / (x-1) ) xc = math.ceil(x) xf = math.floor(x) return np.minimum( epsinf, ((x-xf)*subsample_func_int(xc) + (1-(x-xf))*subsample_func_int(xf)) / (x-1) ) # book keeping self.idxhash[(func, prob)] = self.n # save the index self.n += 1 # increment the number of unique mechanisms self.coeffs.append(coeff) # Update the coefficient self.RDPs.append(subsample_func) # update the analytical functions # also update the integer results up to m_max. if (func,prob) in self.cache: results = self.cache[(func,prob)] else: results = np.zeros_like(self.RDPs_int, float) # m = np.max(self.lambs) mm = np.max(self.alphas) for alpha in range(2, mm+1): results[alpha-1] = subsample_func(alpha) results[0] = results[1] # Provide the trivial upper bound of RDP at alpha = 1 --- the KL privacy. self.cache[(func,prob)] = results # save in cache self.RDPs_int += results * coeff # update the pure DP eps, delta = subsample_epsdelta(func(np.inf), 0, prob) self.RDP_inf += eps * coeff # mm = np.max(self.alphas) # # jvec = np.arange(2, mm+1) # # logterm3plus = np.zeros_like(results) # for j in jvec: # logterm3plus[j-2] = (np.minimum(np.minimum(j * np.log(np.exp(func(np.inf)) - 1) # + np.minimum(np.log(4),cgf(j-1)), np.log(2) + cgf(j-1)), # np.log(4) + 0.5 * deltas[int(2 * np.floor(j / 2.0))-1] # + 0.5 * deltas[int(2 * np.ceil(j / 2.0))-1]) # + j * np.log(prob)) # # for alpha in range(2, mm+1): # if np.isinf(logterm3plus[alpha-1]): # results[alpha-1] = np.inf # else: # tmp = utils.stable_logsumexp(logterm3plus[0:alpha-1] + self.logBinomC[alpha, 2:(alpha+1)]) # results[alpha-1] = utils.stable_logsumexp_two(0, tmp) / (1.0*alpha-1) # # results[0] = results[1] # Provide the trivial upper bound of RDP at alpha = 1 --- the KL privacy. # # self.cache[(func,prob)] = results # save in cache # self.RDPs_int += results # # # For debugging: The following 'results1' should be the same as 'results' above. # # results1 = np.zeros_like(self.RDPs_int, float) # # for j in range(self.m): # # results1[j] = subsample_func(j+1) # # eps, delta = subsample_epsdelta(func(np.inf), 0, prob) # self.RDP_inf += eps def compose_poisson_subsampled_mechanisms(self, func, prob, coeff=1.0): # This function implements the lower bound for subsampled RDP. # It is also the exact formula of poission_subsampled RDP for many mechanisms including Gaussian mech. # # At the moment, we do not support mixing poisson subsampling and standard subsampling. # TODO: modify the caching identifies so that we can distinguish different types of subsampling # self.flag = False self.flag_subsample = True if (func, prob) in self.idxhash: idx = self.idxhash[(func, prob)] # TODO: this is really where it needs to be changed. # update the coefficients of each function self.coeffs[idx] += coeff # also update the integer CGFs self.RDPs_int += self.cache[(func, prob)] * coeff else: # compute an easy to compute upper bound of it. def cgf(x): return x * func(x+1) def subsample_func_int(x): # This function evaluates teh CGF at alpha = x, i.e., lamb = x- 1 if np.isinf(func(x)): return np.inf mm = int(x) # fastbound = fast_poission_subsampled_cgf_upperbound(func, mm, prob) k = self.alphas[-1] fastbound_k = fast_k_subsample_upperbound(func, mm, prob,k) if self.approx == True: return fastbound_k #fastbound = min(fastbound, fastbound_k) if x <= self.alphas[-1]: # compute the bound exactly. moments = [cgf(j-1) +j*np.log(prob) + (mm-j) * np.log(1-prob) + self.logBinomC[mm, j] for j in range(2,mm+1,1)] return utils.stable_logsumexp([(mm-1)*np.log(1-prob)+np.log(1+(mm-1)*prob)]+moments) elif mm <= self.m_lin_max: moments = [cgf(j-1) +j*np.log(prob) + (mm-j) * np.log(1-prob) + utils.logcomb(mm,j) for j in range(2,mm+1,1)] return utils.stable_logsumexp([(mm-1)*np.log(1-prob)+np.log(1+(mm-1)*prob)] + moments) else: return fastbound def subsample_func(x): # linear interpolation upper bound # This function implements the RDP at alpha = x if np.isinf(func(x)): return np.inf if prob == 1.0: return func(x) epsinf, tmp = subsample_epsdelta(func(np.inf),0,prob) if np.isinf(x): return epsinf if (x >= 1.0) and (x <= 2.0): return np.minimum(epsinf, subsample_func_int(2.0) / (2.0-1)) if np.equal(np.mod(x, 1), 0): return np.minimum(epsinf, subsample_func_int(x) / (x-1) ) xc = math.ceil(x) xf = math.floor(x) return np.minimum( epsinf, ((x-xf)*subsample_func_int(xc) + (1-(x-xf))*subsample_func_int(xf)) / (x-1) ) # book keeping self.idxhash[(func, prob)] = self.n # save the index self.n += 1 # increment the number of unique mechanisms self.coeffs.append(coeff) # Update the coefficient self.RDPs.append(subsample_func) # update the analytical functions # also update the integer results, with a vectorized computation. # TODO: pre-computing subsampled RDP for integers is error-prone (implement the same thing twice) # TODO: and its benefits are not clear. We should consider removing it and simply call the lambda function. # if (func,prob) in self.cache: results = self.cache[(func,prob)] else: results = np.zeros_like(self.RDPs_int, float) mm = np.max(self.alphas) # evaluate the RDP up to order mm jvec = np.arange(2, mm + 1) logterm3plus = np.zeros_like(results) # This saves everything from j=2 to j = m+1 for j in jvec: logterm3plus[j-2] = cgf(j-1) + j * np.log(prob) #- np.log(1-prob)) for alpha in range(2, mm+1): if np.isinf(logterm3plus[alpha-1]): results[alpha-1] = np.inf else: tmp = utils.stable_logsumexp(logterm3plus[0:alpha-1] + self.logBinomC[alpha , 2:(alpha + 1)] + (alpha+1-jvec[0:alpha-1])*np.log(1-prob)) results[alpha-1] = utils.stable_logsumexp_two((alpha-1)*np.log(1-prob) + np.log(1+(alpha-1)*prob), tmp) / (1.0*alpha-1) results[0] = results[1] # Provide the trivial upper bound of RDP at alpha = 1 --- the KL privacy. self.cache[(func,prob)] = results # save in cache self.RDPs_int += results * coeff # update the pure DP tracker eps, delta = subsample_epsdelta(func(np.inf), 0, prob) self.RDP_inf += eps * coeff def compose_poisson_subsampled_mechanisms1(self, func, prob, coeff=1.0): # This function implements the general amplification bounds for Poisson sampling. # No additional assumptions are needed. # At the moment, we do not support mixing poisson subsampling and standard subsampling. # self.flag = False self.flag_subsample = True if (func, prob) in self.idxhash: idx = self.idxhash[(func, prob)] # update the coefficients of each function self.coeffs[idx] += coeff # also update the integer CGFs self.RDPs_int += self.cache[(func, prob)] * coeff else: # compute an easy to compute upper bound of it. cgf = lambda x: x*func(x+1) def subsample_func_int(x): # This function evaluates the CGF at alpha = x, i.e., lamb = x- 1 if np.isinf(func(x)): return np.inf if prob == 1.0: return func(x) mm = int(x) fastbound = fast_poission_subsampled_cgf_upperbound(func, mm, prob) if x <= self.alphas[-1]: # compute the bound exactly. moments = [cgf(1) + 2*np.log(prob) + (mm-2) * np.log(1 - prob) + self.logBinomC[mm, 2]] moments = moments + [cgf(j-1+1) +j*np.log(prob) + (mm-j) * np.log(1 - prob) + self.logBinomC[mm, j] for j in range(3,mm+1,1)] return utils.stable_logsumexp([(mm-1)*
np.log(1-prob)
numpy.log
import os import numpy as np from skimage.morphology import binary_dilation from starfish import ImageStack from starfish.core.morphology.label_image import LabelImage from starfish.core.types import Axes, Coordinates from .factories import binary_mask_collection_2d, label_array_2d from ..binary_mask import BinaryMaskCollection def test_from_label_image(): label_image_array, physical_ticks = label_array_2d() label_image = LabelImage.from_label_array_and_ticks( label_image_array, None, physical_ticks, None, ) mask_collection = BinaryMaskCollection.from_label_image(label_image) assert len(mask_collection) == 2 region_0, region_1 = mask_collection.masks() assert region_0.name == '0' assert region_1.name == '1' assert np.array_equal(region_0, np.ones((1, 6), dtype=bool)) temp = np.ones((2, 3), dtype=bool) temp[-1, -1] = False assert np.array_equal(region_1, temp) assert np.array_equal(region_0[Axes.Y.value], [0]) assert np.array_equal(region_0[Axes.X.value], [0, 1, 2, 3, 4, 5]) assert np.array_equal(region_1[Axes.Y.value], [3, 4]) assert np.array_equal(region_1[Axes.X.value], [3, 4, 5]) assert np.array_equal(region_0[Coordinates.Y.value], physical_ticks[Coordinates.Y][0:1]) assert np.array_equal(region_0[Coordinates.X.value], physical_ticks[Coordinates.X][0:6]) assert np.array_equal(region_1[Coordinates.Y.value], physical_ticks[Coordinates.Y][3:5]) assert np.array_equal(region_1[Coordinates.X.value], physical_ticks[Coordinates.X][3:6]) def test_from_fiji_roi_set(): # set up empty dapi imagestack of correct size fake_dapi = ImageStack.from_numpy(array=
np.zeros(shape=(1, 1, 1, 2048, 2048))
numpy.zeros
#! /usr/bin/env python import pickle import albumentations as A import torch import torchvision from facenet_pytorch import MTCNN, InceptionResnetV1 import numpy as np import cv2 import face_recognition import os import matplotlib.pyplot as plt import pandas test_chip = '/mnt/NAS/Photos/pkls/assigned/batch1/imchip_326465.pkl' # test_chip = '/mnt/NAS/Photos/pkls/assigned/batch26/imchip_591528.pkl' def short_vec(image): h, w = image.shape[:2] bbox = [(0, w, h, 0)] encoding = face_recognition.face_encodings(image, known_face_locations = bbox, num_jitters=400, model='large')[0] return encoding def long_vec(image): assert np.abs(image.shape[0] - image.shape[1]) < 3, f"{image.shape[0]} != {image.shape[1]}" image = cv2.resize(image, (160, 160)) image = np.moveaxis(image, 2, 0) image = (image - 127.5) / 128 image = torch.Tensor(image) resnet = InceptionResnetV1(pretrained='vggface2').eval() encoding = resnet(image.unsqueeze(0)) encoding = encoding.detach().numpy().astype(np.float32) encoding = list(encoding[0]) return np.array(encoding) transform = A.Compose([ A.geometric.transforms.Perspective(scale=(0.05, 0.1)), A.geometric.rotate.Rotate(limit=25), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.05), A.ColorJitter(hue=0.03, contrast=0.2), A.RandomFog(p=0.05), ### A.Blur(blur_limit=11), A.GaussNoise(var_limit=(10.0, 80.0), p=0.5), A.CLAHE( p=0.32, clip_limit=(2,3)), # A.geometric.transforms.ElasticTransform(), # A.RandomBrightnessContrast(p=0.5, brightness_limit=(-0.1, 0.4), contrast_limit=(-0.2, 0.2),), ### # A.Flip(), # # A.ToGray(), # A.Downscale( p=0.4), # A.FancyPCA( p=1), ]) def random_center_crop(image, w, h): oversize = np.random.rand() / 4 + 1 im_h, im_w = image.shape[:2] c = np.array(image.shape[:2]) // 2 adj_shape = np.min(image.shape[:2]) * 0.03 c_adj = (np.random.randn(2) * adj_shape ).astype(np.int) c = c + c_adj l = int(c[0] - w * oversize) r = int(c[0] + w * oversize) t = int(c[1] - h * oversize) b = int(c[1] + h * oversize) t = np.max( (0, t) ) l = np.max( (0, l) ) b = np.min( (b, im_h) ) r = np.min( (r, im_w) ) new_w = np.abs(l - r) new_h = np.abs(b - t) im = image[t:b, l:r, :] if np.abs(new_w - new_h) > 1: # Recenter in new chip c = np.array(im.shape[:2]) // 2 size = np.min((new_w, new_h)) // 2 t_prime = int(c[0] - size) b_prime = int(c[0] + size) l_prime = int(c[1] - size) r_prime = int(c[1] + size) im = im[t_prime:b_prime, l_prime:r_prime, :] # print(im.shape) return im def augment_image(data_dict, n_iters = 5): image = data_dict['chipped_image'] w = data_dict['width'] // 2 h = data_dict['height'] // 2 max_extent = max(data_dict['width'], data_dict['height']) scale_up_size = int(np.ceil(np.sqrt(2) * max_extent)) scale_down = 800 / scale_up_size # chip_h = data_dict['height'] * np.sqrt(2) # chip_w = data_dict['width'] * np.sqrt(2) if scale_up_size > 800: # Scale down and re-calculate bounding box. center = np.array(image.shape[:2]) // 2 width = w * scale_down height = h * scale_down top = int(center[0] - height) bot = int(center[0] + height) lef = int(center[1] - width) rig = int(center[1] + width) w = np.ceil(width) h = np.ceil(height) w = h = int(np.min((w, h))) shorts = [] longs = [] for ii in range(n_iters): im = random_center_crop(image, w, h) transformed = transform(image=im) # , cropping_bbox=[l, t, w * 2, h * 2]) transformed_image1 = transformed["image"] enc_512 = long_vec(transformed_image1).astype(np.float16) enc_128 = short_vec(transformed_image1).astype(np.float16) if len(enc_512) == 512 and len(enc_128) == 128: longs.append(enc_512) shorts.append(enc_128) return shorts, longs with open(test_chip, 'rb') as fh : print(test_chip) data = pickle.load(fh) image = data['chipped_image'] w = data['width'] // 2 h = data['height'] // 2 max_extent = max(data['width'], data['height']) scale_up_size = int(np.ceil(np.sqrt(2) * max_extent)) scale_down = 800 / scale_up_size # chip_h = data_dict['height'] * np.sqrt(2) # chip_w = data_dict['width'] * np.sqrt(2) if scale_up_size > 800: # Scale down and re-calculate bounding box. center = np.array(image.shape[:2]) // 2 width = w * scale_down height = h * scale_down top = int(center[0] - height) bot = int(center[0] + height) lef = int(center[1] - width) rig = int(center[1] + width) w = np.ceil(width) h = np.ceil(height) w = h = int(
np.min((w, h))
numpy.min
"""A collection of levitation related mathematical implementations. The fields is one of the most important parts of the package, containing implementations of various ways to calculate levitate-related physical properties. To simplify the management and manipulation of the implemented fields they are wrapped in an additional abstraction layer. The short version is that the classes implemented in the `~levitate.fields` module will not return objects of the called class, but typically objects of `~levitate.field_wrappers.Field`. These objects support algebraic operations, like `+`, `*`, and `abs`. The full description of what the different operands do can be found in the documentation of `~levitate._field_wrappers`. .. autosummary:: :nosignatures: Pressure Velocity GorkovPotential GorkovGradient GorkovLaplacian RadiationForce RadiationForceStiffness RadiationForceCurl RadiationForceGradient SphericalHarmonicsForce References ---------- .. [Gorkov] <NAME>, “On the Forces Acting on a Small Particle in an Acoustical Field in an Ideal Fluid” Soviet Physics Doklady, vol. 6, p. 773, Mar. 1962. .. [Sapozhnikov] <NAME> and <NAME>, “Radiation force of an arbitrary acoustic beam on an elastic sphere in a fluid” J Acoust Soc Am, vol. 133, no. 2, pp. 661–676, Feb. 2013. """ import numpy as np from . import materials, utils from ._field_wrappers import FieldImplementation class Pressure(FieldImplementation): """Complex sound pressure :math:`p`. Calculates the complex-valued sound pressure. """ ndim = 0 values_require = FieldImplementation.requirement(pressure_derivs_summed=0) jacobians_require = FieldImplementation.requirement(pressure_derivs_individual=0) def values(self, pressure_derivs_summed): # noqa: D102 return pressure_derivs_summed[0] def jacobians(self, pressure_derivs_individual): # noqa: D102 return pressure_derivs_individual[0] class Velocity(FieldImplementation): r"""Complex sound particle velocity :math:`v`. Calculates the sound particle velocity .. math:: v = {1 \over j\omega\rho} \nabla p from the relation :math:`\dot v = \rho \nabla p` applied for monofrequent sound fields. This is a vector value using a Cartesian coordinate system. """ ndim = 1 values_require = FieldImplementation.requirement(pressure_derivs_summed=1) jacobians_require = FieldImplementation.requirement(pressure_derivs_individual=1) def __init__(self, array, *args, **kwargs): super().__init__(array, *args, **kwargs) self.pre_grad_2_vel = 1 / (1j * array.medium.rho * array.omega) def __eq__(self, other): return ( super().__eq__(other) and np.allclose(self.pre_grad_2_vel, other.pre_grad_2_vel, atol=0) ) def values(self, pressure_derivs_summed): # noqa: D102 return self.pre_grad_2_vel * pressure_derivs_summed[1:4] def jacobians(self, pressure_derivs_individual): # noqa: D102 return self.pre_grad_2_vel * pressure_derivs_individual[1:4] class GorkovPotential(FieldImplementation): r"""Gor'kov's potential :math:`U`. Calculates the Gor'kov potential [Gorkov]_ .. math:: U = {V \over 4}(f_1 \kappa_0 |p|^2 - {3 \over 2} f_2 \rho_0 |v|^2) where .. math:: f_1 = 1 - {\kappa_p \over \kappa_0}, \qquad f_2 = 2 {\rho_p - \rho_0 \over 2 \rho_p + \rho_0} and :math:`V` is the volume of the particle. Note that this is only a suitable measure for small particles, i.e. :math:`ka<<1`, where :math:`a` is the radius of the particle. """ ndim = 0 values_require = FieldImplementation.requirement(pressure_derivs_summed=1) jacobians_require = FieldImplementation.requirement(pressure_derivs_summed=1, pressure_derivs_individual=1) def __init__(self, array, radius=1e-3, material=materials.styrofoam, *args, **kwargs): # noqa: D205, D400 """ Parameters ---------- array : TransducerArray The object modeling the array. radius : float, default 1e-3 Radius of the spherical beads. material : Material The material of the sphere, default styrofoam. """ super().__init__(array, *args, **kwargs) V = 4 / 3 * np.pi * radius**3 self.mg = V * 9.82 * material.rho monopole_coefficient = 1 - material.compressibility / array.medium.compressibility # f_1 in H. Bruus 2012 dipole_coefficient = 2 * (material.rho / array.medium.rho - 1) / (2 * material.rho / array.medium.rho + 1) # f_2 in H. Bruus 2012 preToVel = 1 / (array.omega * array.medium.rho) # Converting velocity to pressure gradient using equation of motion self.pressure_coefficient = V / 4 * array.medium.compressibility * monopole_coefficient self.gradient_coefficient = V * 3 / 8 * dipole_coefficient * preToVel**2 * array.medium.rho def __eq__(self, other): return ( super().__eq__(other) and np.allclose(self.pressure_coefficient, other.pressure_coefficient, atol=0) and np.allclose(self.gradient_coefficient, other.gradient_coefficient, atol=0) ) def values(self, pressure_derivs_summed): # noqa: D102 values = self.pressure_coefficient * np.real(pressure_derivs_summed[0] * np.conj(pressure_derivs_summed[0])) values -= self.gradient_coefficient * np.real(pressure_derivs_summed[1:4] * np.conj(pressure_derivs_summed[1:4])).sum(axis=0) return values def jacobians(self, pressure_derivs_summed, pressure_derivs_individual): # noqa: D102 jacobians = self.pressure_coefficient * 2 * pressure_derivs_individual[0] * np.conj(pressure_derivs_summed[0]) jacobians -= self.gradient_coefficient * 2 * (pressure_derivs_individual[1:4] * np.conj(pressure_derivs_summed[1:4, None])).sum(axis=0) return jacobians class GorkovGradient(GorkovPotential): r"""Gradient of Gor'kov's potential, :math:`\nabla U`. Calculates the Cartesian spatial gradient of Gor'kov's potential, see `GorkovPotential` and [Gorkov]_. This is a vector value used to calculate the radiation force as .. math:: F = -\nabla U. Note that this value is not suitable for sound fields with strong traveling wave components. If this is the case, use the `RadiationForce` field instead. """ ndim = 1 values_require = FieldImplementation.requirement(pressure_derivs_summed=2) jacobians_require = FieldImplementation.requirement(pressure_derivs_summed=2, pressure_derivs_individual=2) def values(self, pressure_derivs_summed): # noqa: D102 values = np.real(self.pressure_coefficient * np.conj(pressure_derivs_summed[0]) * pressure_derivs_summed[1:4]) # Pressure parts values -= np.real(self.gradient_coefficient * np.conj(pressure_derivs_summed[1]) * pressure_derivs_summed[[4, 7, 8]]) # Vx parts values -= np.real(self.gradient_coefficient * np.conj(pressure_derivs_summed[2]) * pressure_derivs_summed[[7, 5, 9]]) # Vy parts values -= np.real(self.gradient_coefficient * np.conj(pressure_derivs_summed[3]) * pressure_derivs_summed[[8, 9, 6]]) # Vz parts return values * 2 def jacobians(self, pressure_derivs_summed, pressure_derivs_individual): # noqa: D102 jacobians = self.pressure_coefficient * (np.conj(pressure_derivs_summed[0]) * pressure_derivs_individual[1:4] + np.conj(pressure_derivs_summed[1:4, None]) * pressure_derivs_individual[0]) # Pressure parts jacobians -= self.gradient_coefficient * (np.conj(pressure_derivs_summed[1]) * pressure_derivs_individual[[4, 7, 8]] + np.conj(pressure_derivs_summed[[4, 7, 8], None]) * pressure_derivs_individual[1]) # Vx parts jacobians -= self.gradient_coefficient * (np.conj(pressure_derivs_summed[2]) * pressure_derivs_individual[[7, 5, 9]] + np.conj(pressure_derivs_summed[[7, 5, 9], None]) * pressure_derivs_individual[2]) # Vy parts jacobians -= self.gradient_coefficient * (np.conj(pressure_derivs_summed[3]) * pressure_derivs_individual[[8, 9, 6]] + np.conj(pressure_derivs_summed[[8, 9, 6], None]) * pressure_derivs_individual[3]) # Vz parts return jacobians * 2 class GorkovLaplacian(GorkovPotential): r"""Laplacian of Gor'kov's potential, :math:`\nabla^2 U`. This calculates the Cartesian parts of the Laplacian of Gor'kov's potential, see `GorkovPotential` and [Gorkov]_. This is not really the Laplacian, since the components are not summed. The results can be seen as the local linear spring stiffness of the radiation force. Note that this value is not suitable for sound fields with strong traveling wave components. If this is the case, use the `RadiationForceStiffness` field instead. """ ndim = 1 values_require = FieldImplementation.requirement(pressure_derivs_summed=3) jacobians_require = FieldImplementation.requirement(pressure_derivs_summed=3, pressure_derivs_individual=3) def values(self, pressure_derivs_summed): # noqa: D102 values = np.real(self.pressure_coefficient * (np.conj(pressure_derivs_summed[0]) * pressure_derivs_summed[[4, 5, 6]] + pressure_derivs_summed[[1, 2, 3]] * np.conj(pressure_derivs_summed[[1, 2, 3]]))) values -= np.real(self.gradient_coefficient * (np.conj(pressure_derivs_summed[1]) * pressure_derivs_summed[[10, 15, 17]] + pressure_derivs_summed[[4, 7, 8]] *
np.conj(pressure_derivs_summed[[4, 7, 8]])
numpy.conj
""" Copyright (c) Facebook, Inc. and its affiliates. """ import os import sys import math import copy import time import logging from collections.abc import Iterable from prettytable import PrettyTable import Pyro4 import numpy as np import cv2 from droidlet.shared_data_structs import ErrorWithResponse from droidlet.dashboard.o3dviz import deserialize as o3d_unpickle from droidlet.shared_data_structs import RGBDepth from droidlet.lowlevel.robot_coordinate_utils import ( base_canonical_coords_to_pyrobot_coords, xyz_pyrobot_to_canonical_coords, ) from droidlet.lowlevel.robot_mover import MoverInterface from droidlet.lowlevel.robot_mover_utils import get_camera_angles, angle_diff, transform_pose from droidlet.shared_data_struct.rotation import ( rotation_matrix_x, rotation_matrix_y, rotation_matrix_z, ) from droidlet.lowlevel.robot_coordinate_utils import ( xyz_pyrobot_to_canonical_coords, base_canonical_coords_to_pyrobot_coords, ) from tenacity import retry, stop_after_attempt, wait_fixed from droidlet.lowlevel.pyro_utils import safe_call from .data_compression import * Pyro4.config.SERIALIZER = "pickle" Pyro4.config.SERIALIZERS_ACCEPTED.add("pickle") Pyro4.config.PICKLE_PROTOCOL_VERSION = 2 MAX_PAN_RAD = math.pi / 4 # TODO/FIXME: state machines. state machines everywhere class HelloRobotMover(MoverInterface): """Implements methods that call the physical interfaces of the Robot. Arguments: ip (string): IP of the Robot. """ def __init__(self, ip=None): self.bot = Pyro4.Proxy("PYRONAME:hello_robot@" + ip) self.bot._pyroAsync() self.is_moving = self.bot.is_moving() self.camera_transform = self.bot.get_camera_transform().value self.camera_height = self.camera_transform[2, 3] self.cam = Pyro4.Proxy("PYRONAME:hello_realsense@" + ip) self.slam = Pyro4.Proxy("PYRONAME:slam@" + ip) self.nav = Pyro4.Proxy("PYRONAME:navigation@" + ip) # spin once synchronously self.nav.is_busy() # put in async mode self.nav._pyroAsync() self.nav_result = self.nav.is_busy() self.data_logger = Pyro4.Proxy("PYRONAME:hello_data_logger@" + ip) self.data_logger._pyroAsync() _ = safe_call(self.data_logger.ready) intrinsic_mat = safe_call(self.cam.get_intrinsics) height, width = safe_call(self.cam.get_img_resolution, rotate=False) self.uv_one_in_cam = HelloRobotMover.compute_uvone(intrinsic_mat, height, width) def log_data_start(self, seconds): self.data_logger.save_batch(seconds) def log_data_stop(self): self.data_logger.stop() def bot_step(self): f = not self.bot.is_moving().value return f def relative_pan_tilt(self, dpan, dtilt, turn_base=True): """ move the head so its new tilt is current_tilt + dtilt and pan is current_pan + dpan Args: dpan (float): angle in radians to turn head left-right. positive is right dtilt (float): angle in radians to turn head up-down. positive is up """ # FIXME handle out-of-range values properly dtilt = dtilt or 0 dpan = dpan or 0 new_tilt = self.get_tilt() + dtilt # FIXME: make a safe_base_turn method if np.abs(dpan) > MAX_PAN_RAD and turn_base: dyaw = np.sign(dpan) * (np.abs(dpan) - MAX_PAN_RAD) self.turn(dyaw * 180 / math.pi) pan_rad = np.sign(dpan) * MAX_PAN_RAD else: pan_rad = dpan new_pan = self.get_pan() + pan_rad self.bot.set_pan_tilt(new_pan, new_tilt) return "finished" def set_look(self, pan_rad, tilt_rad, turn_base=True, world=False): """ Sets the agent to look at a specified absolute pan and tilt. These are "absolute" w.r.t. robot current base, if world==False and absolute w.r.t. world coords if world=True Args: pan_rad (float): angle in radians to turn head left-right. positive is right tilt_rad (float): angle in radians to to turn head up-down. positive is down. """ tilt_rad = tilt_rad or self.get_tilt() # TODO handle out-of-range properly dtilt = angle_diff(self.get_tilt(), tilt_rad) if not world: pan_rad = pan_rad or self.get_pan() dpan = angle_diff(self.get_pan(), pan_rad) else: base_pan = self.get_base_pos_in_canonical_coords()[2] pan_rad = pan_rad or base_pan + self.get_pan() dpan = angle_diff(base_pan + self.get_pan(), pan_rad) return self.relative_pan_tilt(dpan, dtilt, turn_base=turn_base) def is_obstacle_in_front(self, return_viz=False): ret = safe_call(self.cam.is_obstacle_in_front, return_viz) if return_viz: obstacle, cpcd, crop, bbox, rest = ret cpcd = o3d_unpickle(cpcd) crop = o3d_unpickle(crop) bbox = o3d_unpickle(bbox) rest = o3d_unpickle(rest) return obstacle, cpcd, crop, bbox, rest else: obstacle = ret return obstacle def look_at(self, target, turn_base=True, face=False): """ Executes "look at" by setting the pan, tilt of the camera or turning the base if required. Uses both the base state and object coordinates in canonical world coordinates to calculate expected yaw and pitch. if face == True will move body so head yaw is 0 Args: target (list): object coordinates as saved in memory. turn_base: if False, will try to look at point only by moving camera and not base """ old_pan = self.get_pan() old_tilt = self.get_tilt() pos = self.get_base_pos_in_canonical_coords() cam_transform = self.bot.get_camera_transform().value cam_pos = cam_transform[0:3, 3] # convert cam_pos to canonical co-ordinates # FIXME ! do this properly in a util, current functions don't do it bc # we are mixing base pos already converted and cam height cam_pos = [pos[0], cam_pos[2], pos[1]] logging.info(f"Current base state (x, z, yaw): {pos}, camera state (x, y, z): {cam_pos}") logging.info(f"looking at x,y,z: {target}") pan_rad, tilt_rad = get_camera_angles(cam_pos, target) # pan_res = angle_diff(pos[2], pan_rad) # For the Hello camera, negative tilt seems to be up, and positive tilt is down # For the locobot camera, it is the opposite # TODO: debug this further, and make things across robots consistent logging.info(f"Returned new pan and tilt angles (radians): ({pan_rad}, {tilt_rad})") if face: # TODO less blocking, make me into state machine dpan = angle_diff(self.get_base_pos_in_canonical_coords()[2], pan_rad) self.turn(dpan * 180 / math.pi) return self.set_look(0, tilt_rad) else: self.set_look(pan_rad, tilt_rad, turn_base=True, world=True) def is_busy(self): return self.nav.is_busy().value and self.bot.is_busy().value def stop(self): """immediately stop the robot.""" self.nav.stop() return self.bot.stop() def unstop(self): """remove a runstop flag via software""" return self.bot.remove_runstop() def get_pan(self): """get yaw in radians.""" return self.bot.get_pan().value def get_tilt(self): """get pitch in radians.""" return self.bot.get_tilt().value def reset_camera(self): """reset the camera to 0 pan and tilt.""" return self.bot.reset() def move_relative(self, xyt_positions, blocking=True): """Command to execute a relative move. Args: xzt_positions: a list of relative (x,y,yaw) positions for the bot to execute. x,y,yaw are in the pyrobot's coordinates. """ if not isinstance(next(iter(xyt_positions)), Iterable): # single xyt position given xyt_positions = [xyt_positions] for xyt in xyt_positions: self.nav_result.wait() self.nav_result = safe_call(self.nav.go_to_relative, xyt) if blocking: self.nav_result.wait() def move_absolute(self, xzt_positions, blocking=True): """Command to execute a move to an absolute position. It receives positions in canonical world coordinates and converts them to pyrobot's coordinates before calling the bot APIs. Args: xzt_positions: a list of (x_c,z_c,yaw) positions for the bot to move to. (x_c,z_c,yaw) are in the canonical world coordinates. """ if not isinstance(next(iter(xzt_positions)), Iterable): # single xzt position given xzt_positions = [xzt_positions] for xzt in xzt_positions: logging.info("Move absolute in canonical coordinates {}".format(xzt)) self.nav_result.wait() robot_coords = base_canonical_coords_to_pyrobot_coords(xzt) self.nav_result = self.nav.go_to_absolute(robot_coords) if blocking: self.nav_result.wait() return "finished" def get_base_pos_in_canonical_coords(self): """get the current robot position in the canonical coordinate system the canonical coordinate systems: from the origin, at yaw=0, front is (x, y, z) = (0, 0, 1), its right direction is (x,y,z) = (1, 0, 0) its up direction is (x,y,z) = (0, 1, 0) yaw is + counterclockwise return: (x, z, yaw) of the robot base in canonical coordinates """ future = safe_call(self.bot.get_base_state) x_robot, y_robot, yaw = future.value z_canonical = x_robot x_canonical = -y_robot return
np.array([x_canonical, z_canonical, yaw])
numpy.array
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 22 17:27:02 2018 Functions to process data for OpenBCI brainwaives reading @author: vyachez """ import sys import os import numpy as np import pandas as pd import matplotlib.pyplot as plt #import sys; sys.path.append('..') # dropping unnecessary staff def dip_drop(dset): dset = dset.drop(columns=[0,9,10,11]) dset = dset.reset_index(drop=True) print(dset.shape) return dset # preparing basics def basics(dset): '''cleaning up time column''' # converting timestamp into seconds (cutting off milisecs) dset[12] = dset[12].str[1:-4] dset = dset.rename(columns={12: "sec"}) print('Realigned time column') return dset # Cleaning data from spikes to prepare for normalisation # iterating through each second to clean-up spikes of data def variance_clean(dset, var): """ dset - dataset to cleanup var - max variance - all that above is to catch and remove """ for chan in range(8): for sec in np.unique(dset['sec']): min_edge = min(dset.loc[dset['sec'] == sec][chan+1]) max_edge = max(dset.loc[dset['sec'] == sec][chan+1]) variance = max_edge - min_edge idx = dset.loc[dset[chan+1] == max_edge].index[0] if variance > var: #print('Channel {} | Second {} | Index {} | Variance:] = {}'.format(chan+1, sec, idx, variance)) dset = dset.drop(index=dset.loc[dset['sec'] == sec].index) # reseting the index dset = dset.reset_index(drop=True) #print('Dropped') print('Cleaned spikes larger than', var) return dset # balancing intervals to set length (optimal number of rows) def balance_intervals(dset, int_no): """ dset - dataset to cleanup int_no - min length of intervals within one second""" idarr = np.array([[i, len(dset['sec'].loc[dset['sec'] == i])] for i in np.unique(dset['sec'])]) for i in idarr: if int(i[1]) < int_no: date = i[0] # removing short/incomplete dset = dset.drop(index=dset.loc[dset['sec'] == date].index) elif int(i[1]) > int_no: date = i[0] end_ind = dset.loc[dset['sec'] == date].index[-1] cut_ind = dset.loc[dset['sec'] == date].index[int_no-1] # cutting excessive dset = dset.drop(dset.index[cut_ind:end_ind]) dset = dset.reset_index(drop=True) return dset # see if all of intervals have the same length def balance_check(dset, dur): for i in np.unique(dset['sec']): if len(dset['sec'].loc[dset['sec'] == i]) != dur: print('Seconds are not equal!') print(np.array([i, len(dset['sec'].loc[dset['sec'] == i])])) print("Check completed for balanced intervals!") return True # checking number of seconds in dataset(unique) def seconds(dset): '''takes dataset as a argument and utputs number of unique seconds''' print("\nSeconds in dataset now: ", len(np.unique(dset['sec']))) # see if all of intervals have the same length by second def sec_disp(dset): return np.array([[i, len(dset['sec'].loc[dset['sec'] == i])] for i in np.unique(dset['sec'])]) # scaling function def scaler(dset, secs, dur): '''Scaling function takes dataset of 8 channels and returns rescaled dataset. Rescales by interval (second). arg 'secs' is number of seconds to take into one scaling tensor. Scaling is between 1 and 0 All datasets for training should be equalized''' # first - getting length of dataset modulo number of seconds for scaling intlv = secs*dur if len(dset['sec'])/intlv > 1: lendset = int(len(dset['sec'])/intlv) dset = dset[0:lendset*intlv] dset = dset.reset_index(drop=True) else: print("Inappropriate length of dataset. Too short. Set up less seconds for batch or choose another dataset.") seconds(dset) # now scaling if balance_check(dset, dur=dur): for chan in range(8): for i in range(int(len(dset['sec'])/intlv)): tmpdat = dset.loc[i*intlv:i*intlv+intlv-1, chan+1] tmpdat = (tmpdat-min(tmpdat))/(max(tmpdat)-min(tmpdat)) dset.loc[i*intlv:i*intlv+intlv-1, chan+1]= tmpdat dset = dset.reset_index(drop=True) print("Dataset has been rescaled \n") return dset else: print("\nDataset intervals are not balanced! Check the code and functions order.") # equalizing datasets by seconds' intervals def equalizing(r_dat, w_dat): '''Taking two datasets and equalising its lengths To fit training algorithms''' # taking length of datasets r_dat_sec = len(np.unique(r_dat['sec'])) w_dat_sec = len(np.unique(w_dat['sec'])) # eualizing if r_dat_sec > w_dat_sec: min_len = min(r_dat_sec, w_dat_sec) for i in range(min_len+1,r_dat_sec+1): r_dat = r_dat.drop(index=r_dat.loc[r_dat['sec'] == np.unique(r_dat['sec'])[-0]].index) #print('Dropped second from r_dat') elif w_dat_sec > r_dat_sec: min_len = min(r_dat_sec, w_dat_sec) for i in range(min_len+1,w_dat_sec+1): w_dat = w_dat.drop(index=w_dat.loc[w_dat['sec'] == np.unique(w_dat['sec'])[-0]].index) #print('Dropped second from r_dat') else: print('Seconds are equal!') r_dat = r_dat.reset_index(drop=True) w_dat = w_dat.reset_index(drop=True) print("Equalized!") # checking number of unique seconds r_dat_sec = len(np.unique(r_dat['sec'])) w_dat_sec = len(np.unique(w_dat['sec'])) print("\nSeconds: r_dat:", r_dat_sec) print("Seconds: w_dat:", w_dat_sec) print("\nr_dat dim:", r_dat.shape) print("w_dat dim:", w_dat.shape) return r_dat, w_dat # plotting function def d_plot(dset, chan=0, seconds=0, start=0, dur=0): '''this can plot each single chanel and within certain number of seconds''' sec = np.array(dset.index) plt.figure(figsize=(20,5)) if chan != 0: if seconds != 0: intv = dur*start intv_1 = intv+dur*seconds sec = np.array(dset.index[intv:intv_1]) plt.plot(sec, np.array(dset[chan][intv:intv_1]), label='ch') plt.legend() _ = plt.ylim() else: plt.plot(sec, np.array(dset[chan]), label='ch') plt.legend() _ = plt.ylim() else: if seconds != 0: intv = dur*start intv_1 = intv+dur*seconds sec = np.array(w_dat.index[intv:intv_1]) plt.plot(sec, np.array(dset[1][intv:intv_1]), label='ch1') plt.plot(sec, np.array(dset[2][intv:intv_1]), label='ch2') plt.plot(sec, np.array(dset[3][intv:intv_1]), label='ch3') plt.plot(sec, np.array(dset[4][intv:intv_1]), label='ch4') plt.plot(sec, np.array(dset[5][intv:intv_1]), label='ch5') plt.plot(sec, np.array(dset[6][intv:intv_1]), label='ch6') plt.plot(sec, np.array(dset[7][intv:intv_1]), label='ch7') plt.plot(sec, np.array(dset[8][intv:intv_1]), label='ch8') plt.legend() _ = plt.ylim() else: plt.plot(sec, np.array(dset[1]), label='ch1') plt.plot(sec, np.array(dset[2]), label='ch2') plt.plot(sec, np.array(dset[3]), label='ch3') plt.plot(sec, np.array(dset[4]), label='ch4') plt.plot(sec, np.array(dset[5]), label='ch5') plt.plot(sec, np.array(dset[6]), label='ch6') plt.plot(sec,
np.array(dset[7])
numpy.array
#!/bin/python import Nio, Ngl import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy from scipy.fftpack import fftshift import math from diag_functions import * import seaborn as sns sns.set_style('darkgrid') dir_in="/glade/scratch/cmc542/tmp/bbenton/WRF_OUTPUT/ctrl/%s" #dir_in = "/glade/u/home/bbenton/PROJ_WRF/ctrl/%s" file_in = "/wrfpost_ctrl_%s_%s.nc" ts_series=[] if False: for year in range(950,1105): for month in range(1,13): if month < 10: month="0"+str(month) else: month=str(month) dat_in = Nio.open_file(dir_in %(year) + file_in %(year,month)) dat_in = dat_in.variables["T_sfc_monthly"][0,:,:] ts_series.append(np.mean(dat_in)) #ts_series.append(np.mean(tmp)) print(ts_series) exit() else: f1=open("/glade/u/home/bbenton/20XXWRF/wrf_pipeline_tools/diagnostics/ctrl_ts_series_1000_1105.txt") f2=open("/glade/u/home/bbenton/20XXWRF/wrf_pipeline_tools/diagnostics/ctrl_ts_series_950_1105.txt") ts_series1=f1.readline().split(",") ts_series2=f2.readline().split(",") ts_series1=[float(x) for x in ts_series1] ts_series2=[float(x) for x in ts_series2] tmp1=[] tmp2=[] avg_len=6 for i in range(int(len(ts_series1)/avg_len)): tmp1.append(np.mean(ts_series1[avg_len*i:avg_len*(i+1)])) for i in range(int(len(ts_series2)/avg_len)): tmp2.append(np.mean(ts_series2[avg_len*i:avg_len*(i+1)])) ts_series1=tmp1 ts_series2=tmp2 ts_series1=[x-np.mean(ts_series1) for x in ts_series1] ts_series2=[x-
np.mean(ts_series2)
numpy.mean
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian import numpy as np import plotly.graph_objects as go import plotly.io as pio pio.templates.default = "simple_white" def test_univariate_gaussian(): # Question 1 - Draw samples and print fitted model q1 = np.random.normal(10,1,1000) x1 = UnivariateGaussian() x1.fit(q1) print("("+str(x1.mu_)+","+str(x1.var_)+")") # Question 2 - Empirically showing sample mean is consistent ms = np.linspace(10,1000,100).astype(int) estimate = np.zeros(100) for i in range(1,estimate.size): estimate[i] = np.abs(x1.fit(q1[:i*10]).mu_-10) go.Figure([go.Scatter(x=ms, y=estimate, mode='markers+lines', name=r'$\widehat\mu$')], layout=go.Layout( title=r"$\text{absolute distance between the estimate and " r"the true value of the expectation}$", xaxis_title="$m\\text{ - number of samples}$", yaxis_title="r$\mu$",height=500)).show() # Question 3 - Plotting Empirical PDF of fitted model x1.fit(q1) go.Figure([go.Scatter(x=q1, y=x1.pdf(q1), mode='markers', name=r'$\widehat\PDF$')], layout=go.Layout( title=r"$\text{sample value and their PDFs}$", xaxis_title="$m\\text{ - number of samples}$", yaxis_title="r$PDF$")).show() def test_multivariate_gaussian(): # Question 4 - Draw samples and print fitted model mu = np.array([0,0,4,0]) sigma = np.array([[1,0.2,0,0.5],[0.2,2,0,0],[0,0,1,0],[0.5,0,0,1]]) q2 = np.random.multivariate_normal(mu, sigma, 1000) x2 = MultivariateGaussian() x2.fit(q2) print("estimated expectation: ") print(x2.mu_) print("covariance: ") print(x2.cov_) # Question 5 - Likelihood evaluation f1 = np.array(np.linspace(-10,10,200)) f3 = np.array(np.linspace(-10,10,200)) log_likely = np.array([[MultivariateGaussian.log_likelihood( np.array([i1,0,i3,0]), sigma, q2) for i3 in f3] for i1 in f1]) np.reshape(log_likely,(200,200)) fig = go.Figure(data=go.Heatmap(x=f1, y=f3, z=np.array(log_likely)), layout=go.Layout(title="log-likelihood heatmap of models" " with different expectation")) fig.show() # Question 6 - Maximum likelihood max1,max3 = np.unravel_index(log_likely.argmax(),log_likely.shape) print(f1[max1], f3[max3]) if __name__ == '__main__':
np.random.seed(0)
numpy.random.seed
#!/usr/bin/env python import os import sys import h5py ROOT_DIR = os.path.abspath(os.path.pardir) sys.path.append(ROOT_DIR) import numpy as np import utils.provider as provider class Dataset(): def __init__(self, filename, npoints=1024, box_size=10, dropout_max=0, training=True): """Create a dataset holder npoints (int): Defaults to 8192. The number of point in each input color (bool): Defaults to True. Whether to use colors or not box_size (int): Defaults to 10. The size of the extracted cube. path (float): Defaults to "dataset/semantic_data/". dropout_max (float): Defaults to 0.875. Maximum dropout to apply on the inputs. accept_rate (float): Minimum rate (between 0.0 and 1.0) of points in the box to accept it. E.g : npoints = 100, then you need at least 50 points. """ # Dataset parameters self.filename = filename self.npoints = npoints self.box_size = box_size self.dropout_max = dropout_max self.num_classes = 2 # Load the data self.load_data() # Precompute the random scene probabilities self.compute_random_scene_index_proba() # Prepare the points weights if it is a training set if training: # Compute the weights labelweights = np.zeros(2) # First, compute the histogram of each labels for seg in self.semantic_labels_list: tmp,_ = np.histogram(seg,range(3)) labelweights += tmp # Then, an heuristic gives the weights : 1/log(1.2 + probability of occurrence) labelweights = labelweights.astype(np.float32) labelweights = labelweights/np.sum(labelweights) self.labelweights = 1/np.log(1.2+labelweights) else: self.labelweights = np.ones(2) def load_data(self): print("Loading semantic data...") self.scene_points_list = list() self.semantic_labels_list = list() f = h5py.File(self.filename, "r") data_points = f["data"][:] data_labels = f["label"][:] # sort according to x to speed up computation of boxes and z-boxes # print np.shape(data_points) # print np.shape(data_points[:,0]) # print np.shape(data_points[:,:,0]) # sort_idx = np.argsort(data_points[:,:,0]) # print np.shape(sort_idx) # print np.shape(data_labels) # data_points = data_points[sort_idx,0] # data_labels = data_labels[sort_idx] # self.scene_points_list = data_points # self.semantic_labels_list = data_labels.astype(np.int8) # # # print np.shape(data_points) # print np.shape(data_points[:,0]) # print np.shape(data_points[:,:,0]) for i in range(len(data_points)): #pc = data_points[i] #sort_idx = np.argsort(pc[:,0]) #print np.shape(sort_idx) #print np.shape(data_labels) #pc = data_points[i,sort_idx] #dl = data_labels[i,sort_idx] #self.scene_points_list.append(data_points[i]) #self.semantic_labels_list.append(data_labels[i].astype(np.int8)) break self.scene_points_list = data_points #self.semantic_labels_list = data_labels.astype(np.int8) for i in range(len(data_labels)): self.semantic_labels_list.append([data_labels[i]] * self.npoints) # Set min to (0,0,0) self.scene_max_list = list() self.scene_min_list = list() self.raw_scene_min_list = list() for i in range(len(self.scene_points_list)): self.raw_scene_min_list.append(np.min(self.scene_points_list[i],axis=0)) self.scene_points_list[i] = self.scene_points_list[i]-
np.min(self.scene_points_list[i], axis=0)
numpy.min
def summary(outroot='summary-18.05.17'): from hsaquery import overlaps from grizli import utils overlaps.summary_table(output='pointing_summary') tab = utils.GTable.gread('pointing_summary.fits') roots = tab['NAME'] tab['Full'] = ['<a href=https://s3.amazonaws.com/aws-grivam/Pipeline/{0}/Extractions/{0}-full.html?chinu_max=2&bic_diff_min=30&zwidth1_max=0.01>Full</a>'.format(root.replace('+','%2B')) for root in roots] tab['fp'] = ['<a href=https://s3.amazonaws.com/aws-grivam/Pipeline/{0}_footprint.png> <img height=200 src=https://s3.amazonaws.com/aws-grivam/Pipeline/{0}_footprint.png></a>'.format(root.replace('+','%2B')) for root in roots] tab['zhist'] = ['<a href=https://s3.amazonaws.com/aws-grivam/Pipeline/{0}/Extractions/{0}_zhist.png> <img height=200 src=https://s3.amazonaws.com/aws-grivam/Pipeline/{0}/Extractions/{0}_zhist.png></a>'.format(root.replace('+','%2B')) for root in roots] #cols = ['NAME', 'RA', 'DEC', 'E(B-V)', 'GalLat', 'GalLon', 'NFILT', 'filter', 'target', 'target_description', 'proposal_id', 'pi_name', 'TexpG102', 'PAG102', 'TexpG141', 'PAG141', 'MAST', 'Full', 'fp', 'zhist'] cols = ['NAME', 'RA', 'DEC', 'E(B-V)', 'GalLat', 'GalLon', 'NFILT', 'filter', 'target', 'proposal_id', 'pi_name', 'TexpG102', 'PAG102', 'TexpG141', 'PAG141', 'MAST', 'Full', 'fp', 'zhist'] tab[cols].write_sortable_html(outroot+'.html', replace_braces=True, localhost=False, max_lines=50000, table_id=None, table_class='display compact', css=None, filter_columns=['mag_auto', 'z_map', 'bic_diff', 'chinu', 'zwidth1', 'is_point', 'sn_SIII', 'sn_Ha', 'sn_OIII', 'sn_Hb', 'sn_OII'], use_json=False) print('aws s3 cp {0}.html s3://aws-grivam/Pipeline/ --acl public-read'.format(outroot)) def regenerate_webpages(outroot='master'): """ roots=`python -c "from grizli_aws import catalogs; roots, dates = catalogs.get_roots(verbose=False); print('\n'.join(roots))"` roots=`ls *phot.fits | sed "s/_phot/ /" | awk '{print $1}'` # ACS BUCKET=grizli-grism roots=`ls ../*footprint.fits | sed "s/\// /g" | sed "s/_foot/ /" | awk '{print $2}'` for root in $roots; do if [ ! -e ${root}.info.fits ]; then aws s3 cp s3://${BUCKET}/Pipeline/${root}/Extractions/${root}.info.fits ./ #aws s3 cp s3://${BUCKET}/Pipeline/${root}/Extractions/${root}_phot.fits ./ else echo $root fi done for root in $roots; do aws s3 ls s3://aws-grivam/Pipeline/${root}/Extractions/ > /tmp/x echo $root grep beams.fits /tmp/x | wc grep full.fits /tmp/x | wc done """ import glob import numpy as np from grizli import utils from astropy import table ## retrieve roots = [file.split('.info')[0] for file in glob.glob('*info.fits')] fpi = open('sync_to_s3.sh', 'w') fpi.write('# \n') fpi.close() tables = [] for root in roots: fit = utils.GTable.gread(root+'.info.fits') phot = utils.GTable.gread(root+'_phot.fits') ix, dr = phot.match_to_catalog_sky(fit) fit['phot_dr'] = dr for c in phot.colnames: if c not in fit.colnames: fit[c] = phot[ix][c] else: pass #print(c) print(root, len(fit)) # # DQ on mag differences # apcorr = fit['flux_auto']/fit['flux_aper_1'] # m140 = 23.9-2.5*np.log10(fit['f140w_flux_aper_1']*apcorr) # dm140 = m140-fit['mag_wfc3,ir,f140w'] # mask = fit['{0}_mask_aper_{1}'.format('f140w', 1)] # bad = mask > 0.2*np.percentile(mask[np.isfinite(mask)], 99.5) # dm140[bad] = np.nan # # m160 = 23.9-2.5*np.log10(fit['f160w_flux_aper_1']*apcorr) # dm160 = m160-fit['mag_wfc3,ir,f160w'] # mask = fit['{0}_mask_aper_{1}'.format('f160w', 1)] # bad = mask > 0.2*np.percentile(mask[np.isfinite(mask)], 99.5) # dm160[bad] = np.nan # # dm = dm140 # dm[(~np.isfinite(dm140)) & np.isfinite(dm160)] = dm160[(~np.isfinite(dm140)) & np.isfinite(dm160)] # dm[~np.isfinite(dm)] = -99 # # fit['fit_dmag'] = dm # fit['fit_dmag'].format = '4.1f' # Point source pa = np.polyfit([16, 21, 24, 25.5], [4.5, 2.6, 2.3, 2.1], 2) py = np.polyval(pa, fit['mag_auto']) point_source = (fit['flux_radius'] < py) #& (fit['mag_auto'] < 23) fit['is_point'] = point_source*2-1 bad = (fit['mag_auto'] > 22) & (fit['flux_radius'] < 1.2) fit['too_small'] = bad*2-1 N = len(fit) aws_col = {} for c in ['png_stack', 'png_full', 'png_line']: aws_col[c] = [] for i in range(N): root = fit['root'][i] aws = 'https://s3.amazonaws.com/aws-grivam/Pipeline/{0}/Extractions/{0}'.format(root) for c in ['png_stack', 'png_full', 'png_line']: pre = fit[c][i] aws_col[c].append(pre.replace(root, aws).replace(root, root.replace('+','%2B'))) for c in ['png_stack', 'png_full', 'png_line']: fit['aws_'+c] = aws_col[c] fit['log_mass'] = np.log10(fit['stellar_mass']) fit['log_mass'].format = '.2f' cols = ['root', 'idx','ra', 'dec', 't_g102', 't_g141', 'mag_auto', 'is_point', 'z_map', 'chinu', 'bic_diff', 'zwidth1', 'a_image', 'sn_SIII', 'sn_Ha', 'sn_OIII', 'sn_Hb', 'sn_OII', 'log_mass', 'png_stack', 'png_full', 'png_line'] # Check grisms cols = ['root', 'idx','ra', 'dec', 'mag_auto', 'is_point', 'z_map', 'z02', 'z97', 'chinu', 'bic_diff', 'zwidth1', 'a_image', 'flux_radius', 'sn_SIII', 'sn_Ha', 'sn_OIII', 'sn_Hb', 'sn_OII', 'log_mass', 'aws_png_stack', 'aws_png_full', 'aws_png_line'] for grism in ['g800l', 'g102', 'g141'][::-1]: if np.isfinite(fit['t_'+grism]).sum() > 0: cols.insert(4, 't_'+grism) fit['ra'].format = '.4f' fit['dec'].format = '.4f' fit['z02'].format = '.2f' fit['z97'].format = '.2f' fit['flux_radius'].format = '.1f' fit['mag_auto'].format = '.2f' fit['t_g800l'].format = '.0f' fit['t_g102'].format = '.0f' fit['t_g141'].format = '.0f' fit['zq'].format = '.1f' fit['zwidth1'].format = '.3f' fit['bic_diff'].format = '.0f' fit['a_image'].format = '.1f' for l in ['Ha','OIII','Hb','OII','SIII']: fit['sn_'+l].format = '.1f' fit[cols].write_sortable_html(root+'-full.html', replace_braces=True, localhost=False, max_lines=50000, table_id=None, table_class='display compact', css=None, filter_columns=['mag_auto', 'z_map', 'z02', 'z97', 'bic_diff', 'chinu', 'a_image', 'flux_radius', 'zwidth1', 'is_point', 'sn_SIII', 'sn_Ha', 'sn_OIII', 'sn_Hb', 'sn_OII'], use_json=True) if '+' in root: ext = 'html' lines = open(root+'-full.'+ext).readlines() for i, line in enumerate(lines): if root in line: lines[i] = line.replace(root, root.replace('+', '%2B')) fp = open(root+'-full.'+ext,'w') fp.writelines(lines) fp.close() ext = 'json' lines = open(root+'-full.'+ext).readlines() for i, line in enumerate(lines): if (root in line) & ('href' in line): lines[i] = line.replace(root, root.replace('+', '%2B')) fp = open(root+'-full.'+ext,'w') fp.writelines(lines) fp.close() fpi = open('sync_to_s3.sh', 'a') fpi.write('aws s3 cp {0}-full.html s3://aws-grivam/Pipeline/{0}/Extractions/ --acl public-read\n'.format(root)) fpi.write('aws s3 cp {0}-full.json s3://aws-grivam/Pipeline/{0}/Extractions/ --acl public-read\n'.format(root)) fpi.close() tables.append(fit) master = table.vstack(tables) cols = ['root', 'idx','ra', 'dec', 'mag_auto', 'is_point', 'z_map', 'z02', 'z97', 'chinu', 'bic_diff', 'zwidth1', 'a_image', 'flux_radius', 'sn_SIII', 'sn_Ha', 'sn_OIII', 'sn_Hb', 'sn_OII', 'log_mass', 'aws_png_stack', 'aws_png_full', 'aws_png_line'] for grism in ['g800l', 'g102', 'g141'][::-1]: if np.isfinite(master['t_'+grism]).sum() > 0: cols.insert(4, 't_'+grism) master[cols].write_sortable_html(outroot+'.html', replace_braces=True, localhost=False, max_lines=500000, table_id=None, table_class='display compact', css=None, filter_columns=['mag_auto', 't_g102', 't_g141', 'z_map', 'z02', 'z97', 'bic_diff', 'chinu', 'a_image', 'flux_radius', 'zwidth1', 'is_point', 'sn_SIII', 'sn_Ha', 'sn_OIII', 'sn_Hb', 'sn_OII', 'log_mass'], use_json=True) #sel = master['bic_diff'] > 30 #master[sel][cols].write_sortable_html(outroot+'.html', replace_braces=True, localhost=False, max_lines=500000, table_id=None, table_class='display compact', css=None, filter_columns=['mag_auto', 't_g102', 't_g141', 'z_map', 'z02', 'z97', 'bic_diff', 'chinu', 'a_image', 'flux_radius', 'zwidth1', 'is_point', 'sn_SIII', 'sn_Ha', 'sn_OIII', 'sn_Hb', 'sn_OII', 'log_mass'], use_json=True) new = utils.GTable() for col in fit.colnames: new[col] = master[col] new.write(outroot+'.fits', overwrite=True) print('aws s3 cp {0}.html s3://aws-grivam/Pipeline/ --acl public-read\n'.format(outroot)) print('aws s3 cp {0}.json s3://aws-grivam/Pipeline/ --acl public-read\n'.format(outroot)) print('aws s3 cp {0}.fits s3://aws-grivam/Pipeline/ --acl public-read\n'.format(outroot)) print ('bash sync_to_s3.sh') def master_catalog(outroot='grizli-18.05.17-full', bucket='grizli-v1', files=None): import glob import numpy as np from grizli import utils from astropy import table ## retrieve if files is None: files = glob.glob('*info.fits') roots = [file.split('.info')[0] for file in files] tabs = [utils.GTable.gread(root+'.info.fits') for root in roots] fit = utils.GTable(table.vstack(tabs)) fit['flux_radius'].format = '.1f' N = len(fit) aws_col = {} for c in ['png_stack', 'png_full', 'png_line', 'png_rgb']: aws_col[c] = [] #bucket='aws-grivam' #bucket='grizli-grism' #bucket='grizli' for i in range(N): root = fit['root'][i] aws = 'https://s3.amazonaws.com/{0}/Pipeline/{1}/Extractions/{1}'.format(bucket, root) for c in ['png_stack', 'png_full', 'png_line']: pre = fit[c].filled()[i] aws_col[c].append(pre.replace(root, aws).replace(root, root.replace('+','%2B'))) pre = fit['png_rgb'].filled()[i] aws_col['png_rgb'].append(pre.replace('../Thumbnails/', '').replace(root, aws).replace('Extractions', 'Thumbnails').replace(root, root.replace('+','%2B'))) for c in ['png_stack', 'png_full', 'png_line', 'png_rgb']: fit['aws_'+c] = aws_col[c] fit['aws_png_sed'] = [l.replace('full.png','sed.png') for l in fit['aws_png_full']] psx = [16, 18.5, 21, 24, 25.5] psy = [8, 4., 2.6, 2.3, 2.1] # New pixel scale psy = np.array(psy)*0.06/0.1 # ACS if False: psx = [16, 21, 24, 25.5, 27] psy = [4.5, 2.9, 2.9, 2.6, 2.6] pa = np.polyfit(psx, psy, 2) py = np.interp(fit['mag_auto'], psx, psy) # Point source point_source = (fit['flux_radius'] < py) & (fit['mag_auto'] < 25.5) #point_source = (fit['flux_radius'] < py) & (fit['mag_auto'] < 24) # ACS fit['is_point'] = point_source*1 fit['log_mass'] = np.log10(fit['stellar_mass']) fit['log_mass'].format = '.2f' ############ # Warnings for ambiguous line IDs dz_line = np.array([5007, 6563])*(1./5007.-1/6563.) col = 'ambiguous_HaOIII' dz_line = np.array([3727, 6563])*(1./3727.-1/6563.) col = 'ambiguous_HaOII' zw1 = fit['zwidth1']/(1+fit['z_map']) zw2 = fit['zwidth2']/(1+fit['z_map']) fit['zw1'] = zw1 fit['zw1'].format = '.3f' fit['zw2'] = zw2 fit['zw2'].format = '.3f' for dz_line, col in zip([np.array([5007, 6563])*(1./5007.-1/6563.), np.array([3727, 6563])*(1./3727.-1/6563.)], ['ambiguous_HaOIII', 'ambiguous_HaOII']): if col in fit.colnames: fit.remove_column(col) for dz_i in dz_line: if col not in fit.colnames: fit[col] = np.abs(zw1 - dz_i) < 0.008 else: fit[col] |= np.abs(zw1 - dz_i) < 0.008 amb = fit['ambiguous_HaOIII']*1+fit['ambiguous_HaOII']*2 ############ # Reliable redshifts, based on 3D-HST COSMOS ambiguous = (fit['ambiguous_HaOIII'] | fit['ambiguous_HaOII']) & (zw2 / zw1 < 1.1) fit['ambiguous'] = ambiguous # Define ambigous as wide zwidth but <= N isolated peaks with width # ambig_sigma ambig_sigma = 0.005 ambig_npeak = 2 ambig_logprob = np.log10(1/np.sqrt(np.pi*ambig_sigma**2)/ambig_npeak) fit.meta['pdf_max'] = ambig_logprob, 'log_pdf_max limit for ambigous lines' fit['ambiguous'] = (zw1 > 0.2) & (fit['log_pdf_max'] > ambig_logprob) min_risk_lim = 0.4 fit['ambiguous'] &= fit['min_risk'] < min_risk_lim fit.meta['min_risk'] = min_risk_lim, 'min_risk limit for ambigous lines' fit['ok_width'] = (fit['zw1'] < 0.02) | fit['ambiguous'] fit['ok_width'].format = 'd' fit['bic_diff_spl'] = fit['bic_spl'] - fit['bic_temp'] fit['bic_diff_spl'].format = '.0f' # Overall data quality fit['use_spec'] = (fit['ok_width']) fit['use_spec'] &= (fit['chinu'] < 10) fit['use_spec'] &= (fit['bic_diff'] > 0) | ((fit['bic_diff'] > -30) & (fit['min_risk'] < 0.05)) fit['use_spec'] &= (fit['flux_radius'] > 1) dz_risk = (fit['z_map'] - fit['z_risk'])/(1+fit['z_map']) fit['use_spec'] &=
np.abs(dz_risk)
numpy.abs
# decompose import copy import torch import torch.nn as nn import tensorly as tl from tensorly.decomposition import parafac, partial_tucker from typing import List # switch to the PyTorch backend tl.set_backend('pytorch') # ================ import numpy as np from scipy.sparse.linalg import svds from scipy.optimize import minimize_scalar def VBMF(Y, cacb, sigma2=None, H=None): """Implementation of the analytical solution to Variational Bayes Matrix Factorization. This function can be used to calculate the analytical solution to VBMF. This is based on the paper and MatLab code by Nakajima et al.: "Global analytic solution of fully-observed variational Bayesian matrix factorization." Notes ----- If sigma2 is unspecified, it is estimated by minimizing the free energy. If H is unspecified, it is set to the smallest of the sides of the input Y. To estimate cacb, use the function EVBMF(). Attributes ---------- Y : numpy-array Input matrix that is to be factorized. Y has shape (L,M), where L<=M. cacb : int Product of the prior variances of the matrices that factorize the input. sigma2 : int or None (default=None) Variance of the noise on Y. H : int or None (default = None) Maximum rank of the factorized matrices. Returns ------- U : numpy-array Left-singular vectors. S : numpy-array Diagonal matrix of singular values. V : numpy-array Right-singular vectors. post : dictionary Dictionary containing the computed posterior values. References ---------- .. [1] Nakajima, Shinichi, et al. "Global analytic solution of fully-observed variational Bayesian matrix factorization." Journal of Machine Learning Research 14.Jan (2013): 1-37. .. [2] Nakajima, Shinichi, et al. "Perfect dimensionality recovery by variational Bayesian PCA." Advances in Neural Information Processing Systems. 2012. """ L, M = Y.shape # has to be L<=M if H is None: H = L # SVD of the input matrix, max rank of H U, s, V = np.linalg.svd(Y) U = U[:, :H] s = s[:H] V = V[:H].T # Calculate residual residual = 0. if H < L: residual = np.sum(np.sum(Y ** 2) - np.sum(s ** 2)) # Estimation of the variance when sigma2 is unspecified if sigma2 is None: upper_bound = (np.sum(s ** 2) + residual) / (L + M) if L == H: lower_bound = s[-1] ** 2 / M else: lower_bound = residual / ((L - H) * M) sigma2_opt = minimize_scalar(VBsigma2, args=(L, M, cacb, s, residual), bounds=[lower_bound, upper_bound], method='Bounded') sigma2 = sigma2_opt.x print("Estimated sigma2: ", sigma2) # Threshold gamma term # Formula above (21) from [1] thresh_term = (L + M + sigma2 / cacb ** 2) / 2 threshold = np.sqrt(sigma2 * (thresh_term + np.sqrt(thresh_term ** 2 - L * M))) # Number of singular values where gamma>threshold pos = np.sum(s > threshold) # Formula (10) from [2] d = np.multiply(s[:pos], 1 - np.multiply(sigma2 / (2 * s[:pos] ** 2), L + M + np.sqrt((M - L) ** 2 + 4 * s[:pos] ** 2 / cacb ** 2))) # Computation of the posterior post = {} zeta = sigma2 / (2 * L * M) * (L + M + sigma2 / cacb ** 2 - np.sqrt((L + M + sigma2 / cacb ** 2) ** 2 - 4 * L * M)) post['ma'] = np.zeros(H) post['mb'] = np.zeros(H) post['sa2'] = cacb * (1 - L * zeta / sigma2) * np.ones(H) post['sb2'] = cacb * (1 - M * zeta / sigma2) * np.ones(H) delta = cacb / sigma2 * (s[:pos] - d - L * sigma2 / s[:pos]) post['ma'][:pos] = np.sqrt(np.multiply(d, delta)) post['mb'][:pos] = np.sqrt(np.divide(d, delta)) post['sa2'][:pos] = np.divide(sigma2 * delta, s[:pos]) post['sb2'][:pos] = np.divide(sigma2, np.multiply(delta, s[:pos])) post['sigma2'] = sigma2 post['F'] = 0.5 * (L * M *
np.log(2 * np.pi * sigma2)
numpy.log
import pickle as pk import pandas as pd import numpy as np from numpy import * import time import matplotlib.pyplot as plt from tqdm import * from pylab import * from multiprocessing import Pool import pickle import os import statsmodels.api as sm import torch import julian import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import copy from scipy.interpolate import griddata from scipy.stats import multivariate_normal as mn from itertools import permutations from scipy import stats from matplotlib.pyplot import figure from matplotlib.transforms import Bbox #import torch from torch.distributions.multivariate_normal import MultivariateNormal nasa_julian = 98 cnes_julian = 90 import warnings warnings.filterwarnings('ignore') from sklearn.metrics import r2_score def y_hat_esti(X_,y_,Beta,Sigma,Lambda,n): """ Estimate y_hat - Beta: (K,nb_fea,nb_tar) - Sigma: (K,nb_tar,nb_tar) - Lambda: (K,1) - n: nb of samples """ K = Beta.shape[0] tars = Beta.shape[2] X = torch.from_numpy(X_).cuda() Y = torch.from_numpy(y_).cuda() Beta_hat = torch.from_numpy(Beta).cuda() Sigma_hat = torch.from_numpy(Sigma).cuda() Lambda_hat = torch.from_numpy(Lambda).cuda() pi_hat = torch.zeros(n,Lambda.shape[0]).cuda() y_hat = torch.zeros(n,tars).cuda() sum_prob = torch.zeros(n,1).cuda() for k in range(K): # Compute the sum of products of the likelihood with a class's prior for each profile (formula 5) sum_prob = sum_prob + Lambda_hat[k]*torch.exp(MultivariateNormal(X@Beta_hat[k,:,:],Sigma_hat[k,:,:]).log_prob(Y)).reshape(n,1) for k in range(K): # Compute how many percentage each class representing in each profile (formla 7) pi_hat[:,k]= Lambda_hat[k]*torch.exp(MultivariateNormal(X@Beta_hat[k,:,:],Sigma_hat[k,:,:]).log_prob(Y))/sum_prob[:,0] for k in range(K): y_hat = y_hat + torch.mul(pi_hat[:,k].reshape(n,1),X@Beta_hat[k,:,:]) y_hat_np = y_hat.cpu().numpy() pi_hat_np = pi_hat.cpu().numpy() return y_hat_np,pi_hat_np def likli_plot(log_likli,coln,row,nb_class,nb_iter_,iter_EM): """ plot the log likelihood of models """ figure(num=None, figsize=(20, 10), dpi=80, facecolor='w', edgecolor='k') for cla_ in range(len(nb_class)): plt.subplot(row, coln, cla_ + 1) for iter_ in range(nb_iter_): plt.plot(range(iter_EM),np.asarray(log_likli[cla_,iter_,:])) plt.ylabel('Log likelihood') plt.xlabel('EM iterations') plt.title('Model with: '+str(nb_class[cla_])+' classes') def bic_box(bic,nb_class): """ plot box plot of model's bics """ fig = plt.figure(figsize=(7,7)) ax = fig.add_axes([1,1,1,1]) labels = [min(nb_class)+i for i in range(len(nb_class))] plt.boxplot(bic, labels = labels) plt.title("Boxplot BIC") xlabel("Nb_of_class") ylabel("BIC") def extract_bsl(beta_,sigma_,lambda_,X,y,nb_class,th_class,nb): """ Etract beta, sigma, lambda of a specific class - th_class: the class number extracted - nb th experience """ index = 0 th = 0 for c in range(len(nb_class)): beta_c = beta_[c,index:index + nb_class[th],:,:] sigma_c = sigma_[c,index:index + nb_class[th],:,:] lambda_c = lambda_[c,index:index + nb_class[th],:] if nb_class[c] == th_class: beta = open('beta_E'+str(nb)+'_'+str(th_class)+'.pkl', 'wb') pickle.dump(beta_c, beta) sigma = open('sigma_E'+str(nb)+'_'+str(th_class)+'.pkl', 'wb') pickle.dump(sigma_c, sigma) lambda_ = open('lambda_E'+str(nb)+'_'+str(th_class)+'.pkl', 'wb') pickle.dump(lambda_c, lambda_) beta.close() sigma.close() lambda_.close() return beta_c,sigma_c,lambda_c break index = index + nb_class[th] th = th +1 def y_eval(beta_,sigma_,lambda_,X,y,nb_class,coln,row, save,nb, test): """ Evaluate the y and its estimation - save: the class saved for result visualization - test: if test True, save as test result - nb: nb th experience """ index = 0 th = 0 figure(num=None, figsize=(15, 15), dpi=80, facecolor='w', edgecolor='k') x_linsp = np.linspace(-5,35,50) markers = 0.1*np.full((y.shape[0], 1), 1) for c in range(len(nb_class)): beta_c = beta_[c,index:index + nb_class[th],:,:] sigma_c = sigma_[c,index:index + nb_class[th],:,:] lambda_c = lambda_[c,index:index + nb_class[th],:] # y_esti,_ = y_hat_esti(X,y,beta_c,sigma_c,lambda_c,X.shape[0]) # save interesting class if nb_class[c] == save: y_esti,_ = y_hat_esti(X,y,beta_c,sigma_c,lambda_c,X.shape[0]) ## new if test: np.savetxt('y_h_test_E'+str(nb)+'_'+str(nb_class[c])+'.txt',y_esti) else: np.savetxt('y_h_train_E'+str(nb)+'_'+str(nb_class[c])+'.txt',y_esti) plt.subplot(row, coln, c+1) plt.scatter(y,y_esti, marker = ".", s = markers, c ='b', label = "r2_score = " +str(r2_score(y, y_esti))) plt.plot(x_linsp,x_linsp,'k') plt.ylabel('Predicted Temperature') plt.xlabel('GT Temperature') plt.title('Model with: '+str(nb_class[c])+' classes') plt.legend() index = index + nb_class[th] th = th +1 def sal_eval(beta_,sigma_,lambda_,X,y,nb_class,coln,row, save,nb, test, fx1 =30 , fx2 = 40): """ Evaluate the y and its estimation - save: the class saved for result visualization - test: if test True, save as test result - nb: nb th experience """ index = 0 th = 0 figure(num=None, figsize=(15, 15), dpi=80, facecolor='w', edgecolor='k') x_linsp = np.linspace(fx1,fx2,50) markers = 0.1*np.full((y.shape[0], 1), 1) for c in range(len(nb_class)): beta_c = beta_[c,index:index + nb_class[th],:,:] sigma_c = sigma_[c,index:index + nb_class[th],:,:] lambda_c = lambda_[c,index:index + nb_class[th],:] y_esti,_ = y_hat_esti(X,y,beta_c,sigma_c,lambda_c,X.shape[0]) # save interesting class if nb_class[c] == save: if test: np.savetxt('y_h_test_E'+str(nb)+'_'+str(nb_class[c])+'.txt',y_esti) else: np.savetxt('y_h_train_E'+str(nb)+'_'+str(nb_class[c])+'.txt',y_esti) plt.subplot(row, coln, c+1) plt.scatter(y,y_esti, marker = ".", s = markers, c ='b', label = "r2_score = " +str(r2_score(y, y_esti))) plt.plot(x_linsp,x_linsp,'k') plt.ylabel('Predicted Salanity') plt.xlabel('GT Salanity') plt.title('Model with: '+str(nb_class[c])+' classes') plt.legend() index = index + nb_class[th] th = th +1 def pi_hat(X_,y_,Beta,Sigma,Lambda,n,nb,th_class, test): """ Estimate p_hat - Beta: (K,nb_fea,nb_tar) - Sigma: (K,nb_tar,nb_tar) - Lambda: (K,1) - n: nb of samples - nb: nb th experience - test : if test is true, save file as test """ K = Beta.shape[0] tars = Beta.shape[2] X = torch.from_numpy(X_).cuda() Y = torch.from_numpy(y_).cuda() Beta_hat = torch.from_numpy(Beta).cuda() Sigma_hat = torch.from_numpy(Sigma).cuda() Lambda_hat = torch.from_numpy(Lambda).cuda() pi_hat = torch.zeros(n,Lambda.shape[0]).cuda() y_hat = torch.zeros(n,tars).cuda() sum_prob = torch.zeros(n,1).cuda() for k in range(K): # Compute the sum of products of the likelihood with a class's prior for each profile (formula 5) sum_prob = sum_prob + Lambda_hat[k]*torch.exp(MultivariateNormal(X@Beta_hat[k,:,:],Sigma_hat[k,:,:]).log_prob(Y)).reshape(n,1) for k in range(K): # Compute how many percentage each class representing in each profile (formla 7) pi_hat[:,k]= Lambda_hat[k]*torch.exp(MultivariateNormal(X@Beta_hat[k,:,:],Sigma_hat[k,:,:]).log_prob(Y))/sum_prob[:,0] for k in range(K): y_hat = y_hat + torch.mul(pi_hat[:,k].reshape(n,1),X@Beta_hat[k,:,:]) pi_hat_np = pi_hat.cpu().numpy() if test: np.savetxt('pi_h_test_E'+str(nb)+'_'+str(th_class)+'.txt',pi_hat_np) else: np.savetxt('pi_h_train_E'+str(nb)+'_'+str(th_class)+'.txt',pi_hat_np) def temp_plot(lon_test,lat_test,map,temp): "Plot surface temperature" lons = lon_test lats = lat_test x, y = map(lons, lats) figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k') markers = np.full((lon_test.shape[0], 1), 1) ax = plt.gca() # map.scatter(x, y, c = temp, s = markers, cmap='coolwarm') map.scatter(x, y, c = temp, s = markers, cmap='Greys') map.drawcoastlines() # plot colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax) def mode(lon_test,lat_test,map,pi_hat, m, title, combine = False, subplot = 221): "Plot dynamical mode distributions" lons = lon_test lats = lat_test x, y = map(lons, lats) if combine: plt.subplot(subplot) markers = np.full((len(pi_hat), 1), 1) map.scatter(x, y, c = pi_hat, label = "mode"+str(m+1), s = markers) map.drawcoastlines() plt.legend() plt.title(title) def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap's dynamic range to be at zero. https://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib Input ----- cmap : The matplotlib colormap to be altered start : Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower offset). Should be between 0.0 and `midpoint`. midpoint : The new center of the colormap. Defaults to 0.5 (no shift). Should be between 0.0 and 1.0. In general, this should be 1 - vmax / (vmax + abs(vmin)) For example if your data range from -15.0 to +5.0 and you want the center of the colormap at 0.0, `midpoint` should be set to 1 - 5/(5 + 15)) or 0.75 stop : Offset from highest point in the colormap's range. Defaults to 1.0 (no upper offset). Should be between `midpoint` and 1.0. ''' cdict = { 'red': [], 'green': [], 'blue': [], 'alpha': [] } # regular index to compute the colors reg_index = np.linspace(start, stop, 257) # shifted index to match the data shift_index = np.hstack([ np.linspace(0.0, midpoint, 128, endpoint=False), np.linspace(midpoint, 1.0, 129, endpoint=True) ]) for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict) plt.register_cmap(cmap=newcmap) return newcmap ######################################### ## Plot target prediction # ######################################### def full_extent(ax, pad=0.0): """Get the full extent of an axes, including axes labels, tick labels, and titles.""" # For text objects, we need to draw the figure first, otherwise the extents # are undefined. ax.figure.canvas.draw() items = ax.get_xticklabels() + ax.get_yticklabels() # items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label] # items += [ax.get_xaxis().get_label(), ax.get_yaxis().get_label()] items += [ax, ax.title] bbox = Bbox.union([item.get_window_extent() for item in items]) return bbox.expanded(1.0 + pad, 1.0 + pad) def target_predict(lon, lat, pres, Nx, Ny, map, gt_targ, est_targ, error, prd_var, neigboors, savename, cmap_temp = True, surf = 0): """ Target prediction in time and space - lat: latitude of the data - lon: longitude of the data - neigboors: for selecting the interpolated region - Nx: number of point discritizing the x axis - Ny: number of point discritizing the y axis - prd_var: predicting variable on which we find targets * a determined pressure at which we present data ± 15 * a latiude * a longitude - surf : int * 0: surface target prediction * 1: predict a target on a longitude * 2: ... latitude """ # create a 2D coordinate grid if surf == 0: x = np.linspace(min(lon),max(lon),Nx) y = np.linspace(min(lat),max(lat),Ny) # interpolating data mask prd_mask = (prd_var-15 < pres)*(pres < prd_var + 15) elif surf == 1: x = np.linspace(min(lat),max(lat),Nx) y = np.linspace(min(pres),max(pres),Ny) prd_mask = (prd_var-3 < lon)*(lon < prd_var + 3) elif surf == 2: x = np.linspace(min(lon),max(lon),Nx) y = np.linspace(min(pres),max(pres),Ny) prd_mask = (prd_var-3 < lat)*(lat < prd_var + 3) else: print("Surf is not a valid number") ## interpolating grid xx, yy = np.meshgrid(x,y) xx = xx.reshape(xx.shape[0]*xx.shape[1],1) yy = yy.reshape(xx.shape[0]*xx.shape[1],1) zz = prd_var*np.ones((xx.shape[0]*xx.shape[1],1)) ## interpolating data ipres = pres[prd_mask] ilat = lat[prd_mask] ilon = lon[prd_mask] igt = gt_targ[prd_mask] iest = est_targ[prd_mask] ierror = error[prd_mask] ## data points N = ilon.shape[0] features = np.concatenate((ilat.reshape(N,1),ilon.reshape(N,1), ipres.reshape(N,1)),axis = 1) if surf == 0: points = np.concatenate((yy,xx,zz),axis = 1) elif surf == 1: points = np.concatenate((xx,zz,yy),axis = 1) elif surf == 2: points = np.concatenate((zz,xx,yy),axis = 1) gt_interpol = griddata(features,igt,points, rescale=True) gt_interpol = gt_interpol.reshape(Ny,Nx) est_interpol = griddata(features,iest,points, rescale=True) est_interpol = est_interpol.reshape(Ny,Nx) err_interpol = griddata(features,ierror,points, rescale=True) err_interpol = err_interpol.reshape(Ny,Nx) # mean squared error mse = np.abs(ierror).mean()**2 vmin = np.min(err_interpol[~np.isnan(err_interpol)]) vmax = np.max(err_interpol[~np.isnan(err_interpol)]) midpoint = 1 - vmax/(vmax + abs(vmin)) if cmap_temp: cmap = 'coolwarm' cmap2 =shiftedColorMap(matplotlib.cm.bwr, midpoint =midpoint) else: cmap = 'jet' cmap2 =shiftedColorMap(matplotlib.cm.bwr, midpoint =midpoint) if surf == 0: fig = plt.figure(figsize = (15,10)) subplots_adjust(wspace = 0.2, hspace = 0.2) ## select interpolated region where the data exists mask_pres = pres < 30 pres_under_30 = pres[prd_mask] lon_30 = lon[prd_mask] lat_30 = lat[prd_mask] # existing data region mask (care only about the surface) mask_region = np.ones((Nx,Ny)) < 2 for k in range(len(lon_30)): i = np.argmin(abs(y - lat_30[k])) j = np.argmin(abs(x - lon_30[k])) mask_region[i-neigboors:i+neigboors,j-neigboors:j+neigboors] = False # apply the mask gt_interpol[mask_region] = nan est_interpol[mask_region] = nan err_interpol[mask_region] = nan plon, plat = map(x, y) xxlon,xxlat = meshgrid(plon,plat) parallels = np.arange(0.,81,5.) # lat meridians = np.arange(10.,351.,5.) # lon ax2 = fig.add_subplot(222) cs = map.contourf(xxlon, xxlat, est_interpol, cmap = cmap) plt.title("EST-PRES-%.f"%prd_var) map.drawcoastlines() map.drawparallels(parallels,labels=[True,False,True,False],linewidth=0.3); map.drawmeridians(meridians,labels=[True,False,False,True],linewidth=0.3); divider = make_axes_locatable(ax2) cax2 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax2) extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted()) plt.savefig('.\\figs\\%sEST.jpg'%savename,bbox_inches=extent.expanded(1.3, 1.15)) ax1 = fig.add_subplot(221) map.contourf(xxlon, xxlat, gt_interpol, cmap = cmap,levels = cs.levels) plt.title("GT-PRES-%.f"%prd_var) map.drawcoastlines() map.drawparallels(parallels,labels=[True,False,True,False],linewidth=0.3); map.drawmeridians(meridians,labels=[True,False,False,True],linewidth=0.3); divider = make_axes_locatable(ax1) cax1 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax1) extent = full_extent(ax1).transformed(fig.dpi_scale_trans.inverted()) plt.savefig('.\\figs\\%sGT.jpg'%savename,bbox_inches=extent.expanded(1.3, 1.15)) ax3 = subplot2grid((2,8), (1, 2), colspan=4) map.contourf(xxlon, xxlat, err_interpol, cmap = cmap2, levels = 20) plt.title("%.f-Global-MSE-%.2f"%(prd_var,mse)) map.drawcoastlines() map.drawparallels(parallels,labels=[True,False,True,False],linewidth=0.3); map.drawmeridians(meridians,labels=[True,False,False,True],linewidth=0.3); divider = make_axes_locatable(ax3) cax3 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax3) extent = full_extent(ax3).transformed(fig.dpi_scale_trans.inverted()) plt.savefig('.\\figs\\%sMSE.jpg'%savename,bbox_inches=extent.expanded(1.3, 1.15)) else: fig = plt.figure(figsize = (15,10)) subplots_adjust(wspace = 0.2, hspace = 0.35) if surf == 1: label_, label, labelx ='W','LON', 'LAT' elif surf == 2: label_, label, labelx = 'N','LAT', 'LON' xx = xx.reshape(Nx,Ny) yy = yy.reshape(Nx,Ny) ax2 = fig.add_subplot(222) cs = plt.contourf(xx,yy,est_interpol, cmap = cmap) plt.grid() ax2.set_ylim(ax2.get_ylim()[::-1]) if surf == 1: ax2.set_xlim(ax2.get_xlim()[::-1]) plt.title("EST:%s %.f°%s"%(label,prd_var,label_)) plt.xlabel("%s"%labelx) plt.ylabel("PRES") divider = make_axes_locatable(ax2) cax2 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax2) extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted()) plt.savefig('.\\figs\\%sEST.jpg'%savename,bbox_inches=extent.expanded(1.2, 1.15)) ax1 = fig.add_subplot(221) plt.contourf(xx, yy, gt_interpol, cmap = cmap,levels = cs.levels) plt.grid() ax1.set_ylim(ax1.get_ylim()[::-1]) if surf == 1: ax1.set_xlim(ax1.get_xlim()[::-1]) plt.title("GT:%s %.f°%s"%(label,prd_var,label_)) plt.xlabel("%s"%labelx) plt.ylabel("PRES") divider = make_axes_locatable(ax1) cax1 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax1) extent = full_extent(ax1).transformed(fig.dpi_scale_trans.inverted()) plt.savefig('.\\figs\\%sGT.jpg'%savename,bbox_inches=extent.expanded(1.2, 1.15)) ax3 = subplot2grid((2,8), (1, 2), colspan=4) divider = make_axes_locatable(ax3) plt.contourf(xx, yy, err_interpol, cmap = cmap2, levels = 20) plt.grid() ax3.set_ylim(ax3.get_ylim()[::-1]) if surf == 1: ax3.set_xlim(ax3.get_xlim()[::-1]) plt.title("MSE:%.3f - %s %.f°%s"%(mse,label,prd_var,label_)) plt.xlabel("%s"%labelx) plt.ylabel("PRES") cax3 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax3) extent = full_extent(ax3).transformed(fig.dpi_scale_trans.inverted()) plt.savefig('.\\figs\\%sMSE.jpg'%savename,bbox_inches=extent.expanded(1.22, 1.15)) ############################################ # Plot temporal dynamical mode distribution# ############################################ def temp_dyna_mode_var(pi_hat, lon, lat, juld, pres, sel_lat, sel_lon, sel_pres, lon_thres, lat_thres, pres_thres, thres = 20): """ Plot temporal dynamical mode variation in a specific region in the ocean Args: ----- - pi_hat: priors of dynamical modes - lon: global longitude - lat: global latitude - pres: global pressure - sel_lon: selected longitude - sel_lat: selected latitude - lon_thres: longitude threshold - thres: threshold for dynamical trends ... """ lat_mask = np.abs(lat - sel_lat) < lat_thres lon_mask = np.abs(lon - sel_lon) < lon_thres pres_mask = np.abs(pres - sel_pres) < pres_thres mask = lat_mask*lon_mask*pres_mask print("Number of data points N= "+str(len(np.where(mask)[0]))) # extracted julian days and mode's priori ex_jul = juld[mask] encoded_juld = [julian.from_jd(round(x), fmt='mjd') for x in ex_jul] days_in_year = np.asarray([x.day + (x.month -1)*30 for x in encoded_juld]) ex_priori = pi_hat[mask,:] # monthly mode priors and its variances N = pi_hat.shape[1] mon_mod_pri = np.zeros((365,N)) # cacluate the mode's prior for each day for d in tqdm(range(365), disable=False): day_mask = days_in_year == d for mod in range(N): mon_mod_pri[d,mod] = np.mean(ex_priori[day_mask,mod]) # find trend of temporal dynamical modes for id_ in range(N): mon_mod_pri[~np.isnan(mon_mod_pri[:,id_]),id_] = sm.tsa.filters.hpfilter(mon_mod_pri[~np.isnan(mon_mod_pri[:,id_]),id_], thres)[1] # select pairs of modes which together have a preferring most negative correlation mod_bag = range(8) perms = list(permutations(mod_bag,2)) pearson_coeffs = [stats.pearsonr(mon_mod_pri[~np.isnan(mon_mod_pri[:,k[0]]),k[0]], mon_mod_pri[~np.isnan(mon_mod_pri[:,k[1]]),k[1]])[0] for k in perms] selected_perms = [] while(len(perms) != 0): delete_items = [] delete_pearson = [] max_index = np.argmin(pearson_coeffs) selected_perms.append(perms[max_index]) delete_items.append(perms[max_index]) delete_pearson.append(pearson_coeffs[max_index]) for index, item in enumerate(perms): if item[0] == perms[max_index][0] or item[1] == perms[max_index][1] or item[0] == perms[max_index][1] or item[1] == perms[max_index][0]: if delete_items.count(item) == 0: delete_items.append(item) delete_pearson.append(pearson_coeffs[index]) for del_item in delete_items: perms.remove(del_item) for del_pearson in delete_pearson: pearson_coeffs.remove(del_pearson) fig = plt.figure(figsize = (20,10)) subplots_adjust(wspace = 0.2, hspace = 0.2) for count, sel_item in enumerate(selected_perms): pearson_coeff = stats.pearsonr(mon_mod_pri[~np.isnan(mon_mod_pri[:,sel_item[0]]),sel_item[0]], mon_mod_pri[~np.isnan(mon_mod_pri[:,sel_item[1]]),sel_item[1]])[0] plt.subplot(221+count) plt.plot(mon_mod_pri[:,sel_item[0]], label = 'Dyn-Mode-'+str(sel_item[0]+1)) plt.plot(mon_mod_pri[:,sel_item[1]], label = 'Dyn-Mode - '+str(sel_item[1]+1)) plt.title('Pearson-coeff= %.2f'%pearson_coeff) x_labels = ['Jan','Feb','Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] spots = np.asarray([30*i for i in range(12)]) plt.xticks(spots,x_labels) plt.grid(True) plt.legend() ############################################# ## Plot spatial dynamical mode distribution # ############################################# def spa_dyna_mode_dis(pi_hat, lon, lat, pres, Nx, Ny, prd_var ,neigboors, map, cmaptemp = True, surf = 1): """ Plot the spatial dynamical mode distribution between two depth levels in the ocean. Args: ----- - pi_hat: the prior probabilities for dynamical modes - lon: ... - lat: ... - pres: infos of the pressure at each point in the ocean - prd_mod: predicting variable based modes - map: a basemap object - surf: 0 (surface), 1 (longitude), 2 (latitude) """ import timeit start = timeit.timeit() # create a 2D coordinate grid if surf == 0: x = np.linspace(min(lon),max(lon),Nx) y = np.linspace(min(lat),max(lat),Ny) # interpolating data mask prd_mask = np.array(np.where((prd_var-50 < pres)*(pres < prd_var + 50))[0]) elif surf == 1: x = np.linspace(min(lat),max(lat),Nx) y = np.linspace(min(pres),max(pres),Ny) prd_mask = np.array(np.where((prd_var-3 < lon)*(lon < prd_var + 3))[0]) elif surf == 2: x = np.linspace(min(lon),max(lon),Nx) y = np.linspace(min(pres),max(pres),Ny) prd_mask = np.array(np.where((prd_var-3 < lat)*(lat < prd_var + 3))[0]) else: print("Surf is not a valid number") #prd_mask = prd_mask.reshape(prd_mask.shape[0],1) ## interpolating grid xx, yy = np.meshgrid(x,y) xx = xx.reshape(xx.shape[0]*xx.shape[1],1) yy = yy.reshape(xx.shape[0]*xx.shape[1],1) zz = prd_var*
np.ones((xx.shape[0]*xx.shape[1],1))
numpy.ones
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 21 13:59:39 2017 @author: epicodic """ import matplotlib matplotlib.use('Qt5Agg') import numpy as np import matplotlib.pyplot as plt import scipy.misc import sys import os from enum import Enum #import skimage #from skimage import morphology #from skimage import io #from skimage import img_as_float #from skimage import exposure import skimage.draw #im_raw = io.imread('keepme.tif',mode='RGBA') import math from matplotlib.lines import Line2D from matplotlib.artist import Artist from matplotlib.mlab import dist_point_to_segment from matplotlib.patches import Polygon from matplotlib import colors #from scipy import interpolate from scipy.interpolate import CubicSpline def color_for_class(cl): if(cl==1): return '#FF00FF' else: return '#FFFF00' class PolygonInteractor(object): """ An polygon editor. Key-bindings 't' toggle vertex markers on and off. When vertex markers are on, you can move them, delete them 'd' delete the vertex under point 'i' insert a vertex at point. You must be within epsilon of the line connecting two existing vertices """ showverts = True epsilon = 5 # max pixel distance to count as a vertex hit def __init__(self, ax, poly): if poly.figure is None: raise RuntimeError('You must first add the polygon to a figure or canvas before defining the interactor') self.ax = ax canvas = poly.figure.canvas self.poly = poly x, y = zip(*self.poly.xy) self.line = Line2D(x, y, color = 'yellow', marker='o', markerfacecolor='yellow', animated=True) self.ax.add_line(self.line) #self._update_line(poly) #cid = self.poly.add_callback(self.poly_changed) self._ind = None # the active vert self.set_class(0) self.cid=[] self.cid.append( canvas.mpl_connect('draw_event', self.draw_callback) ) self.cid.append( canvas.mpl_connect('button_press_event', self.button_press_callback) ) self.cid.append( canvas.mpl_connect('key_press_event', self.key_press_callback) ) self.cid.append( canvas.mpl_connect('button_release_event', self.button_release_callback) ) self.cid.append( canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) ) self.canvas = canvas def remove(self): self.line.remove() for i in range(4): self.canvas.mpl_disconnect(self.cid[i]) def __del__(self): #print ("deling", self) pass def draw_callback(self, event): self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self.poly) self.ax.draw_artist(self.line) #self.canvas.blit(self.ax.bbox) pass def poly_changed(self, poly): 'this method is called whenever the polygon object is called' # only copy the artist props to the line (except visibility) print("Poly Changed") vis = self.line.get_visible() Artist.update_from(self.line, poly) self.line.set_visible(vis) # don't use the poly visibility state def get_ind_under_point(self, event): 'get the index of the vertex under point if within epsilon tolerance' # display coords xy = np.asarray(self.poly.xy) xyt = self.poly.get_transform().transform(xy) xt, yt = xyt[:, 0], xyt[:, 1] d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2) indseq = np.nonzero(np.equal(d, np.amin(d)))[0] ind = indseq[0] if d[ind] >= self.epsilon: ind = None return ind def button_press_callback(self, event): if(self.canvas.manager.toolbar._active != None): return 'whenever a mouse button is pressed' if not self.showverts: return if event.inaxes is None: return if event.button != 1: return self._ind = self.get_ind_under_point(event) def button_release_callback(self, event): 'whenever a mouse button is released' if not self.showverts: return if event.button != 1: return self._ind = None def key_press_callback(self, event): 'whenever a key is pressed' if not event.inaxes: return if event.key == 't': self.showverts = not self.showverts self.line.set_visible(self.showverts) if not self.showverts: self._ind = None elif event.key == 'd': ind = self.get_ind_under_point(event) if ind is not None: self.poly.xy = [tup for i, tup in enumerate(self.poly.xy) if i != ind] self.line.set_data(zip(*self.poly.xy)) elif event.key == 'i': xys = self.poly.get_transform().transform(self.poly.xy) p = event.x, event.y # display coords for i in range(len(xys) - 1): s0 = xys[i] s1 = xys[i + 1] d = dist_point_to_segment(p, s0, s1) if d <= self.epsilon: self.poly.xy = np.array( list(self.poly.xy[:i]) + [(event.xdata, event.ydata)] + list(self.poly.xy[i:])) self.line.set_data(zip(*self.poly.xy)) break elif event.key == 'k': self.set_class(1-self.cl) #elif event.key == 'l': # self.set_class(0) self.canvas.draw() def motion_notify_callback(self, event): 'on mouse movement' if not self.showverts: return if self._ind is None: return if event.inaxes is None: return if event.button != 1: return x, y = event.xdata, event.ydata self.poly.xy[self._ind] = x, y if self._ind == 0: self.poly.xy[-1] = x, y elif self._ind == len(self.poly.xy) - 1: self.poly.xy[0] = x, y self.line.set_data(zip(*self.poly.xy)) self.canvas.restore_region(self.background) self.ax.draw_artist(self.poly) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) def set_class(self,cl): self.cl = cl self.line.set_color(color_for_class(self.cl)) self.line.set_markerfacecolor(color_for_class(self.cl)) self.poly.set_color(color_for_class(self.cl)) class Mode(Enum): IDLE = 1 CREATE = 2 EDIT = 3 class ImageToggle(Enum): FULL = 0 R = 1 G = 2 B = 3 RN = 4 class Label: def __init__(self): self.jd = None self.tx = None self.ty = None self.h = None self.ht = None self.D = None self.cl = 0 class Tool(object): def __init__(self, filename): self.mode = Mode.IDLE self.filename = filename self.im_raw = scipy.misc.imread(filename,mode='RGBA') self.im_r = self.im_raw[:,:,0] self.im_r_norm = colors.LogNorm(self.im_r.mean() + 0.5 * self.im_r.std(), self.im_r.max(), clip='True') self.im_g = self.im_raw[:,:,1] self.im_b = self.im_raw[:,:,2] self.img_median = np.array([0,0,0]) self.img_median[0] = np.median(self.im_r) self.img_median[1] = np.median(self.im_g) self.img_median[2] = np.median(self.im_b) self.fig, self.ax = plt.subplots() self.infotext = None self.fig.tight_layout() self.canvas = self.fig.canvas self.imgh = None self.imgtoggle = ImageToggle.FULL self.update_image() self.ax.set_ylim(bottom=10000, top=-10000,auto=True) self.marks = [] self.clicks = [] self.p = None self.labels = [] self.nextjd = 1 self.edit_label = None #canvas.mpl_connect('draw_event', self.draw_callback) self.canvas.mpl_connect('button_press_event', self.button_press_callback) self.canvas.mpl_connect('key_press_event', self.key_press_callback) self.canvas.mpl_connect('key_release_event', self.key_release_callback) self.canvas.mpl_connect('resize_event', self.resize_callback) self.load_labels(filename+".txt") self.update() def update_image(self): if(self.imgh): self.imgh.remove() if(self.imgtoggle == ImageToggle.FULL): self.imgh = self.ax.imshow(self.im_raw) elif(self.imgtoggle == ImageToggle.R): self.imgh = self.ax.imshow(self.im_r,cmap='gray') elif(self.imgtoggle == ImageToggle.RN): self.imgh = self.ax.imshow(self.im_r,cmap='gray', norm=self.im_r_norm) elif(self.imgtoggle == ImageToggle.G): self.imgh = self.ax.imshow(self.im_g,cmap='gray') elif(self.imgtoggle == ImageToggle.B): self.imgh = self.ax.imshow(self.im_b,cmap='gray') self.update() def resize_callback(self, event): aspect = event.width / event.height x1,x2 = self.ax.get_xlim() y1,y2 = self.ax.get_ylim() cx = (x1+x2)/2 # cy = (y1+y2)/2 # w = x2-x1 h = y1-y2 tw = h*aspect # th = w/aspect self.ax.set_xlim(left=cx-tw/2, right=cx+tw/2) def button_press_callback(self, event): if(self.canvas.manager.toolbar._active != None): return if(self.mode == Mode.EDIT): # we are in ellipse edit mode return if(event.button==3): return if event.dblclick: print(event.button) self.clear_clicks() # find clicked label clickedLabelIdx = -1 for i in range(len(self.labels)): dx = abs(event.xdata-self.labels[i].tx) dy = abs(event.ydata-self.labels[i].ty) r = 10 if(dx<r and dy<r): print("CLICKED LABEL: %d" % self.labels[i].jd) clickedLabelIdx = i break if(clickedLabelIdx>=0): self.mode = Mode.EDIT l = self.labels[clickedLabelIdx] xx = l.D[0,:] yy = l.D[1,:] self.add_ellipse_from_poly(xx,yy) self.p.set_class(l.cl) l.h.remove() l.h = None l.ht.remove() l.ht = None self.edit_label = l self.update() else: self.mode = Mode.IDLE self.update() return self.mode = Mode.CREATE line = Line2D([event.xdata], [event.ydata], marker='+', color='r') event.inaxes.add_line(line) self.marks.append(line) self.clicks.append((event.xdata, event.ydata)) if(len(self.clicks)>=3): if(self.add_ellipse(self.clicks)): self.edit_label = None self.mode = Mode.EDIT else: self.mode = Mode.IDLE self.clear_clicks() self.update() def key_press_callback(self, event): if(event.key==' ' and self.p!=None): if(self.edit_label != None): self.update_label(self.p.poly.xy.T, self.p.cl, self.edit_label,False) else: self.add_label(self.p.poly.xy.T, self.p.cl) self.p.remove() self.p = None self.mode = Mode.IDLE self.update() if(event.key=='escape' or event.key=='delete'): self.clear_clicks() self.mode = Mode.IDLE if(self.p!=None): self.p.remove() self.p = None if(self.edit_label != None): if(event.key=='delete'): self.delete_label(self.edit_label) else: self.update_label(None, self.p.cl,self.edit_label,True) self.update() if(event.key=='r' or event.key=='v' or event.key=='x'): self.imgtoggle = ImageToggle.FULL if self.imgtoggle==ImageToggle.R else ImageToggle.R self.update_image() # if(event.key=='v' or event.key=='x'): # self.imgtoggle = ImageToggle.FULL if self.imgtoggle==ImageToggle.RN else ImageToggle.RN # self.update_image() if(event.key=='g'): self.imgtoggle = ImageToggle.FULL if self.imgtoggle==ImageToggle.G else ImageToggle.G self.update_image() if(event.key=='b'): self.imgtoggle = ImageToggle.FULL if self.imgtoggle==ImageToggle.B else ImageToggle.B self.update_image() if(event.key=='e'): self.evaluate() def key_release_callback(self, event): self.update() def clear_clicks(self): for mark in self.marks: mark.remove() self.marks = [] self.clicks = [] self.update() def add_ellipse_from_poly(self,xx,yy): poly = Polygon(list(zip(xx, yy)), animated=True, fill=False, color='yellow', linewidth=0.5) self.ax.add_patch(poly) self.p = PolygonInteractor(self.ax, poly) def add_ellipse(self,clicks): pts=np.array(clicks) x=pts[:,0] y=pts[:,1] cx=(x[0]+x[1])/2 cy=(y[0]+y[1])/2 phi = math.atan2(y[1]-y[0],x[1]-x[0]) a = math.cos(phi)*(x[0]-cx) + math.sin(phi)*(y[0]-cy) p3x = math.cos(phi)*(x[2]-cx) + math.sin(phi)*(y[2]-cy) p3y = - math.sin(phi)*(x[2]-cx) + math.cos(phi)*(y[2]-cy) sqdenum = a**2-p3x**2; if(sqdenum<=0): print("Invalid points") return False b = abs( (a*p3y)/math.sqrt(a**2-p3x**2) ) #R = np.arange(0,2.0*np.pi, 0.01) R = np.linspace(0,2.0*np.pi, 9) xx = cx + a*np.cos(R)*np.cos(phi) - b*np.sin(R)*np.sin(phi) yy = cy + a*np.cos(R)*np.sin(phi) + b*np.sin(R)*np.cos(phi) self.add_ellipse_from_poly(xx,yy) return True def to_smooth_poly(self, D): theta = np.linspace(0,1,D.shape[1]) cs = CubicSpline(theta,D.T, bc_type='periodic') ts = np.linspace(0, 1, 50) out=cs(ts); return out[:,0],out[:,1] def draw_label(self, l): xx,yy = self.to_smooth_poly(l.D) l.h, = self.ax.plot(xx,yy, color = color_for_class(l.cl)) if(l.ht==None): l.ht = self.ax.text(l.tx, l.ty, ("%d" % l.jd), fontsize=10, color=color_for_class(l.cl), ha='center', va='center') def insert_label(self, D, jd, cl): l = Label() l.jd = jd l.cl = cl l.tx = np.mean(D[0,:]) l.ty = np.mean(D[1,:]) l.D = D self.labels.append(l) self.draw_label(l) if(jd>=self.nextjd): self.nextjd=jd+1 return l def update_label(self,D,cl,l,revert): if(not revert): l.D = D l.cl = cl l.tx = np.mean(D[0,:]) l.ty =
np.mean(D[1,:])
numpy.mean
import numpy as np from desc.backend import jnp, put, Tristate from desc.grid import Grid from desc.basis import DoubleFourierSeries from desc.transform import Transform def format_bdry(bdry, Rb_basis:DoubleFourierSeries, Zb_basis:DoubleFourierSeries, mode:str='spectral'): """Formats arrays for boundary conditions and converts between real space and fourier representations Parameters ---------- bdry : ndarray, shape(Nbdry,4) array of fourier coeffs [m,n,Rcoeff, Zcoeff] or array of real space coordinates, [theta,phi,R,Z] Rb_basis : DoubleFourierSeries spectral basis for R boundary coefficients Zb_basis : DoubleFourierSeries spectral basis for Z boundary coefficients mode : str one of 'real', 'spectral'. Whether bdry is specified in real or spectral space. Returns ------- cRb : ndarray spectral coefficients for R boundary cZb : ndarray spectral coefficients for Z boundary """ if mode == 'real': theta = bdry[:, 0] phi = bdry[:, 1] rho = np.ones_like(theta) nodes = np.array([rho, theta, phi]).T grid = Grid(nodes) Rb_transf = Transform(grid, Rb_basis) Zb_transf = Transform(grid, Zb_basis) # fit real data to spectral coefficients cRb = Rb_transf.fit(bdry[:, 2]) cZb = Zb_transf.fit(bdry[:, 3]) else: cRb = np.zeros((Rb_basis.num_modes,)) cZb = np.zeros((Zb_basis.num_modes,)) for m, n, bR, bZ in bdry: idx_R = np.where(np.logical_and(Rb_basis.modes[:, 1] == int(m), Rb_basis.modes[:, 2] == int(n)))[0] idx_Z = np.where(np.logical_and(Zb_basis.modes[:, 1] == int(m), Zb_basis.modes[:, 2] == int(n)))[0] cRb = put(cRb, idx_R, bR) cZb = put(cZb, idx_Z, bZ) return cRb, cZb # XXX: Note that this method cannot be improved with FFT due to non-uniform grid def compute_bdry_err(cR, cZ, cL, cRb, cZb, R1_transform, Z1_transform, L_transform, bdry_ratio): """Compute boundary error in (theta,phi) Fourier coefficients from non-uniform interpolation grid Parameters ---------- cR : ndarray, shape(RZ_transform.num_modes,) spectral coefficients of R cZ : ndarray, shape(RZ_transform.num_modes,) spectral coefficients of Z cL : ndarray, shape(L_transform.num_modes,) spectral coefficients of lambda cRb : ndarray, shape(bdry_basis.num_modes,) spectral coefficients of R boundary cZb : ndarray, shape(bdry_basis.num_modes,) spectral coefficients of Z boundary bdry_ratio : float fraction in range [0,1] of the full non-axisymmetric boundary to use R1_transform : Transform transforms cR to physical space at the boundary Z1_transform : Transform transforms cZ to physical space at the boundary L_transform : Transform transforms cL to physical space Returns ------- errR : ndarray, shape(N_bdry_pts,) vector of R errors in boundary spectral coeffs errZ : ndarray, shape(N_bdry_pts,) vector of Z errors in boundary spectral coeffs """ # coordinates rho = L_transform.grid.nodes[:, 0] vartheta = L_transform.grid.nodes[:, 1] zeta = L_transform.grid.nodes[:, 2] lamda = L_transform.transform(cL) theta = vartheta - lamda phi = zeta # cannot use Transform object with JAX nodes = jnp.array([rho, theta, phi]).T if L_transform.basis.sym == None: A = L_transform.basis.evaluate(nodes) pinv_R = jnp.linalg.pinv(A, rcond=1e-6) pinv_Z = pinv_R ratio_Rb = jnp.where(L_transform.basis.modes[:, 2] != 0, bdry_ratio, 1) ratio_Zb = ratio_Rb else: Rb_basis = DoubleFourierSeries( M=L_transform.basis.M, N=L_transform.basis.N, NFP=L_transform.basis.NFP, sym=Tristate(True)) Zb_basis = DoubleFourierSeries( M=L_transform.basis.M, N=L_transform.basis.N, NFP=L_transform.basis.NFP, sym=Tristate(False)) AR = Rb_basis.evaluate(nodes) AZ = Zb_basis.evaluate(nodes) pinv_R = jnp.linalg.pinv(AR, rcond=1e-6) pinv_Z = jnp.linalg.pinv(AZ, rcond=1e-6) ratio_Rb = jnp.where(Rb_basis.modes[:, 2] != 0, bdry_ratio, 1) ratio_Zb = jnp.where(Zb_basis.modes[:, 2] != 0, bdry_ratio, 1) # LCFS transform and fit R = R1_transform.transform(cR) Z = Z1_transform.transform(cZ) cR_lcfs = jnp.matmul(pinv_R, R) cZ_lcfs = jnp.matmul(pinv_Z, Z) # compute errors errR = cR_lcfs - cRb*ratio_Rb errZ = cZ_lcfs - cZb*ratio_Zb return errR, errZ # FIXME: this method might not be stable, but could yield speed improvements def compute_bdry_err_sfl(cR, cZ, cL, cRb, cZb, RZ_transform, L_transform, bdry_transform, bdry_ratio): """Compute boundary error in (theta,phi) Fourier coefficients from non-uniform interpolation grid Parameters ---------- cR : ndarray, shape(RZ_transform.num_modes,) spectral coefficients of R cZ : ndarray, shape(RZ_transform.num_modes,) spectral coefficients of Z cL : ndarray, shape(L_transform.num_modes,) spectral coefficients of lambda cRb : ndarray, shape(bdry_basis.num_modes,) spectral coefficients of R boundary cZb : ndarray, shape(bdry_basis.num_modes,) spectral coefficients of Z boundary bdry_ratio : float fraction in range [0,1] of the full non-axisymmetric boundary to use RZ_transform : Transform transforms cR and cZ to physical space L_transform : Transform transforms cL to physical space bdry_transform : Transform transforms cRb and cZb to physical space Returns ------- errR : ndarray, shape(N_bdry_pts,) vector of R errors in boundary spectral coeffs errZ : ndarray, shape(N_bdry_pts,) vector of Z errors in boundary spectral coeffs """ # coordinates rho = L_transform.grid.nodes[:, 0] vartheta = L_transform.grid.nodes[:, 1] zeta = L_transform.grid.nodes[:, 2] lamda = L_transform.transform(cL) theta = vartheta - lamda phi = zeta # boundary transform nodes = np.array([rho, theta, phi]).T grid = Grid(nodes) transf = Transform(grid, bdry_transform.basis) # transform to real space and fit back to sfl spectral basis R = transf.transform(cRb) Z = transf.transform(cZb) cRb_sfl = bdry_transform.fit(R) cZb_sfl = bdry_transform.fit(Z) # compute errors errR =
np.zeros_like(cRb_sfl)
numpy.zeros_like
import numpy as np ROWS, COLUMNS = 20, 10 TILES = np.array([ [[[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]], [[[0, 0, 0, 0], [7, 7, 7, 7], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0]], [[0, 0, 0, 0], [7, 7, 7, 7], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0], [0, 0, 7, 0]]], [[[0, 0, 0, 0], [2, 2, 2, 0], [0, 0, 2, 0], [0, 0, 0, 0]], [[0, 2, 0, 0], [0, 2, 0, 0], [2, 2, 0, 0], [0, 0, 0, 0]], [[2, 0, 0, 0], [2, 2, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 2, 2, 0], [0, 2, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0]]], [[[0, 0, 0, 0], [3, 3, 3, 0], [3, 0, 0, 0], [0, 0, 0, 0]], [[3, 3, 0, 0], [0, 3, 0, 0], [0, 3, 0, 0], [0, 0, 0, 0]], [[0, 0, 3, 0], [3, 3, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 3, 0, 0], [0, 3, 0, 0], [0, 3, 3, 0], [0, 0, 0, 0]]], [[[4, 4, 0, 0], [0, 4, 4, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 4, 0, 0], [4, 4, 0, 0], [4, 0, 0, 0], [0, 0, 0, 0]], [[4, 4, 0, 0], [0, 4, 4, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 4, 0, 0], [4, 4, 0, 0], [4, 0, 0, 0], [0, 0, 0, 0]]], [[[0, 5, 5, 0], [5, 5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[5, 0, 0, 0], [5, 5, 0, 0], [0, 5, 0, 0], [0, 0, 0, 0]], [[0, 5, 5, 0], [5, 5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[5, 0, 0, 0], [5, 5, 0, 0], [0, 5, 0, 0], [0, 0, 0, 0]]], [[[0, 6, 0, 0], [6, 6, 6, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 6, 0, 0], [0, 6, 6, 0], [0, 6, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [6, 6, 6, 0], [0, 6, 0, 0], [0, 0, 0, 0]], [[0, 6, 0, 0], [6, 6, 0, 0], [0, 6, 0, 0], [0, 0, 0, 0]]], ], dtype=np.int32) NUM_TILES = TILES.shape[0] TILE_SIZE = TILES.shape[-1] PADDING = TILE_SIZE - 1 # get the tiles indexed by positions def make_indices(positions): batch_size = positions.shape[0] # index upper left corner tile_indices = np.arange(TILE_SIZE, dtype=np.intp) # offset corner by tile position rows_offsets = positions[:, 0, np.newaxis] + tile_indices columns_offsets = positions[:, 1, np.newaxis] + tile_indices # generate indices, every '1' will be subject to broadcasting batch_index = np.arange(batch_size, dtype=np.intp).reshape((-1, 1, 1)) rows_index = rows_offsets.reshape((-1, TILE_SIZE, 1)) columns_index = columns_offsets.reshape((-1, 1, TILE_SIZE)) # return ready-to-use tuple return batch_index, rows_index, columns_index # test move for validity def test_multiple_tiles(boards, tiles, positions): indices = make_indices(positions) # cut tile location from board cutouts = boards[indices] # check for overlap return np.any(np.logical_and(tiles, cutouts), axis=(1, 2)) # insert tiles into the board def put_tiles_in_boards(boards, tiles, positions): indices = make_indices(positions) boards[indices] += tiles return boards # get depth maps def multiple_board_depths(boards): return (boards != 0).argmax(axis=1) # return maximum drop depth for a given tile def drop_depths(tiles, boards, positions): # get columns overlapping with tile tile_indices = np.arange(TILE_SIZE, dtype=np.intp) columns_offsets = positions[:, 1, np.newaxis] + tile_indices batch_index = np.arange(boards.shape[0], dtype=np.intp)[:, np.newaxis, np.newaxis] rows_index = np.arange(boards.shape[1], dtype=np.intp)[np.newaxis, :, np.newaxis] columns_index = columns_offsets[:, np.newaxis, :] # index board relevant_columns = boards[batch_index, rows_index, columns_index] # find downwards tile extent tile_extent = TILE_SIZE - np.argmax(tiles[:, ::-1, :], axis=1) # correct tile extent with the amount the tile has already dropped tile_extent += positions[:, 0, np.newaxis] # mask: true if field is below tile extent is_below_tile_extent = np.arange(relevant_columns.shape[1])[np.newaxis, :, np.newaxis] >= tile_extent[:, np.newaxis, :] # find first collision point below tile extent collisions = np.logical_and(relevant_columns != 0, is_below_tile_extent) collision_depths = np.argmax(collisions, axis=1) # find how much a tile can be dropped from its original position relative_collision_depths = collision_depths - tile_extent # filter out columns which the tile does not overlap by setting depth to max no_overlap = np.logical_not(np.any(tiles, axis=1)) relevant_relative_collision_depths = np.where(no_overlap, ROWS, relative_collision_depths) # the drop depth is the minimum collision depth over the valid columns depths = np.min(relevant_relative_collision_depths, axis=1) return depths # clear full rows def clear_multiple_boards(boards): keep = np.logical_not(
np.all(boards, axis=2)
numpy.all
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from gnpy.core.utils import (load_json, itufs, freq2wavelength, lin2db, db2lin) from gnpy.core import network topology = load_json('edfa_example_network.json') nw = network.network_from_json(topology) pch2d_legend_data = np.loadtxt('Pchan2DLegend.txt') pch2d = np.loadtxt('Pchan2D.txt') ch_spacing = 0.05 fc = itufs(ch_spacing) lc = freq2wavelength(fc) / 1000 nchan = np.arange(len(lc)) df = np.ones(len(lc)) * ch_spacing edfa1 = [n for n in nw.nodes() if n.uid == 'Edfa1'][0] edfa1.gain_target = 20.0 edfa1.tilt_target = -0.7 edfa1.calc_nf() results = [] for Pin in pch2d: chgain = edfa1.gain_profile(Pin) pase = edfa1.noise_profile(chgain, fc, df) pout = lin2db(db2lin(Pin + chgain) + db2lin(pase)) results.append(pout) # Generate legend text pch2d_legend = [] for ea in pch2d_legend_data: s = ''.join([chr(xx) for xx in ea.astype(dtype=int)]).strip() pch2d_legend.append(s) # Plot axis_font = {'fontname': 'Arial', 'size': '16', 'fontweight': 'bold'} title_font = {'fontname': 'Arial', 'size': '17', 'fontweight': 'bold'} tic_font = {'fontname': 'Arial', 'size': '12'} plt.rcParams["font.family"] = "Arial" plt.figure() plt.plot(nchan, pch2d.T, '.-', lw=2) plt.xlabel('Channel Number', **axis_font) plt.ylabel('Channel Power [dBm]', **axis_font) plt.title('Input Power Profiles for Different Channel Loading', **title_font) plt.legend(pch2d_legend, loc=5) plt.grid() plt.ylim((-100, -10)) plt.xlim((0, 110)) plt.xticks(np.arange(0, 100, 10), **tic_font) plt.yticks(
np.arange(-110, -10, 10)
numpy.arange
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from datetime import timedelta from hypothesis import given, settings, strategies as st from hypothesis.extra.numpy import arrays, array_shapes import numpy as np from numpy.testing import assert_allclose import pytest from cotede.fuzzy import fuzzy_uncertainty from ..qctests.compare import compare_compound_feature_input_types CFG = { "output": { "low": {"type": "trimf", "params": [0.0, 0.225, 0.45]}, "medium": {"type": "trimf", "params": [0.275, 0.5, 0.725]}, "high": {"type": "smf", "params": [0.55, 0.775]}, }, "features": { "f1": { "weight": 1, "low": {"type": "zmf", "params": [0.07, 0.2]}, "medium": {"type": "trapmf", "params": [0.07, 0.2, 2, 6]}, "high": {"type": "smf", "params": [2, 6]}, }, "f2": { "weight": 1, "low": {"type": "zmf", "params": [3, 4]}, "medium": {"type": "trapmf", "params": [3, 4, 5, 6]}, "high": {"type": "smf", "params": [5, 6]}, }, "f3": { "weight": 1, "low": {"type": "zmf", "params": [0.5, 1.5]}, "medium": {"type": "trapmf", "params": [0.5, 1.5, 3, 4]}, "high": {"type": "smf", "params": [3, 4]}, }, }, } def test_fuzzy_uncertainty(): features = {"f1": np.array([1.0]), "f2":
np.array([5.2])
numpy.array
# %% import numpy as np import csv # import predict as util # %% w1 = np.matrix([ [0.01, 0.05, 0.07], [0.2, 0.041, 0.11], [0.04, 0.56, 0.13], [0.1, 0.1, 0.1] ]) w2 = np.matrix([ [0.04, 0.78], [0.4, 0.45], [0.65, 0.23], [0.1, 0.1] ]) w3 = np.matrix([ [0.04], [0.41], [0.1] ]) x_size=4 z1_size=6 z2_size=6 z3_size=4 w1=np.random.normal(-1,1,(x_size,z1_size)) w2=np.random.normal(-1,1,(z1_size+1,z2_size)) w3=np.random.normal(-1,1,(z2_size+1,z3_size)) # x=[0.1, -0.1, -0.22, 0.3] # x=np.random.randint(7, size=(10,4))/3.5-1 x=np.random.normal(-1,1,(2,x_size)) z2 = np.dot(x, w1) a2 = np.tanh(z2) ba2 = np.ones((x.shape[0], 1)) a2 = np.concatenate((a2, ba2), axis=1) z3 = np.dot(a2, w2) a3 = np.tanh(z3) # we add the the 1 unit (bias) at the output of the second layer ba3 = np.ones((a3.shape[0], 1)) a3 = np.concatenate((a3, ba3), axis=1) # output layer, prediction of our network z4 = np.dot(a3, w3) a4 = np.tanh(z4) r = [] for a_ in a4: r.append(np.where(a_ ==
np.amax(a_)
numpy.amax
# -*- coding: utf-8 -*- """ Unit tests for the kCSD methods This was written by : <NAME>, Laboratory of Neuroinformatics, Nencki Institute of Exprimental Biology, Warsaw. :license: Modified BSD, see LICENSE.txt for details. """ import unittest import numpy as np from kcsd import ValidateKCSD1D, ValidateKCSD2D, ValidateKCSD3D from kcsd import csd_profile as CSD from kcsd import KCSD1D, KCSD2D, MoIKCSD, KCSD3D class KCSD1D_TestCase(unittest.TestCase): def setUp(self): dim = 1 utils = ValidateKCSD1D(csd_seed=42) self.ele_pos = utils.generate_electrodes(total_ele=10, ele_lims=[0.1, 0.9]) self.csd_profile = CSD.gauss_1d_mono self.csd_at, self.csd = utils.generate_csd(self.csd_profile, csd_seed=42) pots = utils.calculate_potential(self.csd, self.csd_at, self.ele_pos, h=1., sigma=0.3) self.pots = np.reshape(pots, (-1, 1)) self.test_method = 'KCSD1D' self.test_params = {'h': 1., 'sigma': 0.3, 'R_init': 0.2, 'n_src_init': 100, 'xmin': 0., 'xmax': 1.,} def test_kcsd1d_estimate(self, cv_params={}): self.test_params.update(cv_params) result = KCSD1D(self.ele_pos, self.pots, **self.test_params) result.cross_validate() vals = result.values() true_csd = self.csd_profile(result.estm_x, 42) rms = np.linalg.norm(
np.array(vals[:, 0])
numpy.array
import numpy as np import theano from theano import tensor as tt import pymc3 as pm from pymc3.distributions.dist_math import rho2sd, log_normal, log_normal_mv from pymc3.variational.opvi import Approximation from pymc3.theanof import memoize __all__ = [ 'MeanField', 'FullRank', 'Empirical', 'sample_approx' ] class MeanField(Approximation): """Mean Field approximation to the posterior where spherical Gaussian family is fitted to minimize KL divergence from True posterior. It is assumed that latent space variables are uncorrelated that is the main drawback of the method Parameters ---------- local_rv : dict[var->tuple] mapping {model_variable -> local_variable (:math:`\\mu`, :math:`\\rho`)} Local Vars are used for Autoencoding Variational Bayes See (AEVB; Kingma and Welling, 2014) for details model : :class:`pymc3.Model` PyMC3 model for inference start : `Point` initial mean cost_part_grad_scale : `scalar` Scaling score part of gradient can be useful near optimum for archiving better convergence properties. Common schedule is 1 at the start and 0 in the end. So slow decay will be ok. See (Sticking the Landing; <NAME>, <NAME>, <NAME>, 2016) for details scale_cost_to_minibatch : `bool` Scale cost to minibatch instead of full dataset, default False random_seed : None or int leave None to use package global RandomStream or other valid value to create instance specific one References ---------- - <NAME>, <NAME>, <NAME>, 2016 Sticking the Landing: A Simple Reduced-Variance Gradient for ADVI approximateinference.org/accepted/RoederEtAl2016.pdf """ @property def mean(self): return self.shared_params['mu'] @property def rho(self): return self.shared_params['rho'] @property def cov(self): return tt.diag(rho2sd(self.rho)**2) @property def std(self): return rho2sd(self.rho) def create_shared_params(self, **kwargs): start = kwargs.get('start') if start is None: start = self.model.test_point else: start_ = self.model.test_point.copy() pm.sampling._update_start_vals(start_, start, self.model) start = start_ start = self.gbij.map(start) return {'mu': theano.shared( pm.floatX(start), 'mu'), 'rho': theano.shared( np.zeros((self.global_size,), dtype=theano.config.floatX), 'rho') } def log_q_W_global(self, z): """ log_q_W samples over q for global vars """ mu = self.scale_grad(self.mean) rho = self.scale_grad(self.rho) z = z[self.global_slc] logq = tt.sum(log_normal(z, mu, rho=rho)) return logq def random_global(self, size=None, no_rand=False): initial = self.initial(size, no_rand, l=self.global_size) sd = rho2sd(self.rho) mu = self.mean return sd * initial + mu class FullRank(Approximation): """Full Rank approximation to the posterior where Multivariate Gaussian family is fitted to minimize KL divergence from True posterior. In contrast to MeanField approach correlations between variables are taken in account. The main drawback of the method is computational cost. Parameters ---------- local_rv : dict[var->tuple] mapping {model_variable -> local_variable (:math:`\\mu`, :math:`\\rho`)} Local Vars are used for Autoencoding Variational Bayes See (AEVB; Kingma and Welling, 2014) for details model : PyMC3 model for inference start : Point initial mean cost_part_grad_scale : float or scalar tensor Scaling score part of gradient can be useful near optimum for archiving better convergence properties. Common schedule is 1 at the start and 0 in the end. So slow decay will be ok. See (Sticking the Landing; <NAME>, <NAME>, <NAME>, 2016) for details scale_cost_to_minibatch : bool, default False Scale cost to minibatch instead of full dataset random_seed : None or int leave None to use package global RandomStream or other valid value to create instance specific one Other Parameters ---------------- gpu_compat : bool use GPU compatible version or not References ---------- - <NAME>, <NAME>, <NAME>, 2016 Sticking the Landing: A Simple Reduced-Variance Gradient for ADVI approximateinference.org/accepted/RoederEtAl2016.pdf """ def __init__(self, local_rv=None, model=None, cost_part_grad_scale=1, scale_cost_to_minibatch=False, gpu_compat=False, random_seed=None, **kwargs): super(FullRank, self).__init__( local_rv=local_rv, model=model, cost_part_grad_scale=cost_part_grad_scale, scale_cost_to_minibatch=scale_cost_to_minibatch, random_seed=random_seed, **kwargs ) self.gpu_compat = gpu_compat @property def L(self): return self.shared_params['L_tril'][self.tril_index_matrix] @property def mean(self): return self.shared_params['mu'] @property def cov(self): L = self.L return L.dot(L.T) @property def num_tril_entries(self): n = self.global_size return int(n * (n + 1) / 2) @property def tril_index_matrix(self): n = self.global_size num_tril_entries = self.num_tril_entries tril_index_matrix = np.zeros([n, n], dtype=int) tril_index_matrix[np.tril_indices(n)] = np.arange(num_tril_entries) tril_index_matrix[np.tril_indices(n)[::-1]] =
np.arange(num_tril_entries)
numpy.arange
""" initialize.py Initializes grid """ import sys sys.path.append("..") import numpy as np from ..common.NC import NC def initialize(self, DISP=False, factor=True): #Number of points self.Na = (self.NP-1) * self.NMa + 1 self.Nr = (self.NP-1) * self.NMr + 1 self.Nelem = self.Na * self.Nr #Coordinate properties self.xa = np.linspace(0, np.pi, self.Na+1) self.ha = self.xa[1] - self.xa[0] self.xa = self.xa + self.ha/2 self.xa = self.xa[:-1] self.xa = (self.xa - np.flipud(self.xa - np.pi))/2 self.xr = np.linspace(0, self.L, self.Nr+1) self.hr = self.xr[1] - self.xr[0] self.xr = self.xr + self.hr/2 self.xr = self.xr[:-1] Nrange = len(self.i1) #Boundary region self.bcN = int(np.floor(max([self.i1.shape[0], self.i2.shape[0]])/2)) self.bXr = np.linspace(1, self.bcN,self.bcN)*self.hr + self.xr[-1] self.bXr, self.bXa = np.meshgrid(self.bXr, self.xa) self.bXa = np.reshape(self.bXa, self.Na * self.bcN, order="F") self.bXr = np.reshape(self.bXr, self.Na * self.bcN, order="F") #Second grid self.Xr, self.Xa = np.meshgrid(self.xr, self.xa) self.Xa = np.reshape(self.Xa, self.Na * self.Nr, order="F") self.Xr =
np.reshape(self.Xr, self.Na * self.Nr, order="F")
numpy.reshape
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified). __all__ = ['grid_search', 'random_search', 'latin_hyper_cube', 'jittered_sampling', 'multi_jittered', 'is_valid', 'poisson_disk'] # Cell import numpy as np import matplotlib.pyplot as plt # Cell plt.style.use("bmh") plt.rcParams["figure.figsize"] = (10, 10) # Cell def grid_search(x_range, y_range, n=10): visited = set() iteration = 0 while True: divisions = 2 ** iteration + 1 x = np.linspace(*x_range, divisions) y = np.linspace(*y_range, divisions)[::-1] mesh = np.array(np.meshgrid(x, y)) mesh_reshaped = mesh.reshape(2, divisions**2).T for point in mesh_reshaped: point_tuple = tuple(point) if point_tuple not in visited: visited.add(point_tuple) yield point if len(visited) == n: return iteration += 1 # Cell def random_search(x_range, y_range, n=10, seed=42): RNG = np.random.default_rng(seed) xs, ys = RNG.uniform(0, 1, size=(n, 2)).T x_lower, x_upper = x_range xs = xs * (x_upper - x_lower) + x_lower y_lower, y_upper = y_range ys = ys * (y_upper - y_lower) + y_lower for point in zip(xs, ys): yield point # Cell def latin_hyper_cube(x_range, y_range, n=10, seed=42): x_lower, x_upper = x_range y_lower, y_upper = y_range visited = set() iteration = 0 RNG_x = np.random.default_rng(seed) RNG_y = np.random.default_rng(seed+1) RNG_shuffler = np.random.default_rng(seed+2) RNG_init = np.random.default_rng(seed) divisions = 2 limits = np.linspace(0, 1, divisions+1) lower_limits = limits[:-1] upper_limits = limits[1:] xs, ys = zip(*RNG_init.uniform(low=lower_limits, high=upper_limits, size=(2, divisions)).T) xs = np.array(xs) ys = np.array(ys) RNG_shuffler.shuffle(ys) for point in zip(xs, ys): visited.add(tuple(point)) x_scale = point[0] * (x_upper - x_lower) + x_lower y_scale = point[1] * (y_upper - y_lower) + y_lower yield (x_scale, y_scale) if len(visited) >= n: return while True: divisions *= 2 limits = np.linspace(0, 1, divisions+1) lower_limits = limits[:-1] upper_limits = limits[1:] indexes_empty_x = [] indexes_empty_y = [] for index, (lower, upper) in enumerate(zip(lower_limits, upper_limits)): is_occupied_x = any(lower < point[0] < upper for point in visited) indexes_empty_x.append(is_occupied_x) is_occupied_y = any(lower < point[1] < upper for point in visited) indexes_empty_y.append(is_occupied_y) indexes_empty_x = np.array(indexes_empty_x) indexes_empty_y = np.array(indexes_empty_y) xs = RNG_x.uniform(low=lower_limits[~indexes_empty_x], high=upper_limits[~indexes_empty_x]) ys = RNG_y.uniform(low=lower_limits[~indexes_empty_y], high=upper_limits[~indexes_empty_y]) RNG_shuffler.shuffle(ys) for point in zip(xs, ys): visited.add(tuple(point)) x_scale = point[0] * (x_upper - x_lower) + x_lower y_scale = point[1] * (y_upper - y_lower) + y_lower yield (x_scale, y_scale) if len(visited) >= n: return # Cell def jittered_sampling(x_range, y_range, n=10, seed=42): x_lower, x_upper = x_range y_lower, y_upper = y_range visited = set() iteration = 0 RNG_x = np.random.default_rng(seed) RNG_y = np.random.default_rng(seed+1) RNG_shuffler = np.random.default_rng(seed+2) RNG_init = np.random.default_rng(seed) divisions = 2 limits = np.linspace(0, 1, divisions+1) lower_limits, upper_limits = limits[:-1], limits[1:] for lower_x, upper_x in zip(lower_limits, upper_limits): for lower_y, upper_y in zip(lower_limits, upper_limits): x = RNG_x.uniform(low=lower_x, high=upper_x) y = RNG_y.uniform(low=lower_y, high=upper_y) point = (x, y) visited.add(point) x_scale = x * (x_upper - x_lower) + x_lower y_scale = y * (y_upper - y_lower) + y_lower yield (x_scale, y_scale) if len(visited) >= n: return while True: divisions *= 2 limits = np.linspace(0, 1, divisions+1) lower_limits, upper_limits = limits[:-1], limits[1:] for lower_x, upper_x in zip(lower_limits, upper_limits): for lower_y, upper_y in zip(lower_limits, upper_limits): empty = not any(lower_x < point[0] < upper_x and lower_y < point[1] < upper_y for point in visited) if empty: x = RNG_x.uniform(low=lower_x, high=upper_x) y = RNG_y.uniform(low=lower_y, high=upper_y) point = (x, y) visited.add(point) x_scale = x * (x_upper - x_lower) + x_lower y_scale = y * (y_upper - y_lower) + y_lower yield (x_scale, y_scale) if len(visited) >= n: return # Cell def multi_jittered(x_range, y_range, n=10, seed=42): x_lower, x_upper = x_range y_lower, y_upper = y_range RNG_x = np.random.default_rng(seed) RNG_y = np.random.default_rng(seed+1) RNG_shuffler_x = np.random.default_rng(seed+2) RNG_shuffler_y = np.random.default_rng(seed+3) side = int(n ** 0.5 + 0.5) resolution_x, resolution_y = (side, side) cells = resolution_x * resolution_y xs_ = np.linspace(0, 1, resolution_x, endpoint=False) ys_ = np.linspace(0, 1, resolution_y, endpoint=False) xs, ys = np.meshgrid(xs_, ys_) xs = (xs.T + ys_ / resolution_x).T ys = ys + xs_ / resolution_y xs += RNG_x.random(size=xs.shape) / cells ys += RNG_y.random(size=ys.shape) / cells RNG_shuffler_x.shuffle(xs.T) RNG_shuffler_y.shuffle(ys) xs_flat = np.ndarray.flatten(xs) ys_flat = np.ndarray.flatten(ys) points = 0 for x, y in zip(xs_flat, ys_flat): x_scale = x * (x_upper - x_lower) + x_lower y_scale = y * (y_upper - y_lower) + y_lower yield (x_scale, y_scale) points += 1 if points >= n: return # Cell def is_valid(x, y, points, radius): if len(points) == 0: return True new_center = np.array([x, y]) for point in points: center = np.array(point) if np.linalg.norm(center - new_center) <= radius: return False return True def poisson_disk(x_range, y_range, n=10, seed=42, tries=1e3): x_lower, x_upper = x_range y_lower, y_upper = y_range visited = set() RNG_x = np.random.default_rng(seed) RNG_y =
np.random.default_rng(seed+1)
numpy.random.default_rng
from metrics import Metric import os import numpy as np import cv2 import matplotlib as mpl import matplotlib.cm as cm import json from scipy.stats import binned_statistic_2d from scipy.interpolate import NearestNDInterpolator, LinearNDInterpolator import time import warnings warnings.filterwarnings("ignore", category=RuntimeWarning) class Evaluator: def __init__(self, data_root, rgb_shape=(1024, 1920), gated_shape=(720, 1280), bfl_rgb=0.202993 * 2355.722801, bfl_gated=0.202993 * 2322.4, clip_min=0.001, clip_max=28., nb_bins=14): self.data_root = data_root self.gated_height, self.gated_width = gated_shape self.rgb_height, self.rgb_width = rgb_shape self.bfl_rgb = bfl_rgb # baseline times focal length self.bfl_gated = bfl_gated # baseline times focal length self.clip_min = clip_min self.clip_max = clip_max self.metric = Metric() self.fov_h_camera = 40 self.fov_v_camera = 23 self.nb_metrics = len(Metric.get_header()) self.bins, self.mean_bins = self.calc_bins(self.clip_min, self.clip_max, nb_bins) self.frames = { 'monodepth': 'rgb_left', 'semodepth': 'rgb_left', 'psmnet': 'rgb_left', 'unsup': 'rgb_left', 'sparse2dense': 'rgb_left', 'sgm': 'rgb_left', 'lidar_hdl64_rgb_left': 'rgb_left', 'depth': 'rgb_left', 'intermetric': 'rgb_left', } self.crops = { # 'rgb_left': [215, 330, 44, 230], # top, right, bottom, left 'rgb_left': [270, 20, 20, 170], # top, right, bottom, left 'gated': [0, 0, 0, 0], # top, right, bottom, left } @staticmethod def calc_bins(clip_min, clip_max, nb_bins): bins = np.linspace(clip_min, clip_max, num=nb_bins + 1) mean_bins = np.array([0.5 * (bins[i + 1] + bins[i]) for i in range(0, nb_bins)]) return bins, mean_bins @staticmethod def interpolate(depth, method='nearest'): current_coordinates = np.where(depth > 0) missing_coordinates = np.where(depth == 0) if len(missing_coordinates[0]) > 0: current_depth = depth[current_coordinates] if method == 'nearest': interpolator = NearestNDInterpolator(current_coordinates, current_depth) elif method == 'linear': interpolator = LinearNDInterpolator(current_coordinates, current_depth, ) depth[missing_coordinates] = interpolator(missing_coordinates) return depth def disparity2depth(self, disparity, domain='rgb'): depth = np.zeros(disparity.shape) depth[disparity == 0] = float('inf') if domain == 'rgb': depth[disparity != 0] = self.bfl_rgb / disparity[disparity != 0] if domain == 'gated': depth[disparity != 0] = self.bfl_gated / disparity[disparity != 0] return depth def crop_rgb_to_gated(self, rgb): rgb = rgb[215:980, 230:1590] return rgb def crop_eval_region(self, img, frame): crop = self.crops[frame] img = img[crop[0]:(img.shape[0] - crop[2]), crop[3]:(img.shape[1] - crop[1])] return img def evaluate_samples(self, samples, approach): metrics = np.zeros((len(samples), self.nb_metrics)) for idx, sample in enumerate(samples): metrics[idx, :] = self.evaluate_sample(sample, approach, gt_type='intermetric') metrics = np.mean(metrics, axis=0) return metrics def evaluate_samples_binned(self, samples, approach): metrics = np.zeros((len(samples), len(self.mean_bins) + 1, self.nb_metrics + 1)) for idx, sample in enumerate(samples): metrics[idx, :, :] = self.evaluate_sample_binned(sample, approach, gt_type='intermetric') metrics = np.mean(metrics, axis=0) return metrics def evaluate_sample(self, sample, approach, gt_type='intermetric'): depth_gt = self.load_depth_groundtruth(sample.split('_')[0], frame=self.frames[approach], gt_type=gt_type) depth = self.load_depth(sample, approach) return self.metric.calc_metrics(depth, depth_gt, clip_min=self.clip_min, clip_max=self.clip_max) def evaluate_sample_binned(self, sample, approach, gt_type='intermetric'): depth_gt = self.load_depth_groundtruth(sample.split('_')[0], frame=self.frames[approach], gt_type=gt_type).flatten() depth = self.load_depth(sample, approach).flatten() results = np.vstack([depth, depth_gt]) if len(self.bins) == 1: inds = np.zeros((results.shape[-1],), dtype=int) else: inds = np.digitize(results[1, :], self.bins) error_binned = np.zeros((len(self.bins) - 1, self.nb_metrics)) for i, bin in enumerate(self.bins[:-1]): try: metrics = self.metric.calc_metrics(results[0, inds == i], results[1, inds == i], clip_min=self.clip_min, clip_max=self.clip_max) error_binned[i, :] = metrics except ValueError: error_binned[i, :] = np.nan mean_error_binned = np.zeros((self.nb_metrics,)) for i in range(0, self.nb_metrics): mean_error_binned[i] = np.mean(error_binned[~np.isnan(error_binned[:, i]), i]) error_binned = np.hstack([self.mean_bins.reshape((-1, 1)), error_binned]) mean_error_binned = np.hstack([np.zeros((1,)), mean_error_binned]) metric = np.vstack([mean_error_binned, error_binned]) return metric def error_image(self, sample, approach, gt_type='intermetric'): groundtruth = self.load_depth_groundtruth(sample.split('_')[0], frame=self.frames[approach], gt_type=gt_type) output = self.load_depth(sample, approach) error_image = np.zeros(groundtruth.shape) eval_pos = np.logical_and(groundtruth > 0, output > 0) output = output[eval_pos] groundtruth = groundtruth[eval_pos] output = np.clip(output, self.clip_min, self.clip_max) groundtruth = np.clip(groundtruth, self.clip_min, self.clip_max) error_image[eval_pos] = np.abs(output - groundtruth) norm = mpl.colors.Normalize(vmin=0, vmax=self.clip_max - self.clip_min) cmap = cm.hot m = cm.ScalarMappable(norm=norm, cmap=cmap) error_image = m.to_rgba(error_image)[:, :, 0:3] error_image[~eval_pos] = (0, 0, 0) error_image = cv2.cvtColor((255 * error_image).astype(np.uint8), cv2.COLOR_BGR2RGB) return error_image def depth2points(self, depth, P): inv_projection_matrix = np.linalg.inv(P) idx = np.indices((depth.shape[0], depth.shape[1])) index_matrix = np.vstack((idx[1].flatten(), idx[0].flatten(), np.ones((depth.shape[0] * depth.shape[1])))) points = depth.flatten() * np.matmul(inv_projection_matrix, index_matrix) points = points[:, depth.flatten() != 0] return points def create_top_view(self, sample, approach): output = self.load_depth(sample, approach) if self.frames[approach] == 'rgb_left': calib_file = 'calib/calib_cam_stereo_left.json' elif self.frames[approach] == 'gated': calib_file = 'calib/calib_gated_bwv.json' with open(calib_file, 'r') as f: calib = json.load(f) P = np.array(calib['P']).reshape(3, 4)[:, 0:3] P_scaling = np.array([[1, 0, -self.crops[self.frames[approach]][3]], [0, 1, -self.crops[self.frames[approach]][0]], [0, 0, 1]]) P = np.dot(P_scaling, P) pc = self.depth2points(output, P).transpose() temp = pc.copy() pc[:, 0] = temp[:, 2] # x to the front pc[:, 1] = -temp[:, 0] # y to the left pc[:, 2] = -temp[:, 1] # z to the top fov_h_camera = 40 fov_v_camera = 23 xbins = 231 ybins = 101 bins = [np.linspace(5, 28, xbins), np.linspace(-5, 5, ybins)] top_view, xedges, yedges, _ = binned_statistic_2d(pc[:, 0], pc[:, 1], pc[:, 2], 'count', bins) xbins_middle = np.array([0.5 * (xedges[i] + xedges[i + 1]) for i in range(len(xedges) - 1)]) fov_area = np.tan(0.5 * np.deg2rad(fov_h_camera)) * np.tan( 0.5 * np.deg2rad(self.fov_v_camera)) * xbins_middle ** 2 fov_area = np.tile(fov_area, (ybins - 1, 1)).transpose() top_view = fov_area * top_view top_view_norm = mpl.colors.Normalize(vmin=0, vmax=pc.shape[0] / 220.0) t = cm.ScalarMappable(norm=top_view_norm, cmap=cm.jet) top_view_color = t.to_rgba(top_view)[:, :, 0:3] top_view = np.rot90(top_view, axes=(0, 1)) top_view_color = np.rot90(top_view_color, axes=(0, 1)) top_view_color = cv2.cvtColor((255 * top_view_color).astype(np.uint8), cv2.COLOR_BGR2RGB) return top_view, top_view_color def load_depth_groundtruth(self, scene, frame='rgb_left', gt_type='intermetric'): if gt_type == 'intermetric': path = os.path.join(self.data_root, 'intermetric_{}'.format(frame), scene + '.npz') elif gt_type == 'lidar': path = os.path.join(self.data_root, 'lidar_hdl64_{}'.format(frame), scene + '.npz') depth = np.load(path)['arr_0'] depth = self.crop_eval_region(depth, frame) return depth def load_depth(self, sample, approach, interpolate=True): if approach == 'intermetric': path = os.path.join(self.data_root, approach + '_' + self.frames[approach], sample + '.npz') else: path = os.path.join(self.data_root, approach, sample + '.npz') depth = np.load(path)['arr_0'] depth = self.pp_depth(depth, approach, interpolate=interpolate) return depth def pp_depth(self, depth, approach, interpolate=True): if approach == 'monodepth': disparity = depth disparity = cv2.resize(disparity, (self.rgb_width, self.rgb_height), interpolation=cv2.INTER_AREA) disparity = disparity * self.rgb_width # it provides relative disparity depth = self.disparity2depth(disparity, domain='rgb') elif approach == 'semodepth': disparity = np.squeeze(depth) # disparity = np.squeeze(disparity) / 960 disparity = cv2.resize(disparity, (self.rgb_width, self.rgb_height), interpolation=cv2.INTER_AREA) # disparity = disparity * self.rgb_width depth = self.disparity2depth(disparity, domain='rgb') elif approach == 'psmnet': disparity = depth disparity = disparity / 960 disparity = cv2.resize(disparity, (self.rgb_width, self.rgb_height), interpolation=cv2.INTER_AREA) disparity = disparity * self.rgb_width depth = self.disparity2depth(disparity, domain='rgb') elif approach == 'unsup': disparity = depth disparity = cv2.resize(disparity, (self.rgb_width, self.rgb_height), interpolation=cv2.INTER_AREA) disparity = disparity * self.rgb_width # it provides relative disparity depth = self.disparity2depth(disparity, domain='rgb') elif approach == 'gated2depth': depth =
np.squeeze(depth['arr_0'])
numpy.squeeze
# Licensed under an MIT open source license - see LICENSE from fil_finder import fil_finder_2D from fil_finder.width_profiles import filament_profile from fil_finder.utilities import eight_con from astropy.io import fits import astropy.units as u import numpy as np import scipy.ndimage as nd import matplotlib.pyplot as p ''' Example of the new radial profiling code for FilFinder. This functionality is still in testing! ''' hdu = fits.open("filaments_updatedhdr.fits")[0] img, hdr = hdu.data, hdu.header # Add some noise
np.random.seed(500)
numpy.random.seed
import gym import numpy as np class TicTacToeEnvV2(gym.Env): metadata = {'render.modes': ['human']} reward_range = (-10, 10) spec = None # Set these in ALL subclasses action_space = gym.spaces.Discrete(1) observation_space = gym.spaces.Discrete(9) def __init__(self): self.turn = None self.state = None self.done = None self.winner = None def step(self, action: int): if self.state[action] != 0: self.done = True reward = -10 return self.state, reward, self.done, {'illegal_action': True} self.state[action] = self.turn is_winner = self.is_winner() reward = 10 if is_winner else -1 if is_winner: self.winner = self.turn self.done = is_winner or self.is_done() self.turn *= -1 return self.state, reward, self.done, {} def reset(self): self.state =
np.zeros(9)
numpy.zeros
import argparse import json import os.path as osp from sklearn.metrics import confusion_matrix from sklearn.neighbors import KDTree from sklearn.preprocessing import normalize import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from itertools import chain import networkx as nx import random import torch from torch.utils.data import DataLoader from models.resnet import make_resnet50_base import sys sys.path.insert(1, "./ZSL _DataSets") from image_folder import ImageFolder from utils import set_gpu, pick_vectors from utlis_graph_zsl import get_classes, classes_split class ImagesEmbeddings: def __init__(self, args, data_path, split_path, save_path): self.data_path = data_path self.split_path = split_path self.images_embed_path = osp.join(save_path, 'matrix_embeds.npy') self.dict_image_embed_path = osp.join(save_path, 'dict_image_embed.npy') self.dict_image_class_path = osp.join(save_path, 'dict_image_class.npy') self.classes_path = osp.join(save_path, 'classes_ordered.npy') self.args = args self.seen_classes, self.unseen_classes = self.classes() self.dict_name_class, self.dict_class_name = self.classes_names_translation() self.cnn = self.cnn_maker() def classes(self): seen_classes, unseen_classes = classes_split(self.args.dataset, self.data_path, self.split_path) return seen_classes, unseen_classes def classes_names_translation(self): awa2_split = json.load(open(self.split_path, 'r')) train_names = awa2_split['train_names'] test_names = awa2_split['test_names'] seen_classes, unseen_classes = self.classes() dict_name_class = {name: c for name, c in zip(chain(train_names, test_names), chain(seen_classes, unseen_classes))} dict_class_name = {c: name for name, c in zip(chain(train_names, test_names), chain(seen_classes, unseen_classes))} return dict_name_class, dict_class_name def cnn_maker(self): cnn = make_resnet50_base() cnn.load_state_dict(torch.load(self.args.cnn)) if self.args.gpu == 0: cnn = cnn.cuda() cnn.eval() return cnn def one_class_images_embed(self, dataset, embed_matrix, count): loader = DataLoader(dataset=dataset, batch_size=32, shuffle=False, num_workers=2) c = 0 for batch_id, batch in enumerate(loader, 1): data, label = batch if cuda: data = data.cuda() with torch.no_grad(): embeds = self.cnn(data) embed_matrix[c:c + loader.batch_size, :] = embeds # (batch_size, d) count += loader.batch_size c += loader.batch_size return embed_matrix, count def images_embed_calculator(self): action = 'test' classes = np.array([]) if osp.exists(self.images_embed_path) and True: embeds_matrix = np.load(self.images_embed_path, allow_pickle=True) dict_image_class = np.load(self.dict_image_class_path, allow_pickle=True).item() dict_image_embed = np.load(self.dict_image_embed_path, allow_pickle=True).item() else: count = 0 for i, name in enumerate( chain(self.dict_class_name[self.unseen_classes], self.dict_class_name[self.seen_classes])): dataset = ImageFolder(osp.join(self.data_path, 'images'), [name], f'{action}') embed_matrix = torch.tensor(np.zeros((len(dataset), 2048))) classes = np.concatenate((classes, np.repeat(name, len(dataset)))) embed_matrix, count = self.one_class_images_embed(dataset, embed_matrix, count) b = np.array(dataset.data).T[0] im = np.array([item.split('/')[-1].split('.')[0] for item in b]) if i == 0: embeds_matrix = embed_matrix ims = im else: embeds_matrix = torch.cat((embeds_matrix, embed_matrix), 1) ims = np.concatenate((ims, im)) dict_image_class = dict(zip(ims, classes)) dict_image_embed = dict(zip(ims, embeds_matrix.numpy())) np.save(self.images_embed_path, embeds_matrix) np.save(self.dict_image_class_path, dict_image_class) np.save(self.dict_image_embed_path, dict_image_embed) return embeds_matrix, dict_image_embed, dict_image_class class Awa2GraphCreator: def __init__(self, embed_matrix, dict_image_embed, dict_name_class, dict_idx_image_class, images_nodes_percentage, args): self.image_graph_path = 'save_data_graph/awa2/image_graph.gpickle' self.pre_knowledge_graph_path = 'materials/imagenet-induced-graph.json' self.knowledge_graph_path = 'save_data_graph/awa2/knowledge_graph.gpickle' self.dict_wnids_class_translation = dict_name_class self.embeddings = normalize(embed_matrix, norm='l2', axis=0) self.dict_image_embed = dict_image_embed self.images = list(dict_image_embed.keys()) self.dict_idx_image_class = dict_idx_image_class self.images_nodes_percentage = images_nodes_percentage self.args = args def index_embed_transform(self): dict_index_embed = {i: item for i, item in enumerate(self.images)} dict_embed_index = {item: i for i, item in enumerate(self.images)} return dict_index_embed, dict_embed_index def create_image_graph(self): if osp.exists(self.image_graph_path) and True: image_gnx = nx.read_gpickle(self.image_graph_path) else: image_gnx = nx.Graph() kdt = KDTree(self.embeddings, leaf_size=40) # image_graph.add_nodes_from(np.arange(len(self.embeddings))) count = 0 for i in range(len(self.embeddings)): neighbors, distances = kdt.query_radius(self.embeddings[i:i + 1], r=self.args.images_threshold, return_distance=True) if len(neighbors[0]) == 1: distances, neighbors = kdt.query(self.embeddings[i:i + 1], k=2, return_distance=True) neighbors, distances = neighbors[0], distances[0] loop_ind = np.where(distances == 0) if len(loop_ind[0]) > 1: loop_ind = np.where(neighbors == i) neighbors = np.delete(neighbors, loop_ind) distances = np.delete(distances, loop_ind) # make distance into weights and fix zero distances edges_weights = [1 / dist if dist > 0 else 1000 for dist in distances] len_neigh = len(neighbors) count += len_neigh mean = count / (i + 1) if i % 1000 == 0: print('Progress:', i, '/', len(self.embeddings), '; Current Mean:', mean) # 37273 weight_edges = list(zip(np.repeat(i, len(neighbors)).astype(str), neighbors.astype(str), edges_weights)) image_gnx.add_weighted_edges_from(weight_edges) nx.write_gpickle(image_gnx, self.image_graph_path) return image_gnx def imagenet_knowledge_graph(self): graph = json.load(open(self.pre_knowledge_graph_path, 'r')) edges = graph['edges'] nodes = graph['wnids'] # dict_nodes_translation = {i: node for i, node in enumerate(nodes)} dict_class_nodes_translation = {node: 'c' + str(i) for i, node in enumerate(nodes)} dict_nodes_class_translation = {'c' + str(i): node for i, node in enumerate(nodes)} dict_class_nodes_translation = {**dict_class_nodes_translation, **dict_nodes_class_translation} # edges = [(dict_nodes_translation[x[0]], # dict_nodes_translation[x[1]]) for x in edges] edges = [('c' + str(x[0]), 'c' + str(x[1])) for x in edges] kg_imagenet = nx.Graph() kg_imagenet.add_edges_from(edges) return kg_imagenet, dict_class_nodes_translation def attributed_graph(self, kg_imagenet, att_weight): graph = json.load(open(self.pre_knowledge_graph_path, 'r')) nodes = graph['wnids'] all_attributes = graph['vectors'] dict_class_nodes = {node: i for i, node in enumerate(nodes)} dict_nodes_class = {i: node for i, node in enumerate(nodes)} dict_class_nodes_translation = {**dict_class_nodes, **dict_nodes_class} awa2_split = json.load(open('materials/awa2-split.json', 'r')) seen_classes = awa2_split['train'] unseen_classes = awa2_split['test'] s_u_classes = seen_classes + unseen_classes s_u_idx = [dict_class_nodes_translation[c] for c in s_u_classes] kd_idx_to_class_idx = {i: dict_class_nodes_translation[c] for i, c in enumerate(s_u_idx)} attributes = np.array([all_attributes[idx] for idx in s_u_idx]) attributes = normalize(attributes, norm='l2', axis=1) kdt = KDTree(attributes, leaf_size=10) # image_graph.add_nodes_from(np.arange(len(self.embeddings))) count = 0 for i in range(len(attributes)): neighbors, distances = kdt.query_radius(attributes[i:i + 1], r=1.15, return_distance=True) if len(neighbors[0]) == 1: distances, neighbors = kdt.query(attributes[i:i + 1], k=2, return_distance=True) neighbors, distances = neighbors[0], distances[0] loop_ind = np.where(distances == 0) if len(loop_ind[0]) > 1: loop_ind = np.where(neighbors == i) neighbors = np.delete(neighbors, loop_ind) distances = np.delete(distances, loop_ind) # make distance into weights and fix zero distances edges_weights = [float(att_weight) / dist if dist > 0 else 1000 for dist in distances] len_neigh = len(neighbors) if len_neigh == 0: print('hi Im number ' + str(i)) count += len_neigh mean = count / (i + 1) if i % 10 == 0: print('Progress:', i, '/', len(attributes), '; Current Mean:', mean) # 37273 neighbors_translation = [dict_class_nodes_translation[kd_idx_to_class_idx[neighbor]] for neighbor in neighbors] weight_edges = list(zip(np.repeat(dict_class_nodes_translation[kd_idx_to_class_idx[i]], len(neighbors)), neighbors_translation, edges_weights)) kg_imagenet.add_weighted_edges_from(weight_edges) # TODO: add the weight from the attributes to the pre graph and not replace them # (minor problem because it is sparse graph) largest_cc = max(nx.connected_components(kg_imagenet), key=len) kg_imagenet = kg_imagenet.subgraph(largest_cc).copy() return kg_imagenet def awa2_knowledge_graph(self): kg_imagenet = self.imagenet_knowledge_graph() awa2_split = json.load(open('materials/awa2-split.json', 'r')) train_wnids = awa2_split['train'] test_wnids = awa2_split['test'] relevant_nodes = list(chain(train_wnids, test_wnids)) kg_awa2 = kg_imagenet.subgraph(relevant_nodes) return kg_awa2 def create_labels_graph(self, dict_class_nodes_translation): labels_graph = nx.Graph() edges = np.array([(key, dict_class_nodes_translation[self.dict_idx_image_class[key]]) for key in list(self.dict_idx_image_class.keys())]).astype(str) labels_graph.add_edges_from(edges) return labels_graph def weighted_graph(self, images_gnx, knowledge_graph, labels_graph, weights_dict): weighted_graph = nx.Graph() classes_nodes = knowledge_graph.nodes images_nodes = images_gnx.nodes labels_edges = labels_graph.edges images_edges = images_gnx.edges classes_edges = knowledge_graph.edges weighted_graph.add_nodes_from(images_nodes, key='movies') weighted_graph.add_nodes_from(classes_nodes, key='classes') # weighted_graph.add_edges_from(images_edges, key='images_edges') # weighted_graph.add_edges_from(classes_edges, key='classes_edges') # weighted_graph.add_edges_from(labels_edges, key='labels_edges') for edge in images_edges: dict_weight = images_gnx.get_edge_data(edge[0], edge[1]) weight = dict_weight.get('weight') if weight is not None: weighted_graph.add_edge(edge[0], edge[1], weight=weight, key='images_edges') classes_weight = weights_dict['classes_edges'] labels_weight = weights_dict['labels_edges'] for edge in classes_edges: weighted_graph.add_edge(edge[0], edge[1], weight=classes_weight, key='images_edges') for edge in labels_edges: weighted_graph.add_edge(edge[0], edge[1], weight=labels_weight, key='labels_edges') images_nodes =
np.array(images_nodes)
numpy.array
import copy import numpy as np from openmdao.api import Group, ExplicitComponent from scipy.interpolate import PchipInterpolator from wisdem.rotorse.precomp import PreComp, Profile, CompositeSection, Orthotropic2DMaterial from wisdem.commonse.utilities import rotate, arc_length from wisdem.rotorse.rail_transport import RailTransport class RunPreComp(ExplicitComponent): # Openmdao component to run precomp and generate the elastic properties of a wind turbine blade def initialize(self): self.options.declare("modeling_options") self.options.declare("opt_options") def setup(self): rotorse_options = self.options["modeling_options"]["WISDEM"]["RotorSE"] self.n_span = n_span = rotorse_options["n_span"] self.n_webs = n_webs = rotorse_options["n_webs"] self.n_layers = n_layers = rotorse_options["n_layers"] self.n_xy = n_xy = rotorse_options["n_xy"] # Number of coordinate points to describe the airfoil geometry mat_init_options = self.options["modeling_options"]["materials"] self.n_mat = n_mat = mat_init_options["n_mat"] self.verbosity = self.options["modeling_options"]["General"]["verbosity"] self.te_ss_var = rotorse_options["te_ss"] self.te_ps_var = rotorse_options["te_ps"] self.spar_cap_ss_var = rotorse_options["spar_cap_ss"] self.spar_cap_ps_var = rotorse_options["spar_cap_ps"] # Outer geometry self.add_input( "r", val=np.zeros(n_span), units="m", desc="radial locations where blade is defined (should be increasing and not go all the way to hub or tip)", ) self.add_input( "theta", val=np.zeros(n_span), units="deg", desc="Twist angle at each section (positive decreases angle of attack)", ) self.add_input("chord", val=np.zeros(n_span), units="m", desc="chord length at each section") self.add_input( "pitch_axis", val=np.zeros(n_span), desc="1D array of the chordwise position of the pitch axis (0-LE, 1-TE), defined along blade span.", ) self.add_input("precurve", val=np.zeros(n_span), units="m", desc="precurve at each section") self.add_input("presweep", val=np.zeros(n_span), units="m", desc="presweep at each section") self.add_input( "coord_xy_interp", val=np.zeros((n_span, n_xy, 2)), desc="3D array of the non-dimensional x and y airfoil coordinates of the airfoils interpolated along span for n_span stations.", ) # Rotor configuration self.add_input( "uptilt", val=0.0, units="deg", desc="Nacelle uptilt angle. A standard machine has positive values." ) self.add_discrete_input("n_blades", val=3, desc="Number of blades of the rotor.") # Inner structure self.add_input( "web_start_nd", val=np.zeros((n_webs, n_span)), desc="2D array of the non-dimensional start point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.", ) self.add_input( "web_end_nd", val=np.zeros((n_webs, n_span)), desc="2D array of the non-dimensional end point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.", ) self.add_input( "layer_web", val=np.zeros(n_layers), desc="1D array of the web id the layer is associated to. If the layer is on the outer profile, this entry can simply stay equal to 0.", ) self.add_discrete_input( "definition_layer", val=np.zeros(n_layers), desc="1D array of flags identifying how layers are specified in the yaml. 1) all around (skin, paint, ) 2) offset+rotation twist+width (spar caps) 3) offset+user defined rotation+width 4) midpoint TE+width (TE reinf) 5) midpoint LE+width (LE reinf) 6) layer position fixed to other layer (core fillers) 7) start and width 8) end and width 9) start and end nd 10) web layer", ) self.add_input( "layer_thickness", val=np.zeros((n_layers, n_span)), units="m", desc="2D array of the thickness of the layers of the blade structure. The first dimension represents each layer, the second dimension represents each entry along blade span.", ) self.add_input( "layer_start_nd", val=np.zeros((n_layers, n_span)), desc="2D array of the non-dimensional start point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.", ) self.add_input( "layer_end_nd", val=np.zeros((n_layers, n_span)), desc="2D array of the non-dimensional end point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.", ) self.add_input( "fiber_orientation", val=np.zeros((n_layers, n_span)), units="deg", desc="2D array of the orientation of the layers of the blade structure. The first dimension represents each layer, the second dimension represents each entry along blade span.", ) # Materials self.add_discrete_input("mat_name", val=n_mat * [""], desc="1D array of names of materials.") self.add_discrete_input( "orth", val=np.zeros(n_mat), desc="1D array of flags to set whether a material is isotropic (0) or orthtropic (1). Each entry represents a material.", ) self.add_input( "E", val=np.zeros([n_mat, 3]), units="Pa", desc="2D array of the Youngs moduli of the materials. Each row represents a material, the three columns represent E11, E22 and E33.", ) self.add_input( "G", val=np.zeros([n_mat, 3]), units="Pa", desc="2D array of the shear moduli of the materials. Each row represents a material, the three columns represent G12, G13 and G23.", ) self.add_input( "nu", val=np.zeros([n_mat, 3]), desc="2D array of the Poisson ratio of the materials. Each row represents a material, the three columns represent nu12, nu13 and nu23.", ) self.add_input( "rho", val=np.zeros(n_mat), units="kg/m**3", desc="1D array of the density of the materials. For composites, this is the density of the laminate.", ) self.add_input( "joint_position", val=0.0, desc="Spanwise position of the segmentation joint.", ) self.add_input("joint_mass", val=0.0, desc="Mass of the joint.") # Outputs - Distributed beam properties self.add_output("z", val=np.zeros(n_span), units="m", desc="locations of properties along beam") self.add_output("A", val=np.zeros(n_span), units="m**2", desc="cross sectional area") self.add_output("EA", val=np.zeros(n_span), units="N", desc="axial stiffness") self.add_output( "EIxx", val=np.zeros(n_span), units="N*m**2", desc="edgewise stiffness (bending about :ref:`x-direction of airfoil aligned coordinate system <blade_airfoil_coord>`)", ) self.add_output( "EIyy", val=np.zeros(n_span), units="N*m**2", desc="flapwise stiffness (bending about y-direction of airfoil aligned coordinate system)", ) self.add_output("EIxy", val=np.zeros(n_span), units="N*m**2", desc="coupled flap-edge stiffness") self.add_output( "GJ", val=np.zeros(n_span), units="N*m**2", desc="torsional stiffness (about axial z-direction of airfoil aligned coordinate system)", ) self.add_output("rhoA", val=np.zeros(n_span), units="kg/m", desc="mass per unit length") self.add_output("rhoJ", val=np.zeros(n_span), units="kg*m", desc="polar mass moment of inertia per unit length") self.add_output( "Tw_iner", val=np.zeros(n_span), units="m", desc="Orientation of the section principal inertia axes with respect the blade reference plane", ) self.add_output( "x_ec", val=np.zeros(n_span), units="m", desc="x-distance to elastic center from point about which above structural properties are computed (airfoil aligned coordinate system)", ) self.add_output( "y_ec", val=np.zeros(n_span), units="m", desc="y-distance to elastic center from point about which above structural properties are computed", ) self.add_output( "x_tc", val=np.zeros(n_span), units="m", desc="X-coordinate of the tension-center offset with respect to the XR-YR axes", ) self.add_output( "y_tc", val=np.zeros(n_span), units="m", desc="Chordwise offset of the section tension-center with respect to the XR-YR axes", ) self.add_output( "x_sc", val=np.zeros(n_span), units="m", desc="X-coordinate of the shear-center offset with respect to the XR-YR axes", ) self.add_output( "y_sc", val=np.zeros(n_span), units="m", desc="Chordwise offset of the section shear-center with respect to the reference frame, XR-YR", ) self.add_output( "x_cg", val=np.zeros(n_span), units="m", desc="X-coordinate of the center-of-mass offset with respect to the XR-YR axes", ) self.add_output( "y_cg", val=np.zeros(n_span), units="m", desc="Chordwise offset of the section center of mass with respect to the XR-YR axes", ) self.add_output( "flap_iner", val=np.zeros(n_span), units="kg/m", desc="Section flap inertia about the Y_G axis per unit length.", ) self.add_output( "edge_iner", val=np.zeros(n_span), units="kg/m", desc="Section lag inertia about the X_G axis per unit length", ) # self.add_output('eps_crit_spar', val=np.zeros(n_span), desc='critical strain in spar from panel buckling calculation') # self.add_output('eps_crit_te', val=np.zeros(n_span), desc='critical strain in trailing-edge panels from panel buckling calculation') self.add_output( "xu_spar", val=np.zeros(n_span), desc="x-position of midpoint of spar cap on upper surface for strain calculation", ) self.add_output( "xl_spar", val=np.zeros(n_span), desc="x-position of midpoint of spar cap on lower surface for strain calculation", ) self.add_output( "yu_spar", val=np.zeros(n_span), desc="y-position of midpoint of spar cap on upper surface for strain calculation", ) self.add_output( "yl_spar", val=np.zeros(n_span), desc="y-position of midpoint of spar cap on lower surface for strain calculation", ) self.add_output( "xu_te", val=np.zeros(n_span), desc="x-position of midpoint of trailing-edge panel on upper surface for strain calculation", ) self.add_output( "xl_te", val=np.zeros(n_span), desc="x-position of midpoint of trailing-edge panel on lower surface for strain calculation", ) self.add_output( "yu_te", val=np.zeros(n_span), desc="y-position of midpoint of trailing-edge panel on upper surface for strain calculation", ) self.add_output( "yl_te", val=np.zeros(n_span), desc="y-position of midpoint of trailing-edge panel on lower surface for strain calculation", ) # Outputs - Overall beam properties self.add_output("blade_mass", val=0.0, units="kg", desc="mass of one blade") self.add_output( "blade_moment_of_inertia", val=0.0, units="kg*m**2", desc="mass moment of inertia of blade about hub" ) self.add_output("mass_all_blades", val=0.0, units="kg", desc="mass of all blades") self.add_output( "I_all_blades", shape=6, units="kg*m**2", desc="mass moments of inertia of all blades in hub c.s. order:Ixx, Iyy, Izz, Ixy, Ixz, Iyz", ) self.add_output( "sc_ss_mats", val=np.zeros((n_span, n_mat)), desc="spar cap, suction side, boolean of materials in each composite layer spanwise, passed as floats for differentiablity, used for Fatigue Analysis", ) self.add_output( "sc_ps_mats", val=np.zeros((n_span, n_mat)), desc="spar cap, pressure side, boolean of materials in each composite layer spanwise, passed as floats for differentiablity, used for Fatigue Analysis", ) self.add_output( "te_ss_mats", val=np.zeros((n_span, n_mat)), desc="trailing edge reinforcement, suction side, boolean of materials in each composite layer spanwise, passed as floats for differentiablity, used for Fatigue Analysis", ) self.add_output( "te_ps_mats", val=np.zeros((n_span, n_mat)), desc="trailing edge reinforcement, pressure side, boolean of materials in each composite layer spanwise, passed as floats for differentiablity, used for Fatigue Analysis", ) def compute(self, inputs, outputs, discrete_inputs, discrete_outputs): ############################## def region_stacking( i, idx, start_nd_arc, end_nd_arc, layer_name, layer_thickness, fiber_orientation, layer_mat, material_dict, materials, region_loc, ): # Recieve start and end of composite sections chordwise, find which composites layers are in each # chordwise regions, generate the precomp composite class instance # error handling to makes sure there were no numeric errors causing values very close too, but not exactly, 0 or 1 start_nd_arc = [ 0.0 if start_nd_arci != 0.0 and np.isclose(start_nd_arci, 0.0) else start_nd_arci for start_nd_arci in start_nd_arc ] end_nd_arc = [ 0.0 if end_nd_arci != 0.0 and np.isclose(end_nd_arci, 0.0) else end_nd_arci for end_nd_arci in end_nd_arc ] start_nd_arc = [ 1.0 if start_nd_arci != 1.0 and np.isclose(start_nd_arci, 1.0) else start_nd_arci for start_nd_arci in start_nd_arc ] end_nd_arc = [ 1.0 if end_nd_arci != 1.0 and np.isclose(end_nd_arci, 1.0) else end_nd_arci for end_nd_arci in end_nd_arc ] # region end points dp = sorted(list(set(start_nd_arc + end_nd_arc))) # initialize n_plies = [] thk = [] theta = [] mat_idx = [] # loop through division points, find what layers make up the stack between those bounds for i_reg, (dp0, dp1) in enumerate(zip(dp[0:-1], dp[1:])): n_pliesi = [] thki = [] thetai = [] mati = [] for i_sec, start_nd_arci, end_nd_arci in zip(idx, start_nd_arc, end_nd_arc): name = layer_name[i_sec] if start_nd_arci <= dp0 and end_nd_arci >= dp1: if name in region_loc.keys(): if region_loc[name][i] == None: region_loc[name][i] = [i_reg] else: region_loc[name][i].append(i_reg) n_pliesi.append(1.0) thki.append(layer_thickness[i_sec]) if fiber_orientation[i_sec] == None: thetai.append(0.0) else: thetai.append(fiber_orientation[i_sec]) mati.append(material_dict[layer_mat[i_sec]]) n_plies.append(np.array(n_pliesi)) thk.append(np.array(thki)) theta.append(np.array(thetai)) mat_idx.append(np.array(mati)) # print('----------------------') # print('dp', dp) # print('n_plies', n_plies) # print('thk', thk) # print('theta', theta) # print('mat_idx', mat_idx) # print('materials', materials) sec = CompositeSection(dp, n_plies, thk, theta, mat_idx, materials) return sec, region_loc ############################## def web_stacking( i, web_idx, web_start_nd_arc, web_end_nd_arc, layer_thickness, fiber_orientation, layer_mat, material_dict, materials, flatback, upperCSi, ): dp = [] n_plies = [] thk = [] theta = [] mat_idx = [] if len(web_idx) > 0: dp = np.mean((np.abs(web_start_nd_arc), np.abs(web_start_nd_arc)), axis=0).tolist() dp_all = [ [-1.0 * start_nd_arci, -1.0 * end_nd_arci] for start_nd_arci, end_nd_arci in zip(web_start_nd_arc, web_end_nd_arc) ] web_dp, web_ids = np.unique(dp_all, axis=0, return_inverse=True) for webi in np.unique(web_ids): # store variable values (thickness, orientation, material) for layers that make up each web, based on the mapping array web_ids n_pliesi = [1.0 for i_reg, web_idi in zip(web_idx, web_ids) if web_idi == webi] thki = [layer_thickness[i_reg] for i_reg, web_idi in zip(web_idx, web_ids) if web_idi == webi] thetai = [fiber_orientation[i_reg] for i_reg, web_idi in zip(web_idx, web_ids) if web_idi == webi] thetai = [0.0 if theta_ij == None else theta_ij for theta_ij in thetai] mati = [ material_dict[layer_mat[i_reg]] for i_reg, web_idi in zip(web_idx, web_ids) if web_idi == webi ] n_plies.append(np.array(n_pliesi)) thk.append(
np.array(thki)
numpy.array
import os import json CONFIG_LOCATION = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, "data", "path_config.json")) with open(CONFIG_LOCATION) as _json_file: CONFIG = json.load(_json_file) DATA_DIR = CONFIG["main_data_dir"] if not os.path.exists(DATA_DIR): PROJECT_ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATA_DIR = os.path.join(PROJECT_ROOT_PATH, "data") os.environ["S2AND_CACHE"] = os.path.join(DATA_DIR, ".feature_cache") os.environ["OMP_NUM_THREADS"] = "8" import copy import argparse import logging import pickle from typing import Dict, Any, Optional, List from collections import defaultdict from tqdm import tqdm import numpy as np import pandas as pd from sklearn.experimental import enable_iterative_imputer # noqa from sklearn.cluster import DBSCAN from sklearn.linear_model import BayesianRidge, LogisticRegressionCV from sklearn.preprocessing import StandardScaler from sklearn.impute import IterativeImputer from sklearn.pipeline import make_pipeline from s2and.data import ANDData from s2and.featurizer import featurize, FeaturizationInfo from s2and.model import PairwiseModeler, Clusterer, FastCluster from s2and.eval import pairwise_eval, cluster_eval, facet_eval from s2and.consts import FEATURIZER_VERSION, DEFAULT_CHUNK_SIZE, NAME_COUNTS_PATH from s2and.file_cache import cached_path from s2and.plotting_utils import plot_facets from hyperopt import hp logger = logging.getLogger("s2and") pd.set_option("display.max_rows", None) pd.set_option("display.max_columns", None) pd.set_option("display.width", None) pd.set_option("display.max_colwidth", None) PAIRWISE_ONLY_DATASETS = {"medline"} BLOCK_TYPE = "s2" N_VAL_TEST_SIZE = 10000 N_ITER = 25 PREPROCESS = True def transfer_helper( source_dataset, target_dataset, experiment_name, random_seed, featurizer_info, nameless_featurizer_info, use_s2_clusters=False, skip_shap=False, ): source_name = source_dataset["name"] target_name = target_dataset["name"] if use_s2_clusters: pairwise_metrics = { "AUROC": None, "Average Precision": None, "F1": None, "Precision": None, "Recall": None, } else: pairwise_metrics = pairwise_eval( target_dataset["X_test"], target_dataset["y_test"], source_dataset["pairwise_modeler"], os.path.join(DATA_DIR, "experiments", experiment_name, f"seed_{random_seed}", "figs"), f"{source_name}_to_{target_name}", featurizer_info.get_feature_names(), nameless_classifier=source_dataset["nameless_pairwise_modeler"], nameless_X=target_dataset["nameless_X_test"], nameless_feature_names=nameless_featurizer_info.get_feature_names(), skip_shap=skip_shap, ) if target_name not in PAIRWISE_ONLY_DATASETS and source_name not in PAIRWISE_ONLY_DATASETS: cluster_metrics, b3_metrics_per_signature = cluster_eval( target_dataset["anddata"], source_dataset["clusterer"], split="test", use_s2_clusters=use_s2_clusters, ) else: cluster_metrics = { "B3 (P, R, F1)": (None, None, None), "Cluster (P, R F1)": (None, None, None), "Cluster Macro (P, R, F1)": (None, None, None), "Pred bigger ratio (mean, count)": (None, None), "True bigger ratio (mean, count)": (None, None), } b3_metrics_per_signature = None if not use_s2_clusters: metrics = {"pairwise": pairwise_metrics, "cluster": cluster_metrics} logger.info(f"{source_name}_to_{target_name}: {metrics}") with open( os.path.join( DATA_DIR, "experiments", experiment_name, f"seed_{random_seed}", "metrics", f"{source_name}_to_{target_name}.json", ), "w", ) as _json_file: json.dump(metrics, _json_file, indent=4) return pairwise_metrics, cluster_metrics, b3_metrics_per_signature def summary_features_analysis( union_firstname_f1, union_affiliation_f1, union_email_f1, union_abstract_f1, union_venue_f1, union_references_f1, union_coauthors_f1, union_s2_firstname_f1, union_s2_affiliation_f1, union_s2_email_f1, union_s2_abstract_f1, union_s2_venue_f1, union_s2_references_f1, union_s2_coauthors_f1, ): """ Aggregates differences in performance for s2and and s2, across different feature availability indicators. """ feature_summary = [] for s2and_feature_facet, s2_feature_facet in zip( [ union_firstname_f1, union_affiliation_f1, union_email_f1, union_abstract_f1, union_venue_f1, union_references_f1, union_coauthors_f1, ], [ union_s2_firstname_f1, union_s2_affiliation_f1, union_s2_email_f1, union_s2_abstract_f1, union_s2_venue_f1, union_s2_references_f1, union_s2_coauthors_f1, ], ): s2and_pres_avg = sum(s2and_feature_facet[1]) / len(s2and_feature_facet[1]) s2and_abs_avg = sum(s2and_feature_facet[0]) / len(s2and_feature_facet[0]) s2_pres_avg = sum(s2_feature_facet[1]) / len(s2_feature_facet[1]) s2_abs_avg = sum(s2_feature_facet[0]) / len(s2_feature_facet[0]) feature_summary.append( [ s2and_pres_avg, s2and_abs_avg, s2_pres_avg, s2_abs_avg, ] ) s2and_feature_facet_scores = { "first_name_diff": np.round(feature_summary[0][0], 3) - np.round(feature_summary[0][1], 3), "affilition_diff": np.round(feature_summary[1][0], 3) -
np.round(feature_summary[1][1], 3)
numpy.round
import ctaplot.ana.ana as ana import numpy as np np.random.seed(42) def test_logspace_decades_nbin(): ca = ana.logspace_decades_nbin(0.1, 10, n=9) assert len(ca) == 19 assert ca[0] == 0.1 assert ca[-1] == 10 def test_class_cta_requirement(): for site in ['north', 'south']: ctaq = ana.cta_requirement(site) ctaq.get_effective_area() ctaq.get_angular_resolution() ctaq.get_energy_resolution() ctaq.get_sensitivity() def test_class_cta_performance(): for site in ['north', 'south']: ctaq = ana.cta_performance(site) ctaq.get_effective_area() ctaq.get_angular_resolution() ctaq.get_energy_resolution() ctaq.get_sensitivity() def test_impact_resolution_per_energy(): true_x = np.random.rand(100) * 1000 true_y = np.random.rand(100) * 1000 reco_x = true_x + 1 reco_y = true_y + 1 energy = np.logspace(-2, 2, 100) E, R = ana.impact_resolution_per_energy(reco_x, reco_y, true_x, true_y, energy) assert (np.isclose(R, np.sqrt(2))).all() def test_resolution(): x = np.linspace(0, 10, 100) assert (ana.resolution(x, x) == np.zeros(3)).all() # For a normal distribution, the resolution at `percentile=68.27` is equal to 1 sigma loc = np.random.rand() * 100 scale = np.random.rand() * 10 size = 1000000 y_true = loc * np.ones(size) y_reco = np.random.normal(loc=loc, scale=scale, size=size) relative_scaling_method = 's1' res = ana.resolution(y_true, y_reco, relative_scaling_method=relative_scaling_method) assert np.isclose(res[0], scale / ana.relative_scaling(y_true, y_reco, relative_scaling_method).mean(), rtol=1e-1) # Test bias bias = np.random.rand() * 100 y_reco_bias = np.random.normal(loc=loc + bias, scale=scale, size=size) assert np.isclose(ana.resolution(y_true, y_reco_bias, bias_correction=True, relative_scaling_method=relative_scaling_method)[0], scale / ana.relative_scaling(y_true, y_reco, relative_scaling_method).mean(), rtol=1e-1) assert np.isclose(ana.resolution(y_true, y_reco)[0], ana.resolution(y_true, y_reco, bias_correction=True)[0], rtol=1e-1, ) # Test relative scaling for relative_scaling_method in ['s0', 's1', 's2', 's3', 's4']: assert np.isclose(ana.resolution(y_true, y_reco_bias, bias_correction=True, relative_scaling_method=relative_scaling_method)[0], scale / ana.relative_scaling(y_true, y_reco, relative_scaling_method).mean(), rtol=1e-1) def test_resolution_per_bin(): # For a normal distribution, the resolution at `percentile=68.27` is equal to 1 sigma size = 1000000 loc = np.random.rand() * 100 scale = np.random.rand() * 10 x = np.linspace(0, 10, size) y_true = loc * np.ones(size) y_reco = np.random.normal(loc=loc, scale=scale, size=size) for scaling in ['s0', 's1', 's2', 's3', 's4']: bins, res = ana.resolution_per_bin(x, y_true, y_reco, bins=6, relative_scaling_method=scaling) np.testing.assert_allclose(res[:, 0], scale / ana.relative_scaling(y_true, y_reco, scaling).mean(), rtol=1e-1) bias = 50 y_reco = np.random.normal(loc=loc + bias, scale=scale, size=size) bins, res = ana.resolution_per_bin(x, y_true, y_reco, bias_correction=True) np.testing.assert_allclose(res[:, 0], scale / ana.relative_scaling(y_true, y_reco).mean(), rtol=1e-1) def test_resolution_per_bin_empty(): ''' testing for empty bins ''' # For a normal distribution, the resolution at `percentile=68.27` is equal to 1 sigma size = 1000000 loc = np.random.rand() * 100 scale = np.random.rand() * 10 x = np.linspace(0, 10, size) bins = np.array([1, 2, 3, 5, 11, 15]) y_true = loc * np.ones(size) y_reco = np.random.normal(loc=loc, scale=scale, size=size) for scaling in ['s0', 's1', 's2', 's3', 's4']: bins, res = ana.resolution_per_bin(x, y_true, y_reco, bins=bins, relative_scaling_method=scaling, bias_correction=True) v = scale / ana.relative_scaling(y_true, y_reco, scaling).mean() expected_res = np.array([v, v, v, v, 0]) np.testing.assert_allclose(res[:, 0], expected_res, rtol=1e-1) def test_resolution_per_energy(): x = np.random.normal(size=100000, scale=1, loc=10) y = 10 * np.ones(x.shape[0]) E = 10 ** (-3 + 6 * np.random.rand(x.shape[0])) e_bin, res_e = ana.resolution_per_energy(y, x, E) assert np.isclose(res_e, 1. / ana.relative_scaling(y, x).mean(), rtol=1e-1).all() def test_power_law_integrated_distribution(): from ctaplot.ana.ana import power_law_integrated_distribution emin = 50. # u.GeV emax = 500.e3 # u.GeV Nevents = 1e6 spectral_index = -2.1 bins = np.logspace(np.log10(emin), np.log10(emax), 40) y = power_law_integrated_distribution(emin, emax, Nevents, spectral_index, bins) np.testing.assert_allclose(Nevents,
np.sum(y)
numpy.sum
import numpy as np from sklearn import preprocessing, neighbors, model_selection, svm import pandas as pd import pickle #import serial import re import random from sklearn.metrics import confusion_matrix, plot_confusion_matrix, plot_precision_recall_curve import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score def load_data(): df_B = pd.read_table('sign2/b.txt', header=None, sep=',')# B = np.array(df_B) df_C = pd.read_table('sign2/c.txt', header=None, sep=',')# C = np.array(df_C) df_D = pd.read_table('sign2/d.txt', header=None, sep=',')# D = np.array(df_D) df_F = pd.read_table('sign2/f.txt', header=None, sep=',')# F = np.array(df_F) df_H = pd.read_table('sign2/h.txt', header=None, sep=',')# df_G = pd.read_table('sign2/g.txt', header=None, sep=',')# G = np.array(df_G) H = np.array(df_H) df_I = pd.read_table('sign2/i.txt', header=None, sep=',')# I = np.array(df_I) df_K = pd.read_table('sign2/k.txt', header=None, sep=',')# K = np.array(df_K) df_L = pd.read_table('sign2/l.txt', header=None, sep=',')# L = np.array(df_L) df_P = pd.read_table('sign2/p.txt', header=None, sep=',')# P = np.array(df_P) df_V = pd.read_table('sign2/v.txt', header=None, sep=',')# V = np.array(df_V) df_O = pd.read_table('sign2/o.txt', header=None, sep=',')# O = np.array(df_O) df_Q = pd.read_table('sign2/q.txt', header=None, sep=',')# Q = np.array(df_Q) df_R = pd.read_table('sign2/r.txt', header=None, sep=',')# R = np.array(df_R) df_W = pd.read_table('sign2/w.txt', header=None, sep=',')# W = np.array(df_W) df_A = pd.read_table('sign2/a.txt', header=None, sep=',') A = np.array(df_A) df_E = pd.read_table('sign2/e.txt', header=None, sep=',') E = np.array(df_E) df_J = pd.read_table('sign2/j.txt', header=None, sep=',') J = np.array(df_J) df_M = pd.read_table('sign2/m.txt', header=None, sep=',') M = np.array(df_M) df_N = pd.read_table('sign2/n.txt', header=None, sep=',') N = np.array(df_N) df_S = pd.read_table('sign2/s.txt', header=None, sep=',') S = np.array(df_S) df_T = pd.read_table('sign2/t.txt', header=None, sep=',') T = np.array(df_T) df_U = pd.read_table('sign2/u.txt', header=None, sep=',') U = np.array(df_U) df_X = pd.read_table('sign2/x.txt', header=None, sep=',') X = np.array(df_X) df_Y = pd.read_table('sign2/y.txt', header=None, sep=',') Y = np.array(df_Y) df_Z = pd.read_table('sign2/z.txt', header=None, sep=',') Z = np.array(df_Z) df = df_A.append(df_B) # df = df.append(df_C) df = df.append(df_D)# df = df.append(df_E) df = df.append(df_F)# df = df.append(df_G)# df = df.append(df_H)# df = df.append(df_I)# df = df.append(df_J) df = df.append(df_K)# df = df.append(df_L)# df = df.append(df_M) df = df.append(df_N) df = df.append(df_O)# df = df.append(df_P)# df = df.append(df_Q)# df = df.append(df_R)# df = df.append(df_S) df = df.append(df_T) df = df.append(df_U) df = df.append(df_V)# df = df.append(df_W)# df = df.append(df_X) df = df.append(df_Y) df = df.append(df_Z) df = df.drop(df.columns[-1], axis=1) data = pd.DataFrame(df).to_numpy() print(type(data)) print(data.shape) class_a = [0 for i in range(len(A))] class_b = [1 for i in range(len(B))]# class_c = [2 for i in range(len(C))]# class_d = [3 for i in range(len(D))]# class_e = [4 for i in range(len(E))] class_f = [5 for i in range(len(F))]# class_g = [6 for i in range(len(G))]# class_h = [7 for i in range(len(H))]# class_i = [8 for i in range(len(I))]# class_j = [9 for i in range(len(J))] class_k = [10 for i in range(len(K))]# class_l = [11 for i in range(len(L))]# class_m = [12 for i in range(len(M))] class_n = [13 for i in range(len(N))] class_o = [14 for i in range(len(O))]# class_p = [15 for i in range(len(P))]# class_q = [16 for i in range(len(Q))]# class_r = [17 for i in range(len(R))]# class_s = [18 for i in range(len(S))] class_t = [19 for i in range(len(T))] class_u = [20 for i in range(len(U))] class_v = [21 for i in range(len(V))]# class_w = [22 for i in range(len(W))]# class_x = [23 for i in range(len(X))] class_y = [24 for i in range(len(Y))] class_z = [25 for i in range(len(Z))] y_label = np.append(class_a, class_b)# y_label = np.append(y_label, class_c) y_label =
np.append(y_label, class_d)
numpy.append
from typing import Tuple, Any import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots from . import cpu_color, mem_color, \ cpu_delta_color, mem_delta_color,\ cpu_color_rgb, mem_color_rgb, \ heatmap_scale from ..config import cpu_max, mem_max, y_axis_max from ..data import get_server_num from ..utils import rgba cpu_hover = 'Server %{x}<br>' \ f'Total CPU: {cpu_max} Core<br>' \ 'Used: %{customdata[0]} Core<br>' \ 'Occupancy: %{customdata[1]:.2f}%' \ '<extra></extra>' mem_hover = 'Server %{x}<br>' \ f'Total MEM: {mem_max} GB<br>' \ 'Used: %{customdata[0]} GB<br>' \ 'Occupancy: %{customdata[1]:.2f}%' \ '<extra></extra>' def __delta_color_marker_helper(delta: Tuple[Any]) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: # insert -> True # delete -> False return ( np.array(list(cpu_delta_color[x] for x in delta[0] > 0)), np.array(list(mem_delta_color[x] for x in delta[1] > 0)), np.array(list(cpu_delta_color[x] for x in delta[2] < 0)), np.array(list(mem_delta_color[x] for x in delta[3] < 0)), ) def _get_figure0_small(server_num, n_intervals, df, show_delta): if n_intervals - show_delta < 0: trace_data = (np.zeros(server_num),) * 4 else: trace_data = ( cpu_max - df['server'][n_intervals - show_delta][..., 0, 0], mem_max - df['server'][n_intervals - show_delta][..., 0, 1], df['server'][n_intervals - show_delta][..., 1, 0] - cpu_max, df['server'][n_intervals - show_delta][..., 1, 1] - mem_max ) rate = ( trace_data[0] / cpu_max * 100, trace_data[1] / mem_max * 100, trace_data[2] / cpu_max * 100, trace_data[3] / mem_max * 100, ) server_list = list(range(server_num)) fig = go.Figure(layout=dict(yaxis=dict( range=[-y_axis_max, y_axis_max], autorange=False, tickmode='array', tickvals=list(range(-200, 200, 50)), ticktext=list(map(abs, range(-200, 200, 50))), zeroline=True, zerolinecolor='gray' ))) fig.add_traces([ go.Bar( x=np.append(server_list, server_list), y=np.append(trace_data[0], trace_data[2]), offsetgroup='C', customdata=np.array([np.append(trace_data[0], -trace_data[2]), np.append(rate[0], -rate[2])]).T, hovertemplate=cpu_hover, marker_color=cpu_color, # opacity=0.8, name='CPU' ), go.Bar( x=np.append(server_list, server_list), y=np.append(trace_data[1], trace_data[3]), offsetgroup='M', customdata=np.array([np.append(trace_data[1], -trace_data[3]), np.append(rate[1], -rate[3])]).T, hovertemplate=mem_hover, marker_color=mem_color, # opacity=0.8, name='MEM' ), ]) if not show_delta: return fig next_trace_data = ( cpu_max - df['server'][n_intervals][..., 0, 0], mem_max - df['server'][n_intervals][..., 0, 1], df['server'][n_intervals][..., 1, 0] - cpu_max, df['server'][n_intervals][..., 1, 1] - mem_max ) delta_data = tuple(i - j for i, j in zip(next_trace_data, trace_data)) # Delta delta_color = __delta_color_marker_helper(delta_data) fig.add_traces([ go.Bar( x=np.append(server_list, server_list), y=
np.append(delta_data[0], delta_data[2])
numpy.append