How to use sim1 method in ATX

Best Python code snippet using ATX

gulls_LSTM_longsims.py

Source:gulls_LSTM_longsims.py Github

copy

Full Screen

1from __future__ import print_function2import numpy as np3import pandas as pd4import tensorflow as tf5import keras6from keras.layers import Input, Embedding, Dense, Dropout, LSTM7from keras.models import Model8from keras.activations import softmax9from keras.losses import categorical_crossentropy10from keras.layers.core import Dense, Dropout, Activation, Masking11from keras.models import Sequential12from keras.utils import np_utils13from keras.optimizers import Adam14from sklearn.preprocessing import StandardScaler15from sklearn.preprocessing import LabelEncoder16from keras.preprocessing.sequence import pad_sequences17from sklearn.metrics import mean_squared_error18filename='gulls40.csv'19data_in=pd.read_csv(filename, sep=',',header=0)20data_in.columns21data_std=data_in22data_transform=data_std.iloc[:, np.r_[10:173]]23# Step 1: Classification24#Normalize the input variables25from sklearn import preprocessing26scaler_in = preprocessing.StandardScaler()27scaler_in.fit(data_transform)28data_transform=scaler_in.transform(data_transform)29scaler_out = preprocessing.StandardScaler()30scaler_out.fit(data_in[['vx','vy']])31encoder = LabelEncoder()32encoder.fit(data_std['state'])33out_ = encoder.transform(data_std['state'])34# convert integers to dummy variables (i.e. one hot encoded)35out_cat = np_utils.to_categorical(out_)36del data_in37idx_BY=[]38len_BY=[]39fold_BY=[]40common_BY=[]41for i in range(1,16,1):42 idx_=np.where((data_std['BirdYear']==i))[0]43 idx_BY.append(idx_)44 len_BY.append(len(idx_))45 fold_BY.append(data_std['fold'][idx_].unique())46 data_fold=data_std.iloc[idx_,:]47 common_BY.append(np.where(data_fold['common']==1)[0])48len_BY=np.array(len_BY)49fold_BY=np.array(fold_BY)50BY1=data_transform[idx_BY[0]].astype(np.float32)51BY2=data_transform[idx_BY[1]].astype(np.float32)52BY3=data_transform[idx_BY[2]].astype(np.float32)53BY4=data_transform[idx_BY[3]].astype(np.float32)54BY5=data_transform[idx_BY[4]].astype(np.float32)55BY6=data_transform[idx_BY[5]].astype(np.float32)56BY7=data_transform[idx_BY[6]].astype(np.float32)57BY8=data_transform[idx_BY[7]].astype(np.float32)58BY9=data_transform[idx_BY[8]].astype(np.float32)59BY10=data_transform[idx_BY[9]].astype(np.float32)60BY11=data_transform[idx_BY[10]].astype(np.float32)61BY12=data_transform[idx_BY[11]].astype(np.float32)62BY13=data_transform[idx_BY[12]].astype(np.float32)63BY14=data_transform[idx_BY[13]].astype(np.float32)64BY15=data_transform[idx_BY[14]].astype(np.float32)65#one hot encoded66out_1=out_cat[idx_BY[0],:]67out_2=out_cat[idx_BY[1],:]68out_3=out_cat[idx_BY[2],:]69out_4=out_cat[idx_BY[3],:]70out_5=out_cat[idx_BY[4],:]71out_6=out_cat[idx_BY[5],:]72out_7=out_cat[idx_BY[6],:]73out_8=out_cat[idx_BY[7],:]74out_9=out_cat[idx_BY[8],:]75out_10=out_cat[idx_BY[9],:]76out_11=out_cat[idx_BY[10],:]77out_12=out_cat[idx_BY[11],:]78out_13=out_cat[idx_BY[12],:]79out_14=out_cat[idx_BY[13],:]80out_15=out_cat[idx_BY[14],:]81#state now coded as 0,1,2,3 not 1,2,4,582out1=out_[idx_BY[0]]83out2=out_[idx_BY[1]]84out3=out_[idx_BY[2]]85out4=out_[idx_BY[3]]86out5=out_[idx_BY[4]]87out6=out_[idx_BY[5]]88out7=out_[idx_BY[6]]89out8=out_[idx_BY[7]]90out9=out_[idx_BY[8]]91out10=out_[idx_BY[9]]92out11=out_[idx_BY[10]]93out12=out_[idx_BY[11]]94out13=out_[idx_BY[12]]95out14=out_[idx_BY[13]]96out15=out_[idx_BY[14]]97out_1dim=np.array([out1, out2, out3, out4, out5, out6, out7, out8, out9, out10, out11, out12, out13, out14, out15])98input_seq=[BY1, BY2, BY3, BY4, BY5, BY6, BY7, BY8, BY9, BY10, BY11, BY12, BY13, BY14, BY15]99#Padded100input_seq_pad=pad_sequences([BY1, BY2, BY3, BY4, BY5, BY6, BY7, BY8, BY9, BY10, BY11, BY12, BY13, BY14, BY15], padding='post', dtype='float32' )101output_seq_pad=pad_sequences([out_1, out_2, out_3, out_4, out_5, out_6, out_7, out_8, out_9, out_10, out_11, out_12, out_13, out_14, out_15], padding='post', dtype='int32' )102#compiling classification model103main_input=Input(shape=(None, 163), name='main_input', dtype='float32')104mask = Masking(mask_value=0.)(main_input)105x=LSTM(250, activation='tanh',return_sequences=True,dropout=0.2, recurrent_dropout=0.1)(mask)106x=Dense(200, activation='relu')(x)107x=Dropout(0.2)(x)108x=Dense(50, activation='relu')(x)109x = Dropout(0.2)(x)110out= Dense(4, activation='softmax')(x)111model_class=Model(inputs=main_input,outputs=out)112optimizer=Adam(lr=0.001)113model_class.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])114#compiling vel state 1 model115main_input1=Input(shape=(None, 163), name='main_input1', dtype='float32')116mask1 = Masking(mask_value=0.)(main_input1)117x1=LSTM(200, activation='tanh',return_sequences=False,dropout=0.1, recurrent_dropout=0.1)(mask1,training=True)118x1=Dense(200, activation='relu')(x1)119x1=Dropout(0.1)(x1,training=True)120out1= Dense(2, activation='linear')(x1)121model1=Model(inputs=main_input1,outputs=out1)122optimizer1=Adam(lr=0.001)123model1.compile(optimizer=optimizer1, loss='mse')124#compiling vel state 2 model125main_input2=Input(shape=(None, 163), name='main_input2', dtype='float32')126mask2 = Masking(mask_value=0.)(main_input2)127x2=LSTM(300, activation='tanh',return_sequences=False,dropout=0.2, recurrent_dropout=0.2)(mask2, training=True)128x2=Dense(250, activation='relu')(x2)129x2=Dropout(0.2)(x2,training=True)130x2=Dense(50, activation='relu')(x2)131x2=Dropout(0.2)(x2,training=True)132out2= Dense(2, activation='linear')(x2)133model2=Model(inputs=main_input2,outputs=out2)134optimizer2=Adam(lr=0.0005)135model2.compile(optimizer=optimizer2, loss='mse')136#compiling vel state 4 model137main_input4=Input(shape=(None, 163), name='main_input4', dtype='float32')138mask4 = Masking(mask_value=0.)(main_input4)139x4=LSTM(250, activation='tanh',return_sequences=False,dropout=0.1, recurrent_dropout=0.1)(mask4, training=True)140x4=Dense(200, activation='relu')(x4)141x4=Dropout(0.1)(x4, training=True)142out4= Dense(2, activation='linear')(x4)143model4=Model(inputs=main_input4,outputs=out4)144optimizer4=Adam(lr=0.001)145model4.compile(optimizer=optimizer4, loss='mse')146#compiling vel state 5 model147main_input5=Input(shape=(None, 163), name='main_input5', dtype='float32')148mask5 = Masking(mask_value=0.)(main_input5)149x5=LSTM(200, activation='tanh',return_sequences=False,dropout=0.1, recurrent_dropout=0.1)(mask5, training=True)150x5=Dense(200, activation='relu')(x5)151x5=Dropout(0.1)(x5,training=True)152out5= Dense(2, activation='linear')(x5)153model5=Model(inputs=main_input5,outputs=out5)154optimizer5=Adam(lr=0.001)155model5.compile(optimizer=optimizer5, loss='mse')156#Fit classification model157fit_class=model_class.fit(input_seq_pad[np.r_[0:6,7:15],:,:], output_seq_pad[np.r_[0:6,7:15],:,:], epochs=50, verbose=0, batch_size=128)158#Fit velocity model state 1159data1 = np.load('input_seq_pad40_1_fold1.npz')160data2 = np.load('input_seq_pad40_1_fold2.npz')161data3 = np.load('input_seq_pad40_1_fold3.npz')162data4 = np.load('input_seq_pad40_1_fold4.npz')163data5 = np.load('input_seq_pad40_1_fold5.npz')164input_seq_pad1 =np.concatenate((data1['a'],data2['a'],data3['a'],data4['a'],data5['a'] ), axis=0)165metadata=np.concatenate((data1['b'],data2['b'],data3['b'],data4['b'],data5['b'] ), axis=0)166output=np.concatenate((data1['c'],data2['c'],data3['c'],data4['c'],data5['c'] ), axis=0)167del data1,data2,data3,data4,data5168fit1=model1.fit(input_seq_pad1[np.where(metadata[:,3]!=7)[0],:,:], output[np.where(metadata[:,3]!=7)[0],:], epochs=8,verbose=0, batch_size=128)169del input_seq_pad1,metadata,output170#Fit velocity model state 2171data1 = np.load('input_seq_pad40_2_fold1.npz')172data2 = np.load('input_seq_pad40_2_fold2.npz')173data3 = np.load('input_seq_pad40_2_fold3.npz')174data4 = np.load('input_seq_pad40_2_fold4.npz')175data5 = np.load('input_seq_pad40_2_fold5.npz')176input_seq_pad2 =np.concatenate((data1['a'],data2['a'],data3['a'],data4['a'],data5['a'] ), axis=0)177metadata=np.concatenate((data1['b'],data2['b'],data3['b'],data4['b'],data5['b'] ), axis=0)178output=np.concatenate((data1['c'],data2['c'],data3['c'],data4['c'],data5['c'] ), axis=0)179del data1,data2,data3,data4,data5180fit2=model2.fit(input_seq_pad2[np.where(metadata[:,3]!=7)[0],:,:], output[np.where(metadata[:,3]!=7)[0],:], epochs=15,verbose=0, batch_size=128)181del input_seq_pad2,metadata,output182#Fit velocity model state 4183data1 = np.load('input_seq_pad40_4_fold1.npz')184data2 = np.load('input_seq_pad40_4_fold2.npz')185data3 = np.load('input_seq_pad40_4_fold3.npz')186data4 = np.load('input_seq_pad40_4_fold4.npz')187data5 = np.load('input_seq_pad40_4_fold5.npz')188input_seq_pad4 =np.concatenate((data1['a'],data2['a'],data3['a'],data4['a'],data5['a'] ), axis=0)189metadata=np.concatenate((data1['b'],data2['b'],data3['b'],data4['b'],data5['b'] ), axis=0)190output=np.concatenate((data1['c'],data2['c'],data3['c'],data4['c'],data5['c'] ), axis=0)191del data1,data2,data3,data4,data5192fit4=model4.fit(input_seq_pad4[np.where(metadata[:,3]!=7)[0],:,:], output[np.where(metadata[:,3]!=7)[0],:], epochs=10, batch_size=128)193del input_seq_pad4,metadata,output194#fit velocity model state 5195data1 = np.load('input_seq_pad40_5_fold1.npz')196data2 = np.load('input_seq_pad40_5_fold2.npz')197data3 = np.load('input_seq_pad40_5_fold3.npz')198data4 = np.load('input_seq_pad40_5_fold4.npz')199data5 = np.load('input_seq_pad40_5_fold5.npz')200input_seq_pad5 =np.concatenate((data1['a'],data2['a'],data3['a'],data4['a'],data5['a'] ), axis=0)201metadata=np.concatenate((data1['b'],data2['b'],data3['b'],data4['b'],data5['b'] ), axis=0)202output=np.concatenate((data1['c'],data2['c'],data3['c'],data4['c'],data5['c'] ), axis=0)203del data1,data2,data3,data4,data5204fit5=model5.fit(input_seq_pad5[np.where(metadata[:,3]!=7)[0],:,:], output[np.where(metadata[:,3]!=7)[0],:], epochs=15,verbose=0, batch_size=128)205del input_seq_pad5,metadata,output206def getClass(parray):207 onehot=np.random.multinomial(1, parray)208 state=np.array([1,2,4,5])[np.argmax(onehot, axis=0)]209 return state210def euc_dist(x1, x2, y1, y2):211 212 dist=((x1-x2)**2+(y1-y2)**2)**(0.5)213 return dist214veuc_dist = np.vectorize(euc_dist)215idx_sim7=np.where( (data_std['BirdYear']==7) )[0]216 217#simulate from state 5 to 1218for sim in range(5):219 sim1=data_std.loc[idx_sim7]220 for r in range(14649,14949,1):221 #Let's start with sim1222 sim_step_in=sim1.iloc[0:(r+1), np.r_[10:173]]223 sim_step_in=scaler_in.transform(sim_step_in)224 sim_step_in=sim_step_in.reshape(1,(r+1),163)225 predstate=model_class.predict(sim_step_in)226 predstate=predstate[-1]227 predstate=predstate[-1]228 predstate=predstate/np.sum(predstate)229 sim1['state'][r]=getClass(predstate)230 if r>=999:231 sim_step_in=sim_step_in[0,(r-999):(r+1),:]232 sim_step_in=sim_step_in.reshape(1,1000,163)233 if sim1['state'][r]==1:234 vxvy_invtransform=scaler_out.inverse_transform(model1.predict(sim_step_in))235 elif sim1['state'][r]==2:236 vxvy_invtransform=scaler_out.inverse_transform(model2.predict(sim_step_in))237 elif sim1['state'][r]==4:238 vxvy_invtransform=scaler_out.inverse_transform(model4.predict(sim_step_in))239 else:240 vxvy_invtransform=scaler_out.inverse_transform(model5.predict(sim_step_in)) 241 sim1.iloc[r:(r+1), np.r_[7:9]]=vxvy_invtransform[-1]242 sim1['x'][r:(r+1)]=sim1['x-1'][r:(r+1)]+sim1['vx'][r:(r+1)]243 sim1['y'][r:(r+1)]=sim1['y-1'][r:(r+1)]+sim1['vy'][r:(r+1)]244 sim1['x-1'][(r+1):(r+2)]=sim1['x'][r:(r+1)]245 sim1['y-1'][(r+1):(r+2)]=sim1['y'][r:(r+1)]246 sim1['vx-1'][(r+1):(r+2)]=sim1['vx'][r:(r+1)]247 sim1['vy-1'][(r+1):(r+2)]=sim1['vy'][r:(r+1)]248 #update lagged x,y249 sim1.iloc[(r+1):(r+2),np.r_[13:52]]=sim1.iloc[r:(r+1),np.r_[12:51]].values#update x-2:x-40250 sim1.iloc[(r+1):(r+2),53:92]=sim1.iloc[r:(r+1),np.r_[52:91]].values#update y-2:y-40251 #update lagged vx, vy252 sim1.iloc[(r+1):(r+2),93:132]=sim1.iloc[r:(r+1),np.r_[92:131]].values#update vx-2:vx-40253 sim1.iloc[(r+1):(r+2),133:172]=sim1.iloc[r:(r+1),np.r_[132:171]].values#update vy-2:vy-40254 #update dist255 sim1['dist'][(r+1):(r+2)]=veuc_dist(sim1['x-1'][(r+1):(r+2)],sim1['x-2'][(r+1):(r+2)],sim1['y-1'][(r+1):(r+2)],sim1['y-2'][(r+1):(r+2)])256 get_sim=sim1.to_numpy()257 filename='/LSTM/'+str(sim)+'LSTM7_5_1.npy'258 np.save(filename, get_sim)259 260# Simulate state 1 to 2261for sim in range(5):262 sim1=data_std.loc[idx_sim7]263 for r in range(2704, 3004, 1):264 #Let's start with sim1265 sim_step_in=sim1.iloc[0:(r+1), np.r_[10:173]]266 sim_step_in=scaler_in.transform(sim_step_in)267 sim_step_in=sim_step_in.reshape(1,(r+1),163)268 predstate=model_class.predict(sim_step_in)269 predstate=predstate[-1]270 predstate=predstate[-1]271 predstate=predstate/np.sum(predstate)272 sim1['state'][r]=getClass(predstate)273 if r>=999:274 sim_step_in=sim_step_in[0,(r-999):(r+1),:]275 sim_step_in=sim_step_in.reshape(1,1000,163)276 if sim1['state'][r]==1:277 vxvy_invtransform=scaler_out.inverse_transform(model1.predict(sim_step_in))278 elif sim1['state'][r]==2:279 vxvy_invtransform=scaler_out.inverse_transform(model2.predict(sim_step_in))280 elif sim1['state'][r]==4:281 vxvy_invtransform=scaler_out.inverse_transform(model4.predict(sim_step_in))282 else:283 vxvy_invtransform=scaler_out.inverse_transform(model5.predict(sim_step_in)) 284 sim1.iloc[r:(r+1), np.r_[7:9]]=vxvy_invtransform[-1]285 sim1['x'][r:(r+1)]=sim1['x-1'][r:(r+1)]+sim1['vx'][r:(r+1)]286 sim1['y'][r:(r+1)]=sim1['y-1'][r:(r+1)]+sim1['vy'][r:(r+1)]287 sim1['x-1'][(r+1):(r+2)]=sim1['x'][r:(r+1)]288 sim1['y-1'][(r+1):(r+2)]=sim1['y'][r:(r+1)]289 sim1['vx-1'][(r+1):(r+2)]=sim1['vx'][r:(r+1)]290 sim1['vy-1'][(r+1):(r+2)]=sim1['vy'][r:(r+1)]291 #update lagged x,y292 sim1.iloc[(r+1):(r+2),np.r_[13:52]]=sim1.iloc[r:(r+1),np.r_[12:51]].values#update x-2:x-40293 sim1.iloc[(r+1):(r+2),53:92]=sim1.iloc[r:(r+1),np.r_[52:91]].values#update y-2:y-40294 #update lagged vx, vy295 sim1.iloc[(r+1):(r+2),93:132]=sim1.iloc[r:(r+1),np.r_[92:131]].values#update vx-2:vx-40296 sim1.iloc[(r+1):(r+2),133:172]=sim1.iloc[r:(r+1),np.r_[132:171]].values#update vy-2:vy-40297 #update dist298 sim1['dist'][(r+1):(r+2)]=veuc_dist(sim1['x-1'][(r+1):(r+2)],sim1['x-2'][(r+1):(r+2)],sim1['y-1'][(r+1):(r+2)],sim1['y-2'][(r+1):(r+2)])299 get_sim=sim1.to_numpy()300 filename='/LSTM/'+str(sim)+'LSTM7_1_2.npy'301 np.save(filename, get_sim)302# Simulate state 4 to 5303for sim in range(5):304 sim1=data_std.loc[idx_sim7]305 for r in range(13772, 14072,1):306 #Let's start with sim1307 sim_step_in=sim1.iloc[0:(r+1), np.r_[10:173]]308 sim_step_in=scaler_in.transform(sim_step_in)309 sim_step_in=sim_step_in.reshape(1,(r+1),163)310 predstate=model_class.predict(sim_step_in)311 predstate=predstate[-1]312 predstate=predstate[-1]313 predstate=predstate/np.sum(predstate)314 sim1['state'][r]=getClass(predstate)315 if r>=999:316 sim_step_in=sim_step_in[0,(r-999):(r+1),:]317 sim_step_in=sim_step_in.reshape(1,1000,163)318 if sim1['state'][r]==1:319 vxvy_invtransform=scaler_out.inverse_transform(model1.predict(sim_step_in))320 elif sim1['state'][r]==2:321 vxvy_invtransform=scaler_out.inverse_transform(model2.predict(sim_step_in))322 elif sim1['state'][r]==4:323 vxvy_invtransform=scaler_out.inverse_transform(model4.predict(sim_step_in))324 else:325 vxvy_invtransform=scaler_out.inverse_transform(model5.predict(sim_step_in)) 326 sim1.iloc[r:(r+1), np.r_[7:9]]=vxvy_invtransform[-1]327 sim1['x'][r:(r+1)]=sim1['x-1'][r:(r+1)]+sim1['vx'][r:(r+1)]328 sim1['y'][r:(r+1)]=sim1['y-1'][r:(r+1)]+sim1['vy'][r:(r+1)]329 sim1['x-1'][(r+1):(r+2)]=sim1['x'][r:(r+1)]330 sim1['y-1'][(r+1):(r+2)]=sim1['y'][r:(r+1)]331 sim1['vx-1'][(r+1):(r+2)]=sim1['vx'][r:(r+1)]332 sim1['vy-1'][(r+1):(r+2)]=sim1['vy'][r:(r+1)]333 #update lagged x,y334 sim1.iloc[(r+1):(r+2),np.r_[13:52]]=sim1.iloc[r:(r+1),np.r_[12:51]].values#update x-2:x-40335 sim1.iloc[(r+1):(r+2),53:92]=sim1.iloc[r:(r+1),np.r_[52:91]].values#update y-2:y-40336 #update lagged vx, vy337 sim1.iloc[(r+1):(r+2),93:132]=sim1.iloc[r:(r+1),np.r_[92:131]].values#update vx-2:vx-40338 sim1.iloc[(r+1):(r+2),133:172]=sim1.iloc[r:(r+1),np.r_[132:171]].values#update vy-2:vy-40339 #update dist340 sim1['dist'][(r+1):(r+2)]=veuc_dist(sim1['x-1'][(r+1):(r+2)],sim1['x-2'][(r+1):(r+2)],sim1['y-1'][(r+1):(r+2)],sim1['y-2'][(r+1):(r+2)])341 get_sim=sim1.to_numpy()342 filename='/LSTM/'+str(sim)+'LSTM7_4_5.npy'343 np.save(filename, get_sim)344 345# Simulate during state 2346for sim in range(5):347 sim1=data_std.loc[idx_sim7]348 for r in range(2890, 3190,1):349 #Let's start with sim1350 sim_step_in=sim1.iloc[0:(r+1), np.r_[10:173]]351 sim_step_in=scaler_in.transform(sim_step_in)352 sim_step_in=sim_step_in.reshape(1,(r+1),163)353 predstate=model_class.predict(sim_step_in)354 predstate=predstate[-1]355 predstate=predstate[-1]356 predstate=predstate/np.sum(predstate)357 sim1['state'][r]=getClass(predstate)358 if r>=999:359 sim_step_in=sim_step_in[0,(r-999):(r+1),:]360 sim_step_in=sim_step_in.reshape(1,1000,163)361 if sim1['state'][r]==1:362 vxvy_invtransform=scaler_out.inverse_transform(model1.predict(sim_step_in))363 elif sim1['state'][r]==2:364 vxvy_invtransform=scaler_out.inverse_transform(model2.predict(sim_step_in))365 elif sim1['state'][r]==4:366 vxvy_invtransform=scaler_out.inverse_transform(model4.predict(sim_step_in))367 else:368 vxvy_invtransform=scaler_out.inverse_transform(model5.predict(sim_step_in)) 369 sim1.iloc[r:(r+1), np.r_[7:9]]=vxvy_invtransform[-1]370 sim1['x'][r:(r+1)]=sim1['x-1'][r:(r+1)]+sim1['vx'][r:(r+1)]371 sim1['y'][r:(r+1)]=sim1['y-1'][r:(r+1)]+sim1['vy'][r:(r+1)]372 sim1['x-1'][(r+1):(r+2)]=sim1['x'][r:(r+1)]373 sim1['y-1'][(r+1):(r+2)]=sim1['y'][r:(r+1)]374 sim1['vx-1'][(r+1):(r+2)]=sim1['vx'][r:(r+1)]375 sim1['vy-1'][(r+1):(r+2)]=sim1['vy'][r:(r+1)]376 #update lagged x,y377 sim1.iloc[(r+1):(r+2),np.r_[13:52]]=sim1.iloc[r:(r+1),np.r_[12:51]].values#update x-2:x-40378 sim1.iloc[(r+1):(r+2),53:92]=sim1.iloc[r:(r+1),np.r_[52:91]].values#update y-2:y-40379 #update lagged vx, vy380 sim1.iloc[(r+1):(r+2),93:132]=sim1.iloc[r:(r+1),np.r_[92:131]].values#update vx-2:vx-40381 sim1.iloc[(r+1):(r+2),133:172]=sim1.iloc[r:(r+1),np.r_[132:171]].values#update vy-2:vy-40382 #update dist383 sim1['dist'][(r+1):(r+2)]=veuc_dist(sim1['x-1'][(r+1):(r+2)],sim1['x-2'][(r+1):(r+2)],sim1['y-1'][(r+1):(r+2)],sim1['y-2'][(r+1):(r+2)])384 get_sim=sim1.to_numpy()385 filename='/LSTM/'+str(sim)+'LSTM7_2.npy'386 np.save(filename, get_sim)387 388#simulate during state 5389for sim in range(5):390 sim1=data_std.loc[idx_sim7]391 for r in range(13824,14124,1):392 #Let's start with sim1393 sim_step_in=sim1.iloc[0:(r+1), np.r_[10:173]]394 sim_step_in=scaler_in.transform(sim_step_in)395 sim_step_in=sim_step_in.reshape(1,(r+1),163)396 predstate=model_class.predict(sim_step_in)397 predstate=predstate[-1]398 predstate=predstate[-1]399 predstate=predstate/np.sum(predstate)400 sim1['state'][r]=getClass(predstate)401 if r>=999:402 sim_step_in=sim_step_in[0,(r-999):(r+1),:]403 sim_step_in=sim_step_in.reshape(1,1000,163)404 if sim1['state'][r]==1:405 vxvy_invtransform=scaler_out.inverse_transform(model1.predict(sim_step_in))406 elif sim1['state'][r]==2:407 vxvy_invtransform=scaler_out.inverse_transform(model2.predict(sim_step_in))408 elif sim1['state'][r]==4:409 vxvy_invtransform=scaler_out.inverse_transform(model4.predict(sim_step_in))410 else:411 vxvy_invtransform=scaler_out.inverse_transform(model5.predict(sim_step_in)) 412 sim1.iloc[r:(r+1), np.r_[7:9]]=vxvy_invtransform[-1]413 sim1['x'][r:(r+1)]=sim1['x-1'][r:(r+1)]+sim1['vx'][r:(r+1)]414 sim1['y'][r:(r+1)]=sim1['y-1'][r:(r+1)]+sim1['vy'][r:(r+1)]415 sim1['x-1'][(r+1):(r+2)]=sim1['x'][r:(r+1)]416 sim1['y-1'][(r+1):(r+2)]=sim1['y'][r:(r+1)]417 sim1['vx-1'][(r+1):(r+2)]=sim1['vx'][r:(r+1)]418 sim1['vy-1'][(r+1):(r+2)]=sim1['vy'][r:(r+1)]419 #update lagged x,y420 sim1.iloc[(r+1):(r+2),np.r_[13:52]]=sim1.iloc[r:(r+1),np.r_[12:51]].values#update x-2:x-40421 sim1.iloc[(r+1):(r+2),53:92]=sim1.iloc[r:(r+1),np.r_[52:91]].values#update y-2:y-40422 #update lagged vx, vy423 sim1.iloc[(r+1):(r+2),93:132]=sim1.iloc[r:(r+1),np.r_[92:131]].values#update vx-2:vx-40424 sim1.iloc[(r+1):(r+2),133:172]=sim1.iloc[r:(r+1),np.r_[132:171]].values#update vy-2:vy-40425 #update dist426 sim1['dist'][(r+1):(r+2)]=veuc_dist(sim1['x-1'][(r+1):(r+2)],sim1['x-2'][(r+1):(r+2)],sim1['y-1'][(r+1):(r+2)],sim1['y-2'][(r+1):(r+2)])427 get_sim=sim1.to_numpy()428 filename='/LSTM/'+str(sim)+'LSTM7_5.npy'429 np.save(filename, get_sim)430 431#simulate from state 2 to 4432for sim in range(5):433 sim1=data_std.loc[idx_sim7]434 for r in range(3013,3313,1):435 #Let's start with sim1436 sim_step_in=sim1.iloc[0:(r+1), np.r_[10:173]]437 sim_step_in=scaler_in.transform(sim_step_in)438 sim_step_in=sim_step_in.reshape(1,(r+1),163)439 predstate=model_class.predict(sim_step_in)440 predstate=predstate[-1]441 predstate=predstate[-1]442 predstate=predstate/np.sum(predstate)443 sim1['state'][r]=getClass(predstate)444 if r>=999:445 sim_step_in=sim_step_in[0,(r-999):(r+1),:]446 sim_step_in=sim_step_in.reshape(1,1000,163)447 if sim1['state'][r]==1:448 vxvy_invtransform=scaler_out.inverse_transform(model1.predict(sim_step_in))449 elif sim1['state'][r]==2:450 vxvy_invtransform=scaler_out.inverse_transform(model2.predict(sim_step_in))451 elif sim1['state'][r]==4:452 vxvy_invtransform=scaler_out.inverse_transform(model4.predict(sim_step_in))453 else:454 vxvy_invtransform=scaler_out.inverse_transform(model5.predict(sim_step_in)) 455 sim1.iloc[r:(r+1), np.r_[7:9]]=vxvy_invtransform[-1]456 sim1['x'][r:(r+1)]=sim1['x-1'][r:(r+1)]+sim1['vx'][r:(r+1)]457 sim1['y'][r:(r+1)]=sim1['y-1'][r:(r+1)]+sim1['vy'][r:(r+1)]458 sim1['x-1'][(r+1):(r+2)]=sim1['x'][r:(r+1)]459 sim1['y-1'][(r+1):(r+2)]=sim1['y'][r:(r+1)]460 sim1['vx-1'][(r+1):(r+2)]=sim1['vx'][r:(r+1)]461 sim1['vy-1'][(r+1):(r+2)]=sim1['vy'][r:(r+1)]462 #update lagged x,y463 sim1.iloc[(r+1):(r+2),np.r_[13:52]]=sim1.iloc[r:(r+1),np.r_[12:51]].values#update x-2:x-40464 sim1.iloc[(r+1):(r+2),53:92]=sim1.iloc[r:(r+1),np.r_[52:91]].values#update y-2:y-40465 #update lagged vx, vy466 sim1.iloc[(r+1):(r+2),93:132]=sim1.iloc[r:(r+1),np.r_[92:131]].values#update vx-2:vx-40467 sim1.iloc[(r+1):(r+2),133:172]=sim1.iloc[r:(r+1),np.r_[132:171]].values#update vy-2:vy-40468 #update dist469 sim1['dist'][(r+1):(r+2)]=veuc_dist(sim1['x-1'][(r+1):(r+2)],sim1['x-2'][(r+1):(r+2)],sim1['y-1'][(r+1):(r+2)],sim1['y-2'][(r+1):(r+2)])470 get_sim=sim1.to_numpy()471 filename='/LSTM/'+str(sim)+'LSTM7_2_4.npy'472 np.save(filename, get_sim)...

