-
Notifications
You must be signed in to change notification settings - Fork 1
/
inversion_module.py
3010 lines (2492 loc) · 135 KB
/
inversion_module.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 Tue Aug 12 12:06:16 2014
@author: Nikolaj
"""
import os
import numpy as np
import math as mat
import subprocess
import shutil
import load_write
class inversion_module:
"""
class containing modules to setup a PEST inversion in the HYTEB enviroment
"""
#==============================================================================
def __init__(self,inversion_ini='inversion_setup.ini', model_dis ='model_dis.ini', hydro_ini = 'hydro_ini.ini',geophys_ini='geophys_TEM.ini'):
#==============================================================================
self.write = load_write.write_file()
self.load = load_write.load_file()
self.load.ini_model_dis(model_dis)
self.load.ini_hydro(hydro_ini)
self.load.ini_inversion(inversion_ini)
self.load.ini_geophys(geophys_ini)
# # --- load from inversion_setup.ini ---
# self.load.pp_file_name = load.pp_file_name
# self.load.pp_name = load.pp_name
#
#
# # --- load from model_dis.ini ---
# self.load.dx = load.dx
# self.load.dy = load.dy
# self.load.dz = load.dz
# self.load.n_layer = load.n_layer
# self.load.n_cap = load.n_cap
# self.load.x = load.x
# self.load.y = load.y
# self.load.nx = load.nx
# self.load.ny = load.ny
# self.load.n_pp_x = load.n_pp_x
# self.load.n_pp_y = load.n_pp_y
#
# # --- load from hydro.ini.ini ---
# self.load.model_name = load.model_name
# self.load.dtype_model = load.dtype_model
# self.load.ibound = load.ibound
# self.load.dtype_ibound = load.dtype_ibound
# self.load.por_name = load.por_name
# self.load.dtype_por = load.dtype_por
# self.load.recharge = load.recharge
# self.load.dtype_recharge = load.dtype_recharge
# self.load.model_name_calib = load.model_name_calib
# self.load.modflow_file_name = load.modflow_file_name
#==============================================================================
def batch_all_models(self,mf_nam,pp_x,pp_y,grid=1,pp_file_name=[]):
#==============================================================================
"""
Write batch file for running both the geophysical and hydrolodical models
Parameters
----------
mf_nam : str
string with name of modflow nam file for running the calibration
pp_x : List(int)
python list - node positions of pilot points in column direction
pp_y : List(int)
python list - node positions of pilot points in row direction
grid : int
grid number used when running model, see ini file for discretization
pp_file_name : Optional(List(str))
Python list with sufix to fac2real-ini files
"""
print 'batch_allmodels: '
# --- open file for writing ---
fid1 = open('allmodels.bat','w')
fid1.write('@echo off'+'\n')
fid1.write('echo ALLMODELS'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('Rem DELETE MODFLOW OUTPUT FILES'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('\n')
fid1.write('del '+self.load.modflow_file_name+'_calib.hds'+'\n')
fid1.write('del '+self.load.modflow_file_name+'_calib.cbb'+'\n')
fid1.write('del '+self.load.modflow_file_name+'_calib.dnn'+'\n')
if self.load.rch_est != 0:
tmp = self.load.rch_est_calc.split('.')
fid1.write('del '+tmp[0]+'.ref'+'\n')
fid1.write('del hk_diff_L*.dat'+'\n')
fid1.write('del '+self.load.model_name_calib+'*.ref'+'\n')
fid1.write('\n')
fid1.write('\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('Rem Now the actual model is run'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('\n')
fid1.write('for %%k in (')
# --- run all geophysical measurements ---
for i in range(len(pp_y)):
fid1.write(str(pp_y[i])+' ')
fid1.write( ') do ('+'\n')
fid1.write(' for %%j in (')
for j in range(len(pp_x)):
fid1.write(str(pp_x[j])+' ')
fid1.write(') do ('+'\n')
fid1.write(' '+self.load.geophys_software+'.exe '+self.load.mod_file+'%%k_%%j.mod > nul'+'\n')
fid1.write(' )'+'\n')
fid1.write(')'+'\n')
fid1.write('\n')
# --- run PEST utility to interpolate parameter values from pilot point
# --- file to grid cells
fid1.write('set /A %F = '+str(self.load.n_layer)+'\n')
fid1.write('\n')
fid1.write('for /L %%k in (1,1,%F%) do ('+'\n')
# --- use grid defind in HYTEB ini ---
if grid == 1:
fid1.write(' fac2real.exe < fac2real_L%%k.in > nul'+'\n')
if grid == 2:
for pp_name in pp_file_name:
fid1.write(' fac2real.exe < fac2real_L%%k'+pp_name+'.in > nul'+'\n')
fid1.write(')'+'\n')
fid1.write('\n')
#--- petrophysical parameter estimation with pilot points ---
if self.load.petro_est ==-3:
fid1.write(self.load.petro_est_calc+'\n')
# --- calc recharge qua linear log log relatioship ---
if self.load.rch_est != 0:
fid1.write(self.load.rch_est_calc+'\n')
fid1.write('\n')
# --- run regularization ---
fid1.write(self.load.reg_calc+'\n')
# --- run modflow-2000 ---
fid1.write('mf2k.exe '+mf_nam+'.nam > nul'+'\n')
# --- run PEST utilities to read binary output data into acis files ---
fid1.write('mod2obs.exe < mod2obs.in > nul'+'\n')
fid1.write('bud2smp.exe < bud2smp_model.in > nul'+'\n')
fid1.write('\n')
fid1.close()
#==============================================================================
def batch_beopest(self,run_inversion ='off'):
#==============================================================================
"""
Writes batch file for running beopest
Parameter
---------
run_inversion : str
off --> do not run PEST
on --> run PEST
"""
print 'batch_beopest: ',
# --- write batch file for running beopest ---
self.write.batch_beopest(self.load.IP_addr,self.load)
# --- run beopest ---
if run_inversion == 'on':
if self.load.PEST_niter != 0:
tmp = open('run_beopest_output.dat','w')
subprocess.call('run_beopest.bat',stdout=tmp)
tmp.close()
# --- if iteration is zero call PEST instead of BeoPEST ---
if self.load.PEST_niter == 0:
program = 'pest.exe'
input1 = self.load.PEST_name+'.pst'
dos_tex = [program,input1]
outputtext= subprocess.call(dos_tex)
#==============================================================================
def batch_gp_model(self):
#==============================================================================
"""
Makes batch stript to run one geophysical model. Using batcht input
parameter to call geophysical forward response.
"""
print 'batch_gp_model: ',
fid1 = open('gp_model.bat','w')
fid1.write('@echo off'+'\n')
fid1.write('echo TEM_MODEL'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('Rem Now the actual model is run'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('\n')
fid1.write('\n')
# --- running python script for calculating regularization ----
fid1.write(self.load.reg_calc+'\n')
# --- call geophysical software for running one forward model ---
fid1.write(self.load.geophys_software+'.exe '+self.load.mod_file+'%1_%2.mod > run_info_Aarhus_Inv.dat'+'\n')
fid1.close()
print 'done'
#==============================================================================
def batch_gw_model(self,mf_nam,pp_x,pp_y,grid=1,pp_file_name=[],run_fac2real=True):
#==============================================================================
"""
Makes batch stript to run groundwater model.
Parameters
----------
mf_nam : str
name of modflow nam file
grid : int
grid number used when running model, see ini file for discretization
pp_file_name : Optional(List((str))
Python list with sufix to fac2real-ini files
run_fac2real : logical
True --> run fac2real to generate hk-field files. One for each layer
"""
print 'batch_gw_model: ',
fid1 = open('gw_model.bat','w')
fid1.write('@echo off'+'\n')
fid1.write('echo GW_MODELS'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('Rem DELETE MODFLOW OUTPUT FILES'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('\n')
fid1.write('del '+self.load.modflow_file_name+'_calib.hds'+'\n')
fid1.write('del '+self.load.modflow_file_name+'_calib.cbb'+'\n')
fid1.write('del '+self.load.modflow_file_name+'_calib.ddn'+'\n')
# --- if gwm is running in prediction mode delete modpath output files ----
if self.load.pred2calibdata < 0:
if self.load.pred2calibdata == -1 or self.load.pred2calibdata == -3:
fid1.write('del endpoint'+'\n')
fid1.write('del pathline'+'\n')
fid1.write('\n')
# --- calc recharge qua linear log log relatioship ---
if self.load.parametrization == -1:
if self.load.rch_est != 0:
if run_fac2real == True:
tmp = self.load.rch_est_calc.split('.')
fid1.write('del '+tmp[0]+'.ref'+'\n')
fid1.write('del hk_diff_L*.dat'+'\n')
if run_fac2real == True:
fid1.write('del '+self.load.model_name_calib+'*.ref'+'\n')
fid1.write('\n')
fid1.write('\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('Rem Now the actual model is run'+'\n')
fid1.write('Rem ###################################'+'\n')
fid1.write('\n')
fid1.write('\n')
# --- run PEST utility to interpolate parameter values from pilot point
# --- file to grid cells
if run_fac2real == True:
if self.load.parametrization == -1 or self.load.parametrization ==-3:
fid1.write('set /A %F = '+str(self.load.n_layer)+'\n')
fid1.write('\n')
fid1.write('for /L %%k in (1,1,%F%) do ('+'\n')
# --- use grid defind in HYTEB ini ---
if grid == 1:
fid1.write(' fac2real.exe < fac2real_L%%k.in > nul'+'\n')
if grid == 2:
for pp_name in pp_file_name:
fid1.write(' fac2real.exe < fac2real_L%%k'+pp_name+'.in > nul'+'\n')
fid1.write(')'+'\n')
fid1.write('\n')
#--- petrophysical parameter estimation with pilot points ---
if self.load.petro_est ==-3:
fid1.write(self.load.petro_est_calc+'\n')
# --- calc recharge qua linear log log relatioship ---
if self.load.rch_est == -1:
fid1.write(self.load.rch_est_calc+'\n')
fid1.write('\n')
# --- run regularization ---
if self.load.parametrization == -1 or self.load.parametrization ==-3:
if self.load.inv_type != 'hydrologic':
if self.load.petro_est == 0 or self.load.petro_est == -1:
fid1.write(self.load.reg_calc+'\n')
elif self.load.petro_est == -2:
tmp1 = self.load.reg_calc.split('.')
fid1.write('set /A %F = '+str(self.load.n_layer)+'\n')
fid1.write('for /L %%k in (1,1,%F%) do ('+'\n')
fid1.write(' '+tmp1[0]+'_L%%k.'+tmp1[1]+'\n')
fid1.write(')'+'\n')
fid1.write('\n')
# --- run modflow-2000 ---
fid1.write('\n')
fid1.write('mf2k.exe '+mf_nam+'.nam >> mf2k.dat'+'\n')
# --- run PEST utilities to read binary output data into acis files --
fid1.write('mod2obs.exe < mod2obs.in > nul'+'\n')
fid1.write('bud2smp.exe < bud2smp_model.in > nul'+'\n')
fid1.write('\n')
# --- add predictions to calibration dataset ---
if self.load.pred2calibdata < 0:
if self.load.pred2calibdata == -1 or self.load.pred2calibdata == -3:
fid1.write('Mpathr5_0.exe < mpathr5_0_pumping.ini \n')
fid1.write('sortbyept.exe'+'\n')
fid1.write('rchsum.exe > rchsum.dat'+'\n')
fid1.write('\n')
if self.load.pred2calibdata == -1 or self.load.pred2calibdata == -2:
fid1.write('mod2obs.exe < mod2obs_pred_pump.in > nul'+'\n')
self.write.mod2obs_in('mod2obs_pred_pump',self.load.modflow_file_name+'_calib',self.load.model_spc,self.load.head_pred_points,self.load.n_layer)
fid1.close()
# --- write ini files for mod2obs.exe and bud2smp.exe ---
self.write.bud2smp_in('bud2smp_model',self.load.modflow_file_name+'_calib',self.load.model_spc,self.load.n_layer,self.load.ibound)
self.write.mod2obs_in('mod2obs',self.load.modflow_file_name+'_calib',self.load.model_spc,self.load.head_obs_points,self.load.n_layer)
print 'done'
#==============================================================================
def copy2slaves(self,pp_x,pp_y,run_allmodels='on',tmp_numb=''):
#==============================================================================
"""
Creates n slave dir.
Make n new slave subdirectories and copy pest and model files to folder
Parameters
----------
pp_x : List(int)
python list - node positions of pilot points in column direction
pp_y : List(int)
python list - node positions of pilot points in row direction
run_allmodel : str
run batch file "allmodels" before copying files into slave dir
tmp_nump : int
"""
import errno
print 'copy2slave:'
cwd = os.getcwd()
path ='C:/temp/HYTEB'+str(tmp_numb)
for i in range(self.load.n_slaves):
try:
shutil.rmtree(path+str(tmp_numb))
except:
# ishutil.Error as e:
print 'copy2slaves: folder does not excist!!! '
# --- delete temporay geophys files ---
for i in pp_y:
for j in pp_x:
try:
os.remove(self.load.tem_name_raw+str(i)+'_'+str(j)+'.tem')
except:
if IOError:
pass
try:
os.remove(self.load.mod_file_temp+str(i)+'_'+str(j)+'.mod')
except:
if IOError:
pass
# --- delete modpath output files ---
try:
os.remove('pathline')
except:
pass
# --- run all_models ---
if run_allmodels == 'on':
if self.load.inv_type == 'joint':
subprocess.call('allmodels.bat')
if self.load.inv_type == 'sequential':
subprocess.call('gw_model.bat')
print 'done'
# --- copy work folde to slave# and move folders back into work folder
for i in range(self.load.n_slaves):
# --- copy to dir ---
print str(i+1)+'/'+str(self.load.n_slaves)
try:
shutil.copytree(cwd,path+'/slave'+str(i+1))
# --- Directories are the same
except shutil.Error as e:
print 'Error in copy2slave:'
print('Directory not copied. Error: %s' % e)
# --- Directories already exist, delete and try copy again
except OSError as e:
try:
shutil.rmtree(path+'/slave'+str(i+1))
except shutil.Error as e:
print 'Error in copy2slave:'
print('Directory not copied. Error: %s' % e)
try:
shutil.copytree(cwd,path+'/slave'+str(i+1))
except shutil.Error as e:
print 'Error in copy2slave:'
print('Directory not copied. Error: %s' % e)
# --- Directories already exist, delete and try copy again
except OSError as e:
print 'Error in copy2slaves:'
print('Directory not copied. Error: %s' % e)
for i in range(self.load.n_slaves):
try:
shutil.move(path+'/slave'+str(i+1),cwd)
# --- Directories are the same
except shutil.Error as e:
print 'Error in copy2slave:'
print('Directory not MOVED. Error: %s' % e)
break
except OSError as e:
if e.errno != errno.EEXIST:
print 'OSError in copyfiles'
break
else:
print 'Error in copy2slave:'
print "\nBE CAREFUL! Directory %s already exists." % path
#==============================================================================
def delete_files(self,del_slave='off',
ext_PEST =('.1','.2','.3','.4','.5','.6','.7','.9','.bat','.jac','.jco','.jst','.mtt','.par','.prf','.pst','.rec','.rmr','rei','.res','.rst','.stp','.svd','.sen','.seo','.sen'),
ext_modflow=('.inf','.spc','.pth','.mpt','.mpn','.nam','.hds','.cbb','.ddn','.glo','.lst','.bas','.dis','.dis','.lpf','.rch','.wel','.oc','.gmg','.riv'),
ext_other = ('.emm','.emo','.err','.dat','.ite','.log','.ref','.tpl','.ins','.ite','.fwr','.tem','.mod','.pts','.dat','.in','.smp','.obs','.vtk','.voo')):
#==============================================================================
"""
Module to cleanup HYTEB for "old" output files
Parameters
----------
del_slave : str
delete PEST slave folders
ext_PEST : tuple(str)
tuple with dtype of PEST file(s) to delete
ext_modflow : tuple(str)
tuple with dtype of modflow file(s) to delete
ext_other : tuple(str)
tuple with dtype of AarhusINV file(s) to delete
"""
print 'delete_fiels:'
cwd = os.getcwd()
# --- deleting foldes with slaves ---
if del_slave == 'on':
print ' deleting all slaves'
for i in range(100):
shutil.rmtree(cwd+'\\'+'slave'+str(i+1),ignore_errors=True)
if del_slave == 'off':
print ' no slaves are deleted'
if del_slave != 'on' and del_slave != 'off':
print ' wrong input for del_slave!'
# --- delete files with extensions ---
def scandirs(path,exts):
for root, dirs, files in os.walk(path):
for currentFile in files:
if any(currentFile.lower().endswith(ext) for ext in exts):
print "deleting file: " + currentFile
os.remove(os.path.join(root, currentFile))
scandirs(cwd,ext_other)
scandirs(cwd,ext_PEST)
scandirs(cwd,ext_modflow)
# --- modpath outputfiles to delete ---
try:
os.remove('pathline')
except:
if IOError:
print " no pathline file"
try:
os.remove('endpoint')
except:
if IOError:
print " no endpoint file"
#==============================================================================
def diff_hk_tpl(self,inifile='diff_hk',left=0,right=39,split='REM'):
#==============================================================================
"""
Writes PEST templates for regularization files
Parameters
----------
inifile : str
file of ini-file for calc regularization
left : int
PEST marker, read from this "left" position to "right"
right : int
PEST marker, read to this "left" position from "left"
split : str
string delimiter
"""
print 'diff_hk_tpl: ',
# --- estimated petrophysical realtionship for all layers ---
if self.load.petro_est == -1:
fid1 = open(inifile+'.ini','r')
text = fid1.readlines()
fid1.close()
fid1 = open(inifile+'.tpl','w')
fid1.write('ptf # \n')
tex = text[0].split('REM')
tmp ='%'+str(left)+'.1s %0.3s %'+str(right-left-3-3)+'.1s %5.'+str(len(tex[1])+5)+'s'
fid1.write(tmp % ('#','p_a','# ',split+' '+tex[1]))
tex = text[1].split('REM')
tmp ='%'+str(left)+'.1s %0.3s %'+str(right-left-3-3)+'.1s %5.'+str(len(tex[1])+5)+'s'
fid1.write(tmp % ('#','p_b','# ',split+' '+tex[1]))
for i in range(2,len(text),1):
fid1.write(text[i])
fid1.close()
# --- esimates one petrophysical relationship for each layer ---
if self.load.petro_est == -2:
for layer in range(self.load.n_layer):
fid1 = open(inifile+str(layer+1)+'.ini','r')
text = fid1.readlines()
fid1.close()
fid1 = open(inifile+str(layer+1)+'.tpl','w')
fid1.write('ptf # \n')
tex = text[0].split('REM')
tmp ='%'+str(left)+'.1s %0.9s %'+str(right-left-3-3)+'.1s %5.'+str(len(tex[1])+5)+'s'
fid1.write(tmp % ('#','p_a_'+str(layer+1),'# ',split+' '+tex[1]))
tex = text[1].split('REM')
tmp ='%'+str(left)+'.1s %0.9s %'+str(right-left-3-3)+'.1s %5.'+str(len(tex[1])+5)+'s'
fid1.write(tmp % ('#','p_b_'+str(layer+1),'# ',split+' '+tex[1]))
for i in range(2,len(text),1):
fid1.write(text[i])
fid1.close()
print 'done'
#==============================================================================
def het2realarray(self,mean_type='A',log_trans=None):
#==============================================================================
"""
Introduce hetrogenity into zone estimated zones.
mean_type A --> arthemetic mean, G --> geometric mean, H --> harmonic mean
Parameters
----------
mean_type : str
A --> arthemetic mean,
G --> geometric mean,
H --> harmonic mean,
log_trans : logical
True/None
"""
# --- import module to do statiscics ---
from scipy import stats
# --- load cat from hydrozones.ini---
hydro_zones = self.load.hydro_zones(self.load.zone_par_file,self.load.n_zone_hk,4)
# --- load estimated hk parameters ---
line = [0,1,2]
par_vec = []
for i in range(1,self.load.blocksis_n_real+1,1):
tmp = self.load.PEST_par(self.load.path_results+'\\'+'case.par.'+str(i),self.load,line=line)
par_vec.append(tmp)
# --- multiply estiated parameter values to n zone realizations ---
realarray = np.zeros((self.load.blocksis_n_real,self.load.ny,self.load.nx,self.load.n_layer),dtype=float)
print 'realizations: '
for n_real in range(1,self.load.blocksis_n_real+1,1):
print n_real,
intarray = self.load.zns2mat(self.load.blocksis_path+'\\'+self.load.blocksis_name+'.'+str(n_real),self.load)
for layer in range(self.load.n_layer):
for i in range(self.load.ny):
for j in range(self.load.nx):
for k in range(len(hydro_zones[0:self.load.n_zone_hk,3])):
if intarray[i,j,layer] == int(hydro_zones[k,3]):
if log_trans == True:
par = np.log10(par_vec[n_real-1][k])
elif log_trans == None:
par = par_vec[n_real-1][k]
else:
print 'Warning in het2realarray; log_trans != True/None!!!'
break
realarray[n_real-1,i,j,layer] = par
# --- calc mean hk fields for n realizations ---
if mean_type == 'A':
x1 = np.mean(realarray,axis=0)
elif mean_type == 'G':
x1 = stats.gmean(realarray,axis=0)
elif mean_type == 'H':
x1 = stats.hmean(realarray,axis=0)
else:
print 'Warning in het2realarray; mean_type = A,G or H!!!'
if log_trans == None:
x2 = x1
elif log_trans == True:
x2 = 10**x1
else:
print 'Warning in het2realarray; log_trans != True/None!!!'
# --- write realarray file ---
# --- return x1,x2,realarray,np.log10(par_vec[n_real-1][k]),intarray
for layer in range(5):
fid1 = open(self.load.pp_file_name+str(layer+1)+'.ref','w')
for i in range(self.load.ny):
for j in range(self.load.nx):
fid1.write('%16.7e' % (x2[i,j,layer]))
fid1.write('\n')
#==============================================================================
def in_diff_hk(self):
#==============================================================================
"""
1e-12 REM a value of the transformation: hk = a*(1/rho)**b.
4 REM b value.
hk_L REM hydraulic conductivity parameter file.
mod\_ REM electrical resistivity parameter file (mod-file).
5 REM n header lines in mod-fil (electrical resistivity parameter file).
model_dis.ini REM ini-file with model discretization.
1 2 3 4 5 REM layers to calc hk diff.
"""
print 'in_diff_hk',
#
if self.load.petro_est == 0 or self.load.petro_est == -1:
fid1 = open('diff_hk.ini','w')
fid1.write(str(self.load.beta_1)+' REM a value of the transformation: hk = a*(1/rho)**b'+'\n')
fid1.write(str(self.load.beta_2)+' REM b value'+'\n')
fid1.write(self.load.model_name_calib+' REM hydraulic conductivity parameter file'+'\n')
fid1.write(self.load.mod_file+' REM electrical resistivity parameter file (mod-file)'+'\n')
fid1.write(str(self.load.n_mod_header)+' REM n header lines in mod-fil (electrical resistivity parameter file)'+'\n')
fid1.write('model_dis.ini'+' REM ini-file with model discretization'+'\n')
for layer in range(self.load.n_layer):
fid1.write(str(layer+1)+' ')
fid1.write(' REM layers to calc hk diff'+'\n')
fid1.close()
# --- ini-files for each layer for estimating petro-relation ---
elif self.load.petro_est == -2:
for layer in range(self.load.n_layer):
# --- copy diff_hk.py to scripts for calc diff for each layer ---
tmp1 = self.load.reg_calc.split('.')
shutil.copy(self.load.reg_calc,tmp1[0]+'_L'+str(layer+1)+'.'+tmp1[1])
# --- write ini-files for diff_hk_l#.ini ---
fid1 = open('diff_hk_L'+str(layer+1)+'.ini','w')
fid1.write(str(self.load.beta_1)+' REM a value of the transformation: hk = a*(1/rho)**b'+'\n')
fid1.write(str(self.load.beta_2)+' REM b value'+'\n')
fid1.write(self.load.model_name_calib+' REM hydraulic conductivity parameter file'+'\n')
fid1.write(self.load.mod_file+' REM electrical resistivity parameter file (mod-file)'+'\n')
fid1.write(str(self.load.n_mod_header)+' REM n header lines in mod-fil (electrical resistivity parameter file)'+'\n')
fid1.write('model_dis.ini'+' REM ini-file with model discretization'+'\n')
fid1.write(str(layer+1)+' ')
fid1.write(' REM layers to calc hk diff'+'\n')
fid1.close()
print 'done'
#==============================================================================
def in_fac2real(self,grid=1,pp_file_name='',low_lim=1e-20,upper_lim=1e20):
#==============================================================================
"""
Writes fac2real ini-files ---
Parameters
----------
grid : int
grid number used when running model, see ini file for discretization
pp_file_name : Optional(List((str))
Python list with sufix to fac2real-ini files
low_lim : float
lower value for interpolating values to grid cells. See PEST doc...
for more details
upper_lim : float
upper value for interpolating values to grid cells. See PEST doc...
for more details
"""
for i in range(self.load.n_layer):
if i < self.load.n_cap:
fid1 = open('fac2real_L'+str(i+1)+pp_file_name+'.in','w')
fid1.write('factors_L'+str(i+1)+'.dat'+'\n')
fid1.write('f'+'\n')
if grid == 1:
fid1.write(self.load.model_name_calib+str(i+1)+'.pts'+'\n')
if grid == 2:
fid1.write(pp_file_name+str(i+1)+'.pts'+'\n')
fid1.write('s'+'\n')
fid1.write(str(low_lim)+'\n')
fid1.write('s'+'\n')
fid1.write(str(upper_lim)+'\n')
if grid == 1:
fid1.write(self.load.model_name_calib+str(i+1)+'.ref'+'\n')
if grid == 2:
fid1.write(pp_file_name+str(i+1)+'.ref'+'\n')
fid1.write('1e35'+'\n')
fid1.close()
elif i >= self.load.n_cap:
fid1 = open('fac2real_L'+str(i+1)+pp_file_name+'.in','w')
fid1.write('factors_L'+str(i+1)+'.dat'+'\n')
fid1.write('f'+'\n')
if grid == 1:
fid1.write(self.load.model_name_calib+str(i+1)+'.pts'+'\n')
if grid == 2:
fid1.write(pp_file_name+str(i+1)+'.pts'+'\n')
fid1.write('s'+'\n')
fid1.write('1e-20'+'\n')
fid1.write('s'+'\n')
fid1.write('1e20'+'\n')
if grid == 1:
fid1.write(self.load.model_name_calib+str(i+1)+'.ref'+'\n')
if grid == 2:
fid1.write(pp_file_name+str(i+1)+'.ref'+'\n')
fid1.write('1e35'+'\n')
fid1.close()
print('in_fac2real: done')
#==============================================================================
def in_ppk2fac(self,output_file,model_spc = 'model.spc',struct_file='struct.ini',structure='structure1',grid=1):
#==============================================================================
"""
Writes ini-files for PEST utility ppk2fac.exe
Parameters
----------
output_file : str
String with outputfile name
model_spc : str
pest model specification file
struct_file : str
pest geostatistical structure file
structure: str
geostatistical structure in struct file
grid : int
pilot point discretization to use, read from model_dis.ini
"""
print 'in_ppk2fac: ',
for layer in range(self.load.n_layer):
if layer < self.load.n_cap:
fid1 = open(output_file+str(layer+1)+'.in','w')
fid1.write(model_spc+'\n')
if grid == 1:
fid1.write(self.load.model_name_calib+str(layer+1)+'.pts'+'\n')
elif grid == 2:
fid1.write('a_L'+str(layer+1)+'.pts'+'\n')
fid1.write('0'+'\n')
if self.load.parametrization == -1 or self.load.parametrization == -3:
tmp = self.load.integer_array_name.split('.')
fid1.write(tmp[0]+'_'+str(layer+1)+'.'+tmp[-1]+'\n')
fid1.write(struct_file+'\n')
if self.load.parametrization == -1:
fid1.write(structure+'\n')
fid1.write('o'+'\n')
fid1.write('1e20'+'\n')
fid1.write('1'+'\n')
fid1.write('8'+'\n')
if self.load.parametrization == -3:
for i in range(len(self.load.pp2zone.split(','))+len(self.load.pp2zone_tied.split(','))):
fid1.write(structure+'\n')
fid1.write('o'+'\n')
fid1.write('1e20'+'\n')
fid1.write('1'+'\n')
fid1.write('8'+'\n')
fid1.write('factors_L'+str(layer+1)+'.dat'+'\n')
fid1.write('f'+'\n')
fid1.write('std_L'+str(layer+1)+'.ref'+'\n')
fid1.write('regularisation_L'+str(layer+1)+'.dat'+'\n')
fid1.close()
elif layer >= self.load.n_cap:
fid1 = open(output_file+str(layer+1)+'.in','w')
fid1.write(model_spc+'\n')
if grid == 1:
fid1.write(self.load.model_name_calib+str(layer+1)+'.pts'+'\n')
elif grid == 2:
fid1.write('a_L'+str(layer+1)+'.pts'+'\n')
fid1.write('0'+'\n')
if self.load.parametrization == -1 or self.load.parametrization == -3:
tmp = self.load.integer_array_name.split('.')
fid1.write(tmp[0]+'_'+str(layer+1)+'.'+tmp[-1]+'\n')
fid1.write(struct_file+'\n')
fid1.write(structure+'\n')
fid1.write('o'+'\n')
fid1.write('1e20'+'\n')
fid1.write('1'+'\n')
fid1.write('8'+'\n')
fid1.write('factors_L'+str(layer+1)+'.dat'+'\n')
fid1.write('f'+'\n')
fid1.write('std_L'+str(layer+1)+'.ref'+'\n')
fid1.write('regularisation_L'+str(layer+1)+'.dat'+'\n')
fid1.close()
print ' done'
#==============================================================================
def ins_files_diff(self,output_file,pp_x,pp_y,x_valley,y_valley,left=39,right=63):
#==============================================================================
"""
Writes PEST instructions files for regularization outputfiles
Parameters
----------
output_file : str
Outputfilename
pp_x : List(int)
python list - node positions of pilot points in column direction
pp_y : List(int)
python list - node positions of pilot points in row direction
x_valley : List(int)
python list - node positions of pilot points in column direction
inside the buried valley
y_valley : List(int)
python list - node positions of pilot points in row direction
inside the buried valley
left : int
PEST marker, read from this "left" position to "right"
right : int
PEST marker, read to this "left" position from "left"
"""
print 'ins_files_diff: ',
for layer in range(self.load.n_layer):
fid1 = open(output_file+str(layer+1) +'.ins','w')
fid1.write('pif #\n')
count1 = 1
count2 = 1
if layer < self.load.n_cap:
for i in range(len(pp_x)*len(pp_y)):
fid1.write('l1 [diff_L'+str(layer+1)+'_'+str(count1)+']'+str(left)+':'+str(right)+'\n')
count1 += 1
elif layer >= self.load.n_cap:
for i in range(len(y_valley[layer-self.load.n_cap])):
for j in range(len(x_valley[layer-self.load.n_cap])):
fid1.write('l1 [diff_L'+str(layer+1)+'_'+str(count2)+']'+str(left)+':'+str(right)+'\n')
count2 += 1
else:
print 'Error: ins_files_diff!!!'
fid1.close()
print 'done'
#==============================================================================
def ins_files_head(self,output_file,left=40,right=48,obs_type='_1'):
#==============================================================================
"""
Write PEST instruction file for head observations
Parameters
----------
output_file : str
Outputfilename
left : int
PEST marker, read from this "left" position to "right"
right : int
PEST marker, read to this "left" position from "left"
obs_type : str
default(1), option to put head observations into seperate groups
doing PEST inversion
"""
print 'ins_files_head: ',
fid1 = open(output_file+'.ins','w')
fid1.write('pif #'+'\n')
if obs_type == '_1':
for i in range(self.load.n_well):
fid1.write('l1 [well_'+str(i+1)+obs_type+']'+str(left)+':'+str(right)+'\n')
elif obs_type == '_2':
for i in range(self.load.n_pred_well):
fid1.write('l1 [well_'+str(i+1)+obs_type+']'+str(left)+':'+str(right)+'\n')
fid1.close()
print 'done'
#==============================================================================
def ins_files_tem(self,output_file,pp_x,pp_y,n_tem_data,left=13,right=25):
#==============================================================================
"""
Write PEST instruction file for AarhusInv datafils
Parameters
----------
output_file : str
Outputfilename
pp_x : List(int)
python list - node positions of pilot points in column direction
pp_y : List(int)
python list - node positions of pilot points in row direction
n_tem_data : List(int)
python list. Index holdes number of gates looped over total
number of tem-file.
left : int
PEST marker, read from this "left" position to "right"
right : int
PEST marker, read to this "left" position from "left"
"""
print 'ins_files_tem: ',
# ---writing TEM-instruction fil---
count = 0
self.load
for i in pp_y:
for j in pp_x:
fid1=open(output_file+str(i)+'_'+str(j)+'.ins','w')
fid1.write('pif #\n')
fid1.write('l11 [dbdt_'+str(i)+'_'+str(j)+'_1]'+str(left)+':'+str(right)+'\n')
for h in range(1,n_tem_data[count],1): # number of measurement. See tem-file
fid1.write('l1 [dbdt_'+str(i)+'_'+str(j)+'_'+str(h+1)+']'+str(left)+':'+str(right)+'\n')
count += 1
fid1.close()
print 'done'