/
mfsimulation.py
1886 lines (1647 loc) · 76.8 KB
/
mfsimulation.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
"""mfsimulation module. contains the MFSimulation class."""
import errno
import sys
import inspect
import collections
import os.path
from ...mbase import run_model
from ..mfbase import PackageContainer, MFFileMgmt, ExtFileAction, \
PackageContainerType, MFDataException, FlopyException, \
VerbosityLevel
from ..mfpackage import MFPackage
from ..data.mfstructure import DatumType
from ..data import mfstructure
from ..utils import binaryfile_utils
from ..utils import mfobservation
from ..modflow import mfnam, mfims, mftdis, mfgwfgnc, mfgwfmvr
from ..data.mfdatautil import MFComment
class SimulationDict(collections.OrderedDict):
"""Class containing custom dictionary for MODFLOW simulations.
Behaves as an OrderedDict with some additional features described below.
Parameters
----------
path : MFFileMgmt
object containing path information for the simulation
Methods
-------
find_in_path : (key_path : string, key_leaf : string) : MFData, int
attempt to find key_leaf in a partial key path key_path
output_keys : (print_keys : boolean) : list
return a list of output data keys the dictionary supports for output
data, print_keys allows those keys to be printed to output.
input_keys : ()
print all input data keys
observation_keys : ()
print observation keys
keys : ()
print all keys, input and output
plot : (key : string, **kwargs)
plot data with key 'key' using **kwargs for plot options
shapefile : (key : string, **kwargs)
create shapefile from data with key 'key' and with additional fields
in **kwargs
rename_all_packages : (name : string)
rename all packages in the simulation and associated models
"""
def __init__(self, path=None):
"""Define the __init__ method.
Parameters:
path (string): File-like path used as dictionary key
"""
collections.OrderedDict.__init__(self)
self._path = path
def __getitem__(self, key):
"""Define the __getitem__ magic method.
Parameters:
key (string): Part or all of a dictionary key
Returns:
MFData or numpy.ndarray
"""
if key == '_path' or not hasattr(self, '_path'):
raise AttributeError(key)
# FIX: Transport - Include transport output files
if key[1] in ('CBC', 'HDS', 'DDN', 'UCN'):
val = binaryfile_utils.MFOutput(self, self._path, key)
return val.data
elif key[-1] == 'Observations':
val = mfobservation.MFObservation(self, self._path, key)
return val.data
if key in self:
val = collections.OrderedDict.__getitem__(self, key)
return val
return AttributeError(key)
def __setitem__(self, key, val):
"""Define the __setitem__ magic method.
Parameters:
key (string): Dictionary key
val (MFData): MFData to store in dictionary
"""
collections.OrderedDict.__setitem__(self, key, val)
def find_in_path(self, key_path, key_leaf):
"""Attempt to find key_leaf in a partial key path key_path.
Parameters:
key_path (string): partial path to the data
key_leaf (string): name of the data
Returns:
MFData: Data found at the path.
int: Data index
"""
key_path_size = len(key_path)
for key, item in self.items():
if key[:key_path_size] == key_path:
if key[-1] == key_leaf:
# found key_leaf as a key in the dictionary
return item, None
if not isinstance(item, MFComment):
data_item_index = 0
data_item_structures = item.structure.data_item_structures
for data_item_struct in data_item_structures:
if data_item_struct.name == key_leaf:
# found key_leaf as a data item name in the data in
# the dictionary
return item, data_item_index
if data_item_struct.type != DatumType.keyword:
data_item_index += 1
return None, None
def output_keys(self, print_keys=True):
"""Return a list of output data keys.
Parameters:
print_keys (bool): print keys to console
Returns:
list: keys for requesting binary output
"""
# get keys to request binary output
x = binaryfile_utils.MFOutputRequester.getkeys(self, self._path,
print_keys=print_keys)
return [key for key in x.dataDict]
def input_keys(self):
"""Return a list of input data keys.
Returns:
list: input data keys
"""
# get keys to request input ie. package data
for key in self:
print(key)
def observation_keys(self):
"""Return a list of observation keys.
Returns:
list: observation keys
"""
# get keys to request observation file output
mfobservation.MFObservationRequester.getkeys(self, self._path)
def keys(self):
"""Return a list of all keys.
Returns:
list: all keys
"""
# overrides the built in keys to print all keys, input and output
self.input_keys()
try:
self.output_keys()
except OSError as e:
if e.errno == errno.EEXIST:
pass
try:
self.observation_keys()
except KeyError:
pass
class MFSimulationData(object):
"""Class containing MODFLOW simulation data and file formatting data.
Parameters
----------
path : string
path on disk to the simulation
Attributes
----------
indent_string : string
string used to define how much indent to use (file formatting)
internal_formatting : list
list defining string to use for internal formatting
external_formatting : list
list defining string to use for external formatting
open_close_formatting : list
list defining string to use for open/close
max_columns_of_data : int
maximum columns of data before line wraps
wrap_multidim_arrays : bool
whether to wrap line for multi-dimensional arrays at the end of a
row/column/layer
float_precision : int
number of decimal points to write for a floating point number
float_characters : int
number of characters a floating point number takes up
sci_note_upper_thres : float
numbers greater than this threshold are written in scientific notation
sci_note_lower_thres : float
numbers less than this threshold are written in scientific notation
mfpath : MFFileMgmt
file path location information for the simulation
model_dimensions : OrderedDict
dictionary containing discretization information for each model
mfdata : SimulationDict
custom dictionary containing all model data for the simulation
"""
def __init__(self, path):
"""Define the __init__ method.
Parameters:
path (string): File-like path to simulation
"""
# --- formatting variables ---
self.indent_string = ' '
self.constant_formatting = ['constant', '']
self.max_columns_of_data = 20
self.wrap_multidim_arrays = True
self.float_precision = 8
self.float_characters = 15
self._sci_note_upper_thres = 100000
self._sci_note_lower_thres = 0.001
self.fast_write = True
self.comments_on = False
self.auto_set_sizes = True
self.verify_data = True
self.debug = False
self.verbose = True
self.verbosity_level = VerbosityLevel.normal
self._update_str_format()
# --- file path ---
self.mfpath = MFFileMgmt(path)
# --- ease of use variables to make working with modflow input and
# output data easier --- model dimension class for each model
self.model_dimensions = collections.OrderedDict()
# --- model data ---
self.mfdata = SimulationDict(self.mfpath)
# --- temporary variables ---
# other external files referenced
self.referenced_files = collections.OrderedDict()
def set_sci_note_upper_thres(self, value):
"""Set threshold number.
Sets threshold number where any number larger than threshold
is represented in scientific notation.
Parameters:
value (float): threshold value
"""
self._sci_note_upper_thres = value
self._update_str_format()
def set_sci_note_lower_thres(self, value):
"""Set threshold number.
Sets threshold number where any number smaller than threshold
is represented in scientific notation.
Parameters:
value (float): threshold value
"""
self._sci_note_lower_thres = value
self._update_str_format()
def _update_str_format(self):
"""Update floating point formatting strings."""
self.reg_format_str = '{:.%dE}' % \
self.float_precision
self.sci_format_str = '{:%d.%df' \
'}' % (self.float_characters,
self.float_precision)
class MFSimulation(PackageContainer):
"""Entry point into any MODFLOW simulation.
MFSimulation is used to load, build, and/or save a MODFLOW6 simulation.
Parameters
----------
sim_name : string
name of the simulation.
version : string
MODFLOW version
exe_name : string
relative path to MODFLOW executable from the simulation working folder
sim_ws : string
path to simulation working folder
verbosity_level : int
verbosity level of standard output
0 : no standard output
1 : standard error/warning messages with some informational
messages
2 : verbose mode with full error/warning/informational messages.
this is ideal for debugging
continue_ : bool
sets the continue option in the simulation name file. the continue
option is a keyword flag to indicate that the simulation should
continue even if one or more solutions do not converge.
nocheck : bool
sets the nocheck option in the simulation name file. the nocheck
option is a keyword flag to indicate that the model input check
routines should not be called prior to each time step. checks
are performed by default.
memory_print_option : str
sets memory_print_option in the simulation name file.
memory_print_option is a flag that controls printing of detailed
memory manager usage to the end of the simulation list file. NONE
means do not print detailed information. SUMMARY means print only
the total memory for each simulation component. ALL means print
information for each variable stored in the memory manager. NONE is
default if memory_print_option is not specified.
Attributes
----------
sim_name : string
name of the simulation
_models : OrderedDict
all models in the simulation
_exchange_files : list
all exchange packages in the simulation
_ims_files : list
all ims packages in the simulation
name_file : MFPackage
simulation name file
_tdis_file
simulation tdis file
sim_package_list
list of all "simulation level" packages
Methods
-------
load : (sim_name : string, version : string, exe_name : string,
sim_ws : string, strict : boolean,
verbosity_level : VerbosityLevel) :
MFSimulation
a class method that loads a simulation from files
write_simulation
writes the simulation to files
set_sim_path : (path : string)
set the file path to the root simulation folder and updates all model
file paths
get_model : (model_name : string)
: [MFModel]
returns the models in the simulation with a given model name, name file
name, or model type
add_model : (model : MFModel, sln_group : integer)
add model to the simulation
remove_model : (model_name : string)
remove model from the simulation
get_package : (type : string)
returns a simulation package based on package type
add_package : (package : MFPackage)
adds a simulation package to the simulation
remove_package : (package_name : string)
removes package from the simulation. package_name can be the
package's name, type, or package object to be removed from
the model
is_valid : () : boolean
checks the validity of the solution and all of its models and packages
set_all_data_external
sets the simulation's list and array data to be stored externally
Examples
--------
>>> s = MFSimulation.load('my simulation', 'simulation.nam')
"""
def __init__(self, sim_name='sim', version='mf6', exe_name='mf6.exe',
sim_ws='.', verbosity_level=1, continue_=None,
nocheck=None, memory_print_option=None):
"""Initialization.
__init__ is used to initialize a simulation object
Parameters:
sim_name : string
name of the simulation.
version : string
MODFLOW version
exe_name : string
relative path to MODFLOW executable from the simulation
working folder
sim_ws : string
path to simulation working folder
verbosity_level : int
verbosity level of standard output
0 : no standard output
1 : standard error/warning messages with some
informational messages
2 : verbose mode with full error/warning/informational
messages. this is ideal for debugging
continue_ : bool
sets the continue option in the simulation name file. the
continue option is a keyword flag to indicate that the
simulation should continue even if one or more solutions do
not converge.
nocheck : bool
sets the nocheck option in the simulation name file. the
nocheckoption is a keyword flag to indicate that the model
input check routines should not be called prior to each time
step. checks are performed by default.
memory_print_option : str
sets memory_print_option in the simulation name file.
memory_print_option is a flag that controls printing of
detailed memory manager usage to the end of the simulation
list file. NONE means do not print detailed information.
SUMMARY means print only the total memory for each
simulation component. ALL means print information for each
variable stored in the memory manager. NONE is default if
memory_print_option is not specified.
"""
super(MFSimulation, self).__init__(MFSimulationData(sim_ws), sim_name)
self.simulation_data.verbosity_level = self._resolve_verbosity_level(
verbosity_level)
# verify metadata
fpdata = mfstructure.MFStructure()
if not fpdata.valid:
excpt_str = 'Invalid package metadata. Unable to load MODFLOW ' \
'file structure metadata.'
raise FlopyException(excpt_str)
# initialize
self.dimensions = None
self.type = 'Simulation'
self.version = version
self.exe_name = exe_name
self._models = collections.OrderedDict()
self._tdis_file = None
self._exchange_files = collections.OrderedDict()
self._ims_files = collections.OrderedDict()
self._ghost_node_files = {}
self._mover_files = {}
self._other_files = collections.OrderedDict()
self.structure = fpdata.sim_struct
self.model_type = None
self._exg_file_num = {}
self._gnc_file_num = 0
self._mvr_file_num = 0
self.simulation_data.mfpath.set_last_accessed_path()
# build simulation name file
self.name_file = mfnam.ModflowNam(
self, filename='mfsim.nam', continue_=continue_, nocheck=nocheck,
memory_print_option=memory_print_option)
# try to build directory structure
sim_path = self.simulation_data.mfpath.get_sim_path()
if not os.path.isdir(sim_path):
try:
os.makedirs(sim_path)
except OSError as e:
if self.simulation_data.verbosity_level.value >= \
VerbosityLevel.quiet.value:
print('An error occurred when trying to create the '
'directory {}: {}'.format(sim_path, e.strerror))
# set simulation validity initially to false since the user must first
# add at least one model to the simulation and fill out the name and
# tdis files
self.valid = False
def __getattr__(self, item):
"""Override __getattr__ to allow retrieving models.
__getattr__ is used to allow for getting models and packages as if
they are attributes
Parameters
----------
item : str
model or package name
Returns
-------
md : Model or package object
Model or package object of type :class:flopy6.mfmodel or
:class:flopy6.mfpackage
"""
if item == 'valid' or not hasattr(self, 'valid'):
raise AttributeError(item)
models = []
if item in self.structure.model_types:
# get all models of this type
for model in self._models.values():
if model.model_type == item:
models.append(model)
if len(models) > 0:
return models
elif item in self._models:
model = self.get_model(item)
if model is not None:
return model
raise AttributeError(item)
else:
package = self.get_package(item)
if package is not None:
return package
raise AttributeError(item)
def __repr__(self):
"""Override __repr__ to print custom string.
Returns:
repr string : str
string describing object
"""
return self._get_data_str(True)
def __str__(self):
"""Override __str__ to print custom string.
Returns:
str string : str
string describing object
"""
return self._get_data_str(False)
def _get_data_str(self, formal):
file_mgt = self.simulation_data.mfpath
data_str = 'sim_name = {}\nsim_path = {}\nexe_name = ' \
'{}\n\n'.format(self.name, file_mgt.get_sim_path(),
self.exe_name)
for package in self._packagelist:
pk_str = package._get_data_str(formal, False)
if formal:
if len(pk_str.strip()) > 0:
data_str = '{}###################\nPackage {}\n' \
'###################\n\n' \
'{}\n'.format(data_str, package._get_pname(),
pk_str)
else:
if len(pk_str.strip()) > 0:
data_str = '{}###################\nPackage {}\n' \
'###################\n\n' \
'{}\n'.format(data_str, package._get_pname(),
pk_str)
for model in self._models.values():
if formal:
mod_repr = repr(model)
if len(mod_repr.strip()) > 0:
data_str = '{}@@@@@@@@@@@@@@@@@@@@\nModel {}\n' \
'@@@@@@@@@@@@@@@@@@@@\n\n' \
'{}\n'.format(data_str, model.name, mod_repr)
else:
mod_str = str(model)
if len(mod_str.strip()) > 0:
data_str = '{}@@@@@@@@@@@@@@@@@@@@\nModel {}\n' \
'@@@@@@@@@@@@@@@@@@@@\n\n' \
'{}\n'.format(data_str, model.name, mod_str)
return data_str
@property
def model_names(self):
"""Return a list of model names associated with this simulation.
Returns:
list: list of model names
"""
return self._models.keys()
@classmethod
def load(cls, sim_name='modflowsim', version='mf6', exe_name='mf6.exe',
sim_ws='.', strict=True, verbosity_level=1, load_only=None,
verify_data=False):
"""Load an existing model.
Parameters
----------
sim_name : string
name of the simulation.
version : string
MODFLOW version
exe_name : string
relative path to MODFLOW executable from the simulation working
folder
sim_ws : string
path to simulation working folder
strict : boolean
strict enforcement of file formatting
verbosity_level : int
verbosity level of standard output
0 : no standard output
1 : standard error/warning messages with some informational
messages
2 : verbose mode with full error/warning/informational
messages. this is ideal for debugging
load_only : list
list of package abbreviations or package names corresponding to
packages that flopy will load. default is None, which loads all
packages. the discretization packages will load regardless of this
setting. subpackages, like time series and observations, will also
load regardless of this setting.
example list: ['ic', 'maw', 'npf', 'oc', 'ims', 'gwf6-gwf6']
verify_data : bool
verify data when it is loaded. this can slow down loading
Returns
-------
sim : MFSimulation object
Examples
--------
>>> s = flopy.mf6.mfsimulation.load('my simulation')
"""
# initialize
instance = cls(sim_name, version, exe_name, sim_ws, verbosity_level)
verbosity_level = instance.simulation_data.verbosity_level
instance.simulation_data.verify_data = verify_data
if verbosity_level.value >= VerbosityLevel.normal.value:
print('loading simulation...')
# build case consistent load_only dictionary for quick lookups
load_only = instance._load_only_dict(load_only)
# load simulation name file
if verbosity_level.value >= VerbosityLevel.normal.value:
print(' loading simulation name file...')
instance.name_file.load(strict)
# load TDIS file
tdis_pkg = 'tdis{}'.format(mfstructure.MFStructure().
get_version_string())
tdis_attr = getattr(instance.name_file, tdis_pkg)
instance._tdis_file = mftdis.ModflowTdis(instance,
filename=tdis_attr.get_data())
instance._tdis_file._filename = instance.simulation_data.mfdata[
('nam', 'timing', tdis_pkg)].get_data()
if verbosity_level.value >= VerbosityLevel.normal.value:
print(' loading tdis package...')
instance._tdis_file.load(strict)
# load models
try:
model_recarray = instance.simulation_data.mfdata[('nam', 'models',
'models')]
models = model_recarray.get_data()
except MFDataException as mfde:
message = 'Error occurred while loading model names from the ' \
'simulation name file.'
raise MFDataException(mfdata_except=mfde,
model=instance.name,
package='nam',
message=message)
for item in models:
# resolve model working folder and name file
path, name_file = os.path.split(item[1])
model_obj = PackageContainer.model_factory(item[0][:-1].lower())
# load model
if verbosity_level.value >= VerbosityLevel.normal.value:
print(' loading model {}...'.format(item[0].lower()))
instance._models[item[2]] = model_obj.load(
instance,
instance.structure.model_struct_objs[item[0].lower()], item[2],
name_file, version, exe_name, strict, path, load_only)
# load exchange packages and dependent packages
try:
exchange_recarray = instance.name_file.exchanges
has_exch_data = exchange_recarray.has_data()
except MFDataException as mfde:
message = 'Error occurred while loading exchange names from the ' \
'simulation name file.'
raise MFDataException(mfdata_except=mfde,
model=instance.name,
package='nam',
message=message)
if has_exch_data:
try:
exch_data = exchange_recarray.get_data()
except MFDataException as mfde:
message = 'Error occurred while loading exchange names from ' \
'the simulation name file.'
raise MFDataException(mfdata_except=mfde,
model=instance.name,
package='nam',
message=message)
for exgfile in exch_data:
if load_only is not None and not \
instance._in_pkg_list(load_only, exgfile[0],
exgfile[2]):
if instance.simulation_data.verbosity_level.value >= \
VerbosityLevel.normal.value:
print(' skipping package {}..'
'.'.format(exgfile[0].lower()))
continue
# get exchange type by removing numbers from exgtype
exchange_type = ''.join([char for char in exgfile[0] if
not char.isdigit()]).upper()
# get exchange number for this type
if exchange_type not in instance._exg_file_num:
exchange_file_num = 0
instance._exg_file_num[exchange_type] = 1
else:
exchange_file_num = instance._exg_file_num[exchange_type]
instance._exg_file_num[exchange_type] += 1
exchange_name = '{}_EXG_{}'.format(exchange_type,
exchange_file_num)
# find package class the corresponds to this exchange type
package_obj = instance.package_factory(
exchange_type.replace('-', '').lower(), '')
if not package_obj:
message = 'An error occurred while loading the ' \
'simulation name file. Invalid exchange type ' \
'"{}" specified.'.format(exchange_type)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(instance.name,
'nam',
'nam',
'loading simulation name file',
exchange_recarray.structure.name,
inspect.stack()[0][3],
type_, value_, traceback_, message,
instance._simulation_data.debug)
# build and load exchange package object
exchange_file = package_obj(instance, exgtype=exgfile[0],
exgmnamea=exgfile[2],
exgmnameb=exgfile[3],
filename=exgfile[1],
pname=exchange_name,
loading_package=True)
if verbosity_level.value >= VerbosityLevel.normal.value:
print(' loading exchange package {}..'
'.'.format(exchange_file._get_pname()))
exchange_file.load(strict)
instance._exchange_files[exgfile[1]] = exchange_file
# load simulation packages
solution_recarray = instance.simulation_data.mfdata[('nam',
'solutiongroup',
'solutiongroup'
)]
try:
solution_group_dict = solution_recarray.get_data()
except MFDataException as mfde:
message = 'Error occurred while loading solution groups from ' \
'the simulation name file.'
raise MFDataException(mfdata_except=mfde,
model=instance.name,
package='nam',
message=message)
for solution_group in solution_group_dict.values():
for solution_info in solution_group:
if load_only is not None and \
not instance._in_pkg_list(load_only,
solution_info[0],
solution_info[2]):
if instance.simulation_data.verbosity_level.value >= \
VerbosityLevel.normal.value:
print(' skipping package {}..'
'.'.format(solution_info[0].lower()))
continue
ims_file = mfims.ModflowIms(instance, filename=solution_info[1],
pname=solution_info[2])
if verbosity_level.value >= VerbosityLevel.normal.value:
print(' loading ims package {}..'
'.'.format(ims_file._get_pname()))
ims_file.load(strict)
instance.simulation_data.mfpath.set_last_accessed_path()
if verify_data:
instance.check()
return instance
def check(self, f=None, verbose=True, level=1):
"""
Check model data for common errors.
Parameters
----------
f : str or file handle
String defining file name or file handle for summary file
of check method output. If a string is passed a file handle
is created. If f is None, check method does not write
results to a summary file. (default is None)
verbose : bool
Boolean flag used to determine if check method results are
written to the screen
level : int
Check method analysis level. If level=0, summary checks are
performed. If level=1, full checks are performed.
Returns
-------
None
Examples
--------
>>> import flopy
>>> m = flopy.modflow.Modflow.load('model.nam')
>>> m.check()
"""
# check instance for simulation-level check
chk_list = []
# check models
for model in self._models.values():
print('Checking model "{}"...'.format(model.name))
chk_list.append(model.check(f, verbose, level))
print('Checking for missing simulation packages...')
if self._tdis_file is None:
if chk_list:
chk_list[0]._add_to_summary(
'Error', desc='\r No tdis package', package='model')
print('Error: no tdis package')
if len(self._ims_files) == 0:
if chk_list:
chk_list[0]._add_to_summary(
'Error', desc='\r No solver package', package='model')
print('Error: no ims package')
return chk_list
@property
def sim_package_list(self):
package_list = []
if self._tdis_file is not None:
package_list.append(self._tdis_file)
for sim_package in self._ims_files.values():
package_list.append(sim_package)
for sim_package in self._exchange_files.values():
package_list.append(sim_package)
for sim_package in self._mover_files.values():
package_list.append(sim_package)
for sim_package in self._other_files.values():
package_list.append(sim_package)
return package_list
def load_package(self, ftype, fname, pname, strict, ref_path,
dict_package_name=None, parent_package=None):
"""Load a package from a file.
Parameters
----------
ftype : string
the file type
fname : string
the name of the file containing the package input
pname : string
the user-defined name for the package
strict : bool
strict mode when loading the file
ref_path : string
path to the file. uses local path if set to None
dict_package_name : string
package name for dictionary lookup
parent_package : MFPackage
parent package
"""
if ftype == 'gnc':
if fname not in self._ghost_node_files:
# get package type from parent package
if parent_package:
package_abbr = parent_package.package_abbr[0:3]
else:
package_abbr = 'GWF'
# build package name and package
gnc_name = '{}-GNC_{}'.format(package_abbr, self._gnc_file_num)
ghost_node_file = mfgwfgnc.ModflowGwfgnc(
self, filename=fname, pname=gnc_name,
parent_file=parent_package, loading_package=True)
ghost_node_file.load(strict)
self._ghost_node_files[fname] = ghost_node_file
self._gnc_file_num += 1
return ghost_node_file
elif ftype == 'mvr':
if fname not in self._mover_files:
# Get package type from parent package
if parent_package:
package_abbr = parent_package.package_abbr[0:3]
else:
package_abbr = 'GWF'
# build package name and package
mvr_name = '{}-MVR_{}'.format(package_abbr, self._mvr_file_num)
mover_file = mfgwfmvr.ModflowGwfmvr(self, filename=fname,
pname=mvr_name,
parent_file=parent_package,
loading_package=True)
mover_file.load(strict)
self._mover_files[fname] = mover_file
self._mvr_file_num += 1
return mover_file
else:
# create package
package_obj = self.package_factory(ftype, '')
package = package_obj(self, filename=fname, pname=dict_package_name,
add_to_package_list=False,
parent_file=parent_package,
loading_package=True)
# verify that this is a utility package
utl_struct = mfstructure.MFStructure().sim_struct.utl_struct_objs
if package.package_type in utl_struct:
package.load(strict)
self._other_files[package.filename] = package
# register child package with the simulation
self._add_package(package, package.path)
if parent_package is not None:
# register child package with the parent package
parent_package._add_package(package, package.path)
else:
if self.simulation_data.verbosity_level.value >= \
VerbosityLevel.normal.value:
print('WARNING: Unsupported file type {} for '
'simulation.'.format(package.package_type))
return package
def register_ims_package(self, ims_file, model_list):
"""Register an ims package with the simulation.
Parameters
ims_file : MFPackage
ims package to register
model_list : list of strings
list of models using the ims package to be registered
"""
if isinstance(model_list, str):
model_list = [model_list]
if not isinstance(ims_file, mfims.ModflowIms):
comment = 'Parameter "ims_file" is not a valid ims file. ' \
'Expected type ModflowIms, but type "{}" was given' \
'.'.format(type(ims_file))
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(None,
'ims',
'',
'registering ims package',
'',
inspect.stack()[0][3], type_,
value_,
traceback_, comment,
self.simulation_data.debug)
in_simulation = False
pkg_with_same_name = None
for file in self._ims_files.values():
if file is ims_file:
in_simulation = True
if file.package_name == ims_file.package_name and \
file != ims_file:
pkg_with_same_name = file
if self.simulation_data.verbosity_level.value >= \
VerbosityLevel.normal.value:
print('WARNING: ims package with name {} already exists. '
'New ims package will replace old package'
'.'.format(file.package_name))
self._remove_package(self._ims_files[file.filename])
del self._ims_files[file.filename]
# register ims package
if not in_simulation: