-
Notifications
You must be signed in to change notification settings - Fork 0
/
Eclipse_Surrogate_History_Matching.py
1612 lines (1240 loc) · 51.7 KB
/
Eclipse_Surrogate_History_Matching.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
# -*- coding: utf-8 -*-
"""
Created on Tuesday November 05 12:05:47 2019
@author: Dr Clement Etienam
@External Collaborator: Dr Rossmary Villegas
@External Colaborator: Dr Oliver dorn
This code is for Ensemble Surrogate reservoir history matching
We also check the fidelity of our surrogate and use the surrogate in a gradeint
history matching approach
Size of reservoir data set is 84*27*4
"""
from __future__ import print_function
print(__doc__)
print('A NOVEL ENSEMBLE BASED HISTORY MATCHING WITH A DEEP LEARNING SURROGATE')
print('.........................IMPORT SOME LIBRARIES.....................')
from numpy import *
import numpy as np
import shutil
import os
import time
import matplotlib.pyplot as plt
import scipy.io as sio
from scipy import interpolate
from scipy.stats import rankdata, norm
from sklearn.preprocessing import MinMaxScaler
import os; os.environ['KERAS_BACKEND'] = 'tensorflow'
import keras
from keras.callbacks import EarlyStopping
from keras.layers import Dense
from keras.models import Sequential
import scipy.io
from joblib import Parallel, delayed
import scipy.ndimage.morphology as spndmo
import datetime
from collections import OrderedDict
import multiprocessing
from multiprocessing import Pool
from keras.models import load_model
import os
print('')
print('-----------DEFINE SOME FUNCTIONS------------------------------------------')
## This section is to prevent Windows from sleeping when executing the Python script
class WindowsInhibitor:
'''Prevent OS sleep/hibernate in windows; code from:
https://github.com/h3llrais3r/Deluge-PreventSuspendPlus/blob/master/preventsuspendplus/core.py
API documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx'''
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
def __init__(self):
pass
def inhibit(self):
import ctypes
#Preventing Windows from going to sleep
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS | \
WindowsInhibitor.ES_SYSTEM_REQUIRED)
def uninhibit(self):
import ctypes
#Allowing Windows to go to sleep
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS)
osSleep = None
# in Windows, prevent the OS from sleeping while we run
if os.name == 'nt':
osSleep = WindowsInhibitor()
osSleep.inhibit()
##------------------------------------------------------------------------------------
def interpolatebetween(xtrain,cdftrain,xnew):
numrows1=len(xnew)
numcols = len(xnew[0])
norm_cdftest2=np.zeros((numrows1,numcols))
for i in range(numcols):
a=xtrain[:,i]
b=cdftrain[:,i]
f = interpolate.interp1d(a, cdftrain[:,i],kind='linear',fill_value=(b.min(), b.max()),bounds_error=False)
#f = interpolate.interp1d((xtrain[:,i]), cdftrain[:,i],kind='linear')
cdftest = f(xnew[:,i])
norm_cdftest2[:,i]=np.ravel(cdftest)
return norm_cdftest2
def gaussianizeit(input1):
numrows1=len(input1)
numcols = len(input1[0])
newbig=np.zeros((numrows1,numcols))
for i in range(numcols):
input11=input1[:,i]
newX = norm.ppf(rankdata(input11)/(len(input11) + 1))
newbig[:,i]=newX.T
return newbig
"""
def read_ecl(filename=None):
out = struct
if not exist(mstring('filename'), mstring('var')):
error(mcat([mstring('\''), filename, mstring('\' does not exist')]))
end
# Open file
fclose(mstring('all'))
fid = fopen(filename)
if fid < 3:
error
mstring('Error while opening file')
end
# Skip header
fread(fid, 1, mstring('int32=>double'), 0, mstring('b'))
# Read one property at the time
i = 0
while not feof(fid):
i = i + 1
# Read field name (keyword) and array size
keyword = deblank(fread(fid, 8, mstring('uint8=>char')).cT)
keyword = strrep(keyword, mstring('+'), mstring('_'))
num = fread(fid, 1, mstring('int32=>double'), 0, mstring('b'))
# Read and interpret data type
dtype = fread(fid, 4, mstring('uint8=>char')).cT
__switch_0__ = dtype
if 0:
pass
elif __switch_0__ == mstring('INTE'):
conv = mstring('int32=>double')
wsize = 4
elif __switch_0__ == mstring('REAL'):
conv = mstring('single=>double')
wsize = 4
elif __switch_0__ == mstring('DOUB'):
conv = mstring('double')
wsize = 8
elif __switch_0__ == mstring('LOGI'):
conv = mstring('int32')
wsize = 4
elif __switch_0__ == mstring('CHAR'):
conv = mstring('uint8=>char')
num = num * 8
wsize = 1
end
# Skip next word
fread(fid, 1, mstring('int32=>double'), 0, mstring('b'))
# Read data array, which may be split into several consecutive
# arrays
data = mcat([])
remnum = num
while remnum > 0:
# Read array size
buflen = fread(fid, 1, mstring('int32=>double'), 0, mstring('b'))
bufnum = buflen / wsize
# Read data and append to array
data = mcat([data, OMPCSEMI, fread(fid, bufnum, conv, 0, mstring('b'))]) ##ok<AGROW>
# Skip next word and reduce counter
fread(fid, 1, mstring('int32=>double'), 0, mstring('b'))
remnum = remnum - bufnum
end
# Special post-processing of the LOGI and CHAR datatypes
__switch_1__ = dtype
if 0:
pass
elif __switch_1__ == mstring('LOGI'):
data = logical(data)
elif __switch_1__ == mstring('CHAR'):
data = reshape(data, 8, mcat([])).cT
end
# Add array to struct. If keyword already exists, append data.
if isfield(out, keyword):
else:
data
end
# Skip next word
fread(fid, 1, mstring('int32=>double'), 0, mstring('b'))
end
fclose(fid)
end
"""
def pinvmat(A,tol = 0):
V,S1,U = np.linalg.svd(A,full_matrices=0)
# Calculate the default value for tolerance if no tolerance is specified
if tol == 0:
tol = np.amax((A.size)*np.spacing(np.linalg.norm(S1,np.inf)))
r1 = sum(S1 > tol)+1
v = V[:,:r1-1]
U1 = U.T
u = U1[:,:r1-1]
S11 = S1[:r1-1]
s = S11[:]
S = 1/s[:]
X = (u*S.T).dot(v.T)
return (V,X,U)
def plot_history(history):
loss = history.history['loss']
val_loss = history.history['val_loss']
x = range(1, len(loss) + 1)
plt.figure(figsize=(7, 7))
plt.plot(x, loss, 'b', label='Training loss')
plt.plot(x, val_loss, 'r', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
def prepare_grid(nx,ny,nz,perm,poro,pressure,saturation,pre2,sat2):
xc = np.linspace(1., nx, nx)
yc = np.linspace(1., ny, ny)
zc = np.linspace(1., nz, nz)
xq, yq, zq = np.meshgrid(xc, yc, zc, indexing='ij')
assert np.all(xq[:,0,0] == xc)
assert np.all(yq[0,:,0] == yc)
assert np.all(zq[0,0,:] == zc)
xq=np.reshape(xq,(-1,1),'F')
yq=np.reshape(yq,(-1,1),'F')
zqall=np.zeros((nx*ny,4))
for i in range(nz):
zqall[:,i]=np.ravel(np.reshape(zq[:,:,i],(-1,1),'F'))
zyes = np.array([])
for i in range(nz):
zyes = np.append(zyes, zqall[:,i],axis=0)
zyes=np.reshape(zyes,(-1,1),'F')
# temp=np.concatenate(xq,yq,zyes,perm,poro,pressure,saturation,pre2,sat2,axis=1)
temp=np.stack([xq,yq,zyes,perm,poro,pressure,saturation,pre2,sat2], axis=1)
return temp
def Plot_Production(x,true,machine,true2,machine2):
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(x, machine, 'b', label='CCR')
plt.plot(x, true, 'r', label='True model')
plt.xlabel('Time (days)')
plt.ylabel('Q_o(Sm^{3}/day)')
plt.ylim((0,25000))
plt.title('Oil production')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(x, machine2, 'b', label='CCR')
plt.plot(x, true2, 'r', label='True model')
plt.xlabel('Time (days)')
plt.ylabel('Q_w(Sm^{3}/day)')
plt.ylim((1,40))
plt.title('Water production')
plt.legend()
os.chdir(Resultsf)
plt.savefig("Surrogate_learn.pdf")
os.chdir(oldfolder)
plt.show()
def Peaceman_well(data,perm,poro,nx,ny,nz,A,Ausew,jigg):
viscosity_water=0.5
viscosity_oil=1.18
oil_density=52
water_density=62.4
BHP=140
water_injection_rate=15000
Injector_location=np.array([9, 9])
producer_location=np.array([69, 9])
h1=100
h2=100
h3=50
perm=np.reshape(perm,(nx,ny,nz),'F')
poro=np.reshape(poro,(nx,ny,nz),'F')
perm_producer=perm[69,9,3]
poro_producer=poro[69,9,3]
perm_injector=perm[9,9,3]
poro_injector=poro[9,9,3]
# % Rd=(sqrt((100^2+100^2))/2)*exp(-0.5*(3-atan(1)-atan(1)))
Rd=0.3468*100
Re=(0.14*(((1**0.5)*(100**2))+((1**0.5)*(100**2)))**0.5)/(0.5*(1**0.25)+(1**0.25));
Qoil=np.zeros((15,4))
Qwater=np.zeros((15,4))
pi=3.142
for i in range (15):
Ause=A[i,:]
jigguse=jigg[i,:]
pressure=np.reshape(data[:,0,i],(84,27,4),'F')
water_saturation=np.reshape(data[:,1,i],(84,27,4),'F')
yess=0
yessw=0
for j in range(4):
perm_producer=perm[69,9,j]
pressureg=pressure[69,9,j]
water_saturationg=water_saturation[69,9,j]
oil_saturationg=1-water_saturationg
mixture_density=(oil_density*oil_saturationg)+ (water_density*water_saturationg)
up=2*pi*mixture_density*h3*sqrt(perm_producer*perm_producer)
mix_viscosity=(viscosity_oil+viscosity_water)/2
down=mix_viscosity*(np.log(Re/Rd))
deltap=((mixture_density*32.2*yess)/2)
deltapw=((mixture_density*32.2*yessw))
side=(BHP-deltap-pressureg)
sidew=(BHP-deltapw-pressureg)
oil_ratio=(oil_density*oil_saturationg)/mixture_density
water_ratio=(water_density*water_saturationg)/mixture_density
Qoil[i,j]=(((((up/down)*side)*oil_ratio)/oil_density)/1.6)*0.00001
Qwater[i,j]=(((((up/down)*sidew)*water_ratio)/water_density)*0.000001)*jigguse
yess=yess+Ause
yessw=yessw+Ausew
Qoil_true=np.mean(Qoil,axis=1)
Qwater=np.mean(Qwater,axis=1)
return Qoil_true,Qwater
def Create_input_stage_1(nx,ny,nz,perm2,poro2):
xc = np.linspace(1., nx, nx)
yc = np.linspace(1., ny, ny)
zc = np.linspace(1., nz, nz)
xq, yq, zq = np.meshgrid(xc, yc, zc, indexing='ij')
assert np.all(xq[:,0,0] == xc)
assert np.all(yq[0,:,0] == yc)
assert np.all(zq[0,0,:] == zc)
xq=np.reshape(xq,(-1,1),'F')
yq=np.reshape(yq,(-1,1),'F')
zqall=np.zeros((nx*ny,nz))
for i in range(nz):
zqall[:,i]=np.ravel(np.reshape(zq[:,:,i],(-1,1),'F'))
zyes = np.array([])
for i in range(nz):
zyes = np.append(zyes, zqall[:,i])
zyes=np.reshape(zyes,(-1,1),'F')
#temp=np.concatenate((xq,yq,zyes,np.reshape(perm2,(-1,1),'F'),np.reshape(poro2,(-1,1),'F')), axis=1)
temp=np.stack([xq,yq,zyes,np.reshape(perm2,(-1,1),'F'),np.reshape(poro2,(-1,1),'F')], axis=1)
os.chdir(oldfolder)
masterp='MASTERin0.out'
np.savetxt(masterp,temp[:,:,0], fmt = '%4.7f',delimiter='\t', newline = '\n')
return temp[:,:,0]
def Reservoir_Learning(ii,training_master):
folder_trueccr = 'CCR_MACHINES'
if ii==1:
if os.path.isdir(folder_trueccr): # value of os.path.isdir(directory) = True
shutil.rmtree(folder_trueccr)
os.mkdir(folder_trueccr)
os.chdir(training_master)
mat = scipy.io.loadmat('training_set.mat')
train_set=mat['tempbig']
os.chdir(oldfolder)
# fillee='MASTER%d.out'%(ii)
data=train_set[:,:,ii-1]
input1=data[:,0:7]
output=data[:,7:9]
input1=gaussianizeit(input1)
scaler = MinMaxScaler()
(scaler.fit(input1))
input1=(scaler.transform(input1))
inputtrain=(input1)
numclement = len(input1[0])
outputtrain=output
outputtrain=np.reshape(outputtrain,(-1,2),'F')
outputtrain=gaussianizeit(outputtrain)
ydamir=outputtrain
scaler1 = MinMaxScaler()
(scaler1.fit(ydamir))
ydamir=(scaler1.transform(ydamir))
print('')
#-------------------#---------------------------------#
filename1='regressor_%d.h5'%(ii)
def parad(filename1):
from keras.layers import Dense
from keras.models import Sequential
np.random.seed(7)
modelDNN = Sequential()
modelDNN.add(Dense(200, activation = 'relu', input_dim = numclement))
modelDNN.add(Dense(units = 420, activation = 'relu'))
modelDNN.add(Dense(units = 21, activation = 'relu'))
modelDNN.add(Dense(units = 2))
modelDNN.compile(loss= 'mean_squared_error', optimizer='Adam', metrics=['mse'])
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=200)
a0=inputtrain
b0=ydamir
if a0.shape[0]!=0 and b0.shape[0]!=0:
history=modelDNN.fit(a0, b0,validation_split=0.01, batch_size = 50, epochs = 300,callbacks=[es])
plot_history(history)
os.chdir(os.path.join(oldfolder,'CCR_MACHINES'))
modelDNN.save(filename1)
# pickle.dump(modelDNN, open(filename1, 'wb'))
os.chdir(oldfolder)
parad(filename1)
print('')
#Parallel(n_jobs=nclusters, verbose=50)(delayed(
# parad)(j)for j in number_of_realisations)
os.chdir(oldfolder)
def Train_True_Model_CCR(nx,ny,nz,folder_true,oldfolder,true_master,training_master):
if os.path.isdir(folder_true): # value of os.path.isdir(directory) = True
shutil.rmtree(folder_true)
os.mkdir(folder_true)
shutil.copy2('POROVANCOUVER.DAT',folder_true)
shutil.copy2('KVANCOUVER.DAT',folder_true)
shutil.copy2('FAULT.DAT',folder_true)
shutil.copy2('MASTER0.DATA',folder_true)
shutil.copy2('Read_off.m',folder_true)
shutil.copy2('read_ecl.m',folder_true)
os.chdir(oldfolder)
os.chdir(true_master)
os.system("@eclrun eclipse MASTER0.DATA")
ROLAND ="matlab -r Read_off"
os.system(ROLAND)
time.sleep(30) # pause 5.5 seconds
response= str(input('press Y if Matlab executed else wait '))
Pressure=np.genfromtxt("Pressure_ensemble.out", dtype='float')
saturation=np.genfromtxt("Saturation_ensemble.out", dtype='float')
os.chdir(oldfolder)
perm=np.genfromtxt("KVANCOUVER.DAT",skip_header = 1,skip_footer = 1, dtype='float')
poro=np.genfromtxt("POROVANCOUVER.DAT",skip_header = 1,skip_footer = 1, dtype='float')
perm=np.reshape(perm,(-1,1),'F')
poro=np.reshape(poro,(-1,1),'F')
tempbig=np.zeros((9072,9,15))
for i in range (15):
# i=0
j=i+1
filename = 'MASTER%d.out'%(j)
temp=prepare_grid(nx,ny,nz,perm,poro,np.reshape(Pressure[:,i],(-1,1),'F'),np.reshape(saturation[:,i],(-1,1),'F'),np.reshape(Pressure[:,i+1],(-1,1),'F'),np.reshape(saturation[:,i+1],(-1,1),'F'))
os.chdir(true_master)
np.savetxt(filename,temp[:,:,0], fmt = '%4.4f',delimiter='\t', newline = '\n')
os.chdir(oldfolder)
tempbig[:,:,i]=temp[:,:,0]
os.chdir(training_master)
sio.savemat('training_set.mat', {'tempbig':tempbig})
os.chdir(oldfolder)
for i in range(15):
jj=i+1
print('Begin for time',jj )
Reservoir_Learning(jj,training_master)
print('')
print('End for time',jj )
os.chdir(training_master)
mat = scipy.io.loadmat('training_set.mat')
train_set=mat['tempbig']
os.chdir(oldfolder)
data=train_set[:,:,0]
input1=data[:,[0,1,2,3,4]]
output=data[:,[5,6]]
input1=gaussianizeit(input1)
scaler = MinMaxScaler()
(scaler.fit(input1))
input1=(scaler.transform(input1))
inputtrain=(input1)
numclement = len(input1[0])
outputtrain=output
outputtrain=np.reshape(outputtrain,(-1,2),'F')
outputtrain=gaussianizeit(outputtrain)
ydamir=outputtrain
scaler1 = MinMaxScaler()
(scaler1.fit(ydamir))
ydamir=(scaler1.transform(ydamir))
filename1='regressor_0.h5'
np.random.seed(7)
modelDNN = Sequential()
modelDNN.add(Dense(200, activation = 'relu', input_dim = numclement))
modelDNN.add(Dense(units = 420, activation = 'relu'))
modelDNN.add(Dense(units = 21, activation = 'relu'))
modelDNN.add(Dense(units = 2))
modelDNN.compile(loss= 'mean_squared_error', optimizer='Adam', metrics=['mse'])
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=200)
a0=inputtrain
b0=ydamir
if a0.shape[0]!=0 and b0.shape[0]!=0:
history=modelDNN.fit(a0, b0,validation_split=0.01, batch_size = 50, epochs = 300,callbacks=[es])
plot_history(history)
os.chdir(os.path.join(oldfolder,'CCR_MACHINES'))
modelDNN.save(filename1)
# pickle.dump(modelDNN, open(filename1, 'wb'))
os.chdir(oldfolder)
return perm,poro
def prediction_stage_1(fillee,masterp):
data=fillee
input1=data[:,[0,1,2,3,4]]
inputini= input1
outputbig=data[:,[5,6]]
output=np.reshape(outputbig,(-1,2),'F')
scaler2 = MinMaxScaler()
(scaler2.fit(output))
print('')
scaler = MinMaxScaler()
input2=gaussianizeit(input1)
input2= scaler.fit(input2).transform(input2)
datatest=masterp
inputtest=datatest
clement=interpolatebetween(input1,input2,inputtest)
inputtest=clement
outputfirst=output
output2=outputfirst
scaler2 = MinMaxScaler()
output2=gaussianizeit(output2)
output2= scaler2.fit(output2).transform(output2)
numrows=len(inputtest) # rows of input
numrowstest=numrows
numcols = len(inputtest[0])
#-------------------Regression prediction---------------------------------------------------#
filename1='regressor_0.h5'
clementanswer1=np.zeros((numrowstest,2))
print('')
print('predict in series')
os.chdir(os.path.join(oldfolder,'CCR_MACHINES'))
loaded_model = load_model(filename1)
# loaded_model = pickle.load(open(filename1, 'rb'))
os.chdir(oldfolder)
##----------------------##------------------------##
a00=inputtest
a00=np.reshape(a00,(-1,numcols),'F')
if a00.shape[0]!=0:
clementanswer1=loaded_model .predict(a00)
clementanswer1=interpolatebetween(output2,outputfirst,clementanswer1)
print('')
matrixyes1=np.concatenate((inputini,clementanswer1), axis=1)
os.chdir(oldfolder)
return matrixyes1
# -*- coding: utf-8 -*-
def Reservoir_Prediction(ii,training_master,inputdataa):
oldfolder = os.getcwd()
current_CCR_path = oldfolder
os.chdir(current_CCR_path)
folder_trueccr = 'CCR_MACHINES'
CCR_path = os.path.join(oldfolder,folder_trueccr)
os.chdir(CCR_path)
filename1='regressor_%d.h5'%(ii)
loaded_model = load_model(filename1)
# loaded_model = pickle.load(open(filename1, 'rb'))
os.chdir(oldfolder)
# fillee='MASTER%d.out'%(ii)
data=training_master
# data=np.genfromtxt(fillee, dtype='float')
input1=data[:,0:7]
inputini= input1
outputbig=data[:,7:9]
output=np.reshape(outputbig,(-1,2),'F')
scaler2 = MinMaxScaler()
(scaler2.fit(output))
print('')
scaler = MinMaxScaler()
input2=gaussianizeit(input1)
input2= scaler.fit(input2).transform(input2)
datatest=inputdataa
# datatest=np.genfromtxt(filletest, dtype='float')
inputtest=datatest
clement=interpolatebetween(input1,input2,inputtest)
#inputtest=scaler.transform(inputtest)
inputtest=clement
outputfirst=output
output2=outputfirst
scaler2 = MinMaxScaler()
output2=gaussianizeit(output2)
output2= scaler2.fit(output2).transform(output2)
numrows=len(inputtest) # rows of input
numrowstest=numrows
numcols = len(inputtest[0])
#-------------------Regression prediction---------------------------------------------------#
# filename1='regressor_%d.asv'%(ii)
clementanswer1=np.zeros((numrowstest,2))
##----------------------##------------------------##
a00=inputtest
a00=np.reshape(a00,(-1,numcols),'F')
if a00.shape[0]!=0:
clementanswer1=loaded_model .predict(a00)
os.chdir(current_CCR_path)
clementanswer1=interpolatebetween(output2,outputfirst,clementanswer1)
print('')
matrixyes=np.concatenate((inputini,clementanswer1), axis=1)
masterp='MASTER%d_prediciton.out'%(ii)
os.chdir(os.path.join(oldfolder,'True_model'))
# np.savetxt(masterp,matrixyes, fmt = '%4.7f',delimiter='\t', newline = '\n')
os.chdir(oldfolder)
matrixyes2=np.concatenate((inputini[:,0:5],clementanswer1), axis=1)
os.chdir(oldfolder)
# np.savetxt('MASTER_updated.out',matrixyes2, fmt = '%4.7f',delimiter='\t', newline = '\n')
return clementanswer1,matrixyes2
print('-------------------END PREDICTION PROGRAM----------------------------')
def honour2(rossmary, rossmaryporo,sgsim2,DupdateK,nx,ny,nz,N):
print(' Reading true permeability field ')
uniehonour = np.reshape(rossmary,(nx,ny,nz), 'F')
unieporohonour = np.reshape(rossmaryporo,(nx,ny,nz), 'F')
# Read true porosity well values
aa = np.zeros((4))
bb = np.zeros((4))
aa1 = np.zeros((4))
bb1 = np.zeros((4))
# Read true porosity well values
for j in range(4):
aa[j] = uniehonour[9,9,j]
bb[j] = uniehonour[69,9,j]
aa1[j] = unieporohonour[9,9,j]
bb1[j] = unieporohonour[69,9,j]
# Read permeability ensemble after EnKF update
A = np.reshape(DupdateK,(nx*ny*nz,N),'F') # thses 2 are basically doing the same thing
C = np.reshape(sgsim2,(nx*ny*nz,N),'F')
# Start the conditioning for permeability
print(' Starting the conditioning ')
output = np.zeros((nx*ny*nz,N))
outputporo = np.zeros((nx*ny*nz,N))
for j in range(N):
B = np.reshape(A[:,j],(nx,ny,nz),'F')
D = np.reshape(C[:,j],(nx,ny,nz),'F')
for jj in range(4):
B[9,9,jj] = aa[jj]
B[69,9,jj] = bb[jj]
D[9,9,jj] = aa1[jj]
D[69,9,jj] = bb1[jj]
output[:,j:j+1] = np.reshape(B,(nx*ny*nz,1), 'F')
outputporo[:,j:j+1] = np.reshape(D,(nx*ny*nz,1), 'F')
output[output >= 1500] = 1500 # highest value in true permeability
output[output <= 0.05] = 0.05
outputporo[outputporo >= 0.4] = 0.4
outputporo[outputporo <= 0.05] = 0.05
return (output,outputporo)
def ESMDA(sg,sgporo,f,Sim1,alpha,c,nx,ny,nz,No,N):
sgsim11 = np.reshape(np.log(sg),(nx*ny*nz,N),'F')
sgsim11poro = np.reshape(sgporo,(nx*ny*nz,N),'F')
stddWOPR1 = 0.1*f[0]
stddWWCT1 = 0.1*f[1]
print(' Generating Gaussian noise ')
Error1 = np.ones((No,N))
Error1[0,:] = np.random.normal(0,stddWOPR1,(N))
Error1[1,:] = np.random.normal(0,stddWWCT1,(N))
Cd2 = (Error1.dot(Error1.T))/(N - 1)
Dj = np.zeros((No, N))
for j in range(N):
Dj[:,j] = f + Error1[:,j]
overall = np.zeros((2*nx*ny*nz + No,N))
overall[0:nx*ny*nz,0:N] = sgsim11
overall[nx*ny*nz:2*nx*ny*nz,0:N] = sgsim11poro
overall[2*nx*ny*nz:2*nx*ny*nz + No,0:N] = Sim1
Y = overall
M = np.mean(Sim1, axis = 1)
M2 = np.mean(overall, axis = 1)
S = np.zeros((Sim1.shape[0],N))
yprime = np.zeros(((2)*nx*ny*nz + No,N))
for j in range(N):
S[:,j] = Sim1[:,j]- M
yprime[:,j] = overall[:,j] - M2
print (' Updating the new ensemble')
Cyd = (yprime.dot(S.T))/(N - 1)
Cdd = (S.dot(S.T))/(N - 1)
Usig,Sig,Vsig = np.linalg.svd((Cdd + (alpha*Cd2)), full_matrices = False)
Bsig = np.cumsum(Sig, axis = 0) # vertically addition
valuesig = Bsig[-1] # last element
valuesig = valuesig * 0.9999
indices = ( Bsig >= valuesig ).ravel().nonzero()
toluse = Sig[indices]
tol = toluse[0]
print(' Update the new ensemble ')
#(V,X,U) = np.linalg.pinv((Cdd + (alpha*Cd2)))
Ynew = Y + ((Cyd.dot(np.linalg.pinv((Cdd + (alpha*Cd2))))).dot(Dj - Sim1))
print(' Extracting the active permeability fields ')
value1 = Ynew[0:nx*ny*nz,0:N]
DupdateK = np.exp(value1)
DupdateK[DupdateK >= 1500]=1500
DupdateK[DupdateK <= 100]=100
sgsim2 = Ynew[nx*ny*nz:nx*ny*nz*2,0:N]
sgsim2[sgsim2 >=0.45]=0.45
sgsim2[sgsim2 <= 0.1]=0.1
return sgsim2,DupdateK
def ESMDALocalisation2(sg,sgporo,f,Sim1,alpha,c,nx,ny,nz,No,N):
print(' Loading the files ')
## Get the localization for all the wells
A = np.zeros((84,27,4))
for jj in range(5):
A[9,9,jj] = 1
A[69,9,jj] = 1
print( ' Calculate the Euclidean distance function to the 6 producer wells')
lf = np.reshape(A,(nx,ny,nz),'F')
young = np.zeros((int(nx*ny*nz/nz),4))
for j in range(4):
sdf = lf[:,:,j]
(usdf,IDX) = spndmo.distance_transform_edt(np.logical_not(sdf), return_indices = True)
usdf = np.reshape(usdf,(int(nx*ny*nz/nz)),'F')
young[:,j] = usdf
sdfbig = np.reshape(young,(nx*ny*nz,1),'F')
sdfbig1 = abs(sdfbig)
z = sdfbig1
## the value of the range should be computed accurately.
c0OIL1 = np.zeros((nx*ny*nz,1))
print( ' Computing the Gaspari-Cohn coefficent')
for i in range(nx*ny*nz):
if ( 0 <= z[i,:] or z[i,:] <= c ):
c0OIL1[i,:] = -0.25*(z[i,:]/c)**5 + 0.5*(z[i,:]/c)**4 + 0.625*(z[i,:]/c)**3 - (5.0/3.0)*(z[i,:]/c)**2 + 1
elif ( z < 2*c ):
c0OIL1[i,:] = (1.0/12.0)*(z[i,:]/c)**5 - 0.5*(z[i,:]/c)**4 + 0.625*(z[i,:]/c)**3 + (5.0/3.0)*(z[i,:]/c)**2 - 5*(z[i,:]/c) + 4 - (2.0/3.0)*(c/z[i,:])
elif ( c <= z[i,:] or z[i,:] <= 2*c ):
c0OIL1[i,:] = -5*(z[i,:]/c) + 4 -0.667*(c/z[i,:])
else:
c0OIL1[i,:] = 0
c0OIL1[c0OIL1 < 0 ] = 0
print(' Getting the Gaspari Cohn for Cyd')
schur = c0OIL1
Bsch = np.tile(schur,(1,N))
yoboschur = np.ones((2*nx*ny*nz + No,N))
yoboschur[0:nx*ny*nz,0:N] = Bsch
yoboschur[nx*ny*nz:2*nx*ny*nz,0:N] = Bsch
sgsim11 = np.reshape(np.log(sg),(nx*ny*nz,N),'F')
sgsim11poro = np.reshape(sgporo,(nx*ny*nz,N),'F')
print(' Determining standard deviation of the data ')
stddWOPR1 = 0.15*f[0]
stddWWCT1 = 0.2*f[1]
print(' Generating Gaussian noise ')
Error1 = np.ones((No,N))
Error1[0,:] = np.random.normal(0,stddWOPR1,(N))
Error1[1,:] = np.random.normal(0,stddWWCT1,(N))
Cd2 = (Error1.dot(Error1.T))/(N - 1)
Dj = np.zeros((No, N))
for j in range(N):
Dj[:,j] = f + Error1[:,j]
print(' Generating the ensemble state matrix with parameters and states ')
overall = np.zeros((2*nx*ny*nz + No,N))
overall[0:nx*ny*nz,0:N] = sgsim11
overall[nx*ny*nz:2*nx*ny*nz,0:N] = sgsim11poro
overall[2*nx*ny*nz:2*nx*ny*nz + No,0:N] = Sim1
Y = overall
M = np.mean(Sim1, axis = 1)
M2 = np.mean(overall, axis = 1)
S = np.zeros((Sim1.shape[0],N))
yprime = np.zeros(((2)*nx*ny*nz + No,N))
for j in range(N):
S[:,j] = Sim1[:,j]- M
yprime[:,j] = overall[:,j] - M2
print (' Updating the new ensemble')
Cyd = (yprime.dot(S.T))/(N - 1)
Cdd = (S.dot(S.T))/(N - 1)
Usig,Sig,Vsig = np.linalg.svd((Cdd + (alpha*Cd2)), full_matrices = False)
Bsig = np.cumsum(Sig, axis = 0) # vertically addition
valuesig = Bsig[-1] # last element
valuesig = valuesig * 0.9999
indices = ( Bsig >= valuesig ).ravel().nonzero()
toluse = Sig[indices]
tol = toluse[0]
print(' Update the new ensemble ')
(V,X,U) = pinvmat((Cdd + (alpha*Cd2)),tol)
Ynew = Y + yoboschur*((Cyd.dot(X)).dot(Dj - Sim1))
print(' Extracting the active permeability fields ')
value1 = Ynew[0:nx*ny*nz,0:N]
DupdateK = np.exp(value1)
sgsim2 = Ynew[nx*ny*nz:nx*ny*nz*2,0:N]
return sgsim2,DupdateK
def main_ESMDA_covariance(observation,overallsim,rossmary,rossmaryporo,perm,poro,alpha,c,nx,ny,nz,N,No,Nt):
sgsim = np.reshape(perm,(nx*ny*nz,N), 'F')
sgsimporo = np.reshape(poro,(nx*ny*nz,N),'F')
sg = sgsim
sgporo = sgsimporo
Sim11 = np.reshape(overallsim,(2,15,N), 'F')
# History matching using ESMDA
for i in range(Nt):
print(' Now assimilating timestep %d '%(i+1))
Sim1 = Sim11[:,i,:]
Sim1 = np.reshape(Sim1,(No,N))
f = observation[:,i]
# (sgsim2,DupdateK) = ESMDALocalisation2 (sg,sgporo, f,Sim1,alpha,c)
sgsim2,DupdateK = ESMDA (sg,sgporo, f,Sim1,alpha,c,nx,ny,nz,No,N)
#(output,outputporo) = honour2(rossmary, rossmaryporo,sgsim2,DupdateK,nx,ny,nz,N)
sg = np.reshape(DupdateK,(nx*ny*nz,N),'F')
sgporo = np.reshape(sgsim2,(nx*ny*nz,N),'F')
print('Finished assimilating timestep %d'%(i+1))
sgassimi = DupdateK
sgporoassimi = sgsim2