-
Notifications
You must be signed in to change notification settings - Fork 0
/
ANN_versus_PINN.py
1355 lines (1122 loc) · 61.9 KB
/
ANN_versus_PINN.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
# Ipython startup command
# ipython --no-autoindent --matplotlib=agg --InteractiveShellApp.exec_lines="%matplotlib auto" --InteractiveShellApp.exec_lines="%load_ext autoreload" --InteractiveShellApp.exec_lines="%autoreload 2"
# %% Import
import numpy as np
import pickle
import pandas
import os
from datetime import datetime
import time
import ast # for converting string lists to real lists
import sciann as sn
from utils.sciann_datagenerator import *
import tensorflow as tf
# from tensorflow.python.ops import math_ops
# from tensorflow.python.keras import backend as K
# import tensorflow_probability as tfp
from scipy.interpolate import griddata
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors
from matplotlib.colors import LogNorm, Normalize
matplotlib.use('agg')
# matplotlib.use('tkagg')
plt.style.use("default")
# Own Files
from utils.SciANN_custom_targets import assign_targets_to_input_dim
from utils.template_values import *
from utils.my_func import *
from utils.my_plots import *
matplotlib.rcParams.update(params)
#Set Random Seeds
set_seeds(123)
# %%% SI Units
SI_s, SI_minute, SI_hr, SI_day = 1., 60., 60.*60, 24*60.*60
SI_g, SI_kg = 1.e-3, 1.
SI_mm, SI_cm, SI_m, SI_km = 1e-3, 1e-2, 1.0, 1e3
SI_Pa, SI_kPa, SI_MPa, SI_GPa = 1.0, 1.e3, 1.e6, 1.e9
SI_micro, SI_milli, SI_centi, SI_kilo, SI_mega = 1e-6, 1e-3, 1e-2, 1e3, 1e6
poise = 0.1*SI_Pa*SI_s
Darcy = 9.869233e-13*SI_m**2
# %% Experiment Setup
# The `test_run` option allows to run the whole model with a small amount of epochs to test the workflow
# test_run=True
test_run=False
experiment_FlowPINN = experiment_setup(delay=0.1)
experiment_param_GT_dataset = experiment_FlowPINN.add_param(["ogs_output_a_1e0","ogs_output_a_5e0"],
# fixed_var=1,
default_var=1,
name="Name Ground Truth Dataset")
load_weights_kd = experiment_FlowPINN.add_param([False,True],
fixed_var = 0,
# fixed_var = 1,
default_var=0,
name="Load weights for kd?")
load_weights_pd_pinn = experiment_FlowPINN.add_param([False,True],
fixed_var = 0,
# fixed_var = 1,
default_var=0,
name="Load weights for pd_pinn?")
if test_run==True:
experiment_param_epochs_kd = experiment_FlowPINN.add_param([10,50,100,200],
fixed_var=2,
default_var=0,
name="Number Epochs Training kd")
experiment_param_epochs_pd_pinn = experiment_FlowPINN.add_param([10,15,30,50,100],
# fixed_var = 0,
fixed_var = 4,
# fixed_var = 3,
name="Number Epochs pd(xd) for test run")
else:
experiment_param_epochs_kd = experiment_FlowPINN.add_param([100,300,500],
fixed_var=1,
default_var=0,
name="Number Epochs Training kd")
experiment_param_epochs_pd_pinn = experiment_FlowPINN.add_param([500,1000,2000,3000,],
# fixed_var = 0,
default_var=0,
name="Number Epochs pd")
experiment_param_pd_pinn_retraining = experiment_FlowPINN.add_param([False,True],
# fixed_var = 1,
default_var=0,
name="Perform retraining for too high loss values?")
if experiment_param_pd_pinn_retraining==True:
experiment_param_epochs_pd_pinn_retraining_treshold = experiment_FlowPINN.add_param([1e-3,8e-4,5e-4,1e-4],
fixed_var = 3,
default_var=3,
doc="This threshold value decides if the PINN needs to be retrained with more epochs.",
name="Error Treshold for Retraining PINN")
else: experiment_param_epochs_pd_pinn_retraining_treshold=0.0001
experiment_param_pd_serial_iterx = experiment_FlowPINN.add_param([1,20],
doc="Through how many retraining iterations should the PINN go?",
default_var=0,
name="Number of Iterations")
experiment_param_nr_observation_points = experiment_FlowPINN.add_param([25,10,4,0],
default_var=0,
name="Nr observation points")
experiment_param_sigma_noise = experiment_FlowPINN.add_param([0,0.01,0.02,0.03,0.04,0.1],
# fixed_var = 0,
default_var=0,
name="Standard Deviation of the Gaussian Noise")
experiment_param_pinn_obs = experiment_FlowPINN.add_param([False,True],
doc="This should be set 'True' for Experiment Nr1 and 'False' for Experiment Nr2",
default_var=0,
name="PINN with observation loss term?")
experiment_param_learning_rate_pd_VALUES = experiment_FlowPINN.add_param([
[1e-3, 1e-5],
[1e-4, 1e-6],
],
fixed_var = 0,
default_var=0,
name="Learning Rate values")
experiment_param_learning_rate_pd_method = experiment_FlowPINN.add_param(["constant","linear","step","ExponentialDecay"],
fixed_var = 2,
default_var=3,
name="Learning Rate method")
experiment_param_adaptive_weights = experiment_FlowPINN.add_param([
None,
{'method': 'GN', 'freq': 20, 'use_score': True, 'alpha': 2.0},
{'method': 'NTK', 'freq': 20, 'use_score': True},
{'method': 'GP', 'freq': 20, 'use_score': True},
{'method': 'GP', 'freq': 300, 'use_score': True},
{'method': "inversedirischlet", 'freq': 500, 'use_score': True},
{'method': "self_adaptive_sample_weight", 'freq': 4, 'use_score': True},
],
fixed_var = 0,
# fixed_var = 2,
# fixed_var = 4,
default_var=4,
name="Adaptive Weighting")
experiment_param_safe_figs = experiment_FlowPINN.add_param([False,True],
fixed_var=1,
default_var=0,
name="Safe Plots as PNG?")
experiment_param_create_gif = experiment_FlowPINN.add_param([False,True],
# fixed_var=0,
fixed_var=1,
default_var=0,
name="Create GIF of PNG?")
experiment_FlowPINN.print_summary()
experiment_FlowPINN.abort_if_x()
# %%% Paths to Save and Load Models
# We create for each model a path where it can be saved
save_model = save_models()
model_path_save = save_model.get_path()
experiment_FlowPINN.save_experiment_params(model_path_save)
experiment_FlowPINN.save_to_text(model_path_save)
# load_weights_pd_dat = True
load_weights_pd_dat = False
model_path_load_pd_dat ="saved_models/{}".format("")
model_path_load_kd ="saved_models/{}".format("")
model_path_load_pd_pinn ="saved_models/{}".format("")
# %% Classes and Functions
def equiv_frac_perm(b,a,km):
"""
Scalar formulation of the equivalent fracture permeability
b ... Type: FLOAT
Fracture width in [m]
a ... Type: FLOAT
Mean fracture distance in [m]. This should ne
km ... Type: Float
Matrix permeability
"""
return km + b/a * (b**2/12 - km)
def Gaussian_permeability(k_max,k_min,b_1,x_k,mu,si):
"""
Representation of an equivalent fracture via a Gaussian distribution
b_1 ... width of the equivalent fracture
si ... standard deviation
"""
m = (k_max-k_min)*b_1
return m * 1/(si*np.sqrt(2*np.pi))*np.exp(-0.5*((x_k-mu)/si)**2)+k_min
class DataGenerator_p_xt:
def __init__(self,
X=[0,1],
T=[0,1],
nr_obs_space=100,
nr_obs_time=100,
logT=False,
si_noise=0.1,
dataset_type=None,
load_weights_pd_dat=False
):
self.dataset_type = dataset_type
self.nr_obs_time=nr_obs_time
# =============================================================================
# Observation points over space and time
# =============================================================================
np.random.seed(int(time.time()))
# Random timesteps for each each well
if nr_obs_space<5:self.x = np.concatenate((np.array([X[0]]),np.array([X[1]*0.57]),np.array([X[1]*0.86]),np.array([X[1]])))
else: self.x = np.concatenate((np.array([X[0]]),np.array([X[1]*0.57]),np.array([X[1]*0.86]),np.array([X[1]]),np.random.uniform(xd_min,xd_max,nr_obs_space-3)))
x_stacked = np.meshgrid(self.x,np.ones(nr_obs_time))[0].flatten()
self.t_stacked = np_growing_steps(T[0],T[1],len(x_stacked),plot=False)
# We create normally distributed noise with mu=0 and si=VARIABLE
self.noise = np.random.normal(0,si_noise,len(self.x))
# Set noise for injection point zero:
self.noise[0] = 0
self.noise_stacked = np.meshgrid(self.noise,np.ones(nr_obs_time))[0].flatten()
self.x_stacked = np.meshgrid(self.x,np.ones(nr_obs_time))[0].flatten()
self.inputs = [self.x_stacked.reshape(-1,1),self.t_stacked.reshape(-1,1)]
self.targets = [(np.arange(len(self.x_stacked)),np.zeros(len(self.x_stacked)))]
def get_data(self):
return self.inputs, self.targets
def get_obs_x(self):
return self.x
def plot_obs(self):
plt.scatter(self.x_stacked,self.t_stacked,s=10)
plt.xlabel(r"$\bar{x}$")
plt.ylabel(r"$\bar{t}$")
plt.xlim(np.min(self.x_stacked),np.max(self.x_stacked))
plt.ylim(np.min(self.t_stacked),np.max(self.t_stacked))
plt.title(r"Observation Points for $p(\bar{x},\bar{t})$")
plt.grid()
plt.show()
class DataGenerator_DataDriven_kd:
def __init__(self,
X=[0,1],
T=[0,1],
nr_CP=100,
logT=False,
focus_frac=False,
):
if focus_frac==True:
x = np.clip(np.random.normal(0.5,0.2*dict_equiv_frac_params["a"],int(0.5*nr_CP)),X[0],X[1])
self.x = np.concatenate((x,np.random.uniform(xd_min,xd_max,int(nr_CP-len(x)))))
else: self.x =np.random.uniform(xd_min,xd_max,int(nr_CP))
self.t = np.random.uniform(td_min,td_max,int(nr_CP))
# x_stacked,t_stacked = np.meshgrid(self.x,self.t)
# x_stacked,t_stacked = x_stacked.reshape(-1,1),t_stacked.reshape(-1,1)
self.inputs = [self.x.reshape(-1,1),self.t.reshape(-1,1)]
self.targets = [(np.arange(len(self.x)),np.zeros(len(self.x)))]
def get_data(self,dims="xt"):
if dims=="xt": return self.inputs, self.targets
elif dims=="x": return [self.inputs[0]], self.targets
else: raise ValueError("Please insert either 'xt' or 'x'")
def get_obs_x(self):
return self.x
class Data_Driven_ANN:
def __init__(self,nr_obs_wells=100,si_noise=0):
self.nr_obs_wells = nr_obs_wells
DTYPE = 'float32'
xd_dat = sn.Variable('xd', dtype=DTYPE)
td_dat = sn.Variable('td', dtype=DTYPE)
self.pd = sn.Functional('pd', [xd_dat,td_dat],4*[100], "tanh",output_activation="softplus")
# The Data-Driven Model has just one loss term
self.mod_pd_ANN = sn.SciModel([xd_dat,td_dat],[self.pd], optimizer="adam",loss_func="mse")
def train(self,inputs,targets,val=None,
test_run=False,epochs=200,path_load=None,path_save=None):
self.inputs = inputs
self.targets = targets
batch_size = int(len(self.inputs[0])*epochs/50e3)
if test_run==True:
epochs = 20
batch_size = 64
if isinstance(path_load,str):
self.mod_pd_ANN.load_weights("{}/weights_pd_dat".format(path_load))
self.history = pandas.read_csv("{}/loss_hist_pd_dat.csv".format(path_load,index_col=0))
else:
self.Hist_pd_dat = self.mod_pd_ANN.train(self.inputs, self.targets,
epochs=epochs,
learning_rate={"scheduler": "ExponentialDecay",
"initial_learning_rate": 1e-3,
"final_learning_rate": 1e-5,
"decay_epochs": epochs
},
batch_size=batch_size,
# verbose="True",
save_weights={"path":"%s/checkpoints/"%path_save,
"freq":2},
validation_data=val
)
self.history = self.Hist_pd_dat.history
self.pd.set_trainable(False)
self.mod_pd_ANN.compile()
if isinstance(path_save,str):
self.mod_pd_ANN.save_weights("%s/weights_pd_dat"%(path_save))
pandas.DataFrame(data=self.history).to_csv("%s/loss_hist_pd_dat.csv"%path_save)
def get_pd(self):
return self.pd
def get_SciMod(self):
return self.mod_pd_ANN
def get_hist(self):
return self.Hist_pd_dat
def plot_training(self,gif_duration=500):
dir_list = os.listdir("%s/checkpoints/"%model_path_save)
dir_list.sort()
t_plot = datetime.now().strftime("%Y%m%d_%H%M%S")
for wei in range(len(dir_list)-2):
print(dir_list[wei])
self.mod_pd_ANN.load_weights("%s/checkpoints/%s"%(model_path_save,dir_list[wei]))
self.mod_pd_ANN.compile()
fig, ax1 = plt.subplots(1,1,
# figsize=(10,7)
)
x_test = np.linspace(0,25)
ax1.set_title("Epoch = {}".format(dir_list[wei][1:6]))
for t_test_i in range(len(t_test_p)):
# Prediction
ax1.plot(x_test/x_c, self.pd.eval([x_test/x_c,np.full(x_test.shape,t_test_p[t_test_i]/t_c)]),color=my_cmap["pred"],label="Prediction",
zorder=3,linestyle="dashed",linewidth=3)
# GT
dataset = GT_OGS[["x","p"]].loc[GT_OGS["t"]==t_test_p[t_test_i]].sort_values(by=["x"])
ax1.plot(dataset["x"]/x_c,dataset["p"]/p_c,color=my_cmap["GT"],zorder=2,label="Ground Truth",linewidth=3)
# Training Data Points
ax1.scatter(self.dg_p_dat.get_obs_x(),
griddata(dataset["x"].values/x_c,dataset["p"].values/p_c,self.dg_p_dat.get_obs_x()).flatten(),
s=20,color="yellow",ec="black",alpha=1,zorder=5,label="Training Points")
if t_test_i==0: ax1.legend()
# =============================================================================
# Annotate Timesteps
# =============================================================================
step_index = 50+int(t_test_i*len(dataset["x"])/(len(t_test_p)))
# step_index = 1+int(t_test_i)*4
ax1.grid()
ax1.set_xlabel("xd")
ax1.set_ylabel("pd")
ax1.set_ylim(0,1)
if os.path.exists(model_path_save+"/training_figs")==False: os.mkdir(model_path_save+"/training_figs")
if os.path.exists(model_path_save+"/training_figs/%s"%t_plot)==False: os.mkdir(model_path_save+"/training_figs/%s"%t_plot)
plt.savefig(model_path_save+"/training_figs/%s/Train_pd_dat_ep_%s.png"%(t_plot,dir_list[wei][1:6]))
plt.close()
from PIL import Image
gif = []
image_path = model_path_save+"/training_figs/%s/"%t_plot
if os.path.exists(image_path+"/gif")==False: os.mkdir(image_path+"/gif")
images = os.listdir(image_path)[2:]
images.sort()
for image in images[:len(images)-1]:
gif.append(Image.open(image_path+image))
gif[0].save('%s/gif/temp_result.gif'%image_path, save_all=True,
optimize=False, append_images=gif[1:],
loop=0, duration=gif_duration)
class log_scale_zero_to_one():
"""
This class performs a log-scaling of a certain dataset.
Parameters:
-----------
x_GT : Is the Ground Truth dataset of the parameter. It is used for calculating the x_min and x_max values.
m : Base for the logarithm
n : vertical shift
"""
def __init__(self,func,x_GT,):
self.x_GT = x_GT
self.func = func
self.x_GT_min = np.min(self.x_GT.flatten())
self.x_GT_max = np.max(self.x_GT.flatten())
self.m = self.x_GT_max/self.x_GT_min
self.n = - np.log(self.x_GT_min)/np.log(self.m)
def get_func_scaled(self):
'''
Returns scaled function
-------
TYPE
DESCRIPTION.
'''
self.func_scaled = sn.log(self.func)/np.log(self.m)+self.n
return self.func_scaled
def scale_data(self,x,plot=False):
self.fx = np.log(x)/np.log(self.m)+self.n
if plot==True:
plt.close()
plt.figure(figsize=(10,7))
plt.hist(x,log=True,bins=100,label="Data Distribution before Scaling",alpha=0.5)
plt.hist(self.fx,log=True,bins=100,label="Data Distribution after Scaling",alpha=0.5)
plt.legend(),plt.grid(), plt.show()
return self.fx
def backscale_data(self,fx):
x = (self.x_GT_max/self.x_GT_min)**fx * self.x_GT_min
return x
def backscale_func(self):
"""
Scales back a SciANN functional.
"""
x = sn.pow(self.x_GT_max/self.x_GT_min,self.func) * self.x_GT_min
return x
# %% Preprocessing
# %%% Load Ground Truth
GT_OGS = pandas.read_csv("01_data/{}.csv".format(experiment_param_GT_dataset),index_col=0)
t_start_filter = 1000 #s #If the first few seconds have a convergence performance, we filter these values
GT_OGS = GT_OGS.loc[GT_OGS["t"]>t_start_filter]
# =============================================================================
# Assign Material Properties of Factures to Dictionary
# =============================================================================
frac_matrix = np.array([
# File name a start_si final_si timesteps
["ogs_output_a_1e0", 1e0 , 0.8, 0.15, "[10,18,25,27,30]"],
["ogs_output_a_5e0", 5e0 , 0.2, 0.2, "[2,9,15,28]"],
])
frac_idx = list(frac_matrix[:,0]).index(experiment_param_GT_dataset)
dict_equiv_frac_params = {"k_m":1e-18,"a":float(frac_matrix[frac_idx,1]) ,"b":10e-6,
"si_start":float(frac_matrix[frac_idx,2]),
"si_final":float(frac_matrix[frac_idx,3]),
"ts":list(ast.literal_eval(frac_matrix[frac_idx,4])),
}
if dict_equiv_frac_params["si_final"] == dict_equiv_frac_params["si_start"]:sigma_k_reduction=[dict_equiv_frac_params["si_final"]]
else:
sigma_k_reduction = np_growing_steps(dict_equiv_frac_params["si_final"],dict_equiv_frac_params["si_start"],
experiment_param_pd_serial_iterx,power=1.5,flip_order=True,plot=True)
GT_OGS_t = pandas.DataFrame(data={"t":np.sort(GT_OGS["t"].unique())})
t_test_p = GT_OGS_t.values.flatten()[dict_equiv_frac_params["ts"]]
GT_OGS_x = np.sort(GT_OGS["x"].unique())
GT_OGS_y = np.sort(GT_OGS["y"].unique())
GT_OGS_k = GT_OGS[["x","k"]].loc[(GT_OGS["t"]==GT_OGS_t.iloc[1].values[0])&(GT_OGS["y"]==GT_OGS_y[0])].sort_values(by=["x"])
# %%%% Plot Ground Truth
plt.close()
fig, ax1 = plt.subplots(1)
for i in range(len(GT_OGS_t)):
timestep = list(GT_OGS_t.iloc[i].values)[0]
dataset_GT_plot = GT_OGS[["x","p"]].loc[GT_OGS["t"]==timestep].sort_values(by=["x"])
if timestep in list(t_test_p):
color="red"
else: color=my_cmap["GT"]
ax1.plot(dataset_GT_plot["x"],dataset_GT_plot["p"],color=color,label="Selected timesteps for Visualization" if timestep==t_test_p[0] else None
)
step_index = 1+int(i*len(dataset_GT_plot["x"])/(len(GT_OGS_t)-1)*0.7)
ax1.annotate(r"$\bar{t}=%.2e\,$"%(GT_OGS_t.values[i]),
xy = (dataset_GT_plot["x"].iloc[step_index],dataset_GT_plot["p"].iloc[step_index]),
xytext = (0.5,0),
textcoords='offset points',
bbox={"boxstyle":"round", "fc":"w","ec":"teal"},
horizontalalignment='center',fontsize=10,zorder=6,
)
ax1.legend(loc="upper right")
ax2 = ax1.twinx()
ax2.plot(GT_OGS_k["x"],GT_OGS_k["k"]/max(GT_OGS_k["k"]),linewidth=3,label=r"$k(x)$",color="gray",linestyle="dashed")
ax2.legend(loc="upper center")
ax1.grid()
ax1.set_zorder(ax2.get_zorder() - 1)
ax1.set_ylabel("P /Pa")
ax1.set_xlabel("x /m")
plt.savefig("{}/Fig_01_Groundtruth_dataset.png".format(model_path_save),dpi=300)
plt.show()
# %%%% Equivalent Gaussian Permeability Distribution
x = np.linspace(0,1,1000)
k_min = min(GT_OGS_k["k"].values)
# k_max = max(GT_OGS_k["k"].values)
k_max = equiv_frac_perm(dict_equiv_frac_params["b"],dict_equiv_frac_params["a"],dict_equiv_frac_params["k_m"],)
x_c = max(GT_OGS_x)
a = dict_equiv_frac_params["a"]/x_c
mu = 12.5/x_c
si = dict_equiv_frac_params["si_start"] * a
# =============================================================================
# Assign changed permeability
# =============================================================================
GT_OGS_k_Gauss = pandas.DataFrame(data={'x':GT_OGS_k['x'],
'k': Gaussian_permeability(k_max,k_min,dict_equiv_frac_params["a"],GT_OGS_k['x'],12.5,
dict_equiv_frac_params["si_start"]*dict_equiv_frac_params["a"])
})
plt.close()
plt.figure(figsize=(9,6),tight_layout=True)
plt.plot(GT_OGS_k_Gauss['x'],GT_OGS_k_Gauss['k'],linewidth=3,label=r"Ground Truth Plot",color="black",zorder=3)
plt.plot(x*x_c,Gaussian_permeability(k_max,k_min,a,x,mu,si),linewidth=3,label=r"$k_\mathregular{g}(x)$",color=my_cmap["v"],zorder=3,linestyle="dashed")
# plt.plot([min(x),mu-a/2,mu-a/2,mu+a/2,mu+a/2,max(x)],[k_min,k_min,k_max,k_max,k_min,k_min] ,linewidth=3,label=r"$k(x)$",color=my_cmap["GT"])
plt.plot(GT_OGS_k["x"],GT_OGS_k["k"],linewidth=3,label=r"$k(x)$",color=my_cmap["GT"])
plt.yscale("log")
plt.grid(True, which="both",color="lightgrey")
plt.legend()
plt.savefig("{}/Fig_02_GT_equivalent_permeability.png".format(model_path_save),dpi=300)
plt.show()
# %%% Plot Full Permeability Distribution
# Here we print all disributions of k(x) for each iteration
fig, ax = plt.subplots(figsize=(11,6),tight_layout=False)
ax.plot(GT_OGS_k["x"],GT_OGS_k["k"],linewidth=3,label=r"$k(x)$",color=my_cmap["GT"])
fig.subplots_adjust(left=None, bottom=0, right=30, top=None, wspace=None, hspace=None)
cmap_kx = plt.get_cmap("flare",len(sigma_k_reduction))
for i_sigma_k_reduction in range(len(sigma_k_reduction)):
GT_OGS_k_Gauss_step = pandas.DataFrame(data={'x':GT_OGS_k['x'],
'k': Gaussian_permeability(k_max,k_min,dict_equiv_frac_params["a"],GT_OGS_k['x'],12.5,
sigma_k_reduction[i_sigma_k_reduction]*dict_equiv_frac_params["a"])
})
ax.plot(GT_OGS_k_Gauss_step['x'],GT_OGS_k_Gauss_step['k'],linewidth=1,label=r"$k_\mathregular{g}(x)$",color=cmap_kx(i_sigma_k_reduction),zorder=3)
# plt.plot(x*x_c,Gaussian_permeability(k_max,k_min,a,x,mu,si),linewidth=3,label=r"$k_\mathregular{g}(x)$",color=my_cmap["v"],zorder=3,linestyle="dashed")
if i_sigma_k_reduction==0:plt.legend(fontsize=12)
plt.yscale("log")
plt.xlabel(r"$x$ /m")
plt.ylabel(r"$k(x)$ /m²")
plt.grid(True, which="both",color="lightgrey")
if len(sigma_k_reduction)>1:
# creating ScalarMappable
sm = plt.cm.ScalarMappable(cmap=plt.get_cmap("flare_r",len(sigma_k_reduction)),norm=Normalize(vmin=min(sigma_k_reduction), vmax=max(sigma_k_reduction)))
# cax = plt.axes([1, 0.13, 0.01, 0.8])
cb = plt.colorbar(sm,
#ticks=np.linspace(max(sigma_k_reduction),min(sigma_k_reduction), 9),
label=r"Standard Deviation $\sigma \; /a$",
ax=ax)
plt.savefig("{}/Fig_03_Stepwise Permeability.png".format(model_path_save),dpi=300)
plt.show()
plt.close()
# %%% Physical Parameters
# Domain
Lx = 25 /SI_m
Ly = 1 /SI_m
p_ini= 0 * SI_MPa
p_max = 1*SI_MPa
k_max = np.round(max(GT_OGS_k['k']),18)
k_min = np.round(min(GT_OGS_k['k']),20)
#Material
rho_s = 2690
phi = 0.01
rho_fr_ref_cond = 1e5 #Pa
rho_fr_ref = 998.2 # for P=1e5 and T=20°C=193.15K
k_fr = (rho_fr_ref-1002.7)/((rho_fr_ref_cond)-(10.1e6)) / rho_fr_ref
mu = 1.006e-3 #dyn viscosity
g = 9.81
K_sr = 45e9
biot = 0.2 #determined by Braun (2007)
Ss = (k_fr * phi + (biot-phi) / K_sr)
# %%% Characteristic values
if load_weights_pd_pinn==True or load_weights_kd==True:
experiment_param_dict = pickle.load(open("{}/experiment_param_dict.pkl".format(model_path_load_kd),"rb"))
p_c = experiment_param_dict["p_c"]
k_c = experiment_param_dict["k_c"]
t_c = experiment_param_dict["t_c"]
x_c = experiment_param_dict["x_c"]
v_c = k_c * p_c / mu / x_c
x_end = Lx
x_scaler=x_end/x_c
print("x_end/x_c=",x_scaler)
t_end = Ss * mu / k_min * (Lx**2)
t_scaler = t_end / t_c
print("t_scaler=t_end/t_c=",t_scaler)
experiment_param_dict_file = open("{}/experiment_param_dict.pkl".format(model_path_save),"wb")
else:
experiment_param_dict = {}
experiment_param_dict_file = open("{}/experiment_param_dict.pkl".format(model_path_save),"wb")
p_c = p_max
k_c = max(GT_OGS_k_Gauss["k"])
x_end = Lx
x_c= x_end
x_scaler=x_end/x_c
print("x_end/x_c=",x_scaler)
t_max = max(GT_OGS['t'])
t_c = Ss * mu / k_c * (x_c**2)
t_end = Ss * mu / k_min * (Lx**2)
t_scaler = t_end / t_c
print("t_scaler=t_end/t_c=",t_scaler)
v_c = k_c * p_c / mu / x_c
xd_min, xd_max = 0. , x_end/x_c
yd_min, yd_max = 0. , Ly/x_c
td_min, td_max = 0., t_end/t_c
pd_min,pd_max = 0, p_max / p_c
# Save model parameters
experiment_param_dict["p_c"]=p_c
experiment_param_dict["k_c"]=k_c
experiment_param_dict["t_c"]=t_c
experiment_param_dict["x_c"]=x_c
pickle.dump(experiment_param_dict,experiment_param_dict_file)
experiment_param_dict_file.close()
# %%% Reset SciANN
sn.reset_session()
sn.set_random_seed(124)
# %% Generate Training Data
nr_obs_wells = experiment_param_nr_observation_points
dg_p_dat = DataGenerator_p_xt(X=[xd_min,xd_max], T=[td_min,td_max],nr_obs_space = nr_obs_wells,nr_obs_time=100,logT=False,si_noise=experiment_param_sigma_noise,dataset_type="Training")
dg_input_p, dg_target_p = dg_p_dat.get_data()
dg_p_dat.plot_obs()
dg_p_dat_val = DataGenerator_p_xt(X=[xd_min,xd_max], T=[td_min,td_max],nr_obs_space = nr_obs_wells if nr_obs_wells<5 else int(nr_obs_wells*0.2),
nr_obs_time=int(100*0.2),logT=False,si_noise=experiment_param_sigma_noise,dataset_type="Validation")
dg_input_p_val, dg_target_p_val = dg_p_dat_val.get_data()
# Interpolate targets from Groundtruth dataset
for inp,tar,_class in zip([dg_input_p,dg_input_p_val],
[dg_target_p,dg_target_p_val],
[dg_p_dat,dg_p_dat_val]):
tar[0] = (tar[0][0],griddata(GT_OGS[["x","t"]].values,GT_OGS["p"].values,
np.concatenate((inp[0]*x_c,inp[1]*t_c),axis=1),
method = "linear",fill_value=0.0).flatten()/p_c
)
# add noise
if isinstance(experiment_param_sigma_noise,(float,int)): tar[0] = (tar[0][0],tar[0][1]+_class.noise_stacked)
plt.close()
plt.scatter(dg_input_p[0],dg_target_p[0][1],s=1), plt.xscale("linear"), plt.title("Subsampled target data for Data-Driven NN"), plt.grid(), plt.show()
# %% ANN
# %%% Train ANN
create_dir(model_path_save+"/checkpoints")
pd_ann = Data_Driven_ANN(experiment_param_nr_observation_points,si_noise=experiment_param_sigma_noise)
pd_ann.train(inputs=dg_input_p,targets=dg_target_p,
val=(dg_input_p_val,dg_target_p_val),
epochs=200,
# path_load=model_path_save,
path_save=model_path_save,
test_run=test_run
)
# %%% Plot ANN Result
# history_in_plot=False
history_in_plot=True
if history_in_plot==True:
fig, [ax1,ax2] = plt.subplots(2,1,height_ratios=[3,1],gridspec_kw={"hspace":0.3})
else: fig, ax1 = plt.subplots(1,1,figsize=(6,4),tight_layout=True)
x_test = np.linspace(0,25)
for t_test_i in range(len(t_test_p)):
# Prediction
linewidth = 3
ax1.plot(x_test/x_c, pd_ann.pd.eval([x_test/x_c,np.full(x_test.shape,t_test_p[t_test_i]/t_c)]),color=my_cmap["pred"],label="Prediction",
zorder=3,linestyle="dashed",linewidth=linewidth)
# GT
dataset = GT_OGS[["x","p"]].loc[GT_OGS["t"]==t_test_p[t_test_i]].sort_values(by=["x"])
ax1.plot(dataset["x"]/x_c,dataset["p"]/p_c,color=my_cmap["GT"],zorder=2,label="Ground Truth",linewidth=linewidth)
# Training Data Points
ax1.scatter(dg_p_dat.get_obs_x(),
griddata(dataset["x"].values/x_c,dataset["p"].values/p_c,dg_p_dat.get_obs_x()).flatten()+dg_p_dat.noise,
s=20,color="yellow",ec="black",linewidth=0.7,alpha=1,zorder=5,label="Training Points")
if t_test_i==0: ax1.legend()
# =============================================================================
# Annotate Timesteps
# =============================================================================
step_index = 40+int(t_test_i*len(dataset["x"])/(len(t_test_p)-1)*0.9)
# step_index = 1+int(t_test_i)*4
ax1.annotate(r"$\bar{t}=%.2f\,$"%(t_test_p[t_test_i]/t_c),
xy = (dataset["x"].iloc[step_index]/x_c,dataset["p"].iloc[step_index]/p_c),
# xytext = (0.5,0),
textcoords='offset points',bbox={"boxstyle":"round", "fc":"w","ec":"teal"},
horizontalalignment='center',fontsize=9,zorder=6
)
ax1.grid()
ax1.set_xlabel(r"$\bar{x}$")
ax1.set_ylabel(r"$\bar{p}(\bar{x},\bar{t})$")
ax1.set_ylim(-0.1,1.1)
if history_in_plot==True:
ax2.plot(pd_ann.history["loss"]), ax2.grid(), ax2.set_xlabel("Epochs"), ax2.set_ylabel("Loss"), ax2.set_yscale("log")
if experiment_param_safe_figs==True: plt.savefig("{}/Fig_04_ANN_Regression.png".format(model_path_save),dpi=300)
else:
if experiment_param_safe_figs==True: plt.savefig("{}/Fig_04_ANN_Regression.png".format(model_path_save),dpi=300)
# %% PINN
# %%% NN Setup
#dimensionless variables
xd = sn.Variable('x')
yd = sn.Variable('y')
td = sn.Variable('t')
kd = sn.Functional('k', [xd/x_scaler,td/t_scaler], 4*[20], "tanh", output_activation="softplus", res_net=True)
kd_scaler = log_scale_zero_to_one(kd,GT_OGS_k["k"].values/k_c)
kd_pde = kd_scaler.backscale_func()
mod_kd = sn.SciModel([xd,td],[kd], optimizer="adam",loss_func="mse")
pd_pinn = sn.Functional('p', [xd/x_scaler,td/t_scaler], 4*[100], "tanh", output_activation="softplus", res_net=True)
# %% Iteration
for iteration_nr in range(experiment_param_pd_serial_iterx):
print(iteration_nr)
kd_GT_sigma = sigma_k_reduction[iteration_nr]
if iteration_nr>0:
# dict_equiv_frac_params["si_start"] = 0.6*dict_equiv_frac_params["si_start"]
x = np.linspace(0,1,1000)
k_min = min(GT_OGS_k["k"].values)
# k_max = max(GT_OGS_k["k"].values)
k_max = equiv_frac_perm(dict_equiv_frac_params["b"],dict_equiv_frac_params["a"],dict_equiv_frac_params["k_m"],)
x_c = max(GT_OGS_x)
a = dict_equiv_frac_params["a"]/x_c
mu = 12.5/x_c
si = kd_GT_sigma * a
# =============================================================================
# Assign changed permeability
# =============================================================================
GT_OGS_k_Gauss = pandas.DataFrame(data={'x':GT_OGS_k['x'],
'k': Gaussian_permeability(k_max,k_min,dict_equiv_frac_params["a"],GT_OGS_k['x'],12.5,kd_GT_sigma*dict_equiv_frac_params["a"])
})
plt.figure(figsize=(9,6),tight_layout=True)
plt.plot(GT_OGS_k_Gauss['x']/x_c,GT_OGS_k_Gauss['k'],linewidth=3,label=r"Ground Truth Plot",color="black",zorder=3)
plt.plot(x,Gaussian_permeability(k_max,k_min,a,x,mu,si),linewidth=3,label=r"$k_\mathregular{g}(x)$",color=my_cmap["v"],zorder=3,linestyle="dashed")
plt.plot(GT_OGS_k["x"]/x_c,GT_OGS_k["k"],linewidth=3,label=r"$k(x)$",color=my_cmap["GT"])
plt.yscale("log")
plt.grid(True, which="both",color="lightgrey")
plt.legend()
plt.savefig("{}/Fig_05_{:2d}_plot_GT_equivalent_permeability.png".format(model_path_save,iteration_nr),dpi=300)
# %%% Train kd
Nr_CP_kd = 6400
data_k_x = DataGenerator_DataDriven_kd(X=[xd_min,xd_max],nr_CP = Nr_CP_kd,focus_frac=True)
dg_input_data_k_x, dg_target_data_k_x = data_k_x.get_data(dims="xt")
data_k_x_val = DataGenerator_DataDriven_kd(X=[xd_min,xd_max],nr_CP = Nr_CP_kd*0.2,focus_frac=True)
dg_input_data_k_x_val, dg_target_data_k_x_val = data_k_x_val.get_data(dims="xt")
# Interpolate data from groundtruth
for inp,tar in zip([dg_input_data_k_x,dg_input_data_k_x_val],
[dg_target_data_k_x,dg_target_data_k_x_val]):
p_interpolation = kd_scaler.scale_data(griddata(GT_OGS_k_Gauss["x"].values,GT_OGS_k_Gauss["k"].values,inp[0]*x_c,
method = "linear",fill_value=0.0).flatten()/k_c,plot=True)
tar[0] = (tar[0][0],p_interpolation)
plt.scatter(GT_OGS_k_Gauss["x"].values/x_c,GT_OGS_k_Gauss["k"].values/(k_c),s=1)
plt.scatter(dg_input_data_k_x[0],dg_target_data_k_x[0][1],s=1,alpha=0.5)
plt.show(),plt.close()
plt.hist(dg_input_data_k_x[0],bins=50), plt.show(), plt.close()
plt.hist(dg_target_data_k_x[0][1],bins=50), plt.show(), plt.close()
epochs_kd = experiment_param_epochs_kd
batch_size_kd = int(len(dg_input_data_k_x[0])*epochs_kd/50e3)
if iteration_nr>0: epochs_kd=int(epochs_kd/5)
if test_run ==True: batch_size_kd= 640
# =============================================================================
# Train
# =============================================================================
learning_rate_kd = stepwise_learning_rate(1e-3,1e-5,epochs_kd/int(10),epochs_kd)
# learning_rate_kd = {"scheduler": "ExponentialDecay","initial_learning_rate": 1e-3,"final_learning_rate": 1e-5,"decay_epochs": epochs_kd}
if load_weights_kd==True and iteration_nr==0:
mod_kd.load_weights("{}/weights_kd".format(model_path_load_kd))
loss_kd=pandas.read_csv("%s/loss_hist_kd.csv"%model_path_load_kd,index_col=0)
else:
kd.set_trainable(True)
mod_kd.compile()
Hist_kd = mod_kd.train(dg_input_data_k_x, dg_target_data_k_x,
epochs=epochs_kd,
learning_rate=learning_rate_kd,
batch_size=batch_size_kd,
# verbose="True",
validation_data=(dg_input_data_k_x_val, dg_target_data_k_x_val)
)
mod_kd.save_weights("%s/weights_kd"%(model_path_save))
pandas.DataFrame(data=Hist_kd.history).to_csv("%s/loss_hist_kd.csv"%model_path_save)
kd.set_trainable(False)
mod_kd.compile()
# %%%% Eval kd
# =============================================================================
# Plots
# =============================================================================
switch_plot_history=True
if switch_plot_history==True:
fig, [ax1,ax2] = plt.subplots(2,1,height_ratios=[3,1],gridspec_kw={"hspace":0.3})
else: fig, ax1 = plt.subplots(figsize=(12,6),tight_layout=True)
x_test = np.linspace(0,25,2000)
t_test = np.full(x_test.shape,0.5)
#Original
mu_frac = 12.5/x_c
a_frac = dict_equiv_frac_params["a"]/x_c
k_max_frac = equiv_frac_perm(dict_equiv_frac_params["b"],dict_equiv_frac_params["a"],dict_equiv_frac_params["k_m"])
k_min_frac =dict_equiv_frac_params["k_m"]
ax1.plot(GT_OGS_k["x"]/x_c,
GT_OGS_k["k"]/k_c ,
linewidth=3,label=r"$k(x)$",color=my_cmap["CP"],zorder=2)
# GT
ax1.plot(GT_OGS_k_Gauss["x"]/x_c,GT_OGS_k_Gauss["k"]/k_c,color=my_cmap["GT"],zorder=3,label=r"$k_\mathregular{g}(x)$",
linewidth=3)
# Prediction
ax1.plot(x_test/x_c, kd_pde.eval(mod_kd,[x_test/x_c,t_test]),color=my_cmap["pred"],label=r"$\hat{k}_\mathregular{g}(x)$ ANN",
zorder=3,linestyle="dashed",linewidth=4)
ax1.legend(fontsize="large")
ax1.grid()
ax1.set_yscale("log")
if switch_plot_history==True and load_weights_kd==False:
ax2.plot(Hist_kd.history["loss"])
# ax2.grid()
ax2.legend()
ax2.set_xlabel("Epochs")
ax2.set_ylabel("Loss")
ax2.set_yscale("log")
plt.grid(True, which="both",color="lightgrey",zorder=-1)
plt.savefig("{}/Fig_05_kd_trained.png".format(model_path_save),dpi=300)
# %%% Train pd
pd_xd, pd_xdxd =sn.diff(pd_pinn,xd), sn.diff(pd_pinn,xd,order=2)
L1 = sn.rename(( sn.diff(pd_pinn,td) - (sn.diff(kd_pde,xd) * pd_xd + kd_pde* pd_xdxd)),"PDE")
targets_p_xt_table = np.array([
# 1. Loss Term | 2. Weight | 3. Domain Section | 4. Loss Metric |
# =============================================================================
# Domain Constraints
# =============================================================================
[L1, 1, "domain", "mse", "PDE" , "pde" ],
[sn.rename(1*(pd_pinn),"BC_p_xmax") , 1, "bc-left", "mse", "BC_p_xmax" , "bco" ],
[sn.rename(1*(pd_pinn),"BC_p_xmin") , 1, 'bc-right', "mse", "BC_p_xmin" , "bci" ],
[sn.rename(1*(pd_pinn),"IC_p_tmin") , 1, 'ic', "mse", "IC_p_tmin" , "ic" ],
# =============================================================================
])
if experiment_param_pinn_obs==True:
targets_p_xt_table = np.concatenate((targets_p_xt_table,
np.array([[sn.rename(1*(pd_pinn),"data_p"), 1, 'domain', "mse", "data_p" , "o"]])
))
# %%%% Generate Data
# Nr_CP = int(6400*3)
Nr_CP = 6400*2
if experiment_param_pinn_obs==True:
Nr_CP = int(6400*3)
data_p_xt = DataGeneratorXT(X=[xd_min,xd_max], T=[td_min,td_max],num_sample = Nr_CP,targets=targets_p_xt_table[:,2],logT=False)
data_p_xt.plot_data(name="Training_Data")
dg_input_data_p_xt, dg_target_data_p_xt = data_p_xt.get_data()
data_p_xt_val = DataGeneratorXT(X=[xd_min,xd_max], T=[td_min,td_max],num_sample = Nr_CP*0.2,targets=targets_p_xt_table[:,2],logT=False)
data_p_xt_val.plot_data(name="Validation_Data")
dg_input_data_p_xt_val, dg_target_data_p_xt_val = data_p_xt_val.get_data()
# Assign PDE targets
dg_target_data_p_xt[0] = (dg_target_data_p_xt[0][0],np.zeros(len(dg_target_data_p_xt[0][0])))
dg_target_data_p_xt_val[0] = (dg_target_data_p_xt_val[0][0],np.zeros(len(dg_target_data_p_xt_val[0][0]),dtype=np.float64))
# Assign Pressure BC and IC
target_nr = 1
target_BC_p_x_min = assign_targets_to_input_dim(dg_input_data_p_xt[1],target=dg_target_data_p_xt[target_nr],
input_GT=GT_OGS["t"].loc[(GT_OGS['x']==0.0)].values/t_c,
target_GT=GT_OGS["p"].loc[(GT_OGS['x']==0.0)].values/p_c,
# log=True,base=td_max+1,
)
dg_target_data_p_xt[target_nr] = (target_BC_p_x_min.replace_targets())
target_BC_p_x_min_val = assign_targets_to_input_dim(dg_input_data_p_xt_val[1],target=dg_target_data_p_xt_val[target_nr],
input_GT=GT_OGS["t"].loc[(GT_OGS['x']==0.0)].values/t_c,
target_GT=GT_OGS["p"].loc[(GT_OGS['x']==0.0)].values/p_c,
# log=True,base=td_max+1
)
dg_target_data_p_xt_val[target_nr] = (target_BC_p_x_min_val.replace_targets())
# =============================================================================
# Assign Observation points
# We use the same training data-points that we used for the Data-driven Neural Network
# =============================================================================
if "data_p" in list(targets_p_xt_table[:,4]):
target_nr = list(targets_p_xt_table[:,4]).index("data_p")
dg_input_data_p_xt = [
np.concatenate((dg_input_data_p_xt[0],dg_input_p[0])),
np.concatenate((dg_input_data_p_xt[1],dg_input_p[1])),
]
dg_target_data_p_xt[target_nr]=(dg_target_p[0][0]+Nr_CP,dg_target_p[0][1])
dg_input_data_p_xt_val = [
np.concatenate((dg_input_data_p_xt_val[0],dg_input_p_val[0])),
np.concatenate((dg_input_data_p_xt_val[1],dg_input_p_val[1])),
]
dg_target_data_p_xt_val[target_nr] = (dg_target_p_val[0][0]+int(Nr_CP*0.2),dg_target_p_val[0][1])
# Sample Weights
sample_weights_pd_pinn = np.full(dg_input_data_p_xt[0].shape,1.)
# %%%% Train pd pinn
hist_dict_pd_pinn = {"loss":np.array([1])}
repetion_pd_pinn = 0
# we repeat the training if the loss value did not reach below a certain value
while hist_dict_pd_pinn["loss"][len(hist_dict_pd_pinn["loss"])-1] > experiment_param_epochs_pd_pinn_retraining_treshold:
print("check")
mod_pd_pinn = sn.SciModel([xd,td],list(targets_p_xt_table[:,0]), optimizer="adam",loss_func=list(targets_p_xt_table[:,3]))
pd_pinn.set_trainable(True)
epochs_pd_pinn = experiment_param_epochs_pd_pinn
batch_size_pd_pinn= int(len(dg_input_data_p_xt[0])*epochs_pd_pinn/50e3)