forked from pypest/pyemu
-
Notifications
You must be signed in to change notification settings - Fork 7
/
gw_utils.py
2326 lines (1996 loc) · 89.1 KB
/
gw_utils.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
""" module of utilities for groundwater modeling
"""
import os
import copy
import csv
from datetime import datetime
import shutil
import warnings
import numpy as np
import pandas as pd
import re
pd.options.display.max_colwidth = 100
from pyemu.pst.pst_utils import SFMT,IFMT,FFMT,pst_config,_try_run_inschek,\
parse_tpl_file,try_process_ins_file
from pyemu.utils.os_utils import run
from pyemu.utils.helpers import write_df_tpl
from ..pyemu_warnings import PyemuWarning
PP_FMT = {"name": SFMT, "x": FFMT, "y": FFMT, "zone": IFMT, "tpl": SFMT,
"parval1": FFMT}
PP_NAMES = ["name","x","y","zone","parval1"]
def modflow_pval_to_template_file(pval_file,tpl_file=None):
"""write a template file for a modflow parameter value file.
Uses names in the first column in the pval file as par names.
Parameters
----------
pval_file : str
parameter value file
tpl_file : str, optional
template file to write. If None, use <pval_file>.tpl.
Default is None
Returns
-------
df : pandas.DataFrame
pandas DataFrame with control file parameter information
"""
if tpl_file is None:
tpl_file = pval_file + ".tpl"
pval_df = pd.read_csv(pval_file,delim_whitespace=True,
header=None,skiprows=2,
names=["parnme","parval1"])
pval_df.index = pval_df.parnme
pval_df.loc[:,"tpl"] = pval_df.parnme.apply(lambda x: " ~ {0:15s} ~".format(x))
with open(tpl_file,'w') as f:
f.write("ptf ~\n#pval template file from pyemu\n")
f.write("{0:10d} #NP\n".format(pval_df.shape[0]))
f.write(pval_df.loc[:,["parnme","tpl"]].to_string(col_space=0,
formatters=[SFMT,SFMT],
index=False,
header=False,
justify="left"))
return pval_df
def modflow_hob_to_instruction_file(hob_file):
"""write an instruction file for a modflow head observation file
Parameters
----------
hob_file : str
modflow hob file
Returns
-------
df : pandas.DataFrame
pandas DataFrame with control file observation information
"""
hob_df = pd.read_csv(hob_file,delim_whitespace=True,skiprows=1,
header=None,names=["simval","obsval","obsnme"])
hob_df.loc[:,"ins_line"] = hob_df.obsnme.apply(lambda x:"l1 !{0:s}!".format(x))
hob_df.loc[0,"ins_line"] = hob_df.loc[0,"ins_line"].replace('l1','l2')
ins_file = hob_file + ".ins"
f_ins = open(ins_file, 'w')
f_ins.write("pif ~\n")
f_ins.write(hob_df.loc[:,["ins_line"]].to_string(col_space=0,
columns=["ins_line"],
header=False,
index=False,
formatters=[SFMT]) + '\n')
hob_df.loc[:,"weight"] = 1.0
hob_df.loc[:,"obgnme"] = "obgnme"
f_ins.close()
return hob_df
def modflow_hydmod_to_instruction_file(hydmod_file):
"""write an instruction file for a modflow hydmod file
Parameters
----------
hydmod_file : str
modflow hydmod file
Returns
-------
df : pandas.DataFrame
pandas DataFrame with control file observation information
Note
----
calls modflow_read_hydmod_file()
"""
hydmod_df, hydmod_outfile = modflow_read_hydmod_file(hydmod_file)
hydmod_df.loc[:,"ins_line"] = hydmod_df.obsnme.apply(lambda x:"l1 w !{0:s}!".format(x))
ins_file = hydmod_outfile + ".ins"
with open(ins_file, 'w') as f_ins:
f_ins.write("pif ~\nl1\n")
f_ins.write(hydmod_df.loc[:,["ins_line"]].to_string(col_space=0,
columns=["ins_line"],
header=False,
index=False,
formatters=[SFMT]) + '\n')
hydmod_df.loc[:,"weight"] = 1.0
hydmod_df.loc[:,"obgnme"] = "obgnme"
try:
os.system("inschek {0}.ins {0}".format(hydmod_outfile))
except:
print("error running inschek")
obs_obf = hydmod_outfile + ".obf"
if os.path.exists(obs_obf):
df = pd.read_csv(obs_obf,delim_whitespace=True,header=None,names=["obsnme","obsval"])
df.loc[:,"obgnme"] = df.obsnme.apply(lambda x: x[:-9])
df.to_csv("_setup_"+os.path.split(hydmod_outfile)[-1]+'.csv',index=False)
df.index = df.obsnme
return df
return hydmod_df
def modflow_read_hydmod_file(hydmod_file, hydmod_outfile=None):
""" read in a binary hydmod file and return a dataframe of the results
Parameters
----------
hydmod_file : str
modflow hydmod binary file
hydmod_outfile : str
output file to write. If None, use <hydmod_file>.dat.
Default is None
Returns
-------
df : pandas.DataFrame
pandas DataFrame with hymod_file values
Note
----
requires flopy
"""
try:
import flopy.utils as fu
except Exception as e:
print('flopy is not installed - cannot read {0}\n{1}'.format(hydmod_file, e))
return
#print('Starting to read HYDMOD data from {0}'.format(hydmod_file))
obs = fu.HydmodObs(hydmod_file)
hyd_df = obs.get_dataframe()
hyd_df.columns = [i[2:] if i.lower() != 'totim' else i for i in hyd_df.columns]
#hyd_df.loc[:,"datetime"] = hyd_df.index
hyd_df['totim'] = hyd_df.index.map(lambda x: x.strftime("%Y%m%d"))
hyd_df.rename(columns={'totim': 'datestamp'}, inplace=True)
# reshape into a single column
hyd_df = pd.melt(hyd_df, id_vars='datestamp')
hyd_df.rename(columns={'value': 'obsval'}, inplace=True)
hyd_df['obsnme'] = [i.lower() + '_' + j.lower() for i, j in zip(hyd_df.variable, hyd_df.datestamp)]
vc = hyd_df.obsnme.value_counts().sort_values()
vc = list(vc.loc[vc>1].index.values)
if len(vc) > 0:
hyd_df.to_csv("hyd_df.duplciates.csv")
obs.get_dataframe().to_csv("hyd_org.duplicates.csv")
raise Exception("duplicates in obsnme:{0}".format(vc))
#assert hyd_df.obsnme.value_counts().max() == 1,"duplicates in obsnme"
if not hydmod_outfile:
hydmod_outfile = hydmod_file + '.dat'
hyd_df.to_csv(hydmod_outfile, columns=['obsnme','obsval'], sep=' ',index=False)
#hyd_df = hyd_df[['obsnme','obsval']]
return hyd_df[['obsnme','obsval']], hydmod_outfile
def setup_pilotpoints_grid(ml=None,sr=None,ibound=None,prefix_dict=None,
every_n_cell=4,
use_ibound_zones=False,
pp_dir='.',tpl_dir='.',
shapename="pp.shp"):
""" setup regularly-spaced (gridded) pilot point parameterization
Parameters
----------
ml : flopy.mbase
a flopy mbase dervied type. If None, sr must not be None.
sr : flopy.utils.reference.SpatialReference
a spatial reference use to locate the model grid in space. If None,
ml must not be None. Default is None
ibound : numpy.ndarray
the modflow ibound integer array. Used to set pilot points only in active areas.
If None and ml is None, then pilot points are set in all rows and columns according to
every_n_cell. Default is None.
prefix_dict : dict
a dictionary of pilot point parameter prefix, layer pairs. example : {"hk":[0,1,2,3]} would
setup pilot points with the prefix "hk" for model layers 1 - 4 (zero based). If None, a generic set
of pilot points with the "pp" prefix are setup for a generic nrowXncol grid. Default is None
use_ibound_zones : bool
a flag to use the greater-than-zero values in the ibound as pilot point zones. If False,ibound
values greater than zero are treated as a single zone. Default is False.
pp_dir : str
directory to write pilot point files to. Default is '.'
tpl_dir : str
directory to write pilot point template file to. Default is '.'
shapename : str
name of shapefile to write that containts pilot point information. Default is "pp.shp"
Returns
-------
pp_df : pandas.DataFrame
a dataframe summarizing pilot point information (same information
written to shapename
"""
from . import pp_utils
warnings.warn("setup_pilotpoint_grid has moved to pp_utils...",PyemuWarning)
return pp_utils.setup_pilotpoints_grid(ml=ml,sr=sr,ibound=ibound,
prefix_dict=prefix_dict,
every_n_cell=every_n_cell,
use_ibound_zones=use_ibound_zones,
pp_dir=pp_dir,tpl_dir=tpl_dir,
shapename=shapename)
def pp_file_to_dataframe(pp_filename):
from . import pp_utils
warnings.warn("pp_file_to_dataframe has moved to pp_utils",PyemuWarning)
return pp_utils.pp_file_to_dataframe(pp_filename)
def pp_tpl_to_dataframe(tpl_filename):
from . import pp_utils
warnings.warn("pp_tpl_to_dataframe has moved to pp_utils",PyemuWarning)
return pp_utils.pp_tpl_to_dataframe(tpl_filename)
def write_pp_shapfile(pp_df,shapename=None):
from . import pp_utils
warnings.warn("write_pp_shapefile has moved to pp_utils",PyemuWarning)
pp_utils.write_pp_shapfile(pp_df,shapename=shapename)
def write_pp_file(filename,pp_df):
from . import pp_utils
warnings.warn("write_pp_file has moved to pp_utils",PyemuWarning)
return pp_utils.write_pp_file(filename,pp_df)
def pilot_points_to_tpl(pp_file,tpl_file=None,name_prefix=None):
from . import pp_utils
warnings.warn("pilot_points_to_tpl has moved to pp_utils",PyemuWarning)
return pp_utils.pilot_points_to_tpl(pp_file,tpl_file=tpl_file,
name_prefix=name_prefix)
def fac2real(pp_file=None,factors_file="factors.dat",out_file="test.ref",
upper_lim=1.0e+30,lower_lim=-1.0e+30,fill_value=1.0e+30):
from . import geostats as gs
warnings.warn("fac2real has moved to geostats",PyemuWarning)
return gs.fac2real(pp_file=pp_file,factors_file=factors_file,
out_file=out_file,upper_lim=upper_lim,
lower_lim=lower_lim,fill_value=fill_value)
def setup_mtlist_budget_obs(list_filename,gw_filename="mtlist_gw.dat",sw_filename="mtlist_sw.dat",
start_datetime="1-1-1970",gw_prefix='gw',sw_prefix="sw",
save_setup_file=False):
""" setup observations of gw (and optionally sw) mass budgets from mt3dusgs list file. writes
an instruction file and also a _setup_.csv to use when constructing a pest
control file
Parameters
----------
list_filename : str
modflow list file
gw_filename : str
output filename that will contain the gw budget observations. Default is
"mtlist_gw.dat"
sw_filename : str
output filename that will contain the sw budget observations. Default is
"mtlist_sw.dat"
start_datetime : str
an str that can be parsed into a pandas.TimeStamp. used to give budget
observations meaningful names
gw_prefix : str
a prefix to add to the GW budget observations. Useful if processing
more than one list file as part of the forward run process. Default is 'gw'.
sw_prefix : str
a prefix to add to the SW budget observations. Useful if processing
more than one list file as part of the forward run process. Default is 'sw'.
save_setup_file : (boolean)
a flag to save _setup_<list_filename>.csv file that contains useful
control file information
Returns
-------
frun_line, ins_filenames, df :str, list(str), pandas.DataFrame
the command to add to the forward run script, the names of the instruction
files and a dataframe with information for constructing a control file. If INSCHEK fails
to run, df = None
Note
----
This function uses INSCHEK to get observation values; the observation values are
the values of the list file list_filename. If INSCHEK fails to run, the obseravtion
values are set to 1.0E+10
the instruction files are named <out_filename>.ins
It is recommended to use the default value for gw_filename or sw_filename.
"""
gw,sw = apply_mtlist_budget_obs(list_filename, gw_filename, sw_filename, start_datetime)
gw_ins = gw_filename + ".ins"
_write_mtlist_ins(gw_ins, gw, gw_prefix)
ins_files = [gw_ins]
try:
run("inschek {0}.ins {0}".format(gw_filename))
except:
print("error running inschek")
if sw is not None:
sw_ins = sw_filename + ".ins"
_write_mtlist_ins(sw_ins, sw, sw_prefix)
ins_files.append(sw_ins)
try:
run("inschek {0}.ins {0}".format(sw_filename))
except:
print("error running inschek")
frun_line = "pyemu.gw_utils.apply_mtlist_budget_obs('{0}')".format(list_filename)
gw_obf = gw_filename + ".obf"
df_gw = None
if os.path.exists(gw_obf):
df_gw = pd.read_csv(gw_obf, delim_whitespace=True, header=None, names=["obsnme", "obsval"])
df_gw.loc[:, "obgnme"] = df_gw.obsnme.apply(lambda x: x[:-9])
sw_obf = sw_filename + ".obf"
if os.path.exists(sw_obf):
df_sw = pd.read_csv(sw_obf, delim_whitespace=True, header=None, names=["obsnme", "obsval"])
df_sw.loc[:, "obgnme"] = df_sw.obsnme.apply(lambda x: x[:-9])
df_gw = df_gw.append(df_sw)
if save_setup_file:
df_gw.to_csv("_setup_" + os.path.split(list_filename)[-1] + '.csv', index=False)
df_gw.index = df_gw.obsnme
return frun_line,ins_files,df_gw
def _write_mtlist_ins(ins_filename,df,prefix):
""" write an instruction file for a MODFLOW list file
Parameters
----------
ins_filename : str
name of the instruction file to write
df : pandas.DataFrame
the dataframe of list file entries
prefix : str
the prefix to add to the column names to form
obseravtions names
"""
try:
dt_str = df.index.map(lambda x: x.strftime("%Y%m%d"))
except:
dt_str = df.index.map(lambda x: "{0:08.1f}".format(x).strip())
if prefix == '':
name_len = 11
else:
name_len = 11 - (len(prefix)+1)
with open(ins_filename,'w') as f:
f.write('pif ~\nl1\n')
for dt in dt_str:
f.write("l1 ")
for col in df.columns:
col = col.replace("(",'').replace(")",'')
raw = col.split('_')
name = ''.join([r[:2] for r in raw[:-2]])[:6] + raw[-2] + raw[-1][0]
#raw[0] = raw[0][:6]
#name = ''.join(raw)
if prefix == '':
obsnme = "{1}_{2}".format(prefix,name[:name_len],dt)
else:
obsnme = "{0}_{1}_{2}".format(prefix, name[:name_len], dt)
f.write(" w !{0}!".format(obsnme))
f.write("\n")
def apply_mtlist_budget_obs(list_filename,gw_filename="mtlist_gw.dat",
sw_filename="mtlist_sw.dat",
start_datetime="1-1-1970"):
""" process an MT3D list file to extract mass budget entries.
Parameters
----------
list_filename : str
the mt3d list file
gw_filename : str
the name of the output file with gw mass budget information.
Default is "mtlist_gw.dat"
sw_filename : str
the name of the output file with sw mass budget information.
Default is "mtlist_sw.dat"
start_datatime : str
an str that can be cast to a pandas.TimeStamp. Used to give
observations a meaningful name
Returns
-------
gw : pandas.DataFrame
the gw mass dataframe
sw : pandas.DataFrame (optional)
the sw mass dataframe
Note
----
requires flopy
if SFT is not active, no SW mass budget will be returned
"""
try:
import flopy
except Exception as e:
raise Exception("error import flopy: {0}".format(str(e)))
mt = flopy.utils.MtListBudget(list_filename)
gw, sw = mt.parse(start_datetime=start_datetime, diff=True)
gw = gw.drop([col for col in gw.columns
for drop_col in ["kper", "kstp", "tkstp"]
if (col.lower().startswith(drop_col))], axis=1)
gw.to_csv(gw_filename, sep=' ', index_label="datetime", date_format="%Y%m%d")
if sw is not None:
sw = sw.drop([col for col in sw.columns
for drop_col in ["kper", "kstp", "tkstp"]
if (col.lower().startswith(drop_col))], axis=1)
sw.to_csv(sw_filename, sep=' ', index_label="datetime", date_format="%Y%m%d")
return gw, sw
def setup_mflist_budget_obs(list_filename,flx_filename="flux.dat",
vol_filename="vol.dat",start_datetime="1-1'1970",prefix='',
save_setup_file=False):
""" setup observations of budget volume and flux from modflow list file. writes
an instruction file and also a _setup_.csv to use when constructing a pest
control file
Parameters
----------
list_filename : str
modflow list file
flx_filename : str
output filename that will contain the budget flux observations. Default is
"flux.dat"
vol_filename : str)
output filename that will contain the budget volume observations. Default
is "vol.dat"
start_datetime : str
an str that can be parsed into a pandas.TimeStamp. used to give budget
observations meaningful names
prefix : str
a prefix to add to the water budget observations. Useful if processing
more than one list file as part of the forward run process. Default is ''.
save_setup_file : (boolean)
a flag to save _setup_<list_filename>.csv file that contains useful
control file information
Returns
-------
df : pandas.DataFrame
a dataframe with information for constructing a control file. If INSCHEK fails
to run, reutrns None
Note
----
This function uses INSCHEK to get observation values; the observation values are
the values of the list file list_filename. If INSCHEK fails to run, the obseravtion
values are set to 1.0E+10
the instruction files are named <flux_file>.ins and <vol_file>.ins, respectively
It is recommended to use the default values for flux_file and vol_file.
"""
flx,vol = apply_mflist_budget_obs(list_filename,flx_filename,vol_filename,
start_datetime)
_write_mflist_ins(flx_filename+".ins",flx,prefix+"flx")
_write_mflist_ins(vol_filename+".ins",vol, prefix+"vol")
#run("inschek {0}.ins {0}".format(flx_filename))
#run("inschek {0}.ins {0}".format(vol_filename))
try:
#os.system("inschek {0}.ins {0}".format(flx_filename))
#os.system("inschek {0}.ins {0}".format(vol_filename))
run("inschek {0}.ins {0}".format(flx_filename))
run("inschek {0}.ins {0}".format(vol_filename))
except:
print("error running inschek")
return None
flx_obf = flx_filename+".obf"
vol_obf = vol_filename + ".obf"
if os.path.exists(flx_obf) and os.path.exists(vol_obf):
df = pd.read_csv(flx_obf,delim_whitespace=True,header=None,names=["obsnme","obsval"])
df.loc[:,"obgnme"] = df.obsnme.apply(lambda x: x[:-9])
df2 = pd.read_csv(vol_obf, delim_whitespace=True, header=None, names=["obsnme", "obsval"])
df2.loc[:, "obgnme"] = df2.obsnme.apply(lambda x: x[:-9])
df = df.append(df2)
if save_setup_file:
df.to_csv("_setup_"+os.path.split(list_filename)[-1]+'.csv',index=False)
df.index = df.obsnme
return df
def apply_mflist_budget_obs(list_filename,flx_filename="flux.dat",
vol_filename="vol.dat",
start_datetime="1-1-1970"):
""" process a MODFLOW list file to extract flux and volume water budget entries.
Parameters
----------
list_filename : str
the modflow list file
flx_filename : str
the name of the output file with water budget flux information.
Default is "flux.dat"
vol_filename : str
the name of the output file with water budget volume information.
Default is "vol.dat"
start_datatime : str
an str that can be cast to a pandas.TimeStamp. Used to give
observations a meaningful name
Returns
-------
flx : pandas.DataFrame
the flux dataframe
vol : pandas.DataFrame
the volume dataframe
Note
----
requires flopy
"""
try:
import flopy
except Exception as e:
raise Exception("error import flopy: {0}".format(str(e)))
mlf = flopy.utils.MfListBudget(list_filename)
flx,vol = mlf.get_dataframes(start_datetime=start_datetime,diff=True)
flx.to_csv(flx_filename,sep=' ',index_label="datetime",date_format="%Y%m%d")
vol.to_csv(vol_filename,sep=' ',index_label="datetime",date_format="%Y%m%d")
return flx,vol
def _write_mflist_ins(ins_filename,df,prefix):
""" write an instruction file for a MODFLOW list file
Parameters
----------
ins_filename : str
name of the instruction file to write
df : pandas.DataFrame
the dataframe of list file entries
prefix : str
the prefix to add to the column names to form
obseravtions names
"""
dt_str = df.index.map(lambda x: x.strftime("%Y%m%d"))
name_len = 11 - (len(prefix)+1)
with open(ins_filename,'w') as f:
f.write('pif ~\nl1\n')
for dt in dt_str:
f.write("l1 ")
for col in df.columns:
obsnme = "{0}_{1}_{2}".format(prefix,col[:name_len],dt)
f.write(" w !{0}!".format(obsnme))
f.write("\n")
def setup_hds_timeseries(hds_file,kij_dict,prefix=None,include_path=False,
model=None, postprocess_inact=None):
"""a function to setup extracting time-series from a binary modflow
head save (or equivalent format - ucn, sub, etc). Writes
an instruction file and a _set_ csv
Parameters
----------
hds_file : str
binary filename
kij_dict : dict
dictionary of site_name: [k,i,j] pairs
prefix : str
string to prepend to site_name when forming obsnme's. Default is None
include_path : bool
flag to prepend hds_file path. Useful for setting up
process in separate directory for where python is running.
model : flopy.mbase
a flopy model. If passed, the observation names will have the datetime of the
observation appended to them. If None, the observation names will have the
stress period appended to them. Default is None.
postprocess_inact : float
Inactive flag in heads/ucn file e.g. mt.btn.cinit
Returns
-------
Note
----
This function writes hds_timeseries.config that must be in the same
dir where apply_hds_timeseries() is called during the forward run
assumes model time units are days!!!
"""
try:
import flopy
except Exception as e:
print("error importing flopy, returning {0}".format(str(e)))
return
assert os.path.exists(hds_file),"head save file not found"
if hds_file.lower().endswith(".ucn"):
try:
hds = flopy.utils.UcnFile(hds_file)
except Exception as e:
raise Exception("error instantiating UcnFile:{0}".format(str(e)))
else:
try:
hds = flopy.utils.HeadFile(hds_file)
except Exception as e:
raise Exception("error instantiating HeadFile:{0}".format(str(e)))
nlay,nrow,ncol = hds.nlay,hds.nrow,hds.ncol
#if include_path:
# pth = os.path.join(*[p for p in os.path.split(hds_file)[:-1]])
# config_file = os.path.join(pth,"{0}_timeseries.config".format(hds_file))
#else:
config_file = "{0}_timeseries.config".format(hds_file)
print("writing config file to {0}".format(config_file))
f_config = open(config_file,'w')
if model is not None:
if model.dis.itmuni != 4:
warnings.warn("setup_hds_timeseries only supports 'days' time units...",PyemuWarning)
f_config.write("{0},{1},d\n".format(os.path.split(hds_file)[-1],model.start_datetime))
start = pd.to_datetime(model.start_datetime)
else:
f_config.write("{0},none,none\n".format(os.path.split(hds_file)[-1]))
f_config.write("site,k,i,j\n")
dfs = []
for site,(k,i,j) in kij_dict.items():
assert k >= 0 and k < nlay, k
assert i >= 0 and i < nrow, i
assert j >= 0 and j < ncol, j
site = site.lower().replace(" ",'')
df = pd.DataFrame(data=hds.get_ts((k,i,j)),columns=["totim",site])
if model is not None:
dts = start + pd.to_timedelta(df.totim,unit='d')
df.loc[:,"totim"] = dts
#print(df)
f_config.write("{0},{1},{2},{3}\n".format(site,k,i,j))
df.index = df.pop("totim")
dfs.append(df)
f_config.close()
df = pd.concat(dfs,axis=1)
df.to_csv(hds_file+"_timeseries.processed",sep=' ')
if model is not None:
t_str = df.index.map(lambda x: x.strftime("%Y%m%d"))
else:
t_str = df.index.map(lambda x: "{0:08.2f}".format(x))
ins_file = hds_file+"_timeseries.processed.ins"
print("writing instruction file to {0}".format(ins_file))
with open(ins_file,'w') as f:
f.write('pif ~\n')
f.write("l1 \n")
for t in t_str:
f.write("l1 w ")
for site in df.columns:
if prefix is not None:
obsnme = "{0}_{1}_{2}".format(prefix,site,t)
else:
obsnme = "{0}_{1}".format(site, t)
f.write(" !{0}!".format(obsnme))
f.write('\n')
if postprocess_inact is not None:
_setup_postprocess_hds_timeseries(hds_file, df, config_file, prefix=prefix, model=model)
bd = '.'
if include_path:
bd = os.getcwd()
pth = os.path.join(*[p for p in os.path.split(hds_file)[:-1]])
os.chdir(pth)
config_file = os.path.split(config_file)[-1]
try:
df = apply_hds_timeseries(config_file, postprocess_inact=postprocess_inact)
except Exception as e:
os.chdir(bd)
raise Exception("error in apply_hds_timeseries(): {0}".format(str(e)))
os.chdir(bd)
#df = _try_run_inschek(ins_file,ins_file.replace(".ins",""))
df = try_process_ins_file(ins_file,ins_file.replace(".ins",""))
if df is not None:
df.loc[:,"weight"] = 0.0
if prefix is not None:
df.loc[:,"obgnme"] = df.index.map(lambda x: '_'.join(x.split('_')[:2]))
else:
df.loc[:, "obgnme"] = df.index.map(lambda x: x.split('_')[0])
frun_line = "pyemu.gw_utils.apply_hds_timeseries('{0}',{1})\n".format(config_file, postprocess_inact)
return frun_line,df
def apply_hds_timeseries(config_file=None, postprocess_inact=None):
import flopy
if config_file is None:
config_file = "hds_timeseries.config"
assert os.path.exists(config_file), config_file
with open(config_file,'r') as f:
line = f.readline()
hds_file,start_datetime,time_units = line.strip().split(',')
site_df = pd.read_csv(f)
#print(site_df)
assert os.path.exists(hds_file), "head save file not found"
if hds_file.lower().endswith(".ucn"):
try:
hds = flopy.utils.UcnFile(hds_file)
except Exception as e:
raise Exception("error instantiating UcnFile:{0}".format(str(e)))
else:
try:
hds = flopy.utils.HeadFile(hds_file)
except Exception as e:
raise Exception("error instantiating HeadFile:{0}".format(str(e)))
nlay, nrow, ncol = hds.nlay, hds.nrow, hds.ncol
dfs = []
for site,k,i,j in zip(site_df.site,site_df.k,site_df.i,site_df.j):
assert k >= 0 and k < nlay
assert i >= 0 and i < nrow
assert j >= 0 and j < ncol
df = pd.DataFrame(data=hds.get_ts((k,i,j)),columns=["totim",site])
df.index = df.pop("totim")
dfs.append(df)
df = pd.concat(dfs,axis=1)
#print(df)
df.to_csv(hds_file+"_timeseries.processed",sep=' ')
if postprocess_inact is not None:
_apply_postprocess_hds_timeseries(config_file, postprocess_inact)
return df
def _setup_postprocess_hds_timeseries(hds_file, df, config_file, prefix=None, model=None):
"""Dirty function to post process concentrations in inactive/dry cells"""
warnings.warn(
"Setting up post processing of hds or ucn timeseries obs. "
"Prepending 'pp' to obs name may cause length to exceed 20 chars", PyemuWarning)
if model is not None:
t_str = df.index.map(lambda x: x.strftime("%Y%m%d"))
else:
t_str = df.index.map(lambda x: "{0:08.2f}".format(x))
if prefix is not None:
prefix = "pp{0}".format(prefix)
else:
prefix = "pp"
ins_file = hds_file+"_timeseries.post_processed.ins"
print("writing instruction file to {0}".format(ins_file))
with open(ins_file,'w') as f:
f.write('pif ~\n')
f.write("l1 \n")
for t in t_str:
f.write("l1 w ")
for site in df.columns:
obsnme = "{0}{1}_{2}".format(prefix, site, t)
f.write(" !{0}!".format(obsnme))
f.write('\n')
frun_line = "pyemu.gw_utils._apply_postprocess_hds_timeseries('{0}')\n".format(config_file)
return frun_line
def _apply_postprocess_hds_timeseries(config_file=None, cinact=1e30):
import flopy
if config_file is None:
config_file = "hds_timeseries.config"
assert os.path.exists(config_file), config_file
with open(config_file,'r') as f:
line = f.readline()
hds_file,start_datetime,time_units = line.strip().split(',')
site_df = pd.read_csv(f)
#print(site_df)
assert os.path.exists(hds_file), "head save file not found"
if hds_file.lower().endswith(".ucn"):
try:
hds = flopy.utils.UcnFile(hds_file)
except Exception as e:
raise Exception("error instantiating UcnFile:{0}".format(str(e)))
else:
try:
hds = flopy.utils.HeadFile(hds_file)
except Exception as e:
raise Exception("error instantiating HeadFile:{0}".format(str(e)))
nlay, nrow, ncol = hds.nlay, hds.nrow, hds.ncol
dfs = []
for site, k, i, j in zip(site_df.site, site_df.k, site_df.i, site_df.j):
assert k >= 0 and k < nlay
assert i >= 0 and i < nrow
assert j >= 0 and j < ncol
df = pd.DataFrame(data=hds.get_ts((k, i, j)), columns=["totim", site])
df.index = df.pop("totim")
inact_obs = df[site].apply(lambda x: np.isclose(x, cinact))
if inact_obs.sum() > 0:
assert k+1 < nlay, "Inactive observation in lowest layer"
df_lower = pd.DataFrame(data=hds.get_ts((k+1, i, j)), columns=["totim", site])
df_lower.index = df_lower.pop("totim")
df.loc[inact_obs] = df_lower.loc[inact_obs]
print("{0} observation(s) post-processed for site {1} at kij ({2},{3},{4})".
format(inact_obs.sum(), site, k, i, j))
dfs.append(df)
df = pd.concat(dfs, axis=1)
#print(df)
df.to_csv(hds_file+"_timeseries.post_processed", sep=' ')
return df
def setup_hds_obs(hds_file,kperk_pairs=None,skip=None,prefix="hds"):
"""a function to setup using all values from a
layer-stress period pair for observations. Writes
an instruction file and a _setup_ csv used
construct a control file.
Parameters
----------
hds_file : str
a MODFLOW head-save file. If the hds_file endswith 'ucn',
then the file is treated as a UcnFile type.
kperk_pairs : iterable
an iterable of pairs of kper (zero-based stress
period index) and k (zero-based layer index) to
setup observations for. If None, then a shit-ton
of observations may be produced!
skip : variable
a value or function used to determine which values
to skip when setting up observations. If np.scalar(skip)
is True, then values equal to skip will not be used.
If skip can also be a np.ndarry with dimensions equal to the model.
Obscervations are set up only for cells with Non-zero values in the array.
If not np.ndarray or np.scalar(skip), then skip will be treated as a lambda function that
returns np.NaN if the value should be skipped.
prefix : str
the prefix to use for the observation names. default is "hds".
Returns
-------
(forward_run_line, df) : str, pd.DataFrame
a python code str to add to the forward run script and the setup info for the observations
Note
----
requires flopy
writes <hds_file>.dat.ins instruction file
writes _setup_<hds_file>.csv which contains much
useful information for construction a control file
"""
try:
import flopy
except Exception as e:
print("error importing flopy, returning {0}".format(str(e)))
return
assert os.path.exists(hds_file),"head save file not found"
if hds_file.lower().endswith(".ucn"):
try:
hds = flopy.utils.UcnFile(hds_file)
except Exception as e:
raise Exception("error instantiating UcnFile:{0}".format(str(e)))
else:
try:
hds = flopy.utils.HeadFile(hds_file)
except Exception as e:
raise Exception("error instantiating HeadFile:{0}".format(str(e)))
if kperk_pairs is None:
kperk_pairs = []
for kstp,kper in hds.kstpkper:
kperk_pairs.extend([(kper-1,k) for k in range(hds.nlay)])
if len(kperk_pairs) == 2:
try:
if len(kperk_pairs[0]) == 2:
pass
except:
kperk_pairs = [kperk_pairs]
#if start_datetime is not None:
# start_datetime = pd.to_datetime(start_datetime)
# dts = start_datetime + pd.to_timedelta(hds.times,unit='d')
data = {}
kpers = [kper-1 for kstp,kper in hds.kstpkper]
for kperk_pair in kperk_pairs:
kper,k = kperk_pair
assert kper in kpers, "kper not in hds:{0}".format(kper)
assert k in range(hds.nlay), "k not in hds:{0}".format(k)
kstp = last_kstp_from_kper(hds,kper)
d = hds.get_data(kstpkper=(kstp,kper))[k,:,:]
data["{0}_{1}".format(kper,k)] = d.flatten()
#data[(kper,k)] = d.flatten()
idx,iidx,jidx = [],[],[]
for _ in range(len(data)):
for i in range(hds.nrow):
iidx.extend([i for _ in range(hds.ncol)])
jidx.extend([j for j in range(hds.ncol)])
idx.extend(["i{0:04d}_j{1:04d}".format(i,j) for j in range(hds.ncol)])
idx = idx[:hds.nrow*hds.ncol]
df = pd.DataFrame(data,index=idx)
data_cols = list(df.columns)
data_cols.sort()
#df.loc[:,"iidx"] = iidx
#df.loc[:,"jidx"] = jidx
if skip is not None:
for col in data_cols:
if np.isscalar(skip):
df.loc[df.loc[:,col]==skip,col] = np.NaN
elif isinstance(skip, np.ndarray):
assert skip.ndim >= 2, "skip passed as {}D array, At least 2D (<= 4D) array required".format(skip.ndim)
assert skip.shape[-2:] == (hds.nrow, hds.ncol), \
"Array dimensions of arg. skip needs to match model dimensions ({0},{1}). ({2},{3}) passed".\
format(hds.nrow, hds.ncol, skip.shape[-2], skip.shape[-1])
if skip.ndim == 2:
print("2D array passed for skip, assuming constant for all layers and kper")
skip = np.tile(skip, (len(kpers), hds.nlay, 1, 1))
if skip.ndim == 3:
print("3D array passed for skip, assuming constant for all kper")
skip = np.tile(skip, (len(kpers), 1, 1, 1))
kper, k = [int(c) for c in col.split('_')]
df.loc[df.index.map(
lambda x: skip[kper, k, int(x.split('_')[0].strip('i')), int(x.split('_')[1].strip('j'))] == 0),
col] = np.NaN
else:
df.loc[:,col] = df.loc[:,col].apply(skip)
# melt to long form
df = df.melt(var_name="kperk",value_name="obsval")
# set row and col identifies
df.loc[:,"iidx"] = iidx
df.loc[:,"jidx"] = jidx
#drop nans from skip
df = df.dropna()
#set some additional identifiers