/
structuredgrid.py
1647 lines (1450 loc) · 56.4 KB
/
structuredgrid.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 copy
import os.path
import numpy as np
from .grid import Grid, CachedData
def array_at_verts_basic2d(a):
"""
Computes values at cell vertices on 2d array using neighbor averaging.
Parameters
----------
a : ndarray
Array values at cell centers, could be a slice in any orientation.
Returns
-------
averts : ndarray
Array values at cell vertices, shape (a.shape[0]+1, a.shape[1]+1).
"""
assert a.ndim == 2
shape_verts2d = (a.shape[0] + 1, a.shape[1] + 1)
# create a 3D array of size (nrow+1, ncol+1, 4)
averts3d = np.full(shape_verts2d + (4,), np.nan)
averts3d[:-1, :-1, 0] = a
averts3d[:-1, 1:, 1] = a
averts3d[1:, :-1, 2] = a
averts3d[1:, 1:, 3] = a
# calculate the mean over the last axis, ignoring NaNs
averts = np.nanmean(averts3d, axis=2)
return averts
def array_at_faces_1d(a, delta):
"""
Interpolate array at cell faces of a 1d grid using linear interpolation.
Parameters
----------
a : 1d ndarray
Values at cell centers.
delta : 1d ndarray
Grid steps.
Returns
-------
afaces : 1d ndarray
Array values interpolated at cell faces, shape as input extended by 1.
"""
# extended array with ghost cells on both sides having zero values
ghost_shape = list(a.shape)
ghost_shape[0] += 2
a_ghost = np.zeros(ghost_shape, dtype=a.dtype)
# extended delta with ghost cells on both sides having zero values
delta_ghost = np.zeros(ghost_shape, dtype=a.dtype)
# fill array with ghost cells
a_ghost[1:-1] = a
a_ghost[0] = a[0]
a_ghost[-1] = a[-1]
# calculate weights
delta_ghost[1:-1] = delta
weight2 = delta_ghost[:-1] / (delta_ghost[:-1] + delta_ghost[1:])
weight1 = 1.0 - weight2
# interpolate
afaces = a_ghost[:-1] * weight1 + a_ghost[1:] * weight2
return afaces
class StructuredGrid(Grid):
"""
class for a structured model grid
Parameters
----------
delc
delc array
delr
delr array
Properties
----------
nlay
returns the number of model layers
nrow
returns the number of model rows
ncol
returns the number of model columns
delc
returns the delc array
delr
returns the delr array
xyedges
returns x-location points for the edges of the model grid and
y-location points for the edges of the model grid
Methods
----------
get_cell_vertices(i, j)
returns vertices for a single cell at row, column i, j.
"""
def __init__(
self,
delc=None,
delr=None,
top=None,
botm=None,
idomain=None,
lenuni=None,
epsg=None,
proj4=None,
prj=None,
xoff=0.0,
yoff=0.0,
angrot=0.0,
nlay=None,
nrow=None,
ncol=None,
laycbd=None,
):
super().__init__(
"structured",
top,
botm,
idomain,
lenuni,
epsg,
proj4,
prj,
xoff,
yoff,
angrot,
)
if delc is not None:
self.__nrow = len(delc)
self.__delc = delc.astype(float)
else:
self.__nrow = nrow
self.__delc = delc
if delr is not None:
self.__ncol = len(delr)
self.__delr = delr.astype(float)
else:
self.__ncol = ncol
self.__delr = delr
if top is not None:
assert self.__nrow * self.__ncol == len(np.ravel(top))
if botm is not None:
assert self.__nrow * self.__ncol == len(np.ravel(botm[0]))
if nlay is not None:
self.__nlay = nlay
else:
if laycbd is not None:
self.__nlay = len(botm) - np.count_nonzero(laycbd)
else:
self.__nlay = len(botm)
else:
self.__nlay = nlay
if laycbd is not None:
self._laycbd = laycbd
else:
self._laycbd = np.zeros(self.__nlay or (), dtype=int)
####################
# Properties
####################
@property
def is_valid(self):
if self.__delc is not None and self.__delr is not None:
return True
return False
@property
def is_complete(self):
if (
self.__delc is not None
and self.__delr is not None
and super().is_complete
):
return True
return False
@property
def nlay(self):
return self.__nlay
@property
def nrow(self):
return self.__nrow
@property
def ncol(self):
return self.__ncol
@property
def ncpl(self):
return self.__nrow * self.__ncol
@property
def nnodes(self):
return self.__nlay * self.__nrow * self.__ncol
@property
def nvert(self):
return (self.__nrow + 1) * (self.__ncol + 1)
@property
def iverts(self):
if self._iverts is None:
self._set_structured_iverts()
return self._iverts
@property
def verts(self):
if self._verts is None:
self._set_structured_verts()
return self._verts
@property
def shape(self):
return self.__nlay, self.__nrow, self.__ncol
@property
def extent(self):
self._copy_cache = False
xyzgrid = self.xyzvertices
self._copy_cache = True
return (
np.min(xyzgrid[0]),
np.max(xyzgrid[0]),
np.min(xyzgrid[1]),
np.max(xyzgrid[1]),
)
@property
def delc(self):
return copy.deepcopy(self.__delc)
@property
def delr(self):
return copy.deepcopy(self.__delr)
@property
def delz(self):
cache_index = "delz"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
delz = self.top_botm[:-1, :, :] - self.top_botm[1:, :, :]
self._cache_dict[cache_index] = CachedData(delz)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def top_botm_withnan(self):
"""
Same as top_botm array but with NaN where idomain==0 both above and
below a cell.
"""
cache_index = "top_botm_withnan"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
is_inactive_above = np.full(self.top_botm.shape, True)
is_inactive_above[:-1, :, :] = self._idomain == 0
is_inactive_below = np.full(self.top_botm.shape, True)
is_inactive_below[1:, :, :] = self._idomain == 0
where_to_nan = np.logical_and(is_inactive_above, is_inactive_below)
top_botm_withnan = np.where(where_to_nan, np.nan, self.top_botm)
self._cache_dict[cache_index] = CachedData(top_botm_withnan)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def xyzvertices(self):
"""
Method to get all grid vertices in a layer
Returns:
[]
2D array
"""
cache_index = "xyzgrid"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
xedge = np.concatenate(([0.0], np.add.accumulate(self.__delr)))
length_y = np.add.reduce(self.__delc)
yedge = np.concatenate(
([length_y], length_y - np.add.accumulate(self.delc))
)
xgrid, ygrid = np.meshgrid(xedge, yedge)
zgrid, zcenter = self._zcoords()
if self._has_ref_coordinates:
# transform x and y
pass
xgrid, ygrid = self.get_coords(xgrid, ygrid)
if zgrid is not None:
self._cache_dict[cache_index] = CachedData(
[xgrid, ygrid, zgrid]
)
else:
self._cache_dict[cache_index] = CachedData([xgrid, ygrid])
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def xyedges(self):
"""
Return a list of two 1D numpy arrays: one with the cell edge x
coordinate (size = ncol+1) and the other with the cell edge y
coordinate (size = nrow+1) in model space - not offset or rotated.
"""
cache_index = "xyedges"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
xedge = np.concatenate(([0.0], np.add.accumulate(self.__delr)))
length_y = np.add.reduce(self.__delc)
yedge = np.concatenate(
([length_y], length_y - np.add.accumulate(self.delc))
)
self._cache_dict[cache_index] = CachedData([xedge, yedge])
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def zedges(self):
"""
Return zedges for (column, row)==(0, 0).
"""
cache_index = "zedges"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
zedges = np.concatenate(
(np.array([self.top[0, 0]]), self.botm[:, 0, 0])
)
self._cache_dict[cache_index] = CachedData(zedges)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def zverts_smooth(self):
"""
Get a unique z of cell vertices using bilinear interpolation of top and
bottom elevation layers.
Returns
-------
zverts : ndarray, shape (nlay+1, nrow+1, ncol+1)
z of cell vertices. NaN values are assigned in accordance with
inactive cells defined by idomain.
"""
cache_index = "zverts_smooth"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
zverts_smooth = self.array_at_verts(self.top_botm)
self._cache_dict[cache_index] = CachedData(zverts_smooth)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def xycenters(self):
"""
Return a list of two numpy one-dimensional float arrays for center x
and y coordinates in model space - not offset or rotated.
"""
cache_index = "xycenters"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# get x centers
x = np.add.accumulate(self.__delr) - 0.5 * self.delr
# get y centers
Ly = np.add.reduce(self.__delc)
y = Ly - (np.add.accumulate(self.__delc) - 0.5 * self.__delc)
# store in cache
self._cache_dict[cache_index] = CachedData([x, y])
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def xyzcellcenters(self):
"""
Return a list of three numpy float arrays: two two-dimensional arrays
for center x and y coordinates, and one three-dimensional array for
center z coordinates. Coordinates are given in real-world coordinates.
"""
cache_index = "cellcenters"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# get x centers
x = np.add.accumulate(self.__delr) - 0.5 * self.delr
# get y centers
Ly = np.add.reduce(self.__delc)
y = Ly - (np.add.accumulate(self.__delc) - 0.5 * self.__delc)
x_mesh, y_mesh = np.meshgrid(x, y)
if self.__nlay is not None:
# get z centers
z = np.empty((self.__nlay, self.__nrow, self.__ncol))
z[0, :, :] = (self._top[:, :] + self._botm[0, :, :]) / 2.0
ibs = np.arange(self.__nlay)
quasi3d = [cbd != 0 for cbd in self._laycbd]
if np.any(quasi3d):
ibs[1:] = ibs[1:] + np.cumsum(quasi3d)[: self.__nlay - 1]
for l, ib in enumerate(ibs[1:], 1):
z[l, :, :] = (
self._botm[ib - 1, :, :] + self._botm[ib, :, :]
) / 2.0
else:
z = None
if self._has_ref_coordinates:
# transform x and y
x_mesh, y_mesh = self.get_coords(x_mesh, y_mesh)
# store in cache
self._cache_dict[cache_index] = CachedData([x_mesh, y_mesh, z])
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def grid_lines(self):
"""
Get the grid lines as a list
"""
# get edges initially in model coordinates
use_ref_coords = self.use_ref_coords
self.use_ref_coords = False
xyedges = self.xyedges
self.use_ref_coords = use_ref_coords
xmin = xyedges[0][0]
xmax = xyedges[0][-1]
ymin = xyedges[1][-1]
ymax = xyedges[1][0]
lines = []
# Vertical lines
for j in range(self.ncol + 1):
x0 = xyedges[0][j]
x1 = x0
y0 = ymin
y1 = ymax
lines.append([(x0, y0), (x1, y1)])
# horizontal lines
for i in range(self.nrow + 1):
x0 = xmin
x1 = xmax
y0 = xyedges[1][i]
y1 = y0
lines.append([(x0, y0), (x1, y1)])
if self._has_ref_coordinates:
lines_trans = []
for ln in lines:
lines_trans.append(
[self.get_coords(*ln[0]), self.get_coords(*ln[1])]
)
return lines_trans
return lines
@property
def is_regular_x(self):
"""
Test whether the grid spacing is regular in the x direction.
"""
cache_index = "is_regular_x"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# regularity test in x direction
rel_diff_x = (self.__delr - self.__delr[0]) / self.__delr[0]
is_regular_x = np.count_nonzero(np.abs(rel_diff_x) > rel_tol) == 0
self._cache_dict[cache_index] = CachedData(is_regular_x)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def is_regular_y(self):
"""
Test whether the grid spacing is regular in the y direction.
"""
cache_index = "is_regular_y"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# regularity test in y direction
rel_diff_y = (self.__delc - self.__delc[0]) / self.__delc[0]
is_regular_y = np.count_nonzero(np.abs(rel_diff_y) > rel_tol) == 0
self._cache_dict[cache_index] = CachedData(is_regular_y)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def is_regular_z(self):
"""
Test if the grid spacing is regular in z direction.
"""
cache_index = "is_regular_z"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# regularity test in z direction
rel_diff_thick0 = (
self.delz[0, :, :] - self.delz[0, 0, 0]
) / self.delz[0, 0, 0]
failed = np.abs(rel_diff_thick0) > rel_tol
is_regular_z = np.count_nonzero(failed) == 0
for k in range(1, self.nlay):
rel_diff_zk = (
self.delz[k, :, :] - self.delz[0, :, :]
) / self.delz[0, :, :]
failed = np.abs(rel_diff_zk) > rel_tol
is_regular_z = is_regular_z and np.count_nonzero(failed) == 0
self._cache_dict[cache_index] = CachedData(is_regular_z)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def is_regular_xy(self):
"""
Test if the grid spacing is regular and equal in x and y directions.
"""
cache_index = "is_regular_xy"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# test if the first delta is equal in x and z
rel_diff_0 = (self.__delc[0] - self.__delr[0]) / self.__delr[0]
first_equal = np.abs(rel_diff_0) <= rel_tol
# combine with regularity tests in x and z directions
is_regular_xy = (
first_equal and self.is_regular_x and self.is_regular_y
)
self._cache_dict[cache_index] = CachedData(is_regular_xy)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def is_regular_xz(self):
"""
Test if the grid spacing is regular and equal in x and z directions.
"""
cache_index = "is_regular_xz"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# test if the first delta is equal in x and z
rel_diff_0 = (self.delz[0, 0, 0] - self.__delr[0]) / self.__delr[0]
first_equal = np.abs(rel_diff_0) <= rel_tol
# combine with regularity tests in x and z directions
is_regular_xz = (
first_equal and self.is_regular_x and self.is_regular_z
)
self._cache_dict[cache_index] = CachedData(is_regular_xz)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def is_regular_yz(self):
"""
Test if the grid spacing is regular and equal in y and z directions.
"""
cache_index = "is_regular_yz"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# test if the first delta is equal in y and z
rel_diff_0 = (self.delz[0, 0, 0] - self.__delc[0]) / self.__delc[0]
first_equal = np.abs(rel_diff_0) <= rel_tol
# combine with regularity tests in x and y directions
is_regular_yz = (
first_equal and self.is_regular_y and self.is_regular_z
)
self._cache_dict[cache_index] = CachedData(is_regular_yz)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def is_regular(self):
"""
Test if the grid spacing is regular and equal in x, y and z directions.
"""
cache_index = "is_regular"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# test if the first delta is equal in x and z
rel_diff_0 = (self.delz[0, 0, 0] - self.__delr[0]) / self.__delr[0]
first_equal = np.abs(rel_diff_0) <= rel_tol
# combine with regularity tests in x, y and z directions
is_regular = (
first_equal and self.is_regular_z and self.is_regular_xy
)
self._cache_dict[cache_index] = CachedData(is_regular)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def is_rectilinear(self):
"""
Test whether the grid is rectilinear (it is always so in the x and
y directions, but not necessarily in the z direction).
"""
cache_index = "is_rectilinear"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
# relative tolerance to use in test
rel_tol = 1.0e-5
# rectilinearity test in z direction
is_rect_z = True
for k in range(self.nlay):
rel_diff_zk = (
self.delz[k, :, :] - self.delz[k, 0, 0]
) / self.delz[k, 0, 0]
failed = np.abs(rel_diff_zk) > rel_tol
is_rect_z = is_rect_z and np.count_nonzero(failed) == 0
self._cache_dict[cache_index] = CachedData(is_rect_z)
if self._copy_cache:
return self._cache_dict[cache_index].data
else:
return self._cache_dict[cache_index].data_nocopy
@property
def map_polygons(self):
"""
Get a list of matplotlib Polygon patches for plotting
Returns
-------
list of Polygon objects
"""
try:
import matplotlib.path as mpath
except ImportError:
raise ImportError("matplotlib required to use this method")
cache_index = "xyzgrid"
if (
cache_index not in self._cache_dict
or self._cache_dict[cache_index].out_of_date
):
self.xyzvertices
self._polygons = None
if self._polygons is None:
self._polygons = (self.xvertices, self.yvertices)
return self._polygons
###############
### Methods ###
###############
def intersect(self, x, y, local=False, forgive=False):
"""
Get the row and column of a point with coordinates x and y
When the point is on the edge of two cells, the cell with the lowest
row or column is returned.
Parameters
----------
x : float
The x-coordinate of the requested point
y : float
The y-coordinate of the requested point
local: bool (optional)
If True, x and y are in local coordinates (defaults to False)
forgive: bool (optional)
Forgive x,y arguments that fall outside the model grid and
return NaNs instead (defaults to False - will throw exception)
Returns
-------
row : int
The row number
col : int
The column number
"""
# transform x and y to local coordinates
x, y = super().intersect(x, y, local, forgive)
# get the cell edges in local coordinates
xe, ye = self.xyedges
xcomp = x > xe
if np.all(xcomp) or not np.any(xcomp):
if forgive:
col = np.nan
else:
raise Exception(
"x, y point given is outside of the model area"
)
else:
col = np.where(xcomp)[0][-1]
ycomp = y < ye
if np.all(ycomp) or not np.any(ycomp):
if forgive:
row = np.nan
else:
raise Exception(
"x, y point given is outside of the model area"
)
else:
row = np.where(ycomp)[0][-1]
if np.any(np.isnan([row, col])):
row = col = np.nan
return row, col
def _cell_vert_list(self, i, j):
"""Get vertices for a single cell or sequence of i, j locations."""
self._copy_cache = False
pts = []
xgrid, ygrid = self.xvertices, self.yvertices
pts.append([xgrid[i, j], ygrid[i, j]])
pts.append([xgrid[i + 1, j], ygrid[i + 1, j]])
pts.append([xgrid[i + 1, j + 1], ygrid[i + 1, j + 1]])
pts.append([xgrid[i, j + 1], ygrid[i, j + 1]])
pts.append([xgrid[i, j], ygrid[i, j]])
self._copy_cache = True
if np.isscalar(i):
return pts
else:
vrts = np.array(pts).transpose([2, 0, 1])
return [v.tolist() for v in vrts]
@property
def top_botm(self):
new_top = np.expand_dims(self._top, 0)
return np.concatenate((new_top, self._botm), axis=0)
def get_cell_vertices(self, *args, **kwargs):
"""
Method to get a set of cell vertices for a single cell
used in the Shapefile export utilities and plotting code
:param node: (int) node number
:param i: (int) cell row number
:param j: (int) cell column number
Returns
------- list of x,y cell vertices
"""
nn = None
if kwargs:
if "node" in kwargs:
nn = kwargs.pop("node")
else:
i = kwargs.pop("i")
j = kwargs.pop("j")
if len(args) > 0:
if len(args) == 1:
nn = args[0]
else:
i, j = args[0:2]
if nn is not None:
k, i, j = self.get_lrc(nn)[0]
self._copy_cache = False
cell_verts = [
(self.xvertices[i, j], self.yvertices[i, j]),
(self.xvertices[i, j + 1], self.yvertices[i, j + 1]),
(self.xvertices[i + 1, j + 1], self.yvertices[i + 1, j + 1]),
(self.xvertices[i + 1, j], self.yvertices[i + 1, j]),
]
self._copy_cache = True
return cell_verts
def get_lrc(self, nodes):
"""
Get layer, row, column from a list of zero based
MODFLOW node numbers.
Returns
-------
v : list of tuples containing the layer (k), row (i),
and column (j) for each node in the input list
"""
if not isinstance(nodes, list):
nodes = [nodes]
ncpl = self.ncpl
v = []
for node in nodes:
k = int(np.floor(node / ncpl))
ij = int((node) - (ncpl * k))
i = int(np.floor(ij / self.__ncol))
j = int(ij - (i * self.__ncol))
v.append((k, i, j))
return v
def get_node(self, lrc_list):
"""
Get node number from a list of zero based MODFLOW
layer, row, column tuples.
Returns
-------
v : list of MODFLOW nodes for each layer (k), row (i),
and column (j) tuple in the input list
"""
if not isinstance(lrc_list, list):
lrc_list = [lrc_list]
nrc = self.__nrow * self.__ncol
v = []
for [k, i, j] in lrc_list:
node = int(((k) * nrc) + ((i) * self.__ncol) + j)
v.append(node)
return v
def plot(self, **kwargs):
"""
Plot the grid lines.
Parameters
----------
kwargs : ax, colors. The remaining kwargs are passed into the
the LineCollection constructor.
Returns
-------
lc : matplotlib.collections.LineCollection
"""
from ..plot import PlotMapView
mm = PlotMapView(modelgrid=self)
return mm.plot_grid(**kwargs)
# Importing
@classmethod
def from_gridspec(cls, gridspec_file, lenuni=0):
f = open(gridspec_file, "r")
raw = f.readline().strip().split()
nrow = int(raw[0])
ncol = int(raw[1])
raw = f.readline().strip().split()
xul, yul, rot = float(raw[0]), float(raw[1]), float(raw[2])
delr = []
j = 0
while j < ncol:
raw = f.readline().strip().split()
for r in raw:
if "*" in r:
rraw = r.split("*")
for n in range(int(rraw[0])):
delr.append(float(rraw[1]))
j += 1
else:
delr.append(float(r))
j += 1
delc = []
i = 0
while i < nrow:
raw = f.readline().strip().split()
for r in raw:
if "*" in r:
rraw = r.split("*")
for n in range(int(rraw[0])):
delc.append(float(rraw[1]))
i += 1
else:
delc.append(float(r))
i += 1
f.close()
grd = cls(np.array(delc), np.array(delr), lenuni=lenuni)
xll = grd._xul_to_xll(xul)
yll = grd._yul_to_yll(yul)
cls.set_coord_info(xoff=xll, yoff=yll, angrot=rot)
return cls
def array_at_verts_basic(self, a):
"""
Computes values at cell vertices using neighbor averaging.
Parameters
----------
a : ndarray
Array values at cell centers.
Returns
-------
averts : ndarray
Array values at cell vertices, shape
(a.shape[0]+1, a.shape[1]+1, a.shape[2]+1). NaN values are assigned
in accordance with inactive cells defined by idomain.
"""
assert a.ndim == 3
shape_verts = (a.shape[0] + 1, a.shape[1] + 1, a.shape[2] + 1)
# set to NaN where idomain==0
a[self._idomain == 0] = np.nan
# create a 4D array of size (nlay+1, nrow+1, ncol+1, 8)
averts4d = np.full(shape_verts + (8,), np.nan)
averts4d[:-1, :-1, :-1, 0] = a
averts4d[:-1, :-1, 1:, 1] = a
averts4d[:-1, 1:, :-1, 2] = a
averts4d[:-1, 1:, 1:, 3] = a
averts4d[1:, :-1, :-1, 4] = a
averts4d[1:, :-1, 1:, 5] = a
averts4d[1:, 1:, :-1, 6] = a
averts4d[1:, 1:, 1:, 7] = a