-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclarm_main.py
1953 lines (1604 loc) · 75.8 KB
/
clarm_main.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
''' About this code,
1) A pytorch code
2) CVAE is trained where module number acts as conditional to encoder
3) Temporal correlations are learned in the latent space with LSTM
5) Autoregressive loop help forecast projections in all modules
'''
import torch
import torch.optim as optim
import os
import sys
sys.path.insert(1, os.path.abspath("E:\MSR\codes\RFLA_VAE_LSTM_pyt"))
# APIs and inbuilt functions
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from lib.modifyimsize import MODIFYIMSIZE
# information on cuda
print("Number of CUDA devices",torch.cuda.device_count())
print("Name of CUDA device - 1 ==>",torch.cuda.get_device_name(0))
print("Name of CUDA device - 2 ==>",torch.cuda.get_device_name(1))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device1 = torch.device("cuda:0") if torch.cuda.is_available() else "cpu"
device2 = torch.device("cuda:1")
# path for the dataset
im_path = "E://MSR//data//RFLASimulationData//Alan_HPSim_11_13_23//images//"
labels_path = "E://MSR//data//RFLASimulationData//Alan_HPSim_11_13_23//labels//"
im_dir_list = os.listdir(im_path)
labels_dir_list = os.listdir(labels_path)
print("Files and directories in '", im_path, "' :")
print(im_dir_list)
print("Files and directories in '", labels_path, "' :")
print(labels_dir_list)
# loop to import dataset
imgs_all = []
labels_all = []
n = 0
for i in range(len(im_dir_list)):
n = n+1
load_imgs = np.load(im_path + im_dir_list[i]).astype('float32')
load_labels = np.load(labels_path + labels_dir_list[i]).astype('float32')
imgs_all.append(load_imgs)
labels_all.append(load_labels)
del load_imgs, load_labels
# concatentate the appended dataset
imgs_all_tr = np.concatenate((imgs_all[0],imgs_all[1]),axis=0)
# moveaxis: (p,mod,proj,L,W) -> (p,mod,L,W,proj)
# modify images and normalize require moveaxis
imgs_all_tr = np.moveaxis(imgs_all_tr,2,4)
imgs_all_te = np.moveaxis(imgs_all[2],2,4)
print('Size of the imported train dataset', imgs_all_tr.shape)
print('Size of the imported test dataset',imgs_all_te.shape)
#%% =====>>>> DATASET VISUALIZATION <<<<======
############################################################################################
######################### DATASET VISUALIZATION ###########################################
############################################################################################
#%% plot samples from dataset - across different runs/perturbations (axis=0)
projection = 12
plot_samples = 48*10
plt.figure(figsize=(15,45))
for i in range(plot_samples):
cols = 6
plt.subplot(int(plot_samples/cols) + 1, cols, i + 1)
plt.imshow(imgs_all_tr[i,0,:,:,projection], aspect='auto', origin='lower', cmap='hsv')
plt.tick_params(left = False, right = False , labelleft = False ,
labelbottom = False, bottom = False)
plt.tight_layout()
#plt.savefig('dataset_runs_proj11.png', dpi=300)
#%% plot samples from dataset - across different modules
n_mod = 1
run = 0
plot_samples = 15
plt.figure(figsize=(15,15))
for p in range(plot_samples):
cols = 5
plt.subplot(int(plot_samples/cols) + 1, cols, p + 1)
plt.imshow(np.log(1+imgs_all_tr[run,n_mod,:,:,p]), aspect='auto', origin='lower', cmap='plasma')
plt.tick_params(left = False, right = False , labelleft = False ,
labelbottom = False, bottom = False)
plt.tight_layout()
#plt.savefig('dataset_runs_allproj_mod.png', dpi=300)
#%% plot samples from dataset - different modules - different projections (E-phi)
E_ref = [5.35508654, 41.30085241, 72.59726239, 99.55659545, 113.30694285,
126.54444021, 139.06689037, 153.99711291, 167.78542056, 182.78942052,
196.36477222, 212.36085887, 225.5727351, 242.05917683, 257.87629262,
270.56978027, 287.61654992, 304.05749827, 317.68888699, 334.16846795,
351.99214741, 366.78784088, 381.9247197, 398.52202592, 415.99627685,
430.9371102, 446.40440063, 464.28822739, 482.19924841, 497.70466852,
512.78249953, 529.80507787, 548.09348445, 566.19867131, 582.82614372,
597.95315468, 614.21267512, 632.03148033, 650.15885225, 667.67175433,
683.26887754, 698.57431461, 715.5213991, 733.9661626, 751.98340543,
769.06200623, 784.84248942, 800.09776699]
phi_ref = [11280.83108553, 35524.52623656, 49838.59318148, 61305.903995,
288361.38037085, 319788.38387692, 351209.13837744, 381470.37516268,
411729.70835502, 440524.90018308, 469362.37242238, 498138.63636995,
523347.67225599, 547484.83300091, 571555.07608093, 595678.48363986,
619799.63361058, 643884.756519, 667272.15623005, 690674.49256342,
714044.80546704, 737047.56147925, 760089.84080003, 782414.85757303,
804711.56299811, 827019.32420482, 849350.09611553, 871678.29433691,
893998.67106446, 915579.15614886, 937194.61074431, 958443.63612275,
979675.77897511, 1000909.73863817, 1022126.5531958, 1042646.95242532,
1063171.49187095, 1083695.10086393, 1104198.70898035, 1124705.97951749,
1145215.59676875, 1165731.03826898, 1186267.48596319, 1206785.63240674,
1226584.02594906, 1246374.38559172, 1266166.68815084, 1284803.08186162]
scale1 = 0.01
scale2 = 0.0001
E_ref2 = np.array(E_ref)*scale1
E_ref2 = np.round(E_ref2,1)
phi_ref2 = np.array(phi_ref)*scale2
phi_ref2 = np.round(phi_ref2,1)
phi_b = 60*scale1
E_b = 1.3*0.01*E_ref2*scale2
phi_lb, phi_ub = phi_ref2-60, phi_ref2+60
phi_lb, phi_ub = np.round(phi_lb,1),np.round(phi_ub,1)
E_lb, E_ub = E_ref2-E_b, E_ref2+E_b
E_lb, E_ub = np.round(E_lb,1),np.round(E_ub,1)
projection = 11 # E-phi
plot_samples = 48
plt.figure(figsize=(14,8))
dataplot = imgs_all_tr
for i in range(plot_samples):
cols = 8
plt.subplot(int(plot_samples/cols) + 1, cols, i + 1)
plt.imshow(dataplot[0,i,:,:,projection], aspect='auto', origin='lower', cmap='hsv')
#plt.tick_params(left = False, right = False , labelleft = False ,
#labelbottom = False, bottom = False)
plt.title('Mod.-'+str(i+1), fontsize = 12)
if (i == 0 or i == 8 or i == 16 or i == 24 or i == 32 or i == 40):
plt.ylabel('E (MeV*100)',fontsize=10)
if (i>40 and i<48):
plt.xlabel('$\phi (rad*10^4)$',fontsize=10)
xticks = [phi_lb[i], phi_ref2[i], phi_ub[i]]
yticks = [E_lb[i], E_ref2[i], E_ub[i]]
xticklabels = [str(xticks[0]), str(xticks[1]), str(xticks[2])]
yticklabels = [str(yticks[0]), str(yticks[1]), str(yticks[2])]
plt.xticks([0,128,256], xticklabels, fontsize=12)
plt.yticks([0,128,256], yticklabels, fontsize=12)
plt.tight_layout()
#%% plot samples from dataset - different modules - different projections (E-phi)
projection = 11 # E-phi
plot_samples = 48
plt.figure(figsize=(15,7))
dataplot = imgs_all_tr
for i in range(plot_samples):
cols = 12
plt.subplot(int(plot_samples/cols) + 1, cols, i + 1)
plt.suptitle('$E$ - $\phi$ projection',fontsize=20)
plt.imshow(dataplot[0,i,:,:,projection], aspect='auto', origin='lower', cmap='hsv')
#plt.tick_params(left = False, right = False , labelleft = False ,
#labelbottom = False, bottom = False)
plt.title('Mod.-'+str(i+1), fontsize = 12)
if (i == 0 or i == 12 or i == 24 or i == 36 or i == 48):
plt.ylabel('% $E_{r}$ (MeV)',fontsize=12)
yticks = [-1.3, 0, 1.3]
yticklabels = [str(yticks[0]), str(yticks[1]), str(yticks[2])]
plt.yticks([0,128,256], yticklabels, fontsize=10)
else:
plt.yticks([],fontsize=10)
if (i>35 and i<48):
plt.xlabel('$\Delta \phi (deg)$',fontsize=12)
xticks = [-60, 0, 60]
xticklabels = [str(xticks[0]), str(xticks[1]), str(xticks[2])]
plt.xticks([0,128,256], xticklabels, fontsize=10)
else:
plt.xticks([],fontsize=10)
plt.subplots_adjust(wspace=0.23, hspace=0.32)
plt.savefig('dataset_modules_4x12_proj_'+str(projection)+'.png', bbox_inches='tight',dpi=300)
#%% plot samples from dataset - different modules - 3 projections (E-phi) ==> 2 x 6
path = 'E:/MSR/codes/RFLA_VAE_LSTM_pyt/figures/fig_data/'
projection = 11 # E-phi
plot_samples = 12
pltfig = [0,1,2,3,10,15,20,25,30,35,40,47]
plt.figure(figsize=(15,7))
dataplot = imgs_all_tr
#dataplot = np.log(1+imgs_all_tr)
for i in range(plot_samples):
cols = 6
plt.subplot(int(plot_samples/cols) + 1, cols, i + 1)
plt.suptitle('$E$ - $\phi$ projection',fontsize=20)
plt.imshow(dataplot[0,pltfig[i],:,:,projection], aspect='auto', origin='lower', cmap='plasma')
#plt.tick_params(left = False, right = False , labelleft = False ,
#labelbottom = False, bottom = False)
plt.title('Mod.-'+str(pltfig[i]+1), fontsize = 16)
if (i == 0 or i == 6):
plt.ylabel('% $E_{r}$ (MeV)',fontsize=16)
yticks = [-1.3, 0, 1.3]
yticklabels = [str(yticks[0]), str(yticks[1]), str(yticks[2])]
plt.yticks([0,128,256], yticklabels, fontsize=16)
else:
plt.yticks([],fontsize=10)
if (i>5 and i<13):
plt.xlabel('$\Delta \phi (deg)$',fontsize=16)
xticks = [-60, 0, 60]
xticklabels = [str(xticks[0]), str(xticks[1]), str(xticks[2])]
plt.xticks([0,128,256], xticklabels, fontsize=16)
else:
plt.xticks([],fontsize=10)
plt.subplots_adjust(wspace=0.23, hspace=0.32)
plt.savefig(path + 'dataset_modules_2x6_proj_'+str(projection) + '_unlog' +'.png', bbox_inches='tight',dpi=300)
#%% plot samples from dataset - different modules - 3 projections (x-y) ==> 2 x 6
projection = 1 # x-y
plot_samples = 12
pltfig = [0,1,2,3,10,15,20,25,30,35,40,47]
plt.figure(figsize=(15,7))
for i in range(plot_samples):
cols = 6
plt.subplot(int(plot_samples/cols) + 1, cols, i + 1)
plt.suptitle('$x - y$ projection',fontsize=20)
plt.imshow(dataplot[0,pltfig[i],:,:,projection], aspect='auto', origin='lower', cmap='plasma')
#plt.tick_params(left = False, right = False , labelleft = False ,
#labelbottom = False, bottom = False)
plt.title('Mod.-'+str(pltfig[i]+1), fontsize = 16)
if (i == 0 or i == 6):
plt.ylabel('x(cm)',fontsize=16)
yticks = [-3, 0, 3]
yticklabels = [str(yticks[0]), str(yticks[1]), str(yticks[2])]
plt.yticks([0,128,256], yticklabels, fontsize=16)
else:
plt.yticks([],fontsize=10)
if (i>5 and i<13):
plt.xlabel('$y(cm)$',fontsize=16)
xticks = [-3, 0, 3]
xticklabels = [str(xticks[0]), str(xticks[1]), str(xticks[2])]
plt.xticks([0,128,256], xticklabels, fontsize=16)
else:
plt.xticks([],fontsize=10)
plt.subplots_adjust(wspace=0.23, hspace=0.32)
plt.savefig(path + 'dataset_modules_2x6_proj_'+str(projection) + '_unlog' +'.png',bbox_inches='tight', dpi=300)
#%% plot samples from dataset - different modules - 3 projections (x'-y') ==> 2 x 6
projection = 12 # x'-y'
plot_samples = 12
pltfig = [0,1,2,3,10,15,20,25,30,35,40,47]
plt.figure(figsize=(15,7))
for i in range(plot_samples):
cols = 6
plt.subplot(int(plot_samples/cols) + 1, cols, i + 1)
plt.suptitle('$x^\prime$ - $y^\prime$ projection',fontsize=20)
plt.imshow(dataplot[0,pltfig[i],:,:,projection], aspect='auto', origin='lower', cmap='plasma')
#plt.tick_params(left = False, right = False , labelleft = False ,
#labelbottom = False, bottom = False)
plt.title('Mod.-'+str(pltfig[i]+1), fontsize = 16)
if (i == 0 or i == 6):
plt.ylabel('$x^\prime$ (mrad)',fontsize=16)
yticks = [-10, 0, 10]
yticklabels = [str(yticks[0]), str(yticks[1]), str(yticks[2])]
plt.yticks([0,128,256], yticklabels, fontsize=16)
else:
plt.yticks([],fontsize=10)
if (i>5 and i<13):
plt.xlabel('$y^\prime$ (mrad)',fontsize=16)
xticks = [-10, 0, 10]
xticklabels = [str(xticks[0]), str(xticks[1]), str(xticks[2])]
plt.xticks([0,128,256], xticklabels, fontsize=16)
else:
plt.xticks([],fontsize=10)
plt.subplots_adjust(wspace=0.23, hspace=0.32)
plt.savefig(path + 'dataset_modules_2x6_proj_'+str(projection) + '_unlog' +'.png',bbox_inches='tight', dpi=300)
#%% =====>>>> DATASET PROCESSING <<<<======
############################################################################################
######################### DATASET PRCOESSING #############################################
############################################################################################
#%% module numbers as conditional inputs
mod_num = np.arange(0,48,dtype='float32')
mod_num_nm = mod_num[:,np.newaxis]/np.max(mod_num)
mod_num_tr = np.tile(mod_num_nm, (imgs_all_tr.shape[0],1))
mod_num_te = np.tile(mod_num_nm, (imgs_all_te.shape[0],1))
print('module number input (conditional) shape for train', mod_num_tr.shape)
print('module number input (conditional) shape for test',mod_num_te.shape)
print('module number input (first 48)', mod_num_tr[0:48])
#%% Process the dataset (Reshape & Normalize)
# size of the image we want
imsize = 256
# reshape the dimensions of the dataset from 5D to 4D
imgs_all_tr_rs = imgs_all_tr.reshape(imgs_all_tr.shape[0]*imgs_all_tr.shape[1],
imgs_all_tr.shape[2],
imgs_all_tr.shape[3],
imgs_all_tr.shape[4])
imgs_all_te_rs = imgs_all_te.reshape(imgs_all_te.shape[0]*imgs_all_te.shape[1],
imgs_all_te.shape[2],
imgs_all_te.shape[3],
imgs_all_te.shape[4])
print('Size of reshaped dataset (train)', imgs_all_tr_rs.shape)
print('Size of reshaped dataset (test)',imgs_all_te_rs.shape)
#del imgs_all_tr, imgs_all_te
#%% modify the image size and normalize the data
if (imsize != 256):
imgs_all_tr_rs = MODIFYIMSIZE(imgs_all_tr_rs, imsize)
imgs_all_te_rs = MODIFYIMSIZE(imgs_all_te_rs, imsize)
# function for data normalization
def MinMaxNormalizeData(data):
# simplified to see the memory utilization at each step
# dividing an array with a number takes more time and multiple by (1/number)
minval = np.min(data)
maxval = np.max(data)
diff = maxval-minval
diffinv = 1/diff
data_nm_numer = data - minval
data_nm = data_nm_numer*diffinv
return data_nm, minval, maxval
def UnNormalize(data, minval, maxval):
diff = maxval-minval
data_un = data*diff + minval
return data_un
# Normalize the data
imgs_all_tr_rs_nm, minval_tr, maxval_tr = MinMaxNormalizeData(imgs_all_tr_rs)
imgs_all_te_rs_nm, minval_te, maxval_te = MinMaxNormalizeData(imgs_all_te_rs)
print('Size of resized & normalized dataset (train)', imgs_all_tr_rs_nm.shape)
print('Size of resized & normalized dataset (test)',imgs_all_te_rs_nm.shape)
del imgs_all_tr_rs, imgs_all_te_rs
#%% plot samples from normalized dataset - different modules == E-z
projection = 11
plot_samples = 48
plt.figure(figsize=(14,5))
dataplot = imgs_all_tr_rs_nm
for i in range(plot_samples):
cols = 12
plt.subplot(int(plot_samples/cols) + 1, cols, i + 1)
plt.suptitle('Normalized $E$ - $\phi$ projection',fontsize=16)
plt.imshow(dataplot[i,:,:,projection], aspect='auto', origin='lower', cmap='hsv')
plt.tick_params(left = False, right = False , labelleft = False ,
labelbottom = False, bottom = False)
plt.title('Mod.-'+str(i+1),fontsize=10)
plt.tight_layout()
del dataplot
#%% Some data analysis = SSID and MSE across different perturbations
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import mean_squared_error
module = 40
ssim_da_all = []
mse_da_all=[]
for i in range(imgs_all_tr.shape[0]-1):
img_1 = imgs_all_tr[0,module,:,:,projection]
img_2 = imgs_all_tr[i+1,module,:,:,projection]
ssim_da = ssim(img_1, img_2, data_range=img_1.max() - img_2.min())
mse_da = mean_squared_error(img_1,img_2)
ssim_da_all.append(ssim_da)
mse_da_all.append(mse_da)
plt.figure(figsize = (30, 6))
plt.plot(ssim_da_all,'--or')
plt.ylabel("SSIM",fontsize=20)
plt.yticks(fontsize=20)
plt.figure(figsize = (30, 6))
plt.plot(mse_da_all,'--or')
plt.ylabel("MSE",fontsize=20)
plt.yticks(fontsize=20)
#%% Some data analysis = SSID and MSE across the modules
projection = 11
ssim_matrix = np.zeros((48,48))
mse_matrix = np.zeros((48,48))
data_matrix = imgs_all_tr_rs_nm[0:48,:,:,projection]
for i in range(48):
for j in range(48):
img_1 = data_matrix[i]
img_2 = data_matrix[j]
if j >= i:
maxval = img_2.max()
minval = img_2.min()
else:
maxval = img_1.max()
minval = img_1.min()
ssim_da = ssim(img_1, img_2, data_range=maxval - minval)
mse_da = mean_squared_error(img_1,img_2)
ssim_matrix[i,j] = ssim_da
mse_matrix[i,j] = mse_da
plt.figure(figsize=(20, 20))
plt.imshow(ssim_matrix,cmap='jet')
plt.colorbar()
plt.xticks(fontsize=20)
plt.xticks(np.arange(0,48),fontsize=12)
plt.yticks(np.arange(0,48),fontsize=12)
plt.figure(figsize=(20, 20))
plt.imshow(mse_matrix,cmap='jet')
plt.colorbar()
plt.xticks(np.arange(0,48),fontsize=12)
plt.yticks(np.arange(0,48),fontsize=12)
del data_matrix
#%% =====>>>> TRAINING CVAE <<<<======
############################################################################################
######################### CVAE TRAINING ##################################################
############################################################################################
#%% Transform the np dataset into tensor
imgs_all_tr_rs_nm = np.moveaxis(imgs_all_tr_rs_nm,3,1)
imgs_all_te_rs_nm = np.moveaxis(imgs_all_te_rs_nm,3,1)
imgs_all_tr_rs_tensor = torch.from_numpy(imgs_all_tr_rs_nm)
imgs_all_te_rs_tensor = torch.from_numpy(imgs_all_te_rs_nm)
mod_num_tr_tensor = torch.from_numpy(mod_num_tr)
mod_num_te_tensor = torch.from_numpy(mod_num_te)
print('Size of final train dataset', imgs_all_tr_rs_tensor.shape)
print('Size of final test dataset',imgs_all_te_rs_tensor.shape)
print('Conditional shape for train', mod_num_tr_tensor.shape)
print('Conditional shape for test',mod_num_te_tensor.shape)
del imgs_all_tr_rs_nm, imgs_all_te_rs_nm
#%% Tensor dataset & and use dataloader transforms into a tensor
BATCH_SIZE = 32
from torch.utils.data import Dataset
class DatasetforDataloader(Dataset):
def __init__(self,X,y):
self.X = X
self.y = y
def __len__(self):
return len(self.X)
def __getitem__(self,i):
# create a tuple
return self.X[i], self.y[i]
# Dataset of dataloader
train_dataset = DatasetforDataloader(imgs_all_tr_rs_tensor,mod_num_tr_tensor)
test_dataset = DatasetforDataloader(imgs_all_te_rs_tensor,mod_num_te_tensor)
# train-test split
train_size = int(0.85 * len(imgs_all_tr_rs_tensor))
val_size = len(imgs_all_tr_rs_tensor) - train_size
trainX, valX = torch.utils.data.random_split(train_dataset,[train_size, val_size])
## Dataloader wraps an iterable around the Dataset for easy access to the samples.
dataloader_train = DataLoader(trainX, batch_size = BATCH_SIZE, shuffle=True)
dataloader_val = DataLoader(valX, batch_size = BATCH_SIZE, shuffle=False)
dataloader_test = DataLoader(test_dataset, batch_size = BATCH_SIZE, shuffle=False)
dataloader_trainval = DataLoader(train_dataset, batch_size = BATCH_SIZE, shuffle=False)
print('Length of the training set',len(trainX))
print('Length of the validation set',len(valX))
#%% CVAE model
# Move the model to GPU
# Initialize the autoencoder
from lib.cvae_pyt import cVAE
from lib.elbo_loss import ELBO
imch = 15
f1,f2,f3,f4,f5 = 32,64,128,256,512
neurons = 256
branchneurons = 32
combinedneurons = neurons + branchneurons
latentdim = 8
strides = 2
nfilters = 5
imfinal1 = int(imsize/(strides**nfilters))
imfinal2 = int(imsize/(strides**nfilters))
cvae15 = cVAE(imch,f1,f2,f3,f4,f5,
neurons,branchneurons,combinedneurons,
latentdim,imfinal1,imfinal2,device1)
#cvae15 = torch.nn.DataParallel(cvae15)
cvae15 = cvae15.to(device1)
print("Num params encoder: ", sum(p.numel() for p in cvae15.parameters()))
print('Model architecture', cvae15)
# Define the loss function and optimizer
optimizer = optim.Adam(cvae15.parameters(), lr=0.001)
beta = 1
#%% Training
num_epochs = 1500
def train_epoch_cvae(model,device,dataloader_train,optimizer):
model.train() # Set train mode for model
train_loss = []
train_loss_bce = []
train_loss_kl = []
for step, batch in enumerate(dataloader_train):
x_tr, c_tr = batch
x_tr = x_tr.to(device)
c_tr = c_tr.to(device)
optimizer.zero_grad()
x_hat, mean, log_var, z = model(x_tr,c_tr)
loss, bce, kl = ELBO(x_tr, x_hat, mean, log_var, beta)
loss.backward()
optimizer.step()
train_loss.append(loss.item())
train_loss_bce.append(bce.item())
train_loss_kl.append(kl.item())
return (np.mean(train_loss),np.mean(train_loss_bce),np.mean(train_loss_kl))
def test_epoch_cvae(model, device, dataloader_test):
model.eval() # Set the eval mode for model
test_loss = []
test_loss_bce = []
test_loss_kl = []
with torch.no_grad(): # No need to track the gradients
for step, batch in enumerate(dataloader_test):
x_val, c_val = batch
x_val = x_val.to(device)
c_val = c_val.to(device)
x_hat, mean, log_var, z = model(x_val,c_val)
loss, bce, kl = ELBO(x_val, x_hat, mean, log_var, beta)
test_loss.append(loss.item())
test_loss_bce.append(bce.item())
test_loss_kl.append(kl.item())
return (np.mean(test_loss),np.mean(test_loss_bce),np.mean(test_loss_kl))
diz_loss = {'train_loss':[], 'train_loss_bce':[],'train_loss_kl':[],
'val_loss':[],'val_loss_bce':[],'val_loss_kl':[]}
for epoch in range(num_epochs):
train_loss, tr_bce, tr_kl = train_epoch_cvae(cvae15,device1,dataloader_train,optimizer)
val_loss, val_bce, val_kl = test_epoch_cvae(cvae15,device1,dataloader_val)
print('\n EPOCH {}/{} \t train loss {} \t val loss {} \t train recon {} \t val recon {} \ttrain kl {} \t val kl {}'
.format(epoch + 1, num_epochs,train_loss,val_loss,tr_bce,val_bce,tr_kl,val_kl))
diz_loss['train_loss'].append(train_loss)
diz_loss['train_loss_bce'].append(tr_bce)
diz_loss['train_loss_kl'].append(tr_kl)
diz_loss['val_loss'].append(val_loss)
diz_loss['val_loss_bce'].append(val_bce)
diz_loss['val_loss_kl'].append(val_kl)
# Save the model
torch.save(cvae15.state_dict(), 'cvae_15ch_model.pth')
#%% load the model
cvae15.load_state_dict(torch.load('cvae_15ch_model.pth'))
cvae15.eval()
#%% cVAE training and test loss
# Plot losses
plt.figure(figsize=(10,8))
plt.plot(diz_loss['train_loss'], '-ok', label='Train',)
plt.plot(diz_loss['val_loss'], '-^r', label='Valid')
plt.xlabel('Epoch',fontsize=20)
plt.ylabel('Average Loss',fontsize=20)
plt.legend(["tr_total", "val_total"])
plt.title('Training & Validation loss', fontsize = 20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.ylim(49000, 60000)
plt.show()
# Plot losses on semilog scale
plt.figure(figsize=(10,8))
plt.plot(diz_loss['train_loss_bce'],'-ob', label='Train bce')
plt.plot(diz_loss['val_loss_bce'], '-^r', label='Valid bce')
plt.xlabel('Epoch',fontsize=20)
plt.ylabel('Reconstruction loss',fontsize=20)
plt.legend(["tr_bce", "val_bce"],fontsize=20)
plt.title('Training & Validation loss', fontsize = 20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.ylim(49000, 60000)
plt.show()
# Plot losses on semilog scale
plt.figure(figsize=(10,8))
plt.plot(diz_loss['train_loss_kl'],'-ob', label='Train kl')
plt.plot(diz_loss['val_loss_kl'],'-^r', label='Valid kl')
plt.xlabel('Epoch',fontsize=20)
plt.ylabel('KL divergence loss',fontsize=20)
plt.legend(["tr_kl" , "val_kl"],fontsize=20)
plt.title('Training & Validation loss', fontsize = 20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.ylim(200,500)
plt.show()
#%% =====>>>> RECONSTRUCTION RESULTS <<<<======
############################################################################################
######################### RECONSTRUCTION PART #############################################
############################################################################################
#%% Collect all reconstruction images for training and testing data
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import mean_squared_error
# calculate the reconstruction error
def reconstruction_error(samples, pred_samples):
errors = []
for (image, recon) in zip(samples, pred_samples):
mse = np.mean((image - recon)**2)
errors.append(mse)
return errors
# calculate mse and ssim projection wise
def mse_ssim_projwise(realdata,gendata):
ssim_app = []
mse_app = []
for p in range(realdata.shape[0]):
real = realdata[p]
gen = gendata[p]
sim = ssim(real, gen, data_range=real.max() - real.min())
mse = mean_squared_error(real, gen)
ssim_app.append(sim)
mse_app.append(mse)
return np.array(mse_app), np.array(ssim_app)
# calculate mse and ssim sample wise
def mse_ssim_samplewise(data,recondata):
mse2_app, ss2_app = [], []
for s in range(data.shape[0]):
org = data[s,:,:,:]
recon = recondata[s,:,:,:]
mse, ss = mse_ssim_projwise(org, recon)
mse2_app.append(mse)
ss2_app.append(ss)
return np.array(mse2_app), np.array(ss2_app)
# reconstruction images, mse and ssim calculations
def recon_cVAE(dataloader):
mse3_app, ss3_app = [], []
data_app, recon_app = [], []
with torch.no_grad():
for step, batch in enumerate(dataloader):
print('Step = ', step)
data,mod = batch
data = data.to(device1)
mod = mod.to(device1)
recon,_,_,_ = cvae15(data,mod)
data = data.detach().cpu().numpy()
recon = recon.detach().cpu().numpy()
mse, ss = mse_ssim_samplewise(data,recon)
mse3_app.append(mse)
ss3_app.append(ss)
# save data and recon for plotting
if (step == 0) or (step == 1) or (step == 2):
data_app.append(data)
recon_app.append(recon)
return np.array(data_app), np.array(recon_app), np.array(mse3_app), np.array(ss3_app)
org_tr, recon_tr, mse_tr, ssim_tr = recon_cVAE(dataloader_trainval)
org_te, recon_te, mse_te, ssim_te = recon_cVAE(dataloader_test)
print("Original training shape",org_tr.shape)
print("Original test shape",org_te.shape)
print("ssim training shape",ssim_tr.shape)
print("ssim test shape",ssim_te.shape)
# change the shape of ssim and mse
ssim_tr = ssim_tr.reshape(ssim_tr.shape[0]*ssim_tr.shape[1],ssim_tr.shape[2])
ssim_te = ssim_te.reshape(ssim_te.shape[0]*ssim_te.shape[1],ssim_te.shape[2])
mse_tr = mse_tr.reshape(mse_tr.shape[0]*mse_tr.shape[1],mse_tr.shape[2])
mse_te = mse_te.reshape(mse_te.shape[0]*mse_te.shape[1],mse_te.shape[2])
# change the shape again
ssim_tr, ssim_te = ssim_tr.reshape(1400,48,15), ssim_te.reshape(100,48,15)
mse_tr, mse_te = mse_tr.reshape(1400,48,15), mse_te.reshape(100,48,15)
# reshape org_tr and recon_tr
org_tr = org_tr.reshape(org_tr.shape[0]*org_tr.shape[1],15,256,256)
org_te = org_te.reshape(org_te.shape[0]*org_te.shape[1],15,256,256)
recon_tr = recon_tr.reshape(recon_tr.shape[0]*recon_tr.shape[1],15,256,256)
recon_te = recon_te.reshape(recon_te.shape[0]*recon_te.shape[1],15,256,256)
# change the shape again
org_tr, org_te = org_tr.reshape(2,48,15,256,256), org_te.reshape(2,48,15,256,256)
recon_tr, recon_te = recon_tr.reshape(2,48,15,256,256), recon_te.reshape(2,48,15,256,256)
print("Original training shape",org_tr.shape)
print("Original test shape",org_te.shape)
print("ssim tr shape",ssim_tr.shape)
print("ssim te shape",ssim_te.shape)
#%% plot original and reconstruction images - 3 x 5 pictures
allprojnames = ['$x-p_x$','$x-y$','$x-p_y$','$x-z$','$x-p_z$',
'$y-p_x$','$y-p_y$','$y-z$','$y-p_z$','$z-p_x$',
'$z-p_y$','$z-p_z$','$p_x-p_y$','$p_x-p_z$','$p_z-p_y$']
org_te_un = UnNormalize(org_te, minval_te, maxval_te)
recon_te_un = UnNormalize(recon_te, minval_te, maxval_te)
org_te_un_log = np.log(1 + org_te_un)
recon_te_un_log = np.log(1 + recon_te_un)
randrun = 0
n_mod_recon = 39 # 0,23,47 for paper # 1,2,3,4,9,19,29,39 for supp. info
plot_samples = 15
plt.figure(figsize=(15,12))
# original images as 3 x 5
for p in range(15):
cols = 5
plt.subplot(int(plot_samples/cols) + 1, cols, p + 1)
plt.suptitle('Original projections in module ' + str(n_mod_recon+1) , fontsize = 32, y = 0.99)
plt.title(str(allprojnames[p]), fontsize = 28)
plt.imshow(org_te_un_log[randrun,n_mod_recon,p,:,:], aspect='auto', origin='lower', cmap='plasma')
plt.axis('OFF')
plt.tight_layout()
path = 'E:/MSR/codes/RFLA_VAE_LSTM_pyt/figures/fig_reconstruction/'
#plt.savefig(path + 'reconablity_orgimgs_log_mod_'+str(n_mod_recon+1) + '.png', bbox_inches="tight", dpi=300)
# reconstructed images as 3 x 5
plt.figure(figsize=(15,12))
for p in range(15):
cols = 5
plt.subplot(int(plot_samples/cols) + 1, cols, p + 1)
plt.suptitle('Reconstruction projections in module ' + str(n_mod_recon+1) , fontsize = 32, y = 0.99)
plt.title(str(allprojnames[p]), fontsize = 28)
plt.imshow(recon_te_un_log[randrun,n_mod_recon,p,:,:], aspect='auto', origin='lower', cmap='plasma')
plt.axis('OFF')
plt.tight_layout()
path = 'E:/MSR/codes/RFLA_VAE_LSTM_pyt/figures/fig_reconstruction/'
#plt.savefig(path + 'reconablity_reconimgs_log_mod_'+str(n_mod_recon+1) + '.png', bbox_inches="tight", dpi=300)
#%% plots for MSE and SSIM for the entire training and test with error bounds
def mu_sigma(data):
mu = np.mean(data,axis=0)
sigma = np.std(data,axis=0)
return mu,sigma
mse_recon_avg_tr = np.mean(mse_tr, axis = 0)
ssim_recon_avg_tr = np.mean(ssim_tr, axis = 0)
mse_recon_avg_te = np.mean(mse_te, axis = 0)
ssim_recon_avg_te = np.mean(ssim_te, axis = 0)
print('Avg. MSE Recon te shape', mse_recon_avg_te.shape)
print('Avg. SSIM Recon te shape', ssim_recon_avg_te.shape)
mu_mse_recon_avg_tr, sigma_mse_recon_avg_tr = mu_sigma(mse_recon_avg_tr)
mu_ssim_recon_avg_tr, sigma_ssim_recon_avg_tr = mu_sigma(ssim_recon_avg_tr)
mu_mse_recon_avg_te, sigma_mse_recon_avg_te = mu_sigma(mse_recon_avg_te)
mu_ssim_recon_avg_te, sigma_ssim_recon_avg_te = mu_sigma(ssim_recon_avg_te)
print('Avg. MSE Recon mu te shape', mu_mse_recon_avg_te.shape)
print('Avg. SSIM Recon mu te shape', mu_ssim_recon_avg_te.shape)
lb_mse_tr = mu_mse_recon_avg_tr - sigma_mse_recon_avg_tr
ub_mse_tr = mu_mse_recon_avg_tr + sigma_mse_recon_avg_tr
lb_mse_te = mu_mse_recon_avg_te - sigma_mse_recon_avg_te
ub_mse_te = mu_mse_recon_avg_te + sigma_mse_recon_avg_te
lb_ssim_tr = mu_ssim_recon_avg_tr - sigma_ssim_recon_avg_tr
ub_ssim_tr = mu_ssim_recon_avg_tr + sigma_ssim_recon_avg_tr
lb_ssim_te = mu_ssim_recon_avg_te - sigma_ssim_recon_avg_te
ub_ssim_te = mu_ssim_recon_avg_te + sigma_ssim_recon_avg_te
plt.figure()
xaxis = np.arange(1,16)
fig, ax = plt.subplots(1, 2, figsize=(18, 3))
fig.suptitle('Average reconstruction MSE and SSIM', fontsize = 18)
ax[0].plot(np.arange(1,16),mu_mse_recon_avg_tr,'o-',c ='tab:blue')
ax[0].plot(np.arange(1,16),mu_mse_recon_avg_te,'^--',c='tab:blue')
ax[1].plot(np.arange(1,16),mu_ssim_recon_avg_tr,'o-',c = 'tab:orange')
ax[1].plot(np.arange(1,16),mu_ssim_recon_avg_te,'^--',c='tab:orange')
ax[0].set_ylabel('Avg. recon. MSE', fontsize = 18)
ax[1].set_ylabel('Avg. recon. SSIM', fontsize = 18)
ax[0].set_ylim([0.1e-7,10e-7])
ax[1].set_ylim([0.98,1.0])
ax[0].set_yticks([2e-7,4e-7,6e-7,8e-7,10e-7])
ax[1].set_yticks([0.98,0.985,0.99,0.995,1.00])
ax[0].set_yticklabels((['2','4','6','8','10e-7']),fontsize=15)
ax[1].set_yticklabels((['0.980','0.985','0.990','0.995','1.0']),fontsize=15)
ax[0].set_xticks(range(1,16))
ax[1].set_xticks(range(1,16))
ax[0].set_xticklabels((str(i) for i in range(1,16)),fontsize=15)
ax[1].set_xticklabels((str(i) for i in range(1,16)),fontsize=15)
ax[0].set_xlabel('6d LPS projections', fontsize = 18)
ax[1].set_xlabel('6d LPS projections', fontsize = 18)
ax[0].legend(['train','test'], fontsize=15)
ax[1].legend(['train','test'], fontsize=15)
plt.savefig('mse_ssim_recon.png', bbox_inches='tight' ,dpi=300)
#%% =====>>>> LATENT SPACE RESULTS <<<<======
############################################################################################
################## LATENT SPACE VISUALIZATION PART ########################################
############################################################################################
#%% plot multidimensional latent space as different 2d projections
from lib.colorplots2d import COLORPLOTS_2D
def latentspace(dataloader,model):
model.eval()
latent_app = []
with torch.no_grad():
for step, batch in enumerate(dataloader):
data, mod = batch
data = data.to(device1)
mod = mod.to(device1)
_,_,_,z = model(data,mod)
latent_app.append(z.cpu().detach())
latent_app = torch.cat(latent_app)
return latent_app
latent_train = latentspace(dataloader_train,cvae15).numpy()
latent_val = latentspace(dataloader_val,cvae15).numpy()
latent_combine = latentspace(dataloader_trainval,cvae15).numpy()
latent_test = latentspace(dataloader_test,cvae15).numpy()
print("Shape of the latent train", latent_train.shape)
print("Shape of the latent validation", latent_val.shape)
print("Shape of the latent combine", latent_combine.shape)
print("Shape of the latent test", latent_test.shape)
# color plots in latent
for i in range(1,8):
COLORPLOTS_2D(latent_combine,imgs_all_tr.shape[0],0,i,'2d proj. of 8d latent space')
#plt.savefig(path +'latent_parallelcoords_' + str(0) + '_' + str(i), dpi=300)
#%% parallel cords visualization of the 8d latent space
from lib.parallelcords1_plot import parallelcords1
# plot few training and validation samples in parralelcords
nlines1 = np.random.randint(0, latent_train.shape[0], 2000)
nlines2 = np.random.randint(0, latent_val.shape[0], 300)
data_train_pc = latent_train[nlines1]
data_val_pc = latent_val[nlines2]
# plotting train and test sets
N1 = np.ones(data_train_pc.shape[0],dtype='int64')
N2 = np.ones(data_val_pc.shape[0],dtype='int64')*2
coloring = np.concatenate((N1,N2),axis=0)
data_pc = np.concatenate((data_train_pc,data_val_pc),axis=0)
color1 = "tab:blue"
color2 = "tab:orange"
parallelcords1(data_pc,coloring,color1,color2)
#plt.savefig('latent_parallelcords.png', dpi=300)
#%% parallel cords visualization of the 8d latent space with different modules separated
from lib.parallelcords_modwise import PC_modwise
latent_combine_rs = latent_combine.reshape(1400,48,8)
n_lines = np.random.randint(0, latent_combine_rs.shape[0], 25) # 5 random lines for each module
coloring = []
data_pc = []
for i in range(48):
data_mod = latent_combine_rs[n_lines, i, :]
N = np.ones(data_mod.shape[0],dtype='int64')*(i+1)
coloring.append(N)
data_pc.append(data_mod)
data_pc = np.concatenate(data_pc, axis = 0)
PC_modwise(data_pc, n_lines.shape[0])
path = 'E:/MSR/codes/RFLA_VAE_LSTM_pyt/figures/fig_latentspace/'
plt.savefig(path + 'latent_parallelcords_modwise.png', dpi=300)
#%% latent space via PCA
from lib.PCA import PCAmodel
from lib.trajectors import TRAJECTORIESinLATENT
from lib.colorplotsinlatent import COLORPLOTSinLATENT
pca = PCAmodel()
nd = 2
(Xtr_pca, evr_tr_pca, recon_tr_pca) = pca.pcabuild(latent_train, nd)
(Xval_pca, evr_val_pca, recon_val_pca) = pca.pcabuild(latent_val, nd)
(Xc_pca, evr_tc_pca, recon_tc_pca) = pca.pcabuild(latent_combine, nd)
plt.figure(figsize=(6, 6))
plt.title('PCA of the latent space', fontsize = 20)
plt.scatter(Xtr_pca[:, 0], Xtr_pca[:, 1], c='tab:blue', marker=".")
plt.scatter(Xval_pca[:, 0], Xval_pca[:, 1], c='tab:orange', marker=".")
plt.legend(['Train','Test'], fontsize=18)
plt.xlabel('pca-1', fontsize=20)
plt.ylabel('pca-2', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()
#plt.savefig('pca1_of_latent.png', dpi=300)
# color plots in latent
COLORPLOTSinLATENT(Xc_pca,imgs_all_tr.shape[0], 'pca of 8d latent space', 'pca')
#plt.savefig(path + 'pca2_of_latent.png', dpi=300)
modidx, prt = 4, 3
title = 'Trajectories in the latent manifold'
TRAJECTORIESinLATENT(Xc_pca,modidx,prt,title,'pca')
#plt.savefig('traj_pca2_of_latent.png', dpi=300)
#%% t-sne of the latent space
from sklearn.manifold import TSNE
size_train = latent_train.shape[0]
tsne = TSNE(n_components=2, learning_rate='auto',
init ='pca').fit_transform(latent_combine)
X_train_tsne = tsne[0:size_train,:]
X_test_tsne = tsne[size_train:,:]
plt.figure(figsize=(6, 6))
plt.title('t-SNE of the latent space', fontsize = 20)
plt.scatter(X_train_tsne[:, 0], X_train_tsne[:, 1], c='tab:blue', marker=".")
plt.scatter(X_test_tsne[:, 0], X_test_tsne[:, 1], c='tab:orange', marker=".")
plt.legend(['Train', 'Test'], loc='best', fontsize=18)
plt.xlabel('tsne1', fontsize=20)
plt.ylabel('tsne2', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.savefig('tsne1_of_latent.png', dpi=300)
plt.show()
# color plots in latent
COLORPLOTSinLATENT(tsne,imgs_all_tr.shape[0],'t-sne of 8d latent space', 'tsne')
plt.savefig(path + 'tsne2_of_latent.png', dpi=300)
modidx, prt = 4, 3
title = 'Trajectories in the latent manifold'
TRAJECTORIESinLATENT(tsne,modidx,prt,title,'tsne')
#plt.savefig('traj_tsne2_of_latent.png', dpi=300)
#%% UMAP visualization
import umap
reducer = umap.UMAP(n_components=2)
mapper = reducer.fit(latent_combine)
COLORPLOTSinLATENT(mapper.embedding_,imgs_all_tr.shape[0], 'umap of 8d latent space', 'umap')
plt.savefig(path + 'umap_of_latent.png', dpi=150)
modidx, prt = 4, 3
title = 'Trajectories in the latent manifold'