forked from charlesll/i-melt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imelt.py
1449 lines (1148 loc) · 56.9 KB
/
imelt.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
# (c) Charles Le Losq 2021
# see embedded licence file
# imelt V1.1
import numpy as np
import torch, time
import h5py
import torch.nn.functional as F
from sklearn.metrics import mean_squared_error
class data_loader():
"""custom data loader for batch training
"""
def __init__(self,path_viscosity,path_raman,path_density, path_ri, device, scaling = False):
"""
Inputs
------
path_viscosity : string
path for the viscosity HDF5 dataset
path_raman : string
path for the Raman spectra HDF5 dataset
path_density : string
path for the density HDF5 dataset
path_ri : String
path for the refractive index HDF5 dataset
device : CUDA
scaling : False or True
Scales the input chemical composition.
WARNING : Does not work currently as this is a relic of testing this effect,
but we chose not to scale inputs and Cp are calculated with unscaled values in the network."""
f = h5py.File(path_viscosity, 'r')
# List all groups
self.X_columns = f['X_columns'][()]
# Entropy dataset
X_entropy_train = f["X_entropy_train"][()]
y_entropy_train = f["y_entropy_train"][()]
X_entropy_valid = f["X_entropy_valid"][()]
y_entropy_valid = f["y_entropy_valid"][()]
X_entropy_test = f["X_entropy_test"][()]
y_entropy_test = f["y_entropy_test"][()]
# Viscosity dataset
X_train = f["X_train"][()]
y_train = f["y_train"][()]
X_valid = f["X_valid"][()]
y_valid = f["y_valid"][()]
X_test = f["X_test"][()]
y_test = f["y_test"][()]
# Tg dataset
X_tg_train = f["X_tg_train"][()]
X_tg_valid= f["X_tg_valid"][()]
X_tg_test = f["X_tg_test"][()]
y_tg_train = f["y_tg_train"][()]
y_tg_valid = f["y_tg_valid"][()]
y_tg_test = f["y_tg_test"][()]
f.close()
# Raman dataset
f = h5py.File(path_raman, 'r')
X_raman_train = f["X_raman_train"][()]
y_raman_train = f["y_raman_train"][()]
X_raman_valid = f["X_raman_test"][()]
y_raman_valid = f["y_raman_test"][()]
f.close()
# Density dataset
f = h5py.File(path_density, 'r')
X_density_train = f["X_density_train"][()]
X_density_valid = f["X_density_valid"][()]
X_density_test = f["X_density_test"][()]
y_density_train = f["y_density_train"][()]
y_density_valid = f["y_density_valid"][()]
y_density_test = f["y_density_test"][()]
f.close()
# Refractive Index (ri) dataset
f = h5py.File(path_ri, 'r')
X_ri_train = f["X_ri_train"][()]
X_ri_valid = f["X_ri_valid"][()]
X_ri_test = f["X_ri_test"][()]
lbd_ri_train = f["lbd_ri_train"][()]
lbd_ri_valid = f["lbd_ri_valid"][()]
lbd_ri_test = f["lbd_ri_test"][()]
y_ri_train = f["y_ri_train"][()]
y_ri_valid = f["y_ri_valid"][()]
y_ri_test = f["y_ri_test"][()]
f.close()
# grabbing number of Raman channels
self.nb_channels_raman = y_raman_valid.shape[1]
# preparing data for pytorch
# Scaler
# Warning : this was done for tests and currently will not work,
# as Cp are calculated from unscaled mole fractions...
if scaling == True:
X_scaler_mean = np.mean(X_train[:,0:4], axis=0)
X_scaler_std = np.std(X_train[:,0:4], axis=0)
else:
X_scaler_mean = 0.0
X_scaler_std = 1.0
# The following lines perform scaling (not needed, not active),
# put the data in torch tensors and send them to device (GPU or CPU, as requested)
# viscosity
self.x_visco_train = torch.FloatTensor(self.scaling(X_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.T_visco_train = torch.FloatTensor(X_train[:,4].reshape(-1,1)).to(device)
self.y_visco_train = torch.FloatTensor(y_train[:,0].reshape(-1,1)).to(device)
self.x_visco_valid = torch.FloatTensor(self.scaling(X_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.T_visco_valid = torch.FloatTensor(X_valid[:,4].reshape(-1,1)).to(device)
self.y_visco_valid = torch.FloatTensor(y_valid[:,0].reshape(-1,1)).to(device)
self.x_visco_test = torch.FloatTensor(self.scaling(X_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.T_visco_test = torch.FloatTensor(X_test[:,4].reshape(-1,1)).to(device)
self.y_visco_test = torch.FloatTensor(y_test[:,0].reshape(-1,1)).to(device)
# entropy
self.x_entro_train = torch.FloatTensor(self.scaling(X_entropy_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_entro_train = torch.FloatTensor(y_entropy_train[:,0].reshape(-1,1)).to(device)
self.x_entro_valid = torch.FloatTensor(self.scaling(X_entropy_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_entro_valid = torch.FloatTensor(y_entropy_valid[:,0].reshape(-1,1)).to(device)
self.x_entro_test = torch.FloatTensor(self.scaling(X_entropy_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_entro_test = torch.FloatTensor(y_entropy_test[:,0].reshape(-1,1)).to(device)
# tg
self.x_tg_train = torch.FloatTensor(self.scaling(X_tg_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_tg_train = torch.FloatTensor(y_tg_train.reshape(-1,1)).to(device)
self.x_tg_valid = torch.FloatTensor(self.scaling(X_tg_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_tg_valid = torch.FloatTensor(y_tg_valid.reshape(-1,1)).to(device)
self.x_tg_test = torch.FloatTensor(self.scaling(X_tg_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_tg_test = torch.FloatTensor(y_tg_test.reshape(-1,1)).to(device)
# Density
self.x_density_train = torch.FloatTensor(self.scaling(X_density_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_density_train = torch.FloatTensor(y_density_train.reshape(-1,1)).to(device)
self.x_density_valid = torch.FloatTensor(self.scaling(X_density_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_density_valid = torch.FloatTensor(y_density_valid.reshape(-1,1)).to(device)
self.x_density_test = torch.FloatTensor(self.scaling(X_density_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_density_test = torch.FloatTensor(y_density_test.reshape(-1,1)).to(device)
# Optical
self.x_ri_train = torch.FloatTensor(self.scaling(X_ri_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.lbd_ri_train = torch.FloatTensor(lbd_ri_train.reshape(-1,1)).to(device)
self.y_ri_train = torch.FloatTensor(y_ri_train.reshape(-1,1)).to(device)
self.x_ri_valid = torch.FloatTensor(self.scaling(X_ri_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.lbd_ri_valid = torch.FloatTensor(lbd_ri_valid.reshape(-1,1)).to(device)
self.y_ri_valid = torch.FloatTensor(y_ri_valid.reshape(-1,1)).to(device)
self.x_ri_test = torch.FloatTensor(self.scaling(X_ri_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.lbd_ri_test = torch.FloatTensor(lbd_ri_test.reshape(-1,1)).to(device)
self.y_ri_test = torch.FloatTensor(y_ri_test.reshape(-1,1)).to(device)
# Raman
self.x_raman_train = torch.FloatTensor(self.scaling(X_raman_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_raman_train = torch.FloatTensor(y_raman_train).to(device)
self.x_raman_valid = torch.FloatTensor(self.scaling(X_raman_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device)
self.y_raman_valid = torch.FloatTensor(y_raman_valid).to(device)
def scaling(self,X,mu,s):
"""perform standard scaling"""
return(X-mu)/s
def print_data(self):
"""print the specifications of the datasets"""
print("################################")
print("#### Dataset specifications ####")
print("################################")
# print splitting
size_train = self.x_visco_train.unique(dim=0).shape[0]
size_valid = self.x_visco_valid.unique(dim=0).shape[0]
size_test = self.x_visco_test.unique(dim=0).shape[0]
size_total = size_train+size_valid+size_test
print("")
print("Number of unique compositions (viscosity): {}".format(size_total))
print("Number of unique compositions in training (viscosity): {}".format(size_train))
print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total,
size_valid/size_total,
size_test/size_total))
# print splitting
size_train = self.x_entro_train.unique(dim=0).shape[0]
size_valid = self.x_entro_valid.unique(dim=0).shape[0]
size_test = self.x_entro_test.unique(dim=0).shape[0]
size_total = size_train+size_valid+size_test
print("")
print("Number of unique compositions (entropy): {}".format(size_total))
print("Number of unique compositions in training (entropy): {}".format(size_train))
print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total,
size_valid/size_total,
size_test/size_total))
size_train = self.x_ri_train.unique(dim=0).shape[0]
size_valid = self.x_ri_valid.unique(dim=0).shape[0]
size_test = self.x_ri_test.unique(dim=0).shape[0]
size_total = size_train+size_valid+size_test
print("")
print("Number of unique compositions (refractive index): {}".format(size_total))
print("Number of unique compositions in training (refractive index): {}".format(size_train))
print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total,
size_valid/size_total,
size_test/size_total))
size_train = self.x_density_train.unique(dim=0).shape[0]
size_valid = self.x_density_valid.unique(dim=0).shape[0]
size_test = self.x_density_test.unique(dim=0).shape[0]
size_total = size_train+size_valid+size_test
print("")
print("Number of unique compositions (density): {}".format(size_total))
print("Number of unique compositions in training (density): {}".format(size_train))
print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total,
size_valid/size_total,
size_test/size_total))
size_train = self.x_raman_train.unique(dim=0).shape[0]
size_valid = self.x_raman_valid.unique(dim=0).shape[0]
size_total = size_train+size_valid
print("")
print("Number of unique compositions (Raman): {}".format(size_total))
print("Number of unique compositions in training (Raman): {}".format(size_train))
print("Dataset separations are {:.2f} in train, {:.2f} in valid".format(size_train/size_total,
size_valid/size_total))
# training shapes
print("")
print("This is for checking the consistency of the dataset...")
print("Visco train shape")
print(self.x_visco_train.shape)
print(self.T_visco_train.shape)
print(self.y_visco_train.shape)
print("Entropy train shape")
print(self.x_entro_train.shape)
print(self.y_entro_train.shape)
print("Tg train shape")
print(self.x_tg_train.shape)
print(self.y_tg_train.shape)
print("Density train shape")
print(self.x_density_train.shape)
print(self.y_density_train.shape)
print("Refactive Index train shape")
print(self.x_ri_train.shape)
print(self.lbd_ri_train.shape)
print(self.y_ri_train.shape)
print("Raman train shape")
print(self.x_raman_train.shape)
print(self.y_raman_train.shape)
# testing device
print("")
print("Where are the datasets? CPU or GPU?")
print("Visco device")
print(self.x_visco_train.device)
print(self.T_visco_train.device)
print(self.y_visco_train.device)
print("Entropy device")
print(self.x_entro_train.device)
print(self.y_entro_train.device)
print("Tg device")
print(self.x_tg_train.device)
print(self.y_tg_train.device)
print("Density device")
print(self.x_density_train.device)
print(self.y_density_train.device)
print("Refactive Index device")
print(self.x_ri_test.device)
print(self.lbd_ri_test.device)
print(self.y_ri_test.device)
print("Raman device")
print(self.x_raman_train.device)
print(self.y_raman_train.device)
class model(torch.nn.Module):
"""i-MELT model
"""
def __init__(self, input_size, hidden_size, num_layers, nb_channels_raman,p_drop=0.5, activation_function = torch.nn.ReLU()):
"""Initialization of i-MELT model
Parameters
----------
input_size : int
number of input parameters
hidden_size : int
number of hidden units per hidden layer
num_layers : int
number of hidden layers
nb_channels_raman : int
number of Raman spectra channels, typically provided by the dataset
p_drop : float (optinal)
dropout probability, default = 0.5
activation_function : torch.nn activation function
activation function for the hidden units, default = torch.nn.ReLU()
choose here : https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity
"""
super(model, self).__init__()
# init parameters
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.nb_channels_raman = nb_channels_raman
# network related torch stuffs
self.activation_function = activation_function
self.dropout = torch.nn.Dropout(p=p_drop)
self.linears = torch.nn.ModuleList([torch.nn.Linear(input_size, self.hidden_size)])
self.linears.extend([torch.nn.Linear(self.hidden_size, self.hidden_size) for i in range(1, self.num_layers)])
self.out_thermo = torch.nn.Linear(self.hidden_size, 17) # Linear output
self.out_raman = torch.nn.Linear(self.hidden_size, self.nb_channels_raman) # Linear output
def output_bias_init(self):
"""bias initialisation for self.out_thermo
positions are Tg, Sconf(Tg), Ae, A_am, density, fragility (MYEGA one)
"""
self.out_thermo.bias = torch.nn.Parameter(data=torch.tensor([np.log(1000.),np.log(10.), # Tg, ScTg
-1.5,-1.5,-1.5, -4.5, # A_AG, A_AM, A_CG, A_TVF
np.log(500.), np.log(100.), np.log(400.), # To_CG, C_CG, C_TVF
np.log(2.3),np.log(25.0), # density, fragility
.90,.20,.98,0.6,0.2,1., # Sellmeier coeffs B1, B2, B3, C1, C2, C3
]))
def forward(self, x):
"""foward pass in core neural network"""
for layer in self.linears: # Feedforward
x = self.dropout(self.activation_function(layer(x)))
return x
def at_gfu(self,x):
"""calculate atom per gram formula unit
assumes rows are sio2 al2o3 na2o k2o
"""
out = 3.0*x[:,0] + 5.0*x[:,1] + 3.0*x[:,2] + 3.0*x[:,3]
return torch.reshape(out, (out.shape[0], 1))
def aCpl(self,x):
"""calculate term a in equation Cpl = aCpl + bCpl*T
"""
out = 81.37*x[:,0] + 27.21*x[:,1] + 100.6*x[:,2] + 50.13*x[:,3] + x[:,0]*(x[:,3]*x[:,3])*151.7
return torch.reshape(out, (out.shape[0], 1))
def b_calc(self,x):
"""calculate term b in equation Cpl = aCpl + b*T
"""
out = 0.09428*x[:,1] + 0.01578*x[:,3]
return torch.reshape(out, (out.shape[0], 1))
def ap_calc(self,x):
"""calculate term ap in equation dS = ap ln(T/Tg) + b(T-Tg)
"""
out = self.aCpl(x) - 3.0*8.314462*self.at_gfu(x)
return torch.reshape(out, (out.shape[0], 1))
def dCp(self,x,T):
out = self.ap_calc(x)*(torch.log(T)-torch.log(self.tg(x))) + self.b_calc(x)*(T-self.tg(x))
return torch.reshape(out, (out.shape[0], 1))
def raman_pred(self,x):
"""Raman predicted spectra"""
return self.out_raman(self.forward(x))
def tg(self,x):
"""glass transition temperature Tg"""
out = torch.exp(self.out_thermo(self.forward(x))[:,0])
return torch.reshape(out, (out.shape[0], 1))
def sctg(self,x):
"""configurational entropy at Tg"""
out = torch.exp(self.out_thermo(self.forward(x))[:,1])
return torch.reshape(out, (out.shape[0], 1))
def ae(self,x):
"""Ae parameter in Adam and Gibbs and MYEGA"""
out = self.out_thermo(self.forward(x))[:,2]
return torch.reshape(out, (out.shape[0], 1))
def a_am(self,x):
"""A parameter for Avramov-Mitchell"""
out = self.out_thermo(self.forward(x))[:,3]
return torch.reshape(out, (out.shape[0], 1))
def a_cg(self,x):
"""A parameter for Free Volume (CG)"""
out = self.out_thermo(self.forward(x))[:,4]
return torch.reshape(out, (out.shape[0], 1))
def a_tvf(self,x):
"""A parameter for Free Volume (CG)"""
out = self.out_thermo(self.forward(x))[:,5]
return torch.reshape(out, (out.shape[0], 1))
def to_cg(self,x):
"""A parameter for Free Volume (CG)"""
out = torch.exp(self.out_thermo(self.forward(x))[:,6])
return torch.reshape(out, (out.shape[0], 1))
def c_cg(self,x):
"""C parameter for Free Volume (CG)"""
out = torch.exp(self.out_thermo(self.forward(x))[:,7])
return torch.reshape(out, (out.shape[0], 1))
def c_tvf(self,x):
"""C parameter for Free Volume (CG)"""
out = torch.exp(self.out_thermo(self.forward(x))[:,8])
return torch.reshape(out, (out.shape[0], 1))
def density(self,x):
"""glass density"""
out = torch.exp(self.out_thermo(self.forward(x))[:,9])
return torch.reshape(out, (out.shape[0], 1))
def fragility(self,x):
"""melt fragility"""
out = torch.exp(self.out_thermo(self.forward(x))[:,10])
return torch.reshape(out, (out.shape[0], 1))
def S_B1(self,x):
"""Sellmeir B1"""
out = self.out_thermo(self.forward(x))[:,11]
return torch.reshape(out, (out.shape[0], 1))
def S_B2(self,x):
"""Sellmeir B1"""
out = self.out_thermo(self.forward(x))[:,12]
return torch.reshape(out, (out.shape[0], 1))
def S_B3(self,x):
"""Sellmeir B1"""
out = self.out_thermo(self.forward(x))[:,13]
return torch.reshape(out, (out.shape[0], 1))
def S_C1(self,x):
"""Sellmeir C1, with proper scaling"""
out = 0.01*self.out_thermo(self.forward(x))[:,14]
return torch.reshape(out, (out.shape[0], 1))
def S_C2(self,x):
"""Sellmeir C2, with proper scaling"""
out = 0.1*self.out_thermo(self.forward(x))[:,15]
return torch.reshape(out, (out.shape[0], 1))
def S_C3(self,x):
"""Sellmeir C3, with proper scaling"""
out = 100*self.out_thermo(self.forward(x))[:,16]
return torch.reshape(out, (out.shape[0], 1))
def b_cg(self, x):
"""B in free volume (CG) equation"""
return 0.5*(12.0 - self.a_cg(x)) * (self.tg(x) - self.to_cg(x) + torch.sqrt( (self.tg(x) - self.to_cg(x))**2 + self.c_cg(x)*self.tg(x)))
def b_tvf(self,x):
return (12.0-self.a_tvf(x))*(self.tg(x)-self.c_tvf(x))
def be(self,x):
"""Be term in Adam-Gibbs eq given Ae, Tg and Scong(Tg)"""
return (12.0-self.ae(x))*(self.tg(x)*self.sctg(x))
def sc_t(self, x, T):
"""Melt configurational entropy at temperature T
"""
return self.sctg(x) + self.dCp(x, T)
def ag(self,x,T):
"""viscosity from the Adam-Gibbs equation, given chemistry X and temperature T
"""
return self.ae(x) + self.be(x) / (T* (self.sctg(x) + self.dCp(x, T)))
def myega(self,x, T):
"""viscosity from the MYEGA equation, given entries X and temperature T
"""
return self.ae(x) + (12.0 - self.ae(x))*(self.tg(x)/T)*torch.exp((self.fragility(x)/(12.0-self.ae(x))-1.0)*(self.tg(x)/T-1.0))
def am(self,x, T):
"""viscosity from the Avramov-Mitchell equation, given entries X and temperature T
"""
return self.a_am(x) + (12.0 - self.a_am(x))*(self.tg(x)/T)**(self.fragility(x)/(12.0 - self.a_am(x)))
def cg(self,x, T):
"""free volume theory viscosity equation, given entries X and temperature T
"""
return self.a_cg(x) + 2.0*self.b_cg(x)/(T - self.to_cg(x) + torch.sqrt( (T-self.to_cg(x))**2 + self.c_cg(x)*T))
def tvf(self,x, T):
"""Tamman-Vogel-Fulscher empirical viscosity, given entries X and temperature T
"""
return self.a_tvf(x) + self.b_tvf(x)/(T - self.c_tvf(x))
def sellmeier(self, x, lbd):
"""Sellmeier equation for refractive index calculation, with lbd in microns
"""
return torch.sqrt( 1.0 + self.S_B1(x)*lbd**2/(lbd**2-self.S_C1(x))
+ self.S_B2(x)*lbd**2/(lbd**2-self.S_C2(x))
+ self.S_B3(x)*lbd**2/(lbd**2-self.S_C3(x)))
class loss_scales():
"""loss scales for everything"""
def __init__(self):
# scaling coefficients for loss function
# viscosity is always one
self.entro = 1.
self.raman = 20.
self.density = 1000.
self.ri = 10000.
self.tg = 0.001
def training(neuralmodel, ds, criterion, optimizer, save_switch=True, save_name="./temp", train_patience = 50, min_delta=0.1, verbose=True, mode="main", max_epochs = 5000):
"""train neuralmodel given a dataset, criterion and optimizer
Parameters
----------
neuralmodel : model
a neuravi model
ds : dataset
dataset from data_loader()
criterion : pytorch criterion
the criterion for goodness of fit
optimizer : pytorch optimizer
the optimizer to use
save_name : string
the path to save the model during training
Options
-------
train_patience : int, default = 50
the number of iterations
min_delta : float, default = 0.1
Minimum decrease in the loss to qualify as an improvement,
a decrease of less than or equal to `min_delta` will count as no improvement.
verbose : bool, default = True
Do you want details during training?
mode : string, default = "main"
"main" or "pretrain"
max_epochs : int
maximum number of epochs to perform. Useful in case of prototyping, etc.
Returns
-------
neuralmodel : model
trained model
record_train_loss : list
training loss (global)
record_valid_loss : list
validation loss (global)
"""
if verbose == True:
time1 = time.time()
if mode == "pretrain":
print("! Pretrain mode...\n")
else:
print("Full training.\n")
# scaling coefficients for loss function
# viscosity is always one
# scaling coefficients for loss function
# viscosity is always one
ls = loss_scales()
entro_scale = ls.entro
raman_scale = ls.raman
density_scale = ls.density
ri_scale = ls.ri
tg_scale = ls.tg
neuralmodel.train()
# for early stopping
epoch = 0
best_epoch = 0
val_ex = 0
# for recording losses
record_train_loss = []
record_valid_loss = []
while val_ex <= train_patience:
optimizer.zero_grad()
# Forward pass on training set
y_ag_pred_train = neuralmodel.ag(ds.x_visco_train,ds.T_visco_train)
y_myega_pred_train = neuralmodel.myega(ds.x_visco_train,ds.T_visco_train)
y_am_pred_train = neuralmodel.am(ds.x_visco_train,ds.T_visco_train)
y_cg_pred_train = neuralmodel.cg(ds.x_visco_train,ds.T_visco_train)
y_tvf_pred_train = neuralmodel.tvf(ds.x_visco_train,ds.T_visco_train)
y_raman_pred_train = neuralmodel.raman_pred(ds.x_raman_train)
y_density_pred_train = neuralmodel.density(ds.x_density_train)
y_entro_pred_train = neuralmodel.sctg(ds.x_entro_train)
y_tg_pred_train = neuralmodel.tg(ds.x_tg_train)
y_ri_pred_train = neuralmodel.sellmeier(ds.x_ri_train, ds.lbd_ri_train)
# on validation set
y_ag_pred_valid = neuralmodel.ag(ds.x_visco_valid,ds.T_visco_valid)
y_myega_pred_valid = neuralmodel.myega(ds.x_visco_valid,ds.T_visco_valid)
y_am_pred_valid = neuralmodel.am(ds.x_visco_valid,ds.T_visco_valid)
y_cg_pred_valid = neuralmodel.cg(ds.x_visco_valid,ds.T_visco_valid)
y_tvf_pred_valid = neuralmodel.tvf(ds.x_visco_valid,ds.T_visco_valid)
y_raman_pred_valid = neuralmodel.raman_pred(ds.x_raman_valid)
y_density_pred_valid = neuralmodel.density(ds.x_density_valid)
y_entro_pred_valid = neuralmodel.sctg(ds.x_entro_valid)
y_tg_pred_valid = neuralmodel.tg(ds.x_tg_valid)
y_ri_pred_valid = neuralmodel.sellmeier(ds.x_ri_valid, ds.lbd_ri_valid)
# Compute Loss
# train
loss_ag = criterion(y_ag_pred_train, ds.y_visco_train)
loss_myega = criterion(y_myega_pred_train, ds.y_visco_train)
loss_am = criterion(y_am_pred_train, ds.y_visco_train)
loss_cg = criterion(y_cg_pred_train, ds.y_visco_train)
loss_tvf = criterion(y_tvf_pred_train, ds.y_visco_train)
loss_raman = raman_scale*criterion(y_raman_pred_train,ds.y_raman_train)
loss_tg = tg_scale*criterion(y_tg_pred_train,ds.y_tg_train)
loss_density = density_scale*criterion(y_density_pred_train,ds.y_density_train)
loss_entro = entro_scale*criterion(y_entro_pred_train,ds.y_entro_train)
loss_ri = ri_scale*criterion(y_ri_pred_train,ds.y_ri_train)
if mode == "pretrain":
loss = loss_tg + loss_raman + loss_density + loss_entro + loss_ri
else:
loss = loss_ag + loss_myega + loss_am + loss_cg + loss_tvf + loss_raman + loss_density + loss_entro + loss_ri
record_train_loss.append(loss.item()) # record global loss
# validation
with torch.set_grad_enabled(False):
loss_ag_v = criterion(y_ag_pred_valid, ds.y_visco_valid)
loss_myega_v = criterion(y_myega_pred_valid, ds.y_visco_valid)
loss_am_v = criterion(y_am_pred_valid, ds.y_visco_valid)
loss_cg_v = criterion(y_cg_pred_valid, ds.y_visco_valid)
loss_tvf_v = criterion(y_tvf_pred_valid, ds.y_visco_valid)
loss_raman_v = raman_scale*criterion(y_raman_pred_valid,ds.y_raman_valid)
loss_tg_v = tg_scale*criterion(y_tg_pred_valid,ds.y_tg_valid)
loss_density_v = density_scale*criterion(y_density_pred_valid,ds.y_density_valid)
loss_entro_v = entro_scale*criterion(y_entro_pred_valid,ds.y_entro_valid)
loss_ri_v = ri_scale*criterion(y_ri_pred_valid,ds.y_ri_valid)
if mode == "pretrain":
loss_v = loss_tg_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri_v
else:
loss_v = loss_ag_v + loss_myega_v + loss_am_v + loss_cg_v + loss_tvf_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri
record_valid_loss.append(loss_v.item())
if verbose == True:
if (epoch % 200 == 0):
print('Epoch {} => train loss: {}; valid loss: {}'.format(epoch, loss.item(), loss_v.item()))
###
# calculating ES criterion
###
if epoch == 0:
val_ex = 0
best_loss_v = loss_v.item()
elif loss_v.item() <= best_loss_v - min_delta: # if improvement is significant, this saves the model
val_ex = 0
best_epoch = epoch
best_loss_v = loss_v.item()
if save_switch == True: # save best model
torch.save(neuralmodel.state_dict(), save_name)
else:
val_ex += 1
# Backward pass
loss.backward()
optimizer.step()
epoch += 1
# we test is we are still under a reasonable number of epochs, if not break
if epoch > max_epochs:
break
if verbose == True:
time2 = time.time()
print("Running time in seconds:", time2-time1)
print('Scaled valid loss values are {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f} for Tg, Raman, density, entropy, ri, viscosity (AG)'.format(
loss_tg_v, loss_raman_v, loss_density_v, loss_entro_v, loss_ri_v, loss_ag_v
))
return neuralmodel, record_train_loss, record_valid_loss
def training2(neuralmodel, ds, criterion,optimizer, save_switch=True, save_name="./temp", nb_folds=10, train_patience=50, min_delta=0.1, verbose=True, mode="main", device='cuda'):
"""train neuralmodel given a dataset, criterion and optimizer
Parameters
----------
neuralmodel : model
a neuravi model
ds : dataset
dataset from data_loader()
criterion : pytorch criterion
the criterion for goodness of fit
optimizer : pytorch optimizer
the optimizer to use
save_name : string
the path to save the model during training
Options
-------
nb_folds : int, default = 10
the number of folds for the K-fold training
train_patience : int, default = 50
the number of iterations
min_delta : float, default = 0.1
Minimum decrease in the loss to qualify as an improvement,
a decrease of less than or equal to `min_delta` will count as no improvement.
verbose : bool, default = True
Do you want details during training?
mode : string, default = "main"
"main" or "pretrain"
device : string, default = "cuda"
the device where the calculations are made during training
Returns
-------
neuralmodel : model
trained model
record_train_loss : list
training loss (global)
record_valid_loss : list
validation loss (global)
"""
if verbose == True:
time1 = time.time()
if mode == "pretrain":
print("! Pretrain mode...\n")
else:
print("Full training.\n")
# scaling coefficients for loss function
# viscosity is always one
ls = loss_scales()
entro_scale = ls.entro
raman_scale = ls.raman
density_scale = ls.density
ri_scale = ls.ri
tg_scale = ls.tg
neuralmodel.train()
# for early stopping
epoch = 0
best_epoch = 0
val_ex = 0
# for recording losses
record_train_loss = []
record_valid_loss = []
# new vectors for the K-fold training (each vector contains slices of data separated)
slices_x_visco_train = [ds.x_visco_train[i::nb_folds] for i in range(nb_folds)]
slices_y_visco_train = [ds.y_visco_train[i::nb_folds] for i in range(nb_folds)]
slices_T_visco_train = [ds.T_visco_train[i::nb_folds] for i in range(nb_folds)]
slices_x_raman_train = [ds.x_raman_train[i::nb_folds] for i in range(nb_folds)]
slices_y_raman_train = [ds.y_raman_train[i::nb_folds] for i in range(nb_folds)]
slices_x_density_train = [ds.x_density_train[i::nb_folds] for i in range(nb_folds)]
slices_y_density_train = [ds.y_density_train[i::nb_folds] for i in range(nb_folds)]
slices_x_entro_train = [ds.x_entro_train[i::nb_folds] for i in range(nb_folds)]
slices_y_entro_train = [ds.y_entro_train[i::nb_folds] for i in range(nb_folds)]
slices_x_tg_train = [ds.x_tg_train[i::nb_folds] for i in range(nb_folds)]
slices_y_tg_train = [ds.y_tg_train[i::nb_folds] for i in range(nb_folds)]
slices_x_ri_train = [ds.x_ri_train[i::nb_folds] for i in range(nb_folds)]
slices_y_ri_train = [ds.y_ri_train[i::nb_folds] for i in range(nb_folds)]
slices_lbd_ri_train = [ds.lbd_ri_train[i::nb_folds] for i in range(nb_folds)]
while val_ex <= train_patience:
#
# TRAINING
#
loss = 0 # initialize the sum of losses of each fold
for i in range(nb_folds): # loop for K-Fold training to reduce memory footprint
# vectors are sent to device
# training dataset is not on device yet and needs to be sent there
x_visco_train = slices_x_visco_train[i]#.to(device)
y_visco_train = slices_y_visco_train[i]#.to(device)
T_visco_train = slices_T_visco_train[i]#.to(device)
x_raman_train = slices_x_raman_train[i]#.to(device)
y_raman_train = slices_y_raman_train[i]#.to(device)
x_density_train = slices_x_density_train[i]#.to(device)
y_density_train = slices_y_density_train[i]#.to(device)
x_entro_train = slices_x_entro_train[i]#.to(device)
y_entro_train = slices_y_entro_train[i]#.to(device)
x_tg_train = slices_x_tg_train[i]#.to(device)
y_tg_train = slices_y_tg_train[i]#.to(device)
x_ri_train = slices_x_ri_train[i]#.to(device)
y_ri_train = slices_y_ri_train[i]#.to(device)
lbd_ri_train = slices_lbd_ri_train[i]#.to(device)
# Forward pass on training set
y_ag_pred_train = neuralmodel.ag(x_visco_train,T_visco_train)
y_myega_pred_train = neuralmodel.myega(x_visco_train,T_visco_train)
y_am_pred_train = neuralmodel.am(x_visco_train,T_visco_train)
y_cg_pred_train = neuralmodel.cg(x_visco_train,T_visco_train)
y_tvf_pred_train = neuralmodel.tvf(x_visco_train,T_visco_train)
y_raman_pred_train = neuralmodel.raman_pred(x_raman_train)
y_density_pred_train = neuralmodel.density(x_density_train)
y_entro_pred_train = neuralmodel.sctg(x_entro_train)
y_tg_pred_train = neuralmodel.tg(x_tg_train)
y_ri_pred_train = neuralmodel.sellmeier(x_ri_train,lbd_ri_train)
# Precisions
precision_visco = 1.0#1/(2*torch.exp(-neuralmodel.log_vars[0]))
precision_raman = raman_scale #1/(2*torch.exp(-neuralmodel.log_vars[1]))
precision_density = density_scale #1/(2*torch.exp(-neuralmodel.log_vars[2]))
precision_entro = entro_scale#1/(2*torch.exp(-neuralmodel.log_vars[3]))
precision_tg = tg_scale#1/(2*torch.exp(-neuralmodel.log_vars[4]))
precision_ri = ri_scale#1/(2*torch.exp(-neuralmodel.log_vars[5]))
# Compute Loss
loss_ag = precision_visco * criterion(y_ag_pred_train, y_visco_train) #+ neuralmodel.log_vars[0]
loss_myega = precision_visco * criterion(y_myega_pred_train, y_visco_train) #+ neuralmodel.log_vars[0]
loss_am = precision_visco * criterion(y_am_pred_train, y_visco_train) #+ neuralmodel.log_vars[0]
loss_cg = precision_visco * criterion(y_cg_pred_train, y_visco_train) #+ neuralmodel.log_vars[0]
loss_tvf = precision_visco * criterion(y_tvf_pred_train, y_visco_train) #+ neuralmodel.log_vars[0]
loss_raman = precision_raman * criterion(y_raman_pred_train,y_raman_train) #+ neuralmodel.log_vars[1]
loss_density = precision_density * criterion(y_density_pred_train,y_density_train) #+ neuralmodel.log_vars[2]
loss_entro = precision_entro * criterion(y_entro_pred_train,y_entro_train) #+ neuralmodel.log_vars[3]
loss_tg = precision_tg * criterion(y_tg_pred_train,y_tg_train) #+ neuralmodel.log_vars[4]
loss_ri = precision_ri * criterion(y_ri_pred_train,y_ri_train) #+ neuralmodel.log_vars[5]
if mode == "pretrain":
loss_fold = loss_tg + loss_raman + loss_density + loss_entro + loss_ri
else:
loss_fold = (loss_ag + loss_myega + loss_am + loss_cg +
loss_tvf + loss_raman + loss_density + loss_entro + loss_ri)
optimizer.zero_grad() # initialise gradient
loss_fold.backward() # backward gradient determination
optimizer.step() # optimiser call and step
loss += loss_fold.item() # add the new fold loss to the sum
# record global loss (mean of the losses of the training folds)
record_train_loss.append(loss/nb_folds)
#
# MONITORING VALIDATION SUBSET
#
with torch.set_grad_enabled(False):
# Precisions
precision_visco = 1.0#1/(2*torch.exp(-neuralmodel.log_vars[0]))
precision_raman = raman_scale #1/(2*torch.exp(-neuralmodel.log_vars[1]))
precision_density = density_scale #1/(2*torch.exp(-neuralmodel.log_vars[2]))
precision_entro = entro_scale#1/(2*torch.exp(-neuralmodel.log_vars[3]))
precision_tg = tg_scale#1/(2*torch.exp(-neuralmodel.log_vars[4]))
precision_ri = ri_scale#1/(2*torch.exp(-neuralmodel.log_vars[5]))
# on validation set
y_ag_pred_valid = neuralmodel.ag(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device))
y_myega_pred_valid = neuralmodel.myega(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device))
y_am_pred_valid = neuralmodel.am(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device))
y_cg_pred_valid = neuralmodel.cg(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device))
y_tvf_pred_valid = neuralmodel.tvf(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device))
y_raman_pred_valid = neuralmodel.raman_pred(ds.x_raman_valid.to(device))
y_density_pred_valid = neuralmodel.density(ds.x_density_valid.to(device))
y_entro_pred_valid = neuralmodel.sctg(ds.x_entro_valid.to(device))
y_tg_pred_valid = neuralmodel.tg(ds.x_tg_valid.to(device))
y_cp_pred_valid = neuralmodel.dCp(ds.x_entro_valid.to(device),neuralmodel.tg(ds.x_entro_valid.to(device)))
y_ri_pred_valid = neuralmodel.sellmeier(ds.x_ri_valid.to(device), ds.lbd_ri_valid.to(device))
# validation loss
loss_ag_v = precision_visco * criterion(y_ag_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0]
loss_myega_v = precision_visco * criterion(y_myega_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0]
loss_am_v = precision_visco * criterion(y_am_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0]
loss_cg_v = precision_visco * criterion(y_cg_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0]
loss_tvf_v = precision_visco * criterion(y_tvf_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0]
loss_raman_v = precision_raman * criterion(y_raman_pred_valid,ds.y_raman_valid.to(device)) #+ neuralmodel.log_vars[1]
loss_density_v = precision_density * criterion(y_density_pred_valid,ds.y_density_valid.to(device)) #+ neuralmodel.log_vars[2]
loss_entro_v = precision_entro * criterion(y_entro_pred_valid,ds.y_entro_valid.to(device)) #+ neuralmodel.log_vars[3]
loss_tg_v = precision_tg * criterion(y_tg_pred_valid,ds.y_tg_valid.to(device)) #+ neuralmodel.log_vars[4]
loss_ri_v = precision_ri * criterion(y_ri_pred_valid,ds.y_ri_valid.to(device)) #+ neuralmodel.log_vars[5]
if mode == "pretrain":
loss_v = loss_tg_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri_v
else:
loss_v = loss_ag_v + loss_myega_v + loss_am_v + loss_cg_v + loss_tvf_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri
record_valid_loss.append(loss_v.item())
#
# Print info on screen
#
if verbose == True:
if (epoch % 5 == 0):
print('Epoch {} => train loss: {}; valid loss: {}'.format(epoch, loss/nb_folds, loss_v.item()))
#
# calculating ES criterion
#
if epoch == 0:
val_ex = 0
best_loss_v = loss_v.item()
elif loss_v.item() <= best_loss_v - min_delta: # if improvement is significant, this saves the model
val_ex = 0
best_epoch = epoch
best_loss_v = loss_v.item()
if save_switch == True: # save best model
torch.save(neuralmodel.state_dict(), save_name)
else:
val_ex += 1
epoch += 1
if verbose == True:
time2 = time.time()
print("Running time in seconds:", time2-time1)
print('Scaled valid loss values are {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f} for Tg, Raman, density, entropy, ri, viscosity (AG)'.format(
loss_tg_v, loss_raman_v, loss_density_v, loss_entro_v, loss_ri_v, loss_ag_v
))