-
Notifications
You must be signed in to change notification settings - Fork 303
/
mffileaccess.py
2404 lines (2334 loc) · 96.4 KB
/
mffileaccess.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
import sys, inspect
from copy import deepcopy
import numpy as np
from ..mfbase import MFDataException, VerbosityLevel
from ...utils.datautil import (
PyListUtil,
find_keyword,
DatumUtil,
MultiListIter,
)
from .mfdatautil import convert_data, to_string, MFComment
from ...utils.binaryfile import BinaryHeader
from ...utils import datautil
from ..data.mfstructure import DatumType, MFDataStructure, DataType
class MFFileAccess:
def __init__(
self, structure, data_dimensions, simulation_data, path, current_key
):
self.structure = structure
self._data_dimensions = data_dimensions
self._simulation_data = simulation_data
self._path = path
self._current_key = current_key
@staticmethod
def _get_bintype(modelgrid):
if modelgrid.grid_type == "vertex":
return "vardisv"
elif modelgrid.grid_type == "unstructured":
return "vardisu"
else:
return "vardis"
def _get_next_data_line(self, file_handle):
end_of_file = False
while not end_of_file:
line = file_handle.readline()
if line == "":
message = (
"More data expected when reading {} from file "
"{}".format(self.structure.name, file_handle.name)
)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self.structure.path,
"reading data from file",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
message,
self._simulation_data.debug,
)
clean_line = line.strip()
# If comment or empty line
if not MFComment.is_comment(clean_line, True):
return datautil.PyListUtil.split_data_line(clean_line)
def _read_pre_data_comments(
self, line, file_handle, pre_data_comments, storage
):
line_num = 0
if pre_data_comments:
storage.pre_data_comments = MFComment(
pre_data_comments.text,
self._path,
self._simulation_data,
line_num,
)
else:
storage.pre_data_comments = None
# read through any fully commented or empty lines
PyListUtil.reset_delimiter_used()
arr_line = PyListUtil.split_data_line(line)
while MFComment.is_comment(arr_line, True) and line != "":
if storage.pre_data_comments:
storage.pre_data_comments.add_text("\n")
storage.pre_data_comments.add_text(" ".join(arr_line))
else:
storage.pre_data_comments = MFComment(
arr_line, self._path, self._simulation_data, line_num
)
line = file_handle.readline()
arr_line = PyListUtil.split_data_line(line)
return line
def _get_aux_var_index(self, aux_name):
aux_var_index = None
# confirm whether the keyword found is an auxiliary variable name
aux_var_names = self._data_dimensions.package_dim.get_aux_variables()
if aux_var_names:
for aux_var_name, index in zip(
aux_var_names[0], range(0, len(aux_var_names[0]))
):
if aux_name.lower() == aux_var_name.lower():
aux_var_index = index - 1
return aux_var_index
def _load_keyword(self, arr_line, index_num, keyword):
aux_var_index = None
if keyword != "":
# verify keyword
keyword_found = arr_line[index_num].lower()
keyword_match = keyword.lower() == keyword_found
aux_var_names = None
if not keyword_match:
aux_var_index = self._get_aux_var_index(keyword_found)
if not keyword_match and aux_var_index is None:
aux_text = ""
if aux_var_names is not None:
# TODO: aux_var_names is None, so this is never touched
aux_text = f" or auxiliary variables {aux_var_names[0]}"
message = (
'Error reading variable "{}". Expected '
'variable keyword "{}"{} not found '
'at line "{}". {}'.format(
self.structure.name,
keyword,
aux_text,
" ".join(arr_line),
self._path,
)
)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self.structure.path,
"loading keyword",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
message,
self._simulation_data.debug,
)
return (index_num + 1, aux_var_index)
return (index_num, aux_var_index)
def _open_ext_file(self, fname, binary=False, write=False):
model_dim = self._data_dimensions.package_dim.model_dim[0]
read_file = self._simulation_data.mfpath.resolve_path(
fname, model_dim.model_name
)
if write:
options = "w"
else:
options = "r"
if binary:
options = f"{options}b"
try:
fd = open(read_file, options)
return fd
except:
message = (
"Unable to open file {} in mode {}. Make sure the "
"file is not locked and the folder exists"
".".format(read_file, options)
)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self._data_dimensions.structure.get_model(),
self._data_dimensions.structure.get_package(),
self._data_dimensions.structure.path,
"opening external file for writing",
self._data_dimensions.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
message,
self._simulation_data.debug,
)
@staticmethod
def datum_to_numpy_type(datum_type):
if datum_type == DatumType.integer:
return np.int32, "int"
elif datum_type == DatumType.double_precision:
return np.float64, "double"
elif datum_type == DatumType.string or datum_type == DatumType.keyword:
return str, "str"
else:
return None, None
class MFFileAccessArray(MFFileAccess):
def __init__(
self, structure, data_dimensions, simulation_data, path, current_key
):
super().__init__(
structure, data_dimensions, simulation_data, path, current_key
)
def write_binary_file(
self,
data,
fname,
text,
modelgrid=None,
modeltime=None,
stress_period=0,
precision="double",
write_multi_layer=False,
):
data = self._resolve_cellid_numbers_to_file(data)
fd = self._open_ext_file(fname, binary=True, write=True)
if write_multi_layer:
for layer, value in enumerate(data):
self._write_layer(
fd,
value,
modelgrid,
modeltime,
stress_period,
precision,
text,
fname,
layer + 1,
)
else:
self._write_layer(
fd,
data,
modelgrid,
modeltime,
stress_period,
precision,
text,
fname,
)
data.tofile(fd)
fd.close()
def _write_layer(
self,
fd,
data,
modelgrid,
modeltime,
stress_period,
precision,
text,
fname,
ilay=None,
):
header_data = self._get_header(
modelgrid, modeltime, stress_period, precision, text, fname, ilay
)
header_data.tofile(fd)
data.tofile(fd)
def _get_header(
self,
modelgrid,
modeltime,
stress_period,
precision,
text,
fname,
ilay=None,
):
# handle dis (row, col, lay), disv (ncpl, lay), and disu (nodes) cases
if modelgrid is not None and modeltime is not None:
pertim = modeltime.perlen[stress_period]
totim = modeltime.perlen.sum()
if ilay is None:
ilay = modelgrid.nlay
if modelgrid.grid_type == "structured":
return BinaryHeader.create(
bintype="vardis",
precision=precision,
text=text,
nrow=modelgrid.nrow,
ncol=modelgrid.ncol,
ilay=ilay,
pertim=pertim,
totim=totim,
kstp=1,
kper=stress_period + 1,
)
elif modelgrid.grid_type == "vertex":
if ilay is None:
ilay = modelgrid.nlay
return BinaryHeader.create(
bintype="vardisv",
precision=precision,
text=text,
ncpl=modelgrid.ncpl,
ilay=ilay,
m3=1,
pertim=pertim,
totim=totim,
kstp=1,
kper=stress_period,
)
elif modelgrid.grid_type == "unstructured":
return BinaryHeader.create(
bintype="vardisu",
precision=precision,
text=text,
nodes=modelgrid.nnodes,
m2=1,
m3=1,
pertim=pertim,
totim=totim,
kstp=1,
kper=stress_period,
)
else:
if ilay is None:
ilay = 1
header = BinaryHeader.create(
bintype="vardis",
precision=precision,
text=text,
nrow=1,
ncol=1,
ilay=ilay,
pertim=pertim,
totim=totim,
kstp=1,
kper=stress_period,
)
if (
self._simulation_data.verbosity_level.value
>= VerbosityLevel.normal.value
):
print(
"Model grid does not have a valid type. Using "
"default spatial discretization header values for "
"binary file {}.".format(fname)
)
else:
pertim = np.float64(1.0)
header = BinaryHeader.create(
bintype="vardis",
precision=precision,
text=text,
nrow=1,
ncol=1,
ilay=1,
pertim=pertim,
totim=pertim,
kstp=1,
kper=stress_period,
)
if (
self._simulation_data.verbosity_level.value
>= VerbosityLevel.normal.value
):
print(
"Binary file data not part of a model. Using default "
"spatial discretization header values for binary file "
"{}.".format(fname)
)
return header
def write_text_file(self, data, fp, data_type, data_size):
try:
fd = open(fp, "w")
except:
message = (
"Unable to open file {}. Make sure the file "
"is not locked and the folder exists"
".".format(fp)
)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self._data_dimensions.structure.get_model(),
self._data_dimensions.structure.get_package(),
self._data_dimensions.structure.path,
"opening external file for writing",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
message,
self._simulation_data.debug,
)
fd.write(self.get_data_string(data, data_type, ""))
fd.close()
def read_binary_data_from_file(
self,
fname,
data_shape,
data_size,
data_type,
modelgrid,
read_multi_layer=False,
):
import flopy.utils.binaryfile as bf
fd = self._open_ext_file(fname, True)
numpy_type, name = self.datum_to_numpy_type(data_type)
header_dtype = bf.BinaryHeader.set_dtype(
bintype=self._get_bintype(modelgrid), precision="double"
)
if read_multi_layer and len(data_shape) > 1:
all_data = np.empty(data_shape, numpy_type)
headers = []
layer_shape = data_shape[1:]
data_size = int(data_size / data_shape[0])
for index in range(0, data_shape[0]):
layer_data = self._read_binary_file_layer(
fd, fname, header_dtype, numpy_type, data_size, layer_shape
)
all_data[index, :] = layer_data[0]
headers.append(layer_data[1])
fd.close()
return all_data, headers
else:
bin_data = self._read_binary_file_layer(
fd, fname, header_dtype, numpy_type, data_size, data_shape
)
fd.close()
return bin_data
def get_data_string(self, data, data_type, data_indent=""):
layer_data_string = [str(data_indent)]
line_data_count = 0
indent_str = self._simulation_data.indent_string
data_iter = datautil.PyListUtil.next_item(data)
is_cellid = (
self.structure.data_item_structures[0].numeric_index
or self.structure.data_item_structures[0].is_cellid
)
jag_arr = self.structure.data_item_structures[0].jagged_array
jagged_def = None
jagged_def_index = 0
if jag_arr is not None:
# get jagged array definition
jagged_def_path = self._path[0:-1] + (jag_arr,)
if jagged_def_path in self._simulation_data.mfdata:
jagged_def = self._simulation_data.mfdata[
jagged_def_path
].array
for item, last_item, new_list, nesting_change in data_iter:
# increment data/layer counts
line_data_count += 1
try:
data_lyr = to_string(
item,
data_type,
self._simulation_data,
self._data_dimensions,
is_cellid,
verify_data=self._simulation_data.verify_data,
)
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
comment = (
'Could not convert data "{}" of type "{}" to a '
"string.".format(item, data_type)
)
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"converting data",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
comment,
self._simulation_data.debug,
ex,
)
layer_data_string[-1] += f"{indent_str}{data_lyr}"
if jagged_def is not None:
if line_data_count == jagged_def[jagged_def_index]:
layer_data_string.append(str(data_indent))
line_data_count = 0
jagged_def_index += 1
else:
if self._simulation_data.wrap_multidim_arrays and (
line_data_count
== self._simulation_data.max_columns_of_data
or last_item
):
layer_data_string.append(str(data_indent))
line_data_count = 0
if len(layer_data_string) > 0:
# clean up the text at the end of the array
layer_data_string[-1] = layer_data_string[-1].strip()
if len(layer_data_string) == 1:
return f"{data_indent}{layer_data_string[0].rstrip()}\n"
else:
return "\n".join(layer_data_string)
def _read_binary_file_layer(
self, fd, fname, header_dtype, numpy_type, data_size, data_shape
):
header_data = np.fromfile(fd, dtype=header_dtype, count=1)
data = np.fromfile(fd, dtype=numpy_type, count=data_size)
data = self._resolve_cellid_numbers_from_file(data)
if data.size != data_size:
message = (
"Binary file {} does not contain expected data. "
"Expected array size {} but found size "
"{}.".format(fname, data_size, data.size)
)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self._data_dimensions.structure.get_model(),
self._data_dimensions.structure.get_package(),
self._data_dimensions.structure.path,
"opening external file for writing",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
message,
self._simulation_data.debug,
)
return data.reshape(data_shape), header_data
def read_text_data_from_file(
self,
data_size,
data_type,
data_dim,
layer,
fname=None,
fd=None,
data_item=None,
):
# load variable data from file
current_size = 0
if layer is None:
layer = 0
close_file = False
if fd is None:
close_file = True
fd = self._open_ext_file(fname)
data_raw = []
line = " "
PyListUtil.reset_delimiter_used()
while line != "" and len(data_raw) < data_size:
line = fd.readline()
arr_line = PyListUtil.split_data_line(line, True)
if not MFComment.is_comment(arr_line, True):
data_raw += arr_line
else:
PyListUtil.reset_delimiter_used()
if len(data_raw) < data_size:
message = (
'Not enough data in file {} for data "{}". '
"Expected data size {} but only found "
"{}.".format(
fd.name,
self._data_dimensions.structure.name,
data_size,
current_size,
)
)
type_, value_, traceback_ = sys.exc_info()
if close_file:
fd.close()
raise MFDataException(
self._data_dimensions.structure.get_model(),
self._data_dimensions.structure.get_package(),
self._data_dimensions.structure.path,
"reading data file",
self._data_dimensions.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
message,
self._simulation_data.debug,
)
if data_type == DatumType.double_precision:
data_type = np.float64
elif data_type == DatumType.integer:
data_type = np.int32
data_out = np.fromiter(data_raw, dtype=data_type, count=data_size)
data_out = self._resolve_cellid_numbers_from_file(data_out)
if close_file:
fd.close()
data_out = np.reshape(data_out, data_dim)
return data_out, current_size
def load_from_package(
self,
first_line,
file_handle,
layer_shape,
storage,
keyword,
pre_data_comments=None,
):
# read in any pre data comments
current_line = self._read_pre_data_comments(
first_line, file_handle, pre_data_comments, storage
)
datautil.PyListUtil.reset_delimiter_used()
arr_line = datautil.PyListUtil.split_data_line(current_line)
package_dim = self._data_dimensions.package_dim
if len(arr_line) > 2:
# check for time array series
if arr_line[1].upper() == "TIMEARRAYSERIES":
storage.set_tas(arr_line[2], arr_line[1], self._current_key)
return layer_shape, [False, None]
if not self.structure.data_item_structures[0].just_data:
# verify keyword
index_num, aux_var_index = self._load_keyword(arr_line, 0, keyword)
else:
index_num = 0
aux_var_index = None
# TODO: Add species support
# if layered supported, look for layered flag
if self.structure.layered or aux_var_index is not None:
if (
len(arr_line) > index_num
and arr_line[index_num].lower() == "layered"
):
storage.layered = True
try:
layers = layer_shape
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"resolving layer dimensions",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
None,
self._simulation_data.debug,
ex,
)
if len(layers) > 0:
storage.init_layers(layers)
elif aux_var_index is not None:
# each layer stores a different aux variable
layers = len(package_dim.get_aux_variables()[0]) - 1
layer_shape = (layers,)
storage.layered = True
while storage.layer_storage.list_shape[0] < layers:
storage.add_layer()
else:
storage.flatten()
try:
dimensions = storage.get_data_dimensions(layer_shape)
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
comment = (
f'Could not get data shape for key "{self._current_key}".'
)
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"getting data shape",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
comment,
self._simulation_data.debug,
ex,
)
layer_size = 1
for dimension in dimensions:
layer_size *= dimension
if aux_var_index is None:
# loop through the number of layers
for layer in storage.layer_storage.indexes():
self._load_layer(
layer,
layer_size,
storage,
arr_line,
file_handle,
layer_shape,
)
else:
# write the aux var to it's unique index
self._load_layer(
(aux_var_index,),
layer_size,
storage,
arr_line,
file_handle,
layer_shape,
)
return layer_shape, [False, None]
def _load_layer(
self, layer, layer_size, storage, arr_line, file_handle, layer_shape
):
di_struct = self.structure.data_item_structures[0]
if not di_struct.just_data or datautil.max_tuple_abs_size(layer) > 0:
arr_line = self._get_next_data_line(file_handle)
layer_storage = storage.layer_storage[layer]
# if constant
if arr_line[0].upper() == "CONSTANT":
if len(arr_line) < 2:
message = (
'MFArray "{}" contains a CONSTANT that is not '
"followed by a number.".format(self.structure.name)
)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"loading data layer from file",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
message,
self._simulation_data.debug,
)
# store data
layer_storage.set_internal_constant()
try:
storage.store_internal(
[
convert_data(
arr_line[1],
self._data_dimensions,
self.structure.type,
di_struct,
)
],
layer,
const=True,
)
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"storing data",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
None,
self._simulation_data.debug,
ex,
)
# store anything else as a comment
if len(arr_line) > 2:
layer_storage.comments = MFComment(
" ".join(arr_line[2:]),
self._path,
self._simulation_data,
layer,
)
# if internal
elif arr_line[0].upper() == "INTERNAL":
try:
multiplier, print_format = storage.process_internal_line(
arr_line
)
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"processing line of data",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
None,
self._simulation_data.debug,
ex,
)
storage.layer_storage[layer].set_internal_array()
# store anything else as a comment
if len(arr_line) > 5:
layer_storage.comments = MFComment(
" ".join(arr_line[5:]),
self._path,
self._simulation_data,
layer,
)
try:
# load variable data from current file
if multiplier is not None:
storage.layer_storage[layer].factor = multiplier
if print_format is not None:
storage.layer_storage[layer].iprn = print_format
data_type = storage.data_dimensions.structure.get_datum_type(
True
)
data_from_file = self.read_text_data_from_file(
storage.get_data_size(layer),
data_type,
storage.get_data_dimensions(layer),
layer,
fd=file_handle,
)
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
f"reading data from file {file_handle.name}",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
None,
self._simulation_data.debug,
ex,
)
data_shaped = self._resolve_data_shape(
data_from_file[0], layer_shape, storage
)
try:
storage.store_internal(
data_shaped,
layer,
const=False,
multiplier=[multiplier],
print_format=print_format,
)
except Exception as ex:
comment = f'Could not store data: "{data_shaped}"'
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"storing data",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
comment,
self._simulation_data.debug,
ex,
)
elif arr_line[0].upper() == "OPEN/CLOSE":
try:
storage.process_open_close_line(arr_line, layer)
except Exception as ex:
comment = (
"Could not open open/close file specified by"
' "{}".'.format(" ".join(arr_line))
)
type_, value_, traceback_ = sys.exc_info()
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"storing data",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
comment,
self._simulation_data.debug,
ex,
)
def _is_cellid_or_numeric_index(self):
if (
self.structure.data_item_structures[0].numeric_index
or self.structure.data_item_structures[0].is_cellid
):
return True
return False
def _resolve_cellid_numbers_to_file(self, data):
if self._is_cellid_or_numeric_index():
return abs(data) + 1
else:
return data
def _resolve_cellid_numbers_from_file(self, data):
if self._is_cellid_or_numeric_index():
return abs(data) - 1
else:
return data
def _resolve_data_shape(self, data, layer_shape, storage):
try:
dimensions = storage.get_data_dimensions(layer_shape)
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
comment = (
f'Could not get data shape for key "{self._current_key}".'
)
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"getting data shape",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
comment,
self._simulation_data.debug,
ex,
)
if isinstance(data, list) or isinstance(data, np.ndarray):
try:
return np.reshape(data, dimensions).tolist()
except Exception as ex:
type_, value_, traceback_ = sys.exc_info()
comment = (
f'Could not reshape data to dimensions "{dimensions}".'
)
raise MFDataException(
self.structure.get_model(),
self.structure.get_package(),
self._path,
"reshaping data",
self.structure.name,
inspect.stack()[0][3],
type_,
value_,
traceback_,
comment,
self._simulation_data.debug,
ex,
)
else:
return data
class MFFileAccessList(MFFileAccess):
def __init__(
self, structure, data_dimensions, simulation_data, path, current_key
):
super().__init__(
structure, data_dimensions, simulation_data, path, current_key
)
self._last_line_info = []
self.simple_line = False
def read_binary_data_from_file(
self, read_file, modelgrid, precision="double"
):
# read from file
header, int_cellid_indexes, ext_cellid_indexes = self._get_header(
modelgrid, precision
)
file_array = np.fromfile(read_file, dtype=header, count=-1)
# build data list for recarray
cellid_size = len(self._get_cell_header(modelgrid))
data_list = []
for record in file_array:
data_record = ()
current_cellid_size = 0
current_cellid = ()
for index, data_item in enumerate(record):
if index in ext_cellid_indexes:
current_cellid += (data_item - 1,)
current_cellid_size += 1
if current_cellid_size == cellid_size:
data_record += current_cellid
data_record = (data_record,)