Full Screen

Full Screen

test_accuracy.py

Source:test_accuracy.py Github

copy

Full Screen

1"""2 Accuracy tests of the algorithms3"""4import numpy as np5import pytest6from cayenne.simulation import Simulation7import matplotlib.pyplot as plt8from cayenne.algorithms.tau_adaptive import tau_adaptive as tac9# def calculate_zy(sim: Simulation, time_list: list, mu_list: list, std_list: list):10# z_list = []11# y_list = []12# n_rep = len(sim.results.t_list)13# for ind1, t in enumerate(time_list[1:]):14# results = sim.results.get_state(t)15# mu_obs = np.mean(results)16# std_obs = np.std(results)17# z_list.append(18# np.sqrt(n_rep) * (mu_obs - mu_list[ind1 + 1]) / std_list[ind1 + 1]19# )20# y_list.append(21# np.sqrt(n_rep / 2) * ((std_obs ** 2) / (std_list[ind1 + 1] ** 2) - 1)22# )23# return np.array(z_list), np.array(y_list)24# def calculate_zy_2sp(sim: Simulation, time_list: list, mu_list: list, std_list: list):25# z_list = []26# y_list = []27# n_rep = len(sim.results.t_list)28# for ind1, t in enumerate(time_list[1:]):29# results = sim.results.get_state(t)30# mu_obs = np.mean(results, axis=0)31# std_obs = np.std(results, axis=0)32# z_list.append(33# np.sqrt(n_rep) * (mu_obs - mu_list[ind1 + 1]) / std_list[ind1 + 1]34# )35# y_list.append(36# np.sqrt(n_rep / 2) * ((std_obs ** 2) / (std_list[ind1 + 1] ** 2) - 1)37# )38# return np.array(z_list), np.array(y_list)39# def test_1x(setup_00003):40# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_0000341# sim1 = Simulation(V_r, V_p, X0, k)42# hor = sim1.HOR43# nc = 1044# epsilon = 0.0345# np.random.seed(0)46# sim_seeds = np.random.randint(low=0, high=1e7, size=n_rep)47# print(sim_seeds[4])48# t, x, status = tac(49# react_stoic=V_r,50# prod_stoic=V_p,51# init_state=X0,52# k_det=k,53# hor=hor,54# nc=nc,55# epsilon=epsilon,56# max_t=max_t,57# max_iter=max_iter,58# volume=1.0,59# seed=sim_seeds[4],60# chem_flag=False,61# )62# plt.plot(t, x)63# plt.show()64# # print(x)65# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])66# def test_00001(setup_00001, algorithm):67# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_0000168# sim1 = Simulation(V_r, V_p, X0, k)69# sim1.simulate(70# algorithm=algorithm, max_t=max_t, max_iter=max_iter, chem_flag=False, n_rep=2071# )72# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)73# assert np.all(sim1.results.final[0] > time_list[-1])74# assert (-3 < Z).all()75# assert (Z < 3).all()76# assert (-5 < Y).all()77# assert (Y < 5).all()78# def plot_zy(Z, Y, time_list):79# plt.figure()80# plt.subplot(121)81# plt.plot(time_list[1:], Z)82# plt.hlines(3, 0, 50)83# plt.hlines(-3, 0, 50)84# plt.ylabel("Observed Z")85# plt.subplot(122)86# plt.plot(time_list[1:], Y)87# plt.hlines(5, 0, 50)88# plt.hlines(-5, 0, 50)89# plt.ylabel("Observed Y")90# def plot_sd(sim, time_list, mu_list, std_list, Z, Y):91# mu_obs_list = []92# std_obs_list = []93# for ind1, t in enumerate(time_list[1:]):94# results = sim.results.get_state(t)95# mu_obs_list.append(np.mean(results))96# std_obs_list.append(np.std(results))97# plt.figure()98# plt.subplot(121)99# plt.plot(time_list[1:], mu_obs_list)100# for i in range(len(Z)):101# if -3 <= Z[i] <= 3:102# marker = "green"103# else:104# marker = "red"105# plt.plot(time_list[i + 1], mu_list[i + 1], "o", color=marker)106# plt.hlines(0, 0, 50)107# plt.ylabel("Observed mean")108# plt.subplot(122)109# plt.plot(time_list[1:], std_obs_list)110# for i in range(len(Y)):111# if -5 <= Y[i] <= 5:112# marker = "green"113# else:114# marker = "red"115# plt.plot(time_list[i + 1], std_list[i + 1], "o", color=marker)116# plt.ylabel("Observed SD")117# @pytest.mark.filterwarnings("ignore::UserWarning")118# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])119# def test_00003(setup_00003, algorithm):120# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00003121# sim1 = Simulation(V_r, V_p, X0, k)122# n_rep = 100123# sim1.simulate(124# algorithm=algorithm,125# max_t=max_t,126# max_iter=max_iter,127# chem_flag=False,128# n_rep=n_rep,129# )130# t_final, x_final = sim1.results.final131# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)132# # plot_zy(Z, Y, time_list)133# # plot_sd(sim1, time_list, mu_list, std_list, Z, Y)134# # plt.show()135# assert (np.array(sim1.results.status_list) != 1).all()136# assert (-3 < Z).all()137# assert (Z < 3).all()138# assert (Y < 5).all()139# assert (-5 < Y).all()140# @pytest.mark.filterwarnings("ignore::UserWarning")141# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])142# def test_00004(setup_00004, algorithm):143# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00004144# sim1 = Simulation(V_r, V_p, X0, k)145# sim1.simulate(146# algorithm=algorithm,147# max_t=max_t,148# max_iter=max_iter,149# chem_flag=False,150# n_rep=n_rep,151# )152# t_final, x_final = sim1.results.final153# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)154# assert (np.array(sim1.results.status_list) != 1).all()155# assert (-3 < Z).all()156# assert (Z < 3).all()157# assert (-5 < Y).all()158# assert (Y < 5).all()159# @pytest.mark.filterwarnings("ignore::UserWarning")160# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])161# def test_00005(setup_00005, algorithm):162# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00005163# sim1 = Simulation(V_r, V_p, X0, k)164# sim1.simulate(165# algorithm=algorithm,166# max_t=max_t,167# max_iter=max_iter,168# chem_flag=False,169# n_rep=n_rep,170# )171# t_final, x_final = sim1.results.final172# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)173# assert (np.array(sim1.results.status_list) != 1).all()174# assert (-3 < Z).all()175# assert (Z < 3).all()176# assert (-5 < Y).all()177# assert (Y < 5).all()178# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])179# def test_00011(setup_00011, algorithm):180# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00011181# sim1 = Simulation(V_r, V_p, X0, k)182# sim1.simulate(183# algorithm=algorithm,184# max_t=max_t,185# max_iter=max_iter,186# chem_flag=False,187# n_rep=n_rep,188# )189# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)190# assert (-3 < Z).all()191# assert (Z < 3).all()192# assert (-5 < Y).all()193# assert (Y < 5).all()194# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])195# def test_00020(setup_00020, algorithm):196# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00020197# sim1 = Simulation(V_r, V_p, X0, k)198# sim1.simulate(199# algorithm=algorithm,200# max_t=max_t,201# max_iter=max_iter,202# chem_flag=False,203# n_rep=n_rep,204# )205# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)206# assert (-3 < Z).all()207# assert (Z < 3).all()208# assert (-5 < Y).all()209# assert (Y < 5).all()210# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])211# def test_00021(setup_00021, algorithm):212# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00021213# sim1 = Simulation(V_r, V_p, X0, k)214# sim1.simulate(215# algorithm=algorithm,216# max_t=max_t,217# max_iter=max_iter,218# chem_flag=False,219# n_rep=n_rep,220# )221# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)222# assert (-3 < Z).all()223# assert (Z < 3).all()224# assert (-5 < Y).all()225# assert (Y < 5).all()226# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])227# def test_00022(setup_00022, algorithm):228# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00022229# sim1 = Simulation(V_r, V_p, X0, k)230# sim1.simulate(231# algorithm=algorithm,232# max_t=max_t,233# max_iter=max_iter,234# chem_flag=False,235# n_rep=n_rep,236# )237# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)238# assert (-3 < Z).all()239# assert (Z < 3).all()240# assert (-5 < Y).all()241# assert (Y < 5).all()242# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])243# def test_00023(setup_00023, algorithm):244# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00023245# sim1 = Simulation(V_r, V_p, X0, k)246# sim1.simulate(247# algorithm=algorithm,248# max_t=max_t,249# max_iter=max_iter,250# chem_flag=False,251# n_rep=n_rep,252# )253# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)254# assert (-3 < Z).all()255# assert (Z < 3).all()256# assert (-5 < Y).all()257# assert (Y < 5).all()258# @pytest.mark.filterwarnings("ignore::UserWarning")259# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])260# def test_00030(setup_00030, algorithm):261# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00030262# sim1 = Simulation(V_r, V_p, X0, k)263# sim1.simulate(264# algorithm=algorithm,265# max_t=max_t,266# max_iter=max_iter,267# chem_flag=False,268# n_rep=n_rep,269# )270# Z, Y = calculate_zy_2sp(sim1, time_list, mu_list, std_list)271# assert (np.array(sim1.results.status_list) != 1).all()272# assert (-3 < Z).all()273# assert (Z < 3).all()274# assert (-5 < Y).all()275# assert (Y < 5).all()276# @pytest.mark.filterwarnings("ignore::UserWarning")277# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])278# def test_00031(setup_00031, algorithm):279# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00031280# sim1 = Simulation(V_r, V_p, X0, k)281# sim1.simulate(282# algorithm=algorithm,283# max_t=max_t,284# max_iter=max_iter,285# chem_flag=False,286# n_rep=n_rep,287# )288# Z, Y = calculate_zy_2sp(sim1, time_list, mu_list, std_list)289# assert (-3 < Z).all()290# assert (Z < 3).all()291# assert (-5 < Y).all()292# assert (Y < 5).all()293# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])294# def test_00037(setup_00037, algorithm):295# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00037296# sim1 = Simulation(V_r, V_p, X0, k)297# sim1.simulate(298# algorithm=algorithm,299# max_t=max_t,300# max_iter=max_iter,301# chem_flag=False,302# n_rep=n_rep,303# )304# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)305# assert (-3 < Z).all()306# assert (Z < 3).all()307# assert (-5 < Y).all()308# assert (Y < 5).all()309# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])310# def test_00038(setup_00038, algorithm):311# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00038312# sim1 = Simulation(V_r, V_p, X0, k)313# sim1.simulate(314# algorithm=algorithm,315# max_t=max_t,316# max_iter=max_iter,317# chem_flag=False,318# n_rep=n_rep,319# )320# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)321# assert (-3 < Z).all()322# assert (Z < 3).all()323# assert (-5 < Y).all()324# assert (Y < 5).all()325# @pytest.mark.filterwarnings("ignore::UserWarning")326# @pytest.mark.parametrize("algorithm", ["tau_adaptive"])327# def test_00039(setup_00039, algorithm):328# V_r, V_p, X0, k, time_list, mu_list, std_list, max_t, max_iter, n_rep = setup_00039329# sim1 = Simulation(V_r, V_p, X0, k)330# sim1.simulate(331# algorithm=algorithm,332# max_t=max_t,333# max_iter=max_iter,334# chem_flag=False,335# n_rep=n_rep,336# )337# Z, Y = calculate_zy(sim1, time_list, mu_list, std_list)338# assert (-3 < Z).all()339# assert (Z < 3).all()340# assert (-5 < Y).all()...

