-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmfgrid.py
3778 lines (3058 loc) · 127 KB
/
mfgrid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Definition of Grid class.
A Grid class instance stores a Modflow Grid (rectangular with variable z).
It is used as both a grid container to pass a grid to functions
and as a server to requist numerous grid properties for instance
necessary for plotting. These properties can becomputed on the fly
and need not be storedr.
The Grid class also performs error checking.
Created on Fri Sep 30 04:26:57 2016
@author: Theo
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.axes import Axes
from datetime import datetime
import pandas as pd
from collections import OrderedDict
import scipy.interpolate as ip
import warnings
import unittest
def AND(*args):
"""Return results of multiple and's on array."""
L = args[0]
for arg in args:
L = np.logical_and(L, arg)
return L
def OR(*args):
"""Return results of multiple or's on array."""
L = args[0]
for arg in args:
L = np.logical_or(L, arg)
return L
NOT = np.logical_not
intNaN = -999999
# interpolate along the first dimension (time or z) for points x, y.
# This can be used of your data is (nt, ny, nx) or if it is (nz, ny, nx)
def show_lines(self, ax=None, co_dict=None,**kwargs):
"""Show muliple lines contained in co_dict.
Parameters
----------
ax: plt.Axes
axis or None to generate a fig with axis
co_dict: dict with model coordinates to be plotted
coordinates are co_dict[key][:,0], co_dict[key][:,1]
kwargs ['title', 'xlabel', 'ylabel', 'xlim', 'ylim'] --> ax
all other kwargs --> ax.plot
@TO 180608
"""
if ax is None:
fig, ax = plt.subplots()
ax.set_title(kwargs.pop('title', 'Title'))
ax.set_xlabel(kwargs.pop('xlabel', 'x [m]'))
ax.set_ylabel(kwargs.pop('ylabel', 'y [m]'))
ax.grid()
if 'xlim' in kwargs: ax.set('xlim', kwargs.pop('xlim'))
if 'ylim' in kwargs: ax.set('ylim', kwargs.pop('ylim'))
for k in co_dict:
ax.plot(co_dict[k][:,0], co_dict[k][:,1], label=k)
class StressPeriod:
"""Define stress period object.
Was used with Juliana Canal project for conveniently handling stress
periods and manipulating them.
@TO 2018
"""
def __init__(self, events_df, tsmult=1.25, dt0=1/24.):
"""Return stress period object.
Note that only the start time of the last stress period will be used
as the end time of the simulation. So at least two stress periods
have to be defined. Doing so, only the first is used and its lengt
is defined by the start time of the last stress period.
The number of time steps in each stress period is determined by
tsmult and dt0. The time-step lengths will be adjusted such that
tsmult is applied exactly and the first time_step is less or equal to
dt0.
Parameters
----------
events_df : pd.DataFram
must have the following columns:
['SP', 'year', 'month', 'day', 'hour,
'nstp', 'tsmult', 'remark']
tsmult : float
time step multiplier within stress periods
dt0 : float
approximate length of first time step of each stress period.
"""
# time-unit_conversion from seconds
self.events = events_df
# conversion of tiem dimension
self.ufac = {'s': 1., 'm': 1/60., 'h': 1/3600. , 'd': 1/86400.,
'w': 1/(7 * 86400.)}
columns = set(self.events.columns)
required_columns = set(['SP', 'year', 'month', 'day', 'hour',
'steady', 'remark'])
if not required_columns.issubset(columns):
missed = [m for m in required_columns.difference(columns)]
raise Exception('Missing required columns:' +
', '.join(missed)[1:])
self.events.fillna(method='ffill', inplace=True)
# Extract stress period information. Note that the last SP is a dummy
# that does not count, so select [:-1]
self.SP_numbers = np.asarray(np.unique(self.events['SP']),
dtype=int)
if any(np.diff(self.SP_numbers)>1):
print(self.SP_numbers[1:][np.diff(self.SP_numbers)>1])
raise Exception('Stress periods not consecutive')
self.nper = len(self.SP_numbers)
if self.nper < 1:
raise ValueError('Need at least 2 stress periods.\n' +
'The last one only determines the end time of the simulation.')
self.SP = dict()
prev_sp = -1
for i in self.events.index:
se = self.events.loc[i] # next stress event
sp = int(se['SP'])
""" an arbitrary number of duplicates may be used. This implies
that only the last line with this SP is kept."""
start = np.datetime64(datetime(year =int(se['year']),
month =int(se['month']),
day =int(se['day']),
hour =int(se['hour']),
minute=0,
second=0), 's')
if sp > prev_sp:
# use time and steady of fist event of new sp only (is safe)
self.SP[sp] = {'start' : start, 'steady': se['steady']}
if sp > 0:
# set the end time of prev. sp, it is the start time of the new one
self.SP[prev_sp]['end'] = start
prev_sp = sp
self.SP[sp]['end'] = start # last df_event is the end time of the last sp
# Convert back to pd.DataFrame (now with one entry per stress period)
self.SP = pd.DataFrame(self.SP).T
decreasing = self.SP['start'].diff() < pd.Timedelta(0, 'D')
if np.any(decreasing):
np.where(decreasing)[0]
raise ValueError('Start times for stress period(s) {} not increasing !'
.format(np.where(decreasing)[0]))
""" The three lines above moves the start times of the subsequent SP up.
The original first start_time will end last because it gets the last
index. However, this index is lost as the last stress period is
ignored; only its start time is used as the end time of the simulation.
"""
# Yields perlen in days
self.SP['perlen'] = np.abs(self.SP['end'] - self.SP['start'])
perlen_days = np.asarray(self.SP['perlen'], dtype=float) / (1.e9 * 86400)
"""
Step length multiplier:
`dt0 = perlen ((tsmult-1) / (tsmult**nstp - 1))`
Hence:
nstp = ln(perlen / dt0 * (tsmult -1) + 1) / ln(tsmult)
"""
self.SP['nstp'] = np.array(
np.ceil(
np.log( (np.asarray(perlen_days) / dt0) * (tsmult - 1) + 1)\
/ np.log(tsmult)
), dtype=int)
self.SP['steady'] = np.asarray(self.SP['steady'], dtype=int)
# stready or transient
self.SP['nstp'].loc[self.SP['steady'] == 1] = 1
self.SP['tsmult'] = tsmult
def get_perlen(self, asfloat=True, tunit='D'):
"""Return length of stress periods."""
plen = np.asarray(self.SP['perlen'], dtype='timedelta64[s]')
if asfloat:
return np.asarray(plen, dtype=np.float32) * self.ufac[tunit.lower()]
else:
return plen
@property
def steady(self):
"""Return which stress periods are steady."""
return np.asarray(self.SP['steady'], dtype=bool)
@property
def tsmult(self):
"""Return time step multiplication array."""
return np.asarray(self.SP['tsmult'], dtype=float)
@property
def nstp(self):
"""Return number of time steps for all stress periods."""
return np.asarray(self.SP['nstp'], dtype=int)
def get_datetimes(self, sp_only=False, aslists=True, fmt=None):
"""Return times all steps, starting at t=0.
Rarameters
----------
sp_only : bool
return only values for the end of each stress period
aslists : bool
if True: return as two lists first keys second values
if False: return as tuples (key, value)
fmt: None or format
fmt like in datetime.strfime, results are strings
Returns
-------
an OrderedDict with keys (sp, stpnr)
"""
_datetimes = OrderedDict()
for sp in self.SP.index: # self.SP is a DataFrame
stpNrs = np.arange(self.SP['nstp'][sp], dtype=int)
factors = self.SP['tsmult'][sp] ** stpNrs
dt = np.cumsum(self.SP['perlen'][sp] * \
(factors / np.sum(factors)))
for it, stpnr in enumerate(stpNrs):
deltat = self.SP['start'][sp] + dt[it]
if fmt is None:
_datetimes[(stpnr, sp)] = pd.to_datetime(deltat)
else:
_datetimes[(stpnr, sp)] = pd.to_datetime(deltat).strftime(fmt)
keys = list(_datetimes.keys())
if sp_only:
# the keys for the end of each stress period
kk = [k for k, j in zip(keys[:-1], keys[1:]) if j[0] > k[0]] + [keys[-1]]
od = OrderedDict()
for key in kk:
od[key] = _datetimes[key]
_datetimes=od
if aslists:
return [list(_datetimes.keys()), list(_datetimes.values())]
else:
return _datetimes
def get_keys(self, sp_only=False):
"""Return entry keys for the object."""
return self.get_datetimes(sp_only=sp_only, aslists=True)[0]
def get_oc(self, what=['save_head', 'print_budget', 'save_budget'], sp_only=False):
"""Return input for OC (output control).
Parameters
----------
what: list. Optional items in list:
'save head',
'save drawdown',
'save budget',
'print head',
'print drawdown',
'print budget'
sp_only: bool
return oc only for stress periods (not for time steps)
"""
labels=[]
for w in [w.lower() for w in what]:
if w.startswith('save'): s1 = 'save'
elif w.startswith('print'): s1 = 'print'
else:
raise ValueError("key must start with 'save' or 'print'")
if w.endswith('head'): s2 = 'head'
elif w.endswith('drawdown'): s2 = 'drawdown'
elif w.endswith('budget'): s2 = 'budget'
else:
raise ValueError("key must end with 'head', 'drawdown' or 'budget'" )
labels.append(' '.join([s1, s2]))
keys = self.get_keys(sp_only=sp_only)
sp_stp = [(k[1], k[0]) for k in keys]
return dict().fromkeys(sp_stp, labels)
def get_times(self, asfloats=True, tunit='D', sp_only=False, aslists=True):
"""Return datetime all steps, starting at start time of SP[0].
Returns
-------
OrderedDict with keys (sp, stepnr)
"""
dt = self.get_datetimes(sp_only=False, aslists=False)
keys = list(dt.keys())
_times = OrderedDict()
start = self.SP['start'][0]
for k in keys:
_times[k]=np.timedelta64(dt[k] - start, 's')
if asfloats:
for k in keys:
_times[k]=np.float32(_times[k]) * self.ufac[tunit.lower()] # to days
if sp_only:
# the keys for the end of each stress period
kk = [k for k, j in zip(keys[:-1], keys[1:]) if j[0] > k[0]] + [keys[-1]]
od = OrderedDict()
for k in kk:
od[k] = _times[k]
_times = od
if aslists:
return [list(_times.keys()), list(_times.values())]
else:
return _times
def get_steplen(self, asfloats=True, tunit='D', aslists=True):
"""Return steplen all steps.
Returns
-------
OrderedDict with keys (sp, stepnr)
"""
_dt = self.get_datetimes(aslists=False, sp_only=False)
_steplen = OrderedDict()
keys = list(_dt.keys())
_steplen[keys[0]] = np.timedelta64(_dt[keys[0]] - self.SP['start'][0], 's')
for k0, k1 in zip(keys[:-1], keys[1:]):
_steplen[k1] = np.timedelta64(_dt[k1] - _dt[k0], 's')
if asfloats:
for k in keys:
_steplen[k] = np.float32(_steplen[k]) * self.ufac[tunit.lower()]
if aslists:
return [list(_steplen.keys()),list( _steplen.values())]
else:
return _steplen
def show(self, ax=None, co_dict=None, **kwargs):
"""Show the lekvakken.
Parameters
----------
ax: plt.Axis
axis or None to generate a fig with axis
co_dict: dict with model coordinates to be plotted
coordinates are co_dict[key][:,0], co_dict[key][:,1]
"""
if ax is None:
fig, ax = plt.subplots()
ax.set_title(kwargs.pop('title', 'Title'))
ax.set_xlabel(kwargs.pop('xlabel', 'x [m]'))
ax.set_ylabel(kwargs.pop('ylabel', 'y [m]'))
if 'xlim' in kwargs: ax.set_xlim('xlim')
if 'ylim' in kwargs: ax.set_ylim('ylim')
for i in self.events.index:
se = self.events.loc[i]
ax.plot([se.x1, se.x2, se.x2, se.x1, se.x1],
[se.y2, se.y2, se.y1, se.y1, se.y2], **kwargs)
if co_dict is not None:
for k in co_dict:
ax.plot(co_dict[k][:,0], co_dict[k][:,1], label=k)
def cleanU(U, iu):
"""Clean up relative coordinates U, iu.
Clean up relative coordiantes U, iu such that
U lies between 0 and 1 (within a cell) and iu is
the cell number. The point is inside the model
if the cell number >=0 and <nx or likwise
ny and nz for the other two directions.
"""
U = np.array(U, dtype=float)
iu = np.array(iu, dtype=int)
shift = np.array(U, dtype=int) # integer part of U
shift[U < 0] -= 1
U -= shift # now U is between 0 and 1
iu += shift # iu is update pointing at cell where point is
return U, iu
def index(xp, x, left=-999, right=-999):
"""Return index for points xp in grid x.
Parameters
----------
xp : arraylike
points to be interpolated
x : arraylike
grid points
left : float
value for values left of left-most x
right : float
value for values right of right-most x
Returns
-------
I : arraylike
index of cells of xp
"""
xp = np.array(xp)
x = np.array(x)
if np.any(np.diff(x)<0):
x = -x
xp = - xp
assert np.all(np.diff(x) > 0), "x is not fully increasing or decreasing"
I = np.array(np.interp(xp, x, np.arange(len(x)), left, right),
dtype=int)
return np.fmin(I, len(x))
def lrc(xyz, xyzGr):
"""Return LRC indices (iL,iR, iC) of point (x, y, z).
Parameters
----------
xyz = (x, y,z) coordinates of a point
xyzGr= (xGr, yGr, zGr) grid coordinates
Returns
-------
idx=(iL, iR, iC) indices of point (x, y, z)
"""
LRC = list()
for x, xGr in zip(xyz, xyzGr):
LRC.insert(0, index(x, xGr))
return LRC
def psi_row(frf, row=-1, verbose=True):
"""Return stream function in row (x-section along x-axis).
Parameters
----------
frf: flow right face (nd_array)
3D array of flow right face.
row: int
zero based row number for which the stream function is desired.
verbose: bool
warn user with disclaimer about stream function.
Returns
-------
Psi (zx +1, ny - 1) array for for (x, z) coordinates except for first and last row.
"""
if verbose:
warnings.warn("psi_row only works when there is no flow along columns.")
fr = frf[:, row, :-1]
fr = np.vstack((fr, np.zeros_like(fr[0:1])))
psi = fr[::-1].cumsum(axis=0)[::-1]
return psi
def psi_col(fff, col=0, verbose=True):
"""Return stream function in column (cross section along y axis).
Parameters
----------
fff: flow front face (nd_array)
3D array of flow right face.
row: int
zero based row number for which the stream function is desired.
Returns
-------
Psi (nz, ny - 1) array for all (y, z) coordinates except the first and last column. (See Yp)
"""
if verbose:
warnings.warn("psi_col only works when there is no flow along rows.")
ff = fff[:, :-1, col]
ff = np.vstack((ff, np.zeros_like(ff[0:1])))
psi = ff[::-1].cumsum(axis=0)[::-1]
return psi
def psi_lay(Q, lay=0, verbose=True):
"""Return stream function in layer.
Parameters
----------
Q: net flow into layer (nd_array)
3D array of Q
lay: int
zero based layer number for which the stream function is desired.
Return stream function at the conrner points of the layer (ny +1, nx + 1)
"""
if verbose:
warnings.warn("psi_lay only works when there is no flow between layers.")
Q2 = Q[lay, :, :]
Q2 = np.hstack((np.zeros_like(Q2[:, 0]), Q2, np.zeros_like(Q2[:, -1])))
Q2 = np.vstack((np.zeros_like(Q2[0]), Q2, np.zeros_like(Q2[-1])))
psi = -Q2[::-1].cummsum(axis=0)[::-1]
return psi
class Grid:
"""Define a class to hold 3D finite difference grids.
Grid instances are 3D finite difference grids having many properties
that can be computed when requested. It can also plot itself.
Attributes
----------
`axial` : bool
If true interpret grid as axially symmetric, ignore y-values
`min_dz` : float
Mininum layer thickness to enforce
Methods
-------
`plot(linespec)`
Plot the grid
Examples
--------
gr = Grid(x, y, z, axial=False)
gr.plot('r-')
Obtaining grid property values:
gr.nx, gr.ny, gr.nz, gr.shape, gr.xm, gr.ym, gr.zm etc. etc.
The difficulty or trouble is when LAYCBD is not zero, which means that
one or more layers have a confining unit below them.
There should be now difficulty if nlay is used wherever the model layers
are ment and ncbd whereever the confining beds are meant. Only when there
are no confining beds, nlay==nz
Note that Z is the array of all surface elevations starting at the top of the model
and continuing to its bottom, that is including all boundaries between
the bottom of confining beds and underlying model layers.
The shape of the model must be equal to that of the model cells, excluding
the confininb beds.
The tops and bottom should reference whos of the model layers and or
those of the confining beds.
@TO 160930
"""
def __init__(self, x, y, z, axial=False, min_dz=0.001, tol=1e-10,
LAYCBD=None, georef=None):
"""Construct grid object.
Parameters
----------
`x` : arraylike
x-coordinates of the grid lines.
Will be made unique and ascending.
`y` : arraylike
y-coordinates of the grid lines.
Will be made unique. Use [-0.5 0.5] for cross sections
also when they are axial
`z` : arraylike
z-coordinates of the grid cells' tops and bottoms
z may be a vector, implying all z-planes are horizontal. The
vector holds tops and bottoms of these layers. The length
of z, therefore is one more than the number of layers. `z`
as a vector will be made unique and descending.
z may be a full 3D array holding tops and bottoms of a cells.
The length of z in the 3rd dimension is one more than the
number of layers.
z will be make unique and descending in 3d dimension.
Notice
------
z must inlcude a top and a bottom of every layer and confining bed.
Contrary to modflow, all confining beds must be included. Hence
the length of z in the 3rd dimension must equal the sum of the
number of aquifers and the number of aquitards + 1.
`axial` : bool
If True grid is assumed axially symmetric interpreing x as r
and ignoring actual y-coordinates.
If False grid is assumed linear (regular)
`min_dz` : float
Mininum layer thickness to be enforced (top down)
`tol` : float
Difference in x and y coordinates above with coordinates are
considered distinct. Coordinates will be rounded to tol before
applying uninque to them
`LAYCBD` : None or Vector [nlay]
it should have a value of 1 for every layer having
a confining bed below it and 0 if it has no confining bed
below it.
'georef` : tuple
(x0, x0, xw, yw, angle) relating world and model coordinates
"""
assert (axial is True) or (axial is False), "axial must be True or False."
assert tol > 0, "tol must be > 0."
assert min_dz > 0, "min_dz must be > 0."
self.AND = np.logical_and
self.NOT = np.logical_not
self.intNaN = -9999
self.axial = axial
self._min_dz = min_dz
self._tol = tol
self._digits = int(abs(np.log10(tol)))
x = np.round(np.array(x, dtype=float), self._digits)
if y is None:
y = [-0.5, 0.5]
y = np.round(np.array(y, dtype=float), self._digits)
self._x = np.unique(x)
self._nx= len(self._x) - 1
self._y = np.unique(y)[::-1] # always backward
self._ny = len(self._y) - 1
z = np.array(z)
# Check shape of z:
# It may be a vector for grids having horizontal layers
# or a 3D array where the layers correspond with tops and bottoms at the cell centers.
if len(z.shape) == 1: # z is given as a vector (tops and bottoms of layers)
self._full = False
# unique and put diecton upward increasing
self._Z = np.array(np.unique(z)[::-1], dtype=float)
# enforce min_dz
dz = np.fmax(np.abs(np.diff(self._Z)), self._min_dz)
self._nz = len(dz)
self._Z = self._Z[0] * np.ones(self._nz + 1)
self._Z[1:] -= np.cumsum(dz)
self._Z = self._Z[:, np.newaxis, np.newaxis]
elif len(z.shape)==3: # z is given as full 3D grid
if self._ny != z.shape[1] or self._nx != z.shape[2]:
print("\n\
The number of rows and columsn of Z is ({0},{1}).\n\
But expected was (ny, nx) = (nrow, ncol)=({3}, {4}) !\n\
Maybe the length of x and or y have been changed by\n\
__init__ to eliminate coordinates that are less\n\
than tol={2} apart.\n\
\n\
Remedy:\n\
1. Check that the difference between the sorted x coordinates\n\
is larger than the default or specified tolerance={2}.\n\
2. If so, then check the same for the y coordinates.\n\
3. If also correct, verify the size of your Z array.\n\
It must have (ny=nrows={3}, nx=ncol={4}).".
format(z.shape[0],z.shape[1],self.tol,
self._ny, self._nx))
raise ValueError("See printed message for details")
else:
self._full = True
self._Z = np.array(z, dtype=float)
self._nz = self._Z.shape[0] - 1
# make sure Z runs downward
if np.all(self._Z[0] < self._Z[-1]): # @TO 210629 np.all
self._Z = self._Z[::-1]
# make sure the Z[i] - Z[i+1] >= self._min_dz (min layer thickness)
for iz in range(self.nz):
dz = self._Z[iz] - self._Z[iz + 1] # must be positive
dz[dz <= self._min_dz] = self._min_dz
self._Z[iz + 1] = self._Z[iz] - dz
else: # illegal shape
s ="""\n\
z.shape = {}, but expected was a 1D vector\n\
or 3D array (nz+1, {}, {})""". \
format(z.shape, self._ny, self._nx)
raise ValueError(s)
self._shape = (self._nz, self._ny, self._nx)
"""Here we enter the confining beds defined thouth LAYCBD"""
# First complete the lAYCBD vector
if LAYCBD is None:
LAYCBD = np.zeros(self._nz, dtype=int)
else:
LAYCBD = np.array(LAYCBD, dtype=int)
LAYCBD[LAYCBD!=0] = 1 # valuesa are either 1 or 0
# How many layers and confining beds do we have?
self._ncbd = np.sum(LAYCBD)
self._nlay = self._nz - self._ncbd
# Check if input wass consistent
assert self._nlay > 0 and self._nlay>self._ncbd,\
"sum(LAYCBD)={} must be less than nlay={}"\
.format(self._ncbd, self._nlay)
# Compute ICBD the indices of the Z-layers pertaining to
# model layers (first column) and confing beds (second column)
self.LAYCBD = np.zeros(self._nlay, dtype=int)
self.LAYCBD[:len(LAYCBD)] = LAYCBD
ICBD = np.hstack((np.ones((self._nlay, 1), dtype=int),
self.LAYCBD[:, np.newaxis]))
ICBD = np.cumsum(ICBD.ravel()).reshape((self._nlay, 2))
ICBD = np.array(ICBD, dtype=int) - 1 # zero based
# Store which z pertain to model layers
self._Ilay = ICBD[:,0]
# and which pertain to confining beds
self._Icbd = ICBD[ICBD[:,0]!=ICBD[:,1], 1]
# The grid layer number if it's an CBD
self._ICBD = ICBD[:,1]; self._ICBD[ICBD[:,0] == ICBD[:, 1]] = 0
if georef is None:
georef = np.array([0., 0., 0., 0., 0.])
else:
georef = np.array(georef)
assert len(georef)==5,"georef must be a sequence or array having\
values [xm0, ym0, xw0, yw0, angle]"
self.georef_ = {'xm0': georef[0], 'ym0': georef[1],
'xw0': georef[2], 'yw0': georef[3],
'alfa': georef[4],
'cos': np.cos(georef[4] * np.pi/180.),
'sin': np.sin(georef[4] * np.pi/180.)}
# axial symmetry or not
if not isinstance(self.axial, bool):
raise ValueError(
"""axial={0} must be boolean True or False.\n\
Remedy:
use axial=True or axial=False explicitly\n\
when calling mfgrid.Grid class
""")
if not isinstance(self._min_dz, float) or self._min_dz <= 0.:
raise ValueError(
"""min_dz must be a postive float.
Remedy:
Use min_dz=value explicitly when calling mfgrid.Grid.
""")
@property
def tol(self):
return self._tol
@property
def georef(self):
"""Return the grid's georef = (xm0, ym0, xw0, yw0, alfa)."""
return (self.georef_['xm0'], self.georef_['ym0'],
self.georef_['xw0'], self.georef_['yw0'],
self.georef_['alfa'])
@property
def full(self):
"""Return boolean, indicating if full grid is stored.
If True, the grid stored is a full grid or one in which the z coordinates
are the same througout the grid (horionzontal layers only).
"""
return self._full # prevent ref to original
@property
def min_dz(self):
"""Return min layer thickess (stored in instance)."""
return self._min_dz # prevent ref to original
@property
def x(self):
"""Return vector of x-grid coordinates."""
return self._x.copy() # prevent ref. to self._x
@property
def X(self):
"""Return x-coordinates of model nodes (not world), always 3D."""
return np.ones((self._nz + 1, self._ny +1, 1)) *\
self._x[np.newaxis, np.newaxis, :]
@property
def Y(self):
"""Return y-coordinates of model nodes (not world) always 3D."""
return np.ones((self._nz + 1, 1, self._nx + 1)) *\
self._y[np.newaxis, :, np.newaxis]
@property
def y(self):
"""Return y or ny..0, steps -1 if axial==True."""
if self.axial:
return np.arange(self._ny, -1., -1.) - 1
else:
return self._y.copy() # prevent ref. to self._y
@property
def extent(self):
return self.x[0], self.x[-1], self.y[-1], self.y[0]
@property
def z(self):
"""Return average cell top and bottom elevatons [1, 1, nz+1]."""
if self.full:
return (self._Z).mean(axis=2).mean(axis=1)
else:
return self._Z[:, 0, 0]
@property
def Z(self):
"""Return cell top and bottom elevation [nz+1, ny, nx]."""
if self._full == False:
return self._Z * np.ones((1, self._ny, self._nx))
else:
return self._Z.copy()# prevent ref. to original
@property
def shape(self, cbd=False):
"""Return shape of the grid."""
if cbd == False:
return self._nlay, self._ny, self._nx # prevent ref. to original
else:
return self._ncbd, self._ny, self._nx
@property
def nx(self):
"""Return number of columns in the grid."""
return self._nx
@property
def ncol(self):
"""Return number of columns in the grid."""
return self._nx
@property
def ny(self):
"""Return number of rows in the grid."""
return self._ny
@property
def nrow(self):
"""Return number of rows in the grid."""
return self._ny
@property
def nz(self):
"""Return number of layers in the grid."""
return self._nz
@property
def nlay(self):
"""Return number of model layers in the grid."""
return self._nlay
@property
def ncbd(self):
"""Return number of confiing beds in the grid."""
return self._ncbd
@property
def nod(self):
"""Return number of cells in the grid."""
return self._nlay * self._ny * self._nx
@property
def NOD(self):
"""Return cell numbers in the grid."""
return np.arange(self.nod).reshape((self._nlay, self._ny, self._nx))
def LRC(self, Idx, astuples=None, aslist=None):
"""Return ndarray [L R C] indices generated from global indices or boolean array I.
Parameters
----------
Idx : ndarray of int or bool
if dtype is int, then Idx is global index
if dtype is bool, then Idx is a zone array of shape
[ny, nx] or [nz, ny, nx]
astuples: bool or None
return as ((l, r, c), (l, r, c), ...)
aslist: bool or None:
return as [[l, r, c], [l, r, c], ...]
"""
assert isinstance(Idx, np.ndarray), "I must be a np.ndarray of booleans or ints."
if len(Idx) == 0:
return Idx
assert Idx.dtype == int or Idx.dtype == bool, "I.dtype must be bool or int."
if Idx.dtype == bool:
assert np.all(self.shape == Idx.shape), "If Idx.dtype == bool, then I.shape must be equal to gr.shape"
Idx = self.NOD[Idx]
Idx = Idx.flatten()
ncol = self._nx
nlay = self._ny * ncol
L = np.array(Idx / nlay, dtype=int)
R = np.array((Idx - L * nlay) / ncol, dtype=int)
C = Idx - L * nlay - R * ncol
if astuples:
return tuple((lay, row, col) for lay, row, col in zip(L, R, C))
elif aslist:
return [[lay, row, col] for lay, row, col, in zip(L, R, C)]
else:
return np.vstack((L, R, C)).T
def LRC_zone(self, zone):
"""Return ndarray [L R C] indices generated from zone array zone.
Parameters
----------
zone : ndarray of dtype bool
zonearray, can be o shape (ny, nx) or (nz, ny, nx)
"""
if zone.ndim == 2:
return self.LRC(self.NOD[0][zone])
else:
return self.LRC(self.NOD[zone])
def lrc(self, x, y, z=None, Ilay=None):
"""Return zero-based LRC indices (iL,iR, iC) of points x, y, z.
Points must be given as x, y, z or as x, y, iLay.
The shape of x, y, and z or iLay must be the same.
If z is None then iLay is used.
If iLay is also None, then iLay is all zeros.
Parameters
----------
x : ndarray
x-coordinates
y : ndarray
y-coordinates
z : ndarray | None
z-coordinates
iLay : ndarray | None
layer indices
Returns
-------
[iL, iR, iC]
indices outside the extents of the model are < 0 (-999)
@TO 171105
"""
if np.isscalar(x): x = [x]
if np.isscalar(y): y = [y]
if np.isscalar(z): z = [z]
if np.isscalar(Ilay): Ilay = [Ilay]
x = np.array(x)
y = np.array(y)
if z is not None: z = np.array(z)
if Ilay is not None: Ilay = np.array(Ilay, dtype=int)
assert np.all(x.shape == y.shape), "x.shape must equal y.shape"
if z is not None:
assert np.all(x.shape == z.shape), "x.shape must equal z.shape"
else:
if Ilay is not None:
assert np.all(x.shape == Ilay.shape), "x.shape must equal iLay.shape"
else:
Ilay = np.zeros_like(x, dtype=int)
Icol = index(x, self.x)