-
Notifications
You must be signed in to change notification settings - Fork 0
/
hotspot_file_02.py
1504 lines (957 loc) · 47.2 KB
/
hotspot_file_02.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
from numpy import linalg as LA
from scipy.spatial import distance
import mpi4py
import pandas as pd
#import atomman as am
from lammps import lammps
from itertools import islice
import os
import multiprocessing
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
from sklearn.metrics import mean_squared_error, r2_score
from math import sqrt
#from matplotlib.patches import Circle
#from matplotlib import cm
from sklearn.decomposition import PCA
import math
import re
import glob
#import pymp for parallel processing
import pymp
#import other files
import feature_extract_01
import ML_functions01
class dump_preprocess():
def __init__(self, id, list_of_files, col_to_select, coords_file, coords_loc, prop_files, str):
self.process_id = id
self.string_pat = sorted(list_of_files, key=key_func)
self.column_list = col_to_select
self.xyz_pat = sorted(coords_file, key=key_func)
self.coords_loc = coords_loc
self.prop_files = prop_files
self.prop_str = str
self.hotspot_number = 10 #number of hotspots I'm dealing with
#Call these functions
#self.detect_pe_hotspot()
#for t in range(0, len(self.string_pat)):
def read_files(self):
array_list = []
xyz_array_list = []
bound_list = []
file_count = 0
for file_name in (self.string_pat):
with open(file_name, 'r') as f:
#first read table to get the bounding box
df = pd.read_table(file_name, delim_whitespace=True, header=None, skiprows=9)
df = df.sort_values(by=len(self.column_list), ascending=False) #2 because y
#take note that you're sorting before you're getting rid of columns
array_length = len(df.as_matrix())
series_out = np.empty((array_length, 0)) #specify empty numpy array
for i in range(0, len(self.column_list)):
series_temp = df.loc[:, self.column_list[i]]
series_temp = series_temp.as_matrix()
series_out = np.append(series_out, series_temp[:, None], axis=1)
array_list.append(series_out)
for file_name in (self.xyz_pat): #this is for interatomic distance
with open(file_name, 'r') as f:
file_count += 1
df_bounds = pd.read_table(file_name, delim_whitespace=True, header=None, skiprows=5, nrows=3)
# bounds as array
bound_array = df_bounds.as_matrix()
df = pd.read_table(file_name, delim_whitespace=True, header=None, skiprows=9)
df = df.sort_values(by=0, ascending=True) # 2 because y
array_length = len(df.as_matrix())
series_out = np.empty((array_length, 0)) #specify empty numpy array
for i in range(0, len(self.coords_loc)):
series_temp = df.loc[:, self.coords_loc[i]]
series_temp = series_temp.as_matrix()
series_out = np.append(series_out, series_temp[:, None], axis=1)
xyz_array_list.append(series_out)
bound_list.append(bound_array)
return array_list, xyz_array_list, bound_list
def find_atoms_by_dist(self, array_list, xyz_list, N):
self.xyz_list = []
for t in range(0, len(array_list)):
A1 = array_list[t]
#from A1 I want to find where the maximum interatomic id's exist
#I will select the top N
self.id_1 = (A1[0:N, 0]).astype(int)
self.id_2 = (A1[0:N, 1]).astype(int)
self.max_dist = (A1[0:N, 2])
#index out the corresponding
A2 = xyz_list[t]
#The issue here is that I have not indexed where the ID's are in the XYZ list
#I have to index
idx_1 = self.id_1 - 1
idx_2 = self.id_2 - 1
self.xyz_1 = np.hstack(((A2[idx_1, 1]).reshape(N, 1), (A2[idx_1, 2]).reshape(N, 1), (A2[idx_1, 3]).reshape(N, 1)))
self.xyz_2 = np.hstack(
((A2[idx_2, 1]).reshape(N, 1), (A2[idx_2, 2]).reshape(N, 1), (A2[idx_2, 3]).reshape(N, 1)))
self.xyz_list.append(0.5*(self.xyz_1 + self.xyz_2))
return None
###Need to create a function to draw boxes around
def detect_pe_hotspot(self):
self.pe_array_list, self.pe_hspot = select_by_property(self.prop_files, self.prop_str, self.hotspot_number)
return self.pe_array_list
###-----------files to extract structures
class MD_models():
def __init__(self, list_of_files, forcefile, str, convolve_params):
self.prop_str = str #The list of properties we want to read
self.total_files = sorted(glob.glob(list_of_files), key=key_func)
#Troubleshoot
print self.total_files
self.df_list, z_list, z_coords = read_MD_model(self.total_files)
self.raw_y = get_raw_targets(forcefile)
self.targets = feature_extract_01.configure_targets(file_list=self.total_files, targets=self.raw_y)
#print "configure targets: "
#print self.targets[0:20]
self.RBF, r_v = feature_extract_01.CNT_atoms(self.df_list[0], z_list[0])
#print self.RBF.shape
#r_d, self.RBF_d = feature_extract_01.discretize_features(self.RBF)
#for i in range(0, 7):
#feature_extract_01.plot_features(r_v, self.RBF[244, :, :], i)
#for i in range(0, 7):
#feature_extract_01.plot_features02(r_v, self.RBF[256, :, :], r_d, self.RBF_d[256, :, :], i)
###block of code for the new RBF
self.RBF, self.R_v = feature_extract_01.RBF_Setter(df_list=self.df_list, z_list=z_list, total_files=self.total_files)
#print "RBF list shape: ", (self.RBF).shape
CNT_data, RBF_data, y_out, center_list = feature_extract_01.transfor_rot(df_list=self.df_list, RBF_in=self.RBF, targets=self.targets, z_cords=z_coords)
#additional block to convolve around the circle
#theta_list = feature_extract_01.linearize_cicle(cnt_list=CNT_data, center_list=center_list)
max_y = np.amax(y_out)
y_out = y_out/np.amax(y_out)
RBF_1, RBF_2, _ = feature_extract_01.discretize_2D(cnt_array=CNT_data, RBF_array=RBF_data)
print len(CNT_data)
print len(center_list)
print len(RBF_data)
print CNT_data[100]
print RBF_data[100]
print self.targets
print y_out
RBF_1, RBF_2, cols_dropped = feature_extract_01.RBF_eliminator(RBF_1=RBF_1, RBF_2=RBF_2)
#X_t1, X_t2, Y_t, X_e1, X_e2, Y_e = feature_extract_01.partition_data(X=RBF_1, X2=RBF_2, Y=y_out, f=0.5)
X_t1, X_t2, Y_t, X_e1, X_e2, Y_e = feature_extract_01.partition_data02(X=RBF_1, X2=RBF_2, Y=y_out, n=53)
#X_t1, X_t2, Y_t, X_e1, X_e2, Y_e, X_v1, X_v2, Y_v = feature_extract_01.partition_data03(X=RBF_1, X2=RBF_2, Y=y_out, n=48, n2=53) #replacement
X_t1, X_t2, Y_t = feature_extract_01.shuffle_data(X_t1, X_t2, Y_t)
#save R_v, col_droppped
np.save('col_dropped.npy', cols_dropped)
np.save('R_v.npy', self.R_v)
#RBF_m1, RBF_std1 = feature_extract_01.normalize_RBF(RBF_1)
#print np.where(RBF_1[15, :, :, :] > 0)
#print np.where(RBF_2[15, :, :, :] > 0)
#print self.raw_y
model_cnn = ML_functions01.CNN_model01(RBF_1.shape[1], RBF_1.shape[2], RBF_1.shape[3])
model_cnn = ML_functions01.fit_model(model=model_cnn, X1=X_t1, X2=X_t2, Y=Y_t)
Y = model_cnn.predict([X_e1, X_e2])
e_val = sqrt(mean_squared_error(Y_e, Y.flatten()))
R2_val = r2_score(Y_e.flatten(), Y)
max_err = np.amax(mean_squared_error(Y_e, Y.flatten()))
idx_err = np.argmax(mean_squared_error(Y_e, Y.flatten()))
print Y.flatten()
print Y_e
print e_val
print e_val*max_y
print R2_val
print idx_err
model_2 = ML_functions01.fit_model03(RBF=RBF_1, X1=X_t1, X2=X_t2, Y=Y_t)
#model_2 = ML_functions01.fit_model04(RBF=RBF_1, X1=X_t1, X2=X_t2, Y=Y_t, X_v1=X_v1, X_v2=X_v2, Y_v=Y_v) #replacement for one above
Y2 = model_2.predict([X_e1, X_e2])
e_val2 = sqrt(mean_squared_error(Y_e, Y2.flatten()))
R2_val2 = r2_score(Y_e.flatten(), Y2)
print e_val2
print e_val2 * max_y
print R2_val2
print Y2.flatten()
print Y_e
W = ML_functions01.get_model_weights(model_2)
#model_2.save_weights('W_1b.h5')
print W[0][:, :, :, 0]
print W[0][:, :, :, 1]
#np.save('W0_b.npy', W[0])
Y1, Y2 =feature_extract_01.pick_ogvalues(Y_e, Y2.flatten())
e_val3 = sqrt(mean_squared_error(Y1, Y2))
R2_val3 = r2_score(Y1, Y2)
print e_val3
print e_val3 * max_y
print R2_val3
print Y1*max_y
print Y2*max_y
np.save('Y_e2.npy', Y_e)
np.save('Y_p2.npy', Y.flatten())
#print RBF_1.shape
#need a block here to sort out
####----_Second files for dump processes
class dump_files():
def __init__(self, id, str, total_hotspot, convolve_params, *args):
self.process_id = id #ID of the dump files
self.prop_str = str #The list of properties we want to read
self.peratom_files = sorted(glob.glob(args[0]), key=key_func)
self.unique_type = np.array([1, 2, 3, 4, 5, 9, 11, 12, 13, 15, 16, 18, 20])
if len(args) > 1:
self.local_files = sorted(glob.glob(args[1]), key=key_func)
self.df_list, self.array_list, self.pe_hotspot_list, self.bound_list = select_by_property(file_list=self.peratom_files,
prop_name=self.prop_str, N=total_hotspot, sort_choose=True)
self.convolve_size = convolve_params['channel_size']
self.stride = convolve_params['delta']
self.box_tol = convolve_params['tol']
self.Radius = convolve_params['Radius']
self.epsilon = convolve_params['epsilon']
#find hotspots by convolving
def prop_end_timesteps(self):
end_diff = self.property_list[len(self.property_list) - 1] - self.property_list[0]
return end_diff
def add_del_files(self, delepx_files, delcnt_files):
self.delepx_files = sorted(glob.glob(delepx_files), key=key_func)
self.delcnt_files = sorted(glob.glob(delcnt_files), key=key_func)
self.df_delepx_list, self.delepx_array_list, _, _ = select_by_property(
file_list=self.delepx_files,
prop_name=self.prop_str, N=10, sort_choose=False)
self.df_delcnt_list, self.delcnt_array_list, _, _ = select_by_property(
file_list=self.delcnt_files,
prop_name=self.prop_str, N=10, sort_choose=False)
return None
def add_group_files(self, alkane_file, fun_file, bondedCNT_file):
self.alkane_files = sorted(glob.glob(alkane_file), key=key_func)
self.fun_file = sorted(glob.glob(fun_file), key=key_func)
self.bondedcnt_file = sorted(glob.glob(bondedCNT_file), key=key_func)
self.df_alkane_list, self.alkane_array_list, _, _ = select_by_property(file_list=self.alkane_files, prop_name=[],
N=10, sort_choose=False)
self.df_fun_list, self.fun_array_list, _, _ = select_by_property(file_list=self.fun_file,
prop_name=[],
N=10, sort_choose=False)
self.df_bondedcnt_list, self.bondedcnt_array_list, _, _ = select_by_property(file_list=self.bondedcnt_file,
prop_name=[],
N=10, sort_choose=False)
del self.alkane_array_list[0:2]
print len(self.alkane_files)
print self.alkane_array_list
print len(self.fun_file)
print len(self.bondedcnt_file)
t_max = len(self.alkane_array_list)
dist_alkaneC = np.zeros((t_max,))
dist_cnt = np.zeros_like(dist_alkaneC)
for t in range(0, t_max):
pointC = self.alkane_array_list[t][0, 2:5]
pointO = self.fun_array_list[t][0, 2:5]
pointCNT = self.bondedcnt_array_list[t][0, 2:5]
dist_alkaneC[t] = np.linalg.norm(pointC - pointO)
dist_cnt[t] = np.linalg.norm(pointCNT - pointO)
self.d_alkaneC = dist_alkaneC
self.d_cnt = dist_cnt
return None
def extract_cnt_velocity(self, graph_dict):
cnt_vz = pymp.shared.array((len(self.df_list), ), dtype='float64')
other_vz = pymp.shared.array((len(self.df_list),), dtype='float64')
cnt_disp = pymp.shared.array((len(self.df_list), ), dtype='float64')
#Get data from dict
f_min = graph_dict['f_min']
f_max = graph_dict['f_max']
t_max = graph_dict['t_max']
res = graph_dict['res'] # res -> frequency of timesteps with which we have dump files
#Extracting out indexes to draw graphs
f_idx1 = graph_dict['f_idx1']
f_idx2 = graph_dict['f_idx2']
with pymp.Parallel(multiprocessing.cpu_count()) as p:
for t in p.range(0, len(self.df_list)):
df_tmp = self.df_list[t]
df_cnt = df_tmp[df_tmp['type']==22]
df_other =df_tmp[df_tmp['type']!=22]
df_cnt_v = df_cnt['vz']
df_other_v = df_other['vz']
df_cnt_disp = df_cnt['c_dpa[3]']
cnt_vz[t] = np.mean(np.asarray(df_cnt_v), axis=0)
other_vz[t] = np.mean(np.asarray(df_other_v), axis=0)
cnt_disp[t] = np.mean(np.asarray(df_cnt_disp), axis=0)
self.cnt_mean_velocity = cnt_vz
#stride = 20
stride = 5
dt = 0.1
#v_diff = np.gradient(self.cnt_mean_velocity, 0.1*np.arange(0, len(self.cnt_mean_velocity)))
self.cnt_mean_velocity = self.cnt_mean_velocity[:, None]
self.cnt_mean_velocity = reduce_by_mean(self.cnt_mean_velocity, stride)
#self.cnt_mean_acc = reduce_by_mean(v_diff[:, None], stride)
self.cnt_mean_acc= np.gradient(self.cnt_mean_velocity.flatten())
print "mean", np.mean(self.cnt_mean_velocity)
print self.cnt_mean_acc
cnt_disp = cnt_disp[:, None]
#cnt_disp = reduce_by_mean(cnt_disp, stride)
f = f_min + ((f_max - f_min)/t_max)*(dt*stride*res)*np.arange(0, len(self.cnt_mean_velocity))
#print "f: "
#print f
#extracting out indices for plots
idx_1 = int(len(self.cnt_mean_velocity)*(f_idx1)/(f_max - f_min))
idx_2 = int(len(self.cnt_mean_velocity) * (f_idx2) / (f_max - f_min))
plt.plot(f[idx_1:idx_2], self.cnt_mean_velocity[idx_1:idx_2], 'ko')
plt.xlabel('Pull-out force per atom (kcal/mol-A)')
plt.ylabel('Mean Velocity (A/fs)')
#plt.savefig('fig_1A.eps')
#plt.savefig('fig_1A.pngf')
plt.show()
#np.save('f_00004.npy', f[idx_1:idx_2])
#np.save('v_00004.npy', self.cnt_mean_velocity[idx_1:idx_2])
#np.save('d_00004.npy', cnt_disp[idx_1:idx_2])
plt.plot(f[idx_1:idx_2], cnt_disp[idx_1:idx_2])
plt.xlabel('Pull-out force per atom (kcal/mol-A)')
plt.ylabel('Cummulative displacement (A)')
plt.savefig('fig_1B.eps')
plt.show()
#print f.shape
#print self.cnt_mean_acc
plt.plot(f[idx_1:idx_2], self.cnt_mean_acc[idx_1:idx_2])
plt.xlabel('Pull-out force per atom (kcal/mol-A)')
plt.ylabel('Acceleration (A/fs.squared)')
#plt.savefig('fig_1B.eps')
plt.show()
if hasattr(self, 'd_alkaneC'):
plt.plot(f[idx_1:idx_2], self.d_alkaneC[idx_1:idx_2])
plt.xlabel('Pull-out force per atom (kcal/mol-$\AA$)')
plt.ylabel('Distance between nitrogen and aromatic carbon')
plt.savefig('fig_R-O.eps', format='eps', dpi=1000)
plt.show()
if hasattr(self, 'd_cnt'):
plt.plot(f[idx_1:idx_2], self.d_cnt[idx_1:idx_2])
plt.xlabel('Pull-out force per atom (kcal/mol-$\AA$)')
plt.ylabel('Distance between CNT and oxygen ')
plt.savefig('fig_CNT-O.svg')
plt.show()
#check bonds
return None
def plot_interaction_energy(self, graph_dict, filename):
E2 = pymp.shared.array((len(self.df_list), ), dtype='float64')
E3 = pymp.shared.array((len(self.df_list), ), dtype='float64')
#graph_list = {'f_min': 0, 'f_max': 0.025, 't_max': 500000, 'res': 500}
f_min = graph_dict['f_min']
f_max = graph_dict['f_max']
t_max = graph_dict['t_max']
res = graph_dict['res'] #res -> frequency of timesteps with which we have dump files
with pymp.Parallel(multiprocessing.cpu_count()) as p:
for t in p.range(0, len(self.df_list)):
df_1 = self.df_list[t]
E1[t] = np.sum(np.asarray(df_1[self.prop_str]), axis=0)
df_2 = self.df_delcnt_list[t]
E2[t] = np.sum(np.asarray(df_2[self.prop_str]), axis=0)
df_3 = self.df_delepx_list[t]
E3[t] = np.sum(np.asarray(df_3[self.prop_str]), axis=0)
I = E1 - E2 - E3
I = I[:, None]
stride = 2
dt = 0.1
I2 = reduce_by_mean(I, stride)
plt.plot(f_min + ((f_max - f_min)/t_max)*(dt*stride*res)*np.arange(0, len(I2)), I2, 'ko')
plt.xlabel('Pull-out force per atom (kcal/mol-A)')
plt.ylabel('Interaction Energy (kcal/mol)')
plt.savefig(filename)
plt.show()
return None
def convolve_under_shear(self):
stride = self.stride
temp_channel_init = self.convolve_size.copy()
max_n_points = 10
n_surf = 4 #number of surfaces to convolve over
max_t = len(self.array_list)
bound_old = self.bound_list[0].copy()
print "Max_t: ", max_t
#time period to select
t_p = 1
def_temp = 0
list_count = 0 # counter to compute diff_mat
property_map_list = []
loc_list = []
idx_list_list = []
self.cnt_bound_list = []
#with pymp.Parallel(24) as p:
for t in range(0, t_p):
atom_new = self.array_list[t].copy()
bound_new = self.bound_list[t].copy()
#delatom import
#delcnt_new = self.df_delcnt_list[t].copy()
#delepx_new = self.df_delepx_list[t].copy()
delta_x = (bound_new[0, 1] - bound_new[0, 0]) - (bound_old[0, 1] - bound_old[0, 0])
delta_y = (bound_new[1, 1] - bound_new[1, 0]) - (bound_old[1, 1] - bound_old[1, 0])
delta_z = (bound_new[2, 1] - bound_new[2, 0]) - (bound_old[2, 1] - bound_old[2, 0])
temp_channel = temp_channel_init + np.asarray([delta_x, delta_y, delta_z])
#cnt_bounds, box_bound = extract_cnt_coords(self.df_list[t], bound_new, self.box_tol, self.prop_str)
#now let's start getting the cnt atoms
self.cnt_bounds = extract_cnt_coords(df=self.df_list[t])
self.compute_centroid_and_radius()
print "CNT Bounds: ", self.cnt_bounds
self.cnt_bound_list.append(self.cnt_bounds)
print "Bound list: ", self.bound_list[t]
#define empty arrays for concatenating
I_temp = np.empty((n_surf*max_n_points, )) #4 -> number of surfaces in
box_min_temp = np.empty((n_surf*max_n_points, 3)) #define each convolution by the minimum
#The surface id and the
surface_temp = np.empty_like(I_temp)
loc_temp = np.empty_like(box_min_temp)
#final arrays
loc_final = np.empty((max_n_points, 3))
#numpy arrays to stack
coords_array = np.empty((0, 3))
#print "Bounds: ", bound_new
#for each centroid we will create boxes
#with pymp.Parallel(24) as p:
#block to intend
for i in range(0, 1):
box_bound, atom_bound = self.find_box_atoms(df=self.df_list[t], cnt_point=self.centroids[i], R_vector=self.R_v[i, :], total_bounds=self.bound_list[t])
property_map, x_c, y_c, z_c, count_mat, rho_mat, r = convolve_over_box(atom_array=atom_bound, sim_bounds=box_bound,
channel_size=temp_channel, delta=stride, unique_type=self.unique_type)
filter_coords = np.hstack((x_c.flatten()[:, None], y_c.flatten()[:, None], z_c.flatten()[:, None]))
#print filter_coords.shape
#print coords_array.shape
coords_array = np.vstack((coords_array, filter_coords))
#Redo find_location to find
#I_final, idx_final = find_location_I(I=I_temp, max_n_points=max_n_points)
return count_mat, rho_mat, r
def plot_contour_3D(self, timestep, N):
cnt_bound = self.cnt_bound_list[timestep]
X = self.scatter_list[timestep]
radius = 0.5*(cnt_bound[0, 1] - cnt_bound[0, 0])
height = cnt_bound[2, 1] - cnt_bound[2, 0]
elevation = cnt_bound[2, 0]
resolution = 100
color = 'b'
x_center = 0.5*(cnt_bound[0, 1] + cnt_bound[0, 0])
y_center = 0.5*(cnt_bound[1, 1] + cnt_bound[1, 1])
#extract data for
plot_3D_cylinder(X, radius, height, elevation=elevation, resolution=resolution, color=color, x_center=x_center,
y_center=y_center)
plt.show()
return None
def convolve_shear_102(self):
stride = self.stride
temp_channel_init = self.convolve_size.copy()
max_n_points = 10
n_surf = 4 #number of surfaces to convolve over
max_t = len(self.array_list)
bound_old = self.bound_list[0].copy()
property_map_list = []
U_list = []
idx_list_list = []
cnt_bound_list = []
#shared array to track:
#with pymp.Parallel(24) as p:
for t in range(0, 24):
atom_new = self.array_list[t].copy()
bound_new = self.bound_list[t].copy()
delta_x = (bound_new[0, 1] - bound_new[0, 0]) - (bound_old[0, 1] - bound_old[0, 0])
delta_y = (bound_new[1, 1] - bound_new[1, 0]) - (bound_old[1, 1] - bound_old[1, 0])
delta_z = (bound_new[2, 1] - bound_new[2, 0]) - (bound_old[2, 1] - bound_old[2, 0])
temp_channel = temp_channel_init + np.asarray([delta_x, delta_y, delta_z])
#cnt_bounds, box_bound = extract_cnt_coords(self.df_list[t], bound_new, self.box_tol, self.prop_str)
#now let's start getting the cnt atoms
self.cnt_bounds = extract_cnt_coords(df=self.df_list[t])
self.compute_centroid_and_radius()
#append cnt bound list
cnt_bound_list.append(self.cnt_bounds)
#define empty arrays for concatenating
I_temp = np.empty((n_surf*max_n_points, )) #4 -> number of surfaces in
box_min_temp = np.empty((n_surf*max_n_points, 3)) #define each convolution by the minimum
#The surface id and the
surface_temp = np.empty_like(I_temp)
loc_temp = np.empty_like(box_min_temp)
#final arrays
loc_final = np.empty((max_n_points, 3))
#print "Bounds: ", bound_new
#for each centroid we will create boxes
#with pymp.Parallel(24) as p:
#block to intend
for i in range(0, 4):
box_bound, atom_bound = self.find_box_atoms(df=self.df_list[t], cnt_point=self.centroids[i], R_vector=self.R_v[i, :], total_bounds=self.bound_list[t])
property_map, xyz_array, idx_array = convolve_over_box(atom_array=atom_bound, sim_bounds=box_bound,
channel_size=temp_channel, delta=stride)
I = property_map
print I
I_sort, idx_max = find_location_I(I=I, max_n_points=max_n_points)
print "I: ", I
print "I_sort", I_sort
I_temp[i*max_n_points:(i+1)*max_n_points] = I_sort
surface_temp[i*max_n_points:(i+1)*max_n_points] = i
loc_temp[i*max_n_points:(i+1)*max_n_points, :] = idx_max
box_min_temp[i*max_n_points:(i+1)*max_n_points, :] = np.multiply(idx_max, self.stride) + box_bound[:, 0]
print "troubleshoot stride multiply"
print box_min_temp
#Redo find_location to find
I_final, idx_final = find_location_I(I=I_temp, max_n_points=max_n_points)
idx_final = idx_final.flatten()
print "idx_final: ", idx_final
box_final = box_min_temp[idx_final, :]
#loc_final = loc_temp[idx_final]
surface_final = surface_temp[idx_final]
#print loc_final
return None
def find_box_atoms(self, df, cnt_point, R_vector, total_bounds):
# df_cnt -> dataframe containing CNT properties
# cnt_point -> the centroid of the rectangular box -> array of length 3
# R_vector -> 3D array to add and substract to the cnt_point
box_bounds = total_bounds.copy()
#print "R_vector: ", R_vector
for i in range(0, 3):
if cnt_point[i] - R_vector[i] >= total_bounds[i, 0]:
box_bounds[i, 0] = cnt_point[i] - R_vector[i]
if cnt_point[i] + R_vector[i] <= total_bounds[i, 1]:
box_bounds[i, 1] = cnt_point[i] + R_vector[i]
# creating numpy arrays
ID_mat = np.asarray(df.loc[:, 'id'])
type_mat = np.asarray(df.loc[:, 'type'])
xyz_mat = np.asarray(df.loc[:, ['x', 'y', 'z']])
prop_mat = np.asarray(df.loc[:, self.prop_str])
trans_array = shift_coords(xyz_mat, total_bounds)
trans_bounds = np.transpose(shift_coords(np.transpose(box_bounds), total_bounds))
idx = np.where((trans_array[:, 0] >= trans_bounds[0, 0]) & (trans_array[:, 0] <= trans_bounds[0, 1]) & (
trans_array[:, 1] >= trans_bounds[1, 0])
& (trans_array[:, 1] <= trans_bounds[1, 1]) & (trans_array[:, 2] >= trans_bounds[2, 0]) & (
trans_array[:, 2] <= trans_bounds[2, 1]))
# select from df which atoms go in
ID_bound = ID_mat[idx[0]]
ID_bound = ID_bound[:, None]
xyz_atoms = xyz_mat[idx[0], :]
type_bound = type_mat[idx[0]]
type_bound = type_bound[:, None]
prop_bound = prop_mat[idx[0], :]
atom_bound = np.hstack((ID_bound, type_bound, xyz_atoms, prop_bound ))
return box_bounds, atom_bound
def compute_centroid_and_radius(self):
cnt_bounds = self.cnt_bounds
print "cnt_bounds: ", cnt_bounds
#the cnt bounds will be stored as a numpy array
#the rows in th np array correspond to [x_lo, x_hi, y_lo, y_hi, z_lo, z_hi]
self.centroids = np.zeros((6, 3))
self.centroids[0, :] = np.asarray([cnt_bounds[0, 0], 0.5*(cnt_bounds[1, 0] + cnt_bounds[1, 1]), 0.5*(cnt_bounds[2, 0] + cnt_bounds[2, 1])])
self.centroids[1, :] = np.asarray([cnt_bounds[0, 1], 0.5 * (cnt_bounds[1, 0] + cnt_bounds[1, 1]),
0.5 * (cnt_bounds[2, 0] + cnt_bounds[2, 1])])
self.centroids[2, :] = np.asarray([0.5 * (cnt_bounds[0, 0] + cnt_bounds[0, 1]), cnt_bounds[1, 0], 0.5 * (cnt_bounds[2, 0] + cnt_bounds[2, 1])])
self.centroids[3, :] = np.asarray([0.5 * (cnt_bounds[0, 0] + cnt_bounds[0, 1]), cnt_bounds[1, 1],
0.5 * (cnt_bounds[2, 0] + cnt_bounds[2, 1])])
self.centroids[4, :] = np.asarray([0.5 * (cnt_bounds[0, 0] + cnt_bounds[0, 1]), 0.5 * (cnt_bounds[1, 0] + cnt_bounds[1, 1]), cnt_bounds[2, 0]])
self.centroids[5, :] = np.asarray([0.5 * (cnt_bounds[0, 0] + cnt_bounds[0, 1]), 0.5 * (cnt_bounds[1, 0] + cnt_bounds[1, 1]),
cnt_bounds[2, 1]])
R = self.Radius
e = self.epsilon
self.R_v = np.empty_like(self.centroids)
self.R_v[0, :] = np.asarray([R, e + 0.5*(cnt_bounds[1, 1] - cnt_bounds[1, 0]), e + 0.5*(cnt_bounds[2, 1] - cnt_bounds[2, 0])])
self.R_v[1, :] = np.asarray([R, e + 0.5 * (cnt_bounds[1, 1] - cnt_bounds[1, 0]), e + 0.5 * (cnt_bounds[2, 1] - cnt_bounds[2, 0])])
self.R_v[2, :] = np.asarray([e + 0.5*(cnt_bounds[0, 1] - cnt_bounds[1, 1]), R, e + 0.5 * (cnt_bounds[2, 1] - cnt_bounds[2, 0])])
self.R_v[3, :] = np.asarray([e + 0.5 * (cnt_bounds[0, 1] - cnt_bounds[0, 0]), R, e + 0.5 * (cnt_bounds[2, 1] - cnt_bounds[2, 0])])
self.R_v[4, :] = np.asarray([e + 0.5*(cnt_bounds[0, 1] - cnt_bounds[0, 0]), e + 0.5*(cnt_bounds[1, 1] - cnt_bounds[1, 0]), R])
self.R_v[5, :] = np.asarray([e + 0.5 * (cnt_bounds[0, 1] - cnt_bounds[0, 0]), e + 0.5 * (cnt_bounds[1, 1] - cnt_bounds[1, 0]), R])
return None
class hotspot():
def __init__(self, point_1, R_vector, file_name):
if len(point_1) > 1:
self.center = 0.5*(point_1[0] + point_1[1])
else:
self.center = point_1[0]
self.radius = R_vector
self.xyz_min = self.center - R_vector
self.xyz_max = self.center + R_vector
self.filename = file_name
#the corner is xyz_min
def get_atoms(self):
#This function gets x y z co-ordinates and writes them to file
df = pd.read_table(self.filename, delim_whitespace=True, header=None, skiprows=9)
#read the file to get the header
with open(self.filename) as f:
text = f.readlines()
for line in text:
if line.startswith('ITEM: ATOMS'):
header_choose = line.strip()
header_choose = header_choose.split()
header_choose = header_choose[2:] #getting rid off the first two items, as it is ITEM: ATOMS
#hedaer_choose is the list of headers.
df.columns = header_choose
#print df.query('x > self.xyz_min[0]')
#now let's look at the elements within the bound
idx = [np.where((df['x'] > self.xyz_min[0]) & (df['x'] < self.xyz_max[0]) & (df['y'] > self.xyz_min[1]) & (df['y'] < self.xyz_max[1])
& (df['z'] > self.xyz_min[2]) & (df['z'] < self.xyz_max[2]))]
#idx = [np.where(((df['x'] > self.xyz_min[0]) & (df['x'] < self.xyz_max[0])) | ((df['y'] > self.xyz_min[1]) & (
# df['y'] < self.xyz_max[1])) | ((df['z'] > self.xyz_min[2]) & (df['z'] < self.xyz_max[2])))]
idx = (np.asarray(idx)).ravel()
self.df_bound = df.iloc[idx, :] #The boundary of the simulation box within acceptable limits
return self
####function to create a box in hotspot
def create_box(self):
self.atype = np.asarray(self.df_bound['type'])
self.pos = np.array(self.df_bound.loc[:, ['x', 'y', 'z']])
self.min = np.amin(self.pos, axis=0)
self.pos_transform = self.pos - self.min
#create an Atoms Object
self.atoms = am.Atoms(natoms=len(self.atype), prop={'atype': self.atype, 'pos': self.pos})
self.box = am.Box(a=2*self.radius[0], b=2*self.radius[1], c=2*self.radius[2])
self.system = am.System(atoms=self.atoms, box=self.box, pbc=(True, True, True), scale=False)
sys_info = am.lammps.atom_data.dump(self.system, 'test1.in')
return self
def read_MD_model(file_list):
#first i will read the first file to get an idea of how many lines to skip
filename = file_list[0]
#fix header_list for the pandas table
header_list = ['id', 'type', 'q', 'x', 'y', 'z', 'nx', 'ny', 'nz']
#df_list = pymp.shared.list()
#len_z_list = pymp.shared.list()
#z_coords_list = pymp.shared.list()
df_list = []
len_z_list = []
z_coords_list = []
###fixing params for pymp
rnge = iter(range(len(file_list)))
#with pymp.Parallel(multiprocessing.cpu_count()) as p:
#for t in p.iterate(rnge):
for t in range(0, len(file_list)):
#print file_list[t]
with open(file_list[t]) as f:
df_bounds = pd.read_table(file_list[t], delim_whitespace=True, header=None, skiprows=5, nrows=3)
df_bounds = df_bounds.iloc[:, 0:2].as_matrix()
z_lo = df_bounds[-1, 0]
z_hi = df_bounds[-1, 1]
len_z = z_hi - z_lo
text = f.readlines()
count = 0
skip_count = 0
end_count = 0
for line in text:
count = count + 1
if line.startswith('Atoms'):
skip_count = count
if line.startswith('Velocities'):
end_count = count - 4
break
print "######'"
print file_list[t]
Z = pd.read_table(file_list[t], delim_whitespace=True, header=None, skiprows=skip_count, nrows=(end_count - skip_count))
Z.columns = header_list
df_list.append(Z)
len_z_list.append(len_z)
z_coords_list.append(np.asarray([z_lo, z_hi]))
return df_list, len_z_list, z_coords_list
#Global functions
#functions to read
def select_by_property(file_list, prop_name, N, sort_choose=False):
df_list = []
array_list = []
bound_list = []
pe_hotspot_list = []
for file_name in file_list:
df = pd.read_table(file_name, delim_whitespace=True, header=None, skiprows=9)
#read text to get headers
# read the file to get the header
with open(file_name) as f:
text = f.readlines()
for line in text:
if line.startswith('ITEM: ATOMS'):
header_choose = line.strip()
header_choose = header_choose.split()
header_choose = header_choose[2:] # getting rid off the first two items, as it is ITEM: ATOMS
df_bounds = pd.read_table(file_name, delim_whitespace=True, header=None, skiprows=5, nrows=3)
# bounds as array
bound_array = df_bounds.as_matrix()
df.columns = header_choose
#now to index out the relevant columns
if sort_choose == True:
df = df.sort_values(by=prop_name, ascending=False)
list_init = ['id', 'type', 'x', 'y', 'z']
prop_new = list_init + prop_name
array_out = np.asarray(df.loc[:, prop_new])
array_out = np.asarray(df.loc[:, prop_new])
hspot_array = array_out[:N, :]