Full Screen

Full Screen

test_copy.py

Source:test_copy.py Github

copy

Full Screen

1import rebound2import unittest3import datetime4import socket5import warnings6class TestCopy(unittest.TestCase):7 def test_copy_is_same(self):8 sim = rebound.Simulation()9 sim.add(m=1)10 sim.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)11 sim.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)12 sim.integrator = "whfast"13 sim.integrate(42.)14 sim.save("test.bin")15 16 sim_copy = sim.copy()17 18 self.assertEqual(sim.t,sim_copy.t)19 for i in range(sim.N):20 self.assertEqual(sim.particles[i].x,sim_copy.particles[i].x)21 self.assertEqual(sim.particles[i].y,sim_copy.particles[i].y)22 self.assertEqual(sim.particles[i].z,sim_copy.particles[i].z)23 self.assertEqual(sim.particles[i].vx,sim_copy.particles[i].vx)24 self.assertEqual(sim.particles[i].vy,sim_copy.particles[i].vy)25 self.assertEqual(sim.particles[i].vz,sim_copy.particles[i].vz)26 27 sim_copy.integrate(84.)28 sim.integrate(84.)29 self.assertEqual(sim.t,sim_copy.t)30 for i in range(sim.N):31 self.assertEqual(sim.particles[i].x,sim_copy.particles[i].x)32 self.assertEqual(sim.particles[i].y,sim_copy.particles[i].y)33 self.assertEqual(sim.particles[i].z,sim_copy.particles[i].z)34 self.assertEqual(sim.particles[i].vx,sim_copy.particles[i].vx)35 self.assertEqual(sim.particles[i].vy,sim_copy.particles[i].vy)36 self.assertEqual(sim.particles[i].vz,sim_copy.particles[i].vz)37 38 sim.integrate(126.)39 40 self.assertNotEqual(sim.t,sim_copy.t)41 for i in range(sim.N):42 self.assertNotEqual(sim.particles[i].x,sim_copy.particles[i].x)43 self.assertNotEqual(sim.particles[i].y,sim_copy.particles[i].y)44 self.assertNotEqual(sim.particles[i].z,sim_copy.particles[i].z)45 self.assertNotEqual(sim.particles[i].vx,sim_copy.particles[i].vx)46 self.assertNotEqual(sim.particles[i].vy,sim_copy.particles[i].vy)47 self.assertNotEqual(sim.particles[i].vz,sim_copy.particles[i].vz)48class TestMultiply(unittest.TestCase):49 def test_multiply_with_minus_one(self):50 sim1 = rebound.Simulation()51 sim1.add(m=1)52 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)53 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)54 sim1.integrator = "whfast"55 sim1.integrate(2.)56 57 sim2 = sim1*(-1.)58 59 for i in range(sim1.N):60 self.assertEqual(-sim1.particles[i].x,sim2.particles[i].x)61 self.assertEqual(-sim1.particles[i].y,sim2.particles[i].y)62 self.assertEqual(-sim1.particles[i].z,sim2.particles[i].z)63 self.assertEqual(-sim1.particles[i].vx,sim2.particles[i].vx)64 self.assertEqual(-sim1.particles[i].vy,sim2.particles[i].vy)65 self.assertEqual(-sim1.particles[i].vz,sim2.particles[i].vz)66 67 def test_rmultiply_with_minus_one(self):68 sim1 = rebound.Simulation()69 sim1.add(m=1)70 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)71 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)72 sim1.integrator = "whfast"73 sim1.integrate(2.)74 75 sim2 = -1.*sim176 77 for i in range(sim1.N):78 self.assertEqual(-sim1.particles[i].x,sim2.particles[i].x)79 self.assertEqual(-sim1.particles[i].y,sim2.particles[i].y)80 self.assertEqual(-sim1.particles[i].z,sim2.particles[i].z)81 self.assertEqual(-sim1.particles[i].vx,sim2.particles[i].vx)82 self.assertEqual(-sim1.particles[i].vy,sim2.particles[i].vy)83 self.assertEqual(-sim1.particles[i].vz,sim2.particles[i].vz)84 85 def test_multiply_with_zero(self):86 sim1 = rebound.Simulation()87 sim1.add(m=1)88 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)89 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)90 sim1.integrator = "whfast"91 sim1.integrate(2.)92 sim2 = 0*sim193 94 for i in range(sim1.N):95 self.assertNotEqual(-sim1.particles[i].x,0.)96 self.assertNotEqual(-sim1.particles[i].y,0.)97 self.assertNotEqual(-sim1.particles[i].z,0.)98 self.assertNotEqual(-sim1.particles[i].vx,0.)99 self.assertNotEqual(-sim1.particles[i].vy,0.)100 self.assertNotEqual(-sim1.particles[i].vz,0.)101 for i in range(sim2.N):102 self.assertEqual(-sim2.particles[i].x,0.)103 self.assertEqual(-sim2.particles[i].y,0.)104 self.assertEqual(-sim2.particles[i].z,0.)105 self.assertEqual(-sim2.particles[i].vx,0.)106 self.assertEqual(-sim2.particles[i].vy,0.)107 self.assertEqual(-sim2.particles[i].vz,0.)108 109 def test_div2(self):110 sim1 = rebound.Simulation()111 sim1.add(m=1)112 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)113 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)114 sim1.integrator = "whfast"115 sim1.integrate(2.)116 sim2 = sim1/2117 118 for i in range(sim1.N):119 self.assertEqual(2*sim2.particles[i].x,sim1.particles[i].x)120 self.assertEqual(2*sim2.particles[i].y,sim1.particles[i].y)121 self.assertEqual(2*sim2.particles[i].z,sim1.particles[i].z)122 self.assertEqual(2*sim2.particles[i].vx,sim1.particles[i].vx)123 self.assertEqual(2*sim2.particles[i].vy,sim1.particles[i].vy)124 self.assertEqual(2*sim2.particles[i].vz,sim1.particles[i].vz)125class TestAdd(unittest.TestCase):126 def test_add(self):127 sim1 = rebound.Simulation()128 sim1.add(m=1)129 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)130 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)131 sim1.integrator = "whfast"132 sim2 = sim1.copy()133 sim1.integrate(2.)134 sim3 = sim1 + sim2135 136 for i in range(sim3.N):137 self.assertEqual(sim3.particles[i].x, sim1.particles[i].x +sim2.particles[i].x )138 self.assertEqual(sim3.particles[i].y, sim1.particles[i].y +sim2.particles[i].y )139 self.assertEqual(sim3.particles[i].z, sim1.particles[i].z +sim2.particles[i].z )140 self.assertEqual(sim3.particles[i].vx,sim1.particles[i].vx+sim2.particles[i].vx)141 self.assertEqual(sim3.particles[i].vy,sim1.particles[i].vy+sim2.particles[i].vy)142 self.assertEqual(sim3.particles[i].vz,sim1.particles[i].vz+sim2.particles[i].vz)143 144 def test_iadd(self):145 sim1 = rebound.Simulation()146 sim1.add(m=1)147 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)148 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)149 sim1.integrator = "whfast"150 sim2 = sim1.copy()151 sim1.integrate(2.)152 sim3 = sim1 + sim2153 sim1 += sim2154 155 for i in range(sim3.N):156 self.assertEqual(sim3.particles[i].x, sim1.particles[i].x )157 self.assertEqual(sim3.particles[i].y, sim1.particles[i].y )158 self.assertEqual(sim3.particles[i].z, sim1.particles[i].z )159 self.assertEqual(sim3.particles[i].vx,sim1.particles[i].vx)160 self.assertEqual(sim3.particles[i].vy,sim1.particles[i].vy)161 self.assertEqual(sim3.particles[i].vz,sim1.particles[i].vz)162 163class TestSubtract(unittest.TestCase):164 def test_subtract(self):165 sim1 = rebound.Simulation()166 sim1.add(m=1)167 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)168 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)169 sim1.integrator = "whfast"170 sim2 = sim1.copy()171 sim1.integrate(2.)172 173 sim3 = sim1 - sim2174 175 for i in range(sim3.N):176 self.assertEqual(sim3.particles[i].x, sim1.particles[i].x -sim2.particles[i].x )177 self.assertEqual(sim3.particles[i].y, sim1.particles[i].y -sim2.particles[i].y )178 self.assertEqual(sim3.particles[i].z, sim1.particles[i].z -sim2.particles[i].z )179 self.assertEqual(sim3.particles[i].vx,sim1.particles[i].vx-sim2.particles[i].vx)180 self.assertEqual(sim3.particles[i].vy,sim1.particles[i].vy-sim2.particles[i].vy)181 self.assertEqual(sim3.particles[i].vz,sim1.particles[i].vz-sim2.particles[i].vz)182 183 def test_isubtract(self):184 sim1 = rebound.Simulation()185 sim1.add(m=1)186 sim1.add(m=1e-3,a=1,e=0.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)187 sim1.add(m=1e-3,a=-2,e=1.1,omega=0.1,M=0.1,inc=0.1,Omega=0.1)188 sim1.integrator = "whfast"189 sim2 = sim1.copy()190 sim1.integrate(2.)191 192 sim3 = sim1 - sim2193 sim1 -= sim2194 195 for i in range(sim3.N):196 self.assertEqual(sim3.particles[i].x, sim1.particles[i].x )197 self.assertEqual(sim3.particles[i].y, sim1.particles[i].y )198 self.assertEqual(sim3.particles[i].z, sim1.particles[i].z )199 self.assertEqual(sim3.particles[i].vx,sim1.particles[i].vx)200 self.assertEqual(sim3.particles[i].vy,sim1.particles[i].vy)201 self.assertEqual(sim3.particles[i].vz,sim1.particles[i].vz)202 203if __name__ == "__main__":...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ATX automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful