-
Notifications
You must be signed in to change notification settings - Fork 303
/
mfbase.py
760 lines (661 loc) · 26 KB
/
mfbase.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
import glob
import importlib
import inspect, sys, traceback
import os, copy
from collections.abc import Iterable
from shutil import copyfile
from enum import Enum
# internal handled exceptions
class MFInvalidTransientBlockHeaderException(Exception):
"""
Exception occurs when parsing a transient block header
"""
class ReadAsArraysException(Exception):
"""
Exception occurs when loading ReadAsArrays package as non-ReadAsArrays
package.
"""
# external exceptions for users
class FlopyException(Exception):
"""
General FloPy exception
"""
def __init__(self, error, location=""):
self.message = error
super().__init__(f"{error} ({location})")
class StructException(Exception):
"""
Exception with the package file structure
"""
def __init__(self, error, location):
self.message = error
super().__init__(f"{error} ({location})")
class MFDataException(Exception):
"""
Exception with MODFLOW data. Exception includes detailed error
information.
"""
def __init__(
self,
model=None,
package=None,
path=None,
current_process=None,
data_element=None,
method_caught_in=None,
org_type=None,
org_value=None,
org_traceback=None,
message=None,
debug=None,
mfdata_except=None,
):
if mfdata_except is not None and isinstance(
mfdata_except, MFDataException
):
# copy constructor - copying values from original exception
self.model = mfdata_except.model
self.package = mfdata_except.package
self.current_process = mfdata_except.current_process
self.data_element = mfdata_except.data_element
self.path = mfdata_except.path
self.messages = mfdata_except.messages
self.debug = mfdata_except.debug
self.method_caught_in = mfdata_except.method_caught_in
self.org_type = mfdata_except.org_type
self.org_value = mfdata_except.org_value
self.org_traceback = mfdata_except.org_traceback
self.org_tb_string = mfdata_except.org_tb_string
else:
self.messages = []
if mfdata_except is not None and (
isinstance(mfdata_except, StructException)
or isinstance(mfdata_except, FlopyException)
):
self.messages.append(mfdata_except.message)
self.model = None
self.package = None
self.current_process = None
self.data_element = None
self.path = None
self.debug = False
self.method_caught_in = None
self.org_type = None
self.org_value = None
self.org_traceback = None
self.org_tb_string = None
# override/assign any values that are not none
if model is not None:
self.model = model
if package is not None:
self.package = package
if current_process is not None:
self.current_process = current_process
if data_element is not None:
self.data_element = data_element
if path is not None:
self.path = path
if message is not None:
self.messages.append(message)
if debug is not None:
self.debug = debug
if method_caught_in is not None:
self.method_caught_in = method_caught_in
if org_type is not None:
self.org_type = org_type
if org_value is not None:
self.org_value = org_value
if org_traceback is not None:
self.org_traceback = org_traceback
self.org_tb_string = traceback.format_exception(
self.org_type, self.org_value, self.org_traceback
)
# build error string
error_message = "An error occurred in "
if self.data_element is not None and self.data_element != "":
error_message += f'data element "{self.data_element}" '
if self.model is not None and self.model != "":
error_message += f'model "{self.model}" '
error_message += (
f'package "{self.package}". The error occurred while '
f'{self.current_process} in the "{self.method_caught_in}" method.'
)
if len(self.messages) > 0:
error_message += "\nAdditional Information:\n"
error_message += "\n".join(
f"({idx}) {msg}" for (idx, msg) in enumerate(self.messages, 1)
)
super().__init__(error_message)
class VerbosityLevel(Enum):
"""Determines how much information FloPy writes to the console"""
quiet = 1
normal = 2
verbose = 3
class PackageContainerType(Enum):
"""Determines whether a package container is a simulation, model, or
package."""
simulation = 1
model = 2
package = 3
class ExtFileAction(Enum):
"""Defines what to do with external files when the simulation or model's
path change."""
copy_all = 1
copy_none = 2
copy_relative_paths = 3
class MFFilePath:
"""Class that stores a single file path along with the associated model
name."""
def __init__(self, file_path, model_name):
self.file_path = file_path
self.model_name = {model_name: 0}
def isabs(self):
return os.path.isabs(self.file_path)
class MFFileMgmt:
"""
Class containing MODFLOW path data
Parameters
----------
path : str
Path on disk to the simulation
Attributes
----------
model_relative_path : dict
Dictionary of relative paths to each model folder
"""
def __init__(self, path, mfsim=None):
self.simulation = mfsim
self._sim_path = ""
self.set_sim_path(path, True)
# keys:fully pathed filenames, vals:FilePath instances
self.existing_file_dict = {}
# keys:filenames,vals:instance name
self.model_relative_path = {}
self._last_loaded_sim_path = None
self._last_loaded_model_relative_path = {}
def copy_files(self, copy_relative_only=True):
"""Copy files external to updated path.
Parameters
----------
copy_relative_only : bool
Only copy files with relative paths.
"""
num_files_copied = 0
if self._last_loaded_sim_path is not None:
for mffile_path in self.existing_file_dict.values():
# resolve previous simulation path. if mf6 changes
# so that paths are relative to the model folder, then
# this call should have "model_name" instead of "None"
path_old = self.resolve_path(mffile_path, None, True)
if os.path.isfile(path_old) and (
not mffile_path.isabs() or not copy_relative_only
):
# change "None" to "model_name" as above if mf6
# supports model relative paths
path_new = self.resolve_path(mffile_path, None)
if path_old != path_new:
new_folders = os.path.split(path_new)[0]
if not os.path.exists(new_folders):
os.makedirs(new_folders)
try:
copyfile(path_old, path_new)
except:
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"appending data",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
None,
self._simulation_data.debug,
)
num_files_copied += 1
return num_files_copied
def get_updated_path(
self, external_file_path, model_name, ext_file_action
):
"""For internal FloPy use, not intended for end user."""
return external_file_path
def _build_relative_path(self, model_name):
old_abs_path = self.resolve_path("", model_name, True)
current_abs_path = self.resolve_path("", model_name, False)
return os.path.relpath(old_abs_path, current_abs_path)
def strip_model_relative_path(self, model_name, path):
"""Strip out the model relative path part of `path`. For internal
FloPy use, not intended for end user."""
if model_name in self.model_relative_path:
model_rel_path = self.model_relative_path[model_name]
new_path = None
while path:
path, leaf = os.path.split(path)
if leaf != model_rel_path:
if new_path:
new_path = os.path.join(leaf, new_path)
else:
new_path = leaf
return new_path
@staticmethod
def unique_file_name(file_name, lookup):
"""Generate a unique file name. For internal FloPy use, not intended
for end user."""
num = 0
while MFFileMgmt._build_file(file_name, num) in lookup:
num += 1
return MFFileMgmt._build_file(file_name, num)
@staticmethod
def _build_file(file_name, num):
file, ext = os.path.splitext(file_name)
if ext:
return f"{file}_{num}{ext}"
else:
return f"{file}_{num}"
@staticmethod
def string_to_file_path(fp_string):
"""Interpret string as a file path. For internal FloPy use, not
intended for end user."""
file_delimiters = ["/", "\\"]
new_string = fp_string
for delimiter in file_delimiters:
arr_string = new_string.split(delimiter)
if len(arr_string) > 1:
if os.path.isabs(fp_string):
if not arr_string[0] and not arr_string[1]:
new_string = f"{delimiter}{delimiter}"
else:
new_string = (
f"{arr_string[0]}{delimiter}{arr_string[1]}"
)
else:
new_string = os.path.join(arr_string[0], arr_string[1])
if len(arr_string) > 2:
for path_piece in arr_string[2:]:
new_string = os.path.join(new_string, path_piece)
return new_string
def set_last_accessed_path(self):
"""Set the last accessed simulation path to the current simulation
path. For internal FloPy use, not intended for end user."""
self._last_loaded_sim_path = self._sim_path
self.set_last_accessed_model_path()
def set_last_accessed_model_path(self):
"""Set the last accessed model path to the current model path.
For internal FloPy use, not intended for end user."""
for key, item in self.model_relative_path.items():
self._last_loaded_model_relative_path[key] = copy.deepcopy(item)
def get_model_path(self, key, last_loaded_path=False):
"""Returns the model working path for the model `key`.
Parameters
----------
key : str
Model name whose path flopy will retrieve
last_loaded_path : bool
Get the last path loaded by FloPy which may not be the most
recent path.
Returns
-------
model path : str
"""
if last_loaded_path:
return os.path.join(
self._last_loaded_sim_path,
self._last_loaded_model_relative_path[key],
)
else:
if key in self.model_relative_path:
return os.path.join(
self._sim_path, self.model_relative_path[key]
)
else:
return self._sim_path
def get_sim_path(self, last_loaded_path=False):
"""Get the simulation path."""
if last_loaded_path:
return self._last_loaded_sim_path
else:
return self._sim_path
def add_ext_file(self, file_path, model_name):
"""Add an external file to the path list. For internal FloPy use, not
intended for end user."""
if file_path in self.existing_file_dict:
if model_name not in self.existing_file_dict[file_path].model_name:
self.existing_file_dict[file_path].model_name[model_name] = 0
else:
new_file_path = MFFilePath(file_path, model_name)
self.existing_file_dict[file_path] = new_file_path
def set_sim_path(self, path, internal_use=False):
"""
Set the file path to the simulation files. Internal use only,
call MFSimulation's set_sim_path method instead.
Parameters
----------
path : str
Full path or relative path from working directory to
simulation folder
Returns
-------
Examples
--------
self.simulation_data.mfdata.set_sim_path('sim_folder')
"""
if not internal_use:
print(
"WARNING: MFFileMgt's set_sim_path has been deprecated. "
"Please use MFSimulation's set_sim_path in the future."
)
if self.simulation is not None:
self.simulation.set_sim_path(path)
return
# recalculate paths for everything
# resolve path type
path = self.string_to_file_path(path)
if os.path.isabs(path):
self._sim_path = path
else:
# assume path is relative to working directory
self._sim_path = os.path.join(os.getcwd(), path)
def resolve_path(
self, path, model_name, last_loaded_path=False, move_abs_paths=False
):
"""Resolve a simulation or model path. For internal FloPy use, not
intended for end user."""
if isinstance(path, MFFilePath):
file_path = path.file_path
else:
file_path = path
if os.path.isabs(file_path):
# path is an absolute path
if move_abs_paths:
return self.get_sim_path(last_loaded_path)
else:
return file_path
else:
# path is a relative path
return os.path.join(self.get_sim_path(last_loaded_path), file_path)
class PackageContainer:
"""
Base class for any class containing packages.
Parameters
----------
simulation_data : SimulationData
The simulation's SimulationData object
name : str
Name of the package container object
Attributes
----------
package_type_dict : dictionary
Dictionary of packages by package type
package_name_dict : dictionary
Dictionary of packages by package name
package_key_dict : dictionary
Dictionary of packages by package key
"""
def __init__(self, simulation_data, name):
self.type = "PackageContainer"
self.simulation_data = simulation_data
self.name = name
self._packagelist = []
self.package_type_dict = {}
self.package_name_dict = {}
self.package_key_dict = {}
@staticmethod
def package_factory(package_type, model_type):
"""Static method that returns the appropriate package type object based
on the package_type and model_type strings. For internal FloPy use
only, not intended for end users.
Parameters
----------
package_type : str
Type of package to create
model_type : str
Type of model that package is a part of
Returns
-------
package : MFPackage subclass
"""
package_abbr = f"{model_type}{package_type}"
package_utl_abbr = f"utl{package_type}"
package_list = []
# iterate through python files
package_file_paths = PackageContainer.get_package_file_paths()
for package_file_path in package_file_paths:
module = PackageContainer.get_module(package_file_path)
if module is not None:
# iterate imported items
for item in dir(module):
value = PackageContainer.get_module_val(
module, item, "package_abbr"
)
if value is not None:
abbr = value.package_abbr
if package_type is None:
# don't store packages "group" classes
if len(abbr) <= 8 or abbr[-8:] != "packages":
package_list.append(value)
else:
# check package type
if (
value.package_abbr == package_abbr
or value.package_abbr == package_utl_abbr
):
return value
if package_type is None:
return package_list
else:
return None
@staticmethod
def model_factory(model_type):
"""Static method that returns the appropriate model type object based
on the model_type string. For internal FloPy use only, not intended
for end users.
Parameters
----------
model_type : str
Type of model that package is a part of
Returns
-------
model : MFModel subclass
"""
package_file_paths = PackageContainer.get_package_file_paths()
for package_file_path in package_file_paths:
module = PackageContainer.get_module(package_file_path)
if module is not None:
# iterate imported items
for item in dir(module):
value = PackageContainer.get_module_val(
module, item, "model_type"
)
if value is not None and value.model_type == model_type:
return value
return None
@staticmethod
def get_module_val(module, item, attrb):
"""Static method that returns a python class module value. For
internal FloPy use only, not intended for end users."""
value = getattr(module, item)
# verify this is a class
if (
not value
or not inspect.isclass(value)
or not hasattr(value, attrb)
):
return None
return value
@staticmethod
def get_module(package_file_path):
"""Static method that returns the python module library. For
internal FloPy use only, not intended for end users."""
package_file_name = os.path.basename(package_file_path)
module_path = os.path.splitext(package_file_name)[0]
module_name = f"Modflow{module_path[2].upper()}{module_path[3:]}"
if module_name.startswith("__"):
return None
# import
return importlib.import_module(f"flopy.mf6.modflow.{module_path}")
@staticmethod
def get_package_file_paths():
"""Static method that gets the paths of all the FloPy python package
files. For internal FloPy use only, not intended for end users.
"""
base_path = os.path.split(os.path.realpath(__file__))[0]
package_path = os.path.join(base_path, "modflow")
return glob.glob(os.path.join(package_path, "*.py"))
@property
def package_dict(self):
"""Returns a copy of the package name dictionary."""
return self.package_name_dict.copy()
@property
def package_names(self):
"""Returns a list of package names."""
return list(self.package_name_dict.keys())
def _add_package(self, package, path):
# put in packages list and update lookup dictionaries
self._packagelist.append(package)
if package.package_name is not None:
self.package_name_dict[package.package_name.lower()] = package
self.package_key_dict[path[-1].lower()] = package
if package.package_type not in self.package_type_dict:
self.package_type_dict[package.package_type.lower()] = []
self.package_type_dict[package.package_type.lower()].append(package)
def _remove_package(self, package):
self._packagelist.remove(package)
if (
package.package_name is not None
and package.package_name.lower() in self.package_name_dict
):
del self.package_name_dict[package.package_name.lower()]
del self.package_key_dict[package.path[-1].lower()]
package_list = self.package_type_dict[package.package_type.lower()]
package_list.remove(package)
if len(package_list) == 0:
del self.package_type_dict[package.package_type.lower()]
# collect keys of items to be removed from main dictionary
items_to_remove = []
for key in self.simulation_data.mfdata:
is_subkey = True
for pitem, ditem in zip(package.path, key):
if pitem != ditem:
is_subkey = False
break
if is_subkey:
items_to_remove.append(key)
# remove items from main dictionary
for key in items_to_remove:
del self.simulation_data.mfdata[key]
def _rename_package(self, package, new_name):
# fix package_name_dict key
if (
package.package_name is not None
and package.package_name.lower() in self.package_name_dict
):
del self.package_name_dict[package.package_name.lower()]
self.package_name_dict[new_name.lower()] = package
# fix package_key_dict key
new_package_path = package.path[:-1] + (new_name,)
del self.package_key_dict[package.path[-1].lower()]
self.package_key_dict[new_package_path.lower()] = package
# get keys to fix in main dictionary
main_dict = self.simulation_data.mfdata
items_to_fix = []
for key in main_dict:
is_subkey = True
for pitem, ditem in zip(package.path, key):
if pitem != ditem:
is_subkey = False
break
if is_subkey:
items_to_fix.append(key)
# fix keys in main dictionary
for key in items_to_fix:
new_key = (
package.path[:-1] + (new_name,) + key[len(package.path) - 1 :]
)
main_dict[new_key] = main_dict.pop(key)
def get_package(self, name=None):
"""
Finds a package by package name, package key, package type, or partial
package name. returns either a single package, a list of packages,
or None.
Parameters
----------
name : str
Name of the package, 'RIV', 'LPF', etc.
Returns
-------
pp : Package object
"""
if name is None:
return self._packagelist[:]
# search for full package name
if name.lower() in self.package_name_dict:
return self.package_name_dict[name.lower()]
# search for package type
if name.lower() in self.package_type_dict:
if len(self.package_type_dict[name.lower()]) == 0:
return None
elif len(self.package_type_dict[name.lower()]) == 1:
return self.package_type_dict[name.lower()][0]
else:
return self.package_type_dict[name.lower()]
# search for package key
if name.lower() in self.package_key_dict:
return self.package_key_dict[name.lower()]
# search for partial and case-insensitive package name
for pp in self._packagelist:
if pp.package_name is not None:
# get first package of the type requested
package_name = pp.package_name.lower()
if len(package_name) > len(name):
package_name = package_name[0 : len(name)]
if package_name.lower() == name.lower():
return pp
return None
def register_package(self, package):
"""Base method for registering a package. Should be overridden."""
path = (package.package_name,)
return (path, None)
@staticmethod
def _load_only_dict(load_only):
if load_only is None:
return None
if isinstance(load_only, dict):
return load_only
if not isinstance(load_only, Iterable):
raise FlopyException(
"load_only must be iterable or None. "
'load_only value of "{}" is '
"invalid".format(load_only)
)
load_only_dict = {}
for item in load_only:
load_only_dict[item.lower()] = True
return load_only_dict
@staticmethod
def _in_pkg_list(pkg_list, pkg_type, pkg_name):
if pkg_type is not None:
pkg_type = pkg_type.lower()
if pkg_name is not None:
pkg_name = pkg_name.lower()
if pkg_type in pkg_list or pkg_name in pkg_list:
return True
# split to make cases like "gwf6-gwf6" easier to process
pkg_type = pkg_type.split("-")
try:
# if there is a number on the end of the package try
# excluding it
int(pkg_type[0][-1])
for key in pkg_list.keys():
key = key.split("-")
if len(key) == len(pkg_type):
matches = True
for key_item, pkg_item in zip(key, pkg_type):
if pkg_item[0:-1] != key_item and pkg_item != key_item:
matches = False
if matches:
return True
except ValueError:
return False
return False