-
Notifications
You must be signed in to change notification settings - Fork 323
/
Copy pathtest_export.py
2118 lines (1734 loc) · 66.7 KB
/
test_export.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 math
import os
import shutil
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pytest
from flaky import flaky
from modflow_devtools.markers import excludes_platform, requires_exe, requires_pkg
from modflow_devtools.misc import has_pkg
import flopy
from autotest.conftest import get_example_data_path
from flopy.discretization import StructuredGrid, UnstructuredGrid
from flopy.export import NetCdf
from flopy.export.shapefile_utils import recarray2shp, shp2recarray
from flopy.export.utils import (
export_array,
export_array_contours,
export_contourf,
export_contours,
)
from flopy.export.vtk import Vtk
from flopy.mf6 import (
MFSimulation,
ModflowGwf,
ModflowGwfchd,
ModflowGwfdis,
ModflowGwfdisu,
ModflowGwfdisv,
ModflowGwfic,
ModflowGwfnpf,
ModflowIms,
ModflowTdis,
)
from flopy.modflow import Modflow, ModflowDis
from flopy.modpath import Modpath6, Modpath6Bas
from flopy.utils import (
CellBudgetFile,
HeadFile,
PathlineFile,
import_optional_dependency,
)
from flopy.utils import postprocessing as pp
from flopy.utils.crs import get_authority_crs
from flopy.utils.geometry import Polygon
HAS_PYPROJ = has_pkg("pyproj", strict=True)
if HAS_PYPROJ:
import pyproj
def namfiles() -> list[Path]:
mf2005_path = get_example_data_path() / "mf2005_test"
return list(mf2005_path.rglob("*.nam"))
def disu_sim(name, tmpdir, missing_arrays=False):
"""
Get a simulation with a GWF model on a DISU grid,
optionally removing angldegx arrays. In this case
a warning is currently shown but export proceeds.
"""
from flopy.utils.gridgen import Gridgen
Lx = 10000.0
Ly = 10500.0
nlay = 3
nrow = 21
ncol = 20
delr = Lx / ncol
delc = Ly / nrow
top = 400
botm = [220, 200, 0]
ml5 = Modflow()
dis5 = ModflowDis(
ml5,
nlay=nlay,
nrow=nrow,
ncol=ncol,
delr=delr,
delc=delc,
top=top,
botm=botm,
)
g = Gridgen(ml5.modelgrid, model_ws=str(tmpdir))
xmin = 7 * delr
xmax = 12 * delr
ymin = 8 * delc
ymax = 13 * delc
rfpoly = [[[(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax), (xmin, ymin)]]]
g.add_refinement_features(rfpoly, "polygon", 2, [0])
g.build(verbose=False)
gridprops = g.get_gridprops_disu6()
if missing_arrays:
del gridprops["angldegx"]
sim = MFSimulation(sim_name=name, sim_ws=tmpdir, exe_name="mf6")
tdis = ModflowTdis(sim)
ims = ModflowIms(sim)
gwf = ModflowGwf(sim, modelname=name, save_flows=True)
dis = ModflowGwfdisu(gwf, **gridprops)
ic = ModflowGwfic(gwf, strt=np.random.random_sample(gwf.modelgrid.nnodes) * 350)
npf = ModflowGwfnpf(gwf, k=np.random.random_sample(gwf.modelgrid.nnodes) * 10)
return sim
@pytest.fixture
def unstructured_grid(example_data_path):
ws = example_data_path / "unstructured"
# load vertices
verts = load_verts(ws / "ugrid_verts.dat")
# load the index list into iverts, xc, and yc
iverts, xc, yc = load_iverts(ws / "ugrid_iverts.dat", closed=True)
# create a 3 layer model grid
ncpl = np.array(3 * [len(iverts)])
nnodes = np.sum(ncpl)
top = np.ones(nnodes)
botm = np.ones(nnodes)
# set top and botm elevations
i0 = 0
i1 = ncpl[0]
elevs = [100, 0, -100, -200]
for ix, cpl in enumerate(ncpl):
top[i0:i1] *= elevs[ix]
botm[i0:i1] *= elevs[ix + 1]
i0 += cpl
i1 += cpl
return UnstructuredGrid(
vertices=verts,
iverts=iverts,
xcenters=xc,
ycenters=yc,
top=top,
botm=botm,
ncpl=ncpl,
)
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
@pytest.mark.parametrize("pathlike", (True, False))
def test_output_helper_shapefile_export(pathlike, function_tmpdir, example_data_path):
ml = Modflow.load(
"freyberg.nam",
model_ws=str(example_data_path / "freyberg_multilayer_transient"),
)
head = HeadFile(os.path.join(ml.model_ws, "freyberg.hds"))
cbc = CellBudgetFile(os.path.join(ml.model_ws, "freyberg.cbc"))
if pathlike:
outpath = function_tmpdir / "test-pathlike.shp"
else:
outpath = os.path.join(function_tmpdir, "test.shp")
flopy.export.utils.output_helper(
outpath, ml, {"HDS": head, "cbc": cbc}, mflay=1, kper=10
)
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
@pytest.mark.slow
def test_freyberg_export(function_tmpdir, example_data_path):
# steady state
name = "freyberg"
namfile = f"{name}.nam"
ws = example_data_path / name
m = flopy.modflow.Modflow.load(namfile, model_ws=ws, check=False, verbose=False)
# test export at model, package and object levels
shpfile_path = function_tmpdir / "model.shp"
m.export(shpfile_path)
assert shpfile_path.exists()
shpfile_path = function_tmpdir / "wel.shp"
m.wel.export(shpfile_path)
assert shpfile_path.exists()
shpfile_path = function_tmpdir / "hk.shp"
m.lpf.hk.export(shpfile_path)
assert shpfile_path.exists()
shpfile_path = function_tmpdir / "riv_spd.shp"
m.riv.stress_period_data.export(shpfile_path)
assert shpfile_path.exists()
# transient
# (doesn't work at model level because the total size of
# the attribute fields exceeds the shapefile limit)
ws = example_data_path / "freyberg_multilayer_transient"
m = flopy.modflow.Modflow.load(
namfile,
model_ws=ws,
verbose=False,
load_only=["DIS", "BAS6", "NWT", "OC", "RCH", "WEL", "DRN", "UPW"],
)
# test export without instantiating a modelgrid
m.modelgrid.crs = None
shape = function_tmpdir / f"{name}_drn_sparse.shp"
m.drn.stress_period_data.export(shape, sparse=True)
for suffix in [".dbf", ".shp", ".shx"]:
part = shape.with_suffix(suffix)
assert part.exists()
part.unlink()
assert not shape.with_suffix(".prj").exists()
m.modelgrid = StructuredGrid(delc=m.dis.delc.array, delr=m.dis.delr.array, crs=3070)
# test export with a modelgrid, regardless of whether or not wkt was found
m.drn.stress_period_data.export(shape, sparse=True)
for suffix in [".dbf", ".prj", ".shp", ".shx"]:
part = shape.with_suffix(suffix)
assert part.exists()
part.unlink()
m.modelgrid = StructuredGrid(delc=m.dis.delc.array, delr=m.dis.delr.array, crs=3070)
# verify that attributes have same modelgrid as parent
assert m.drn.stress_period_data.mg.crs == m.modelgrid.crs
assert m.drn.stress_period_data.mg.xoffset == m.modelgrid.xoffset
assert m.drn.stress_period_data.mg.yoffset == m.modelgrid.yoffset
assert m.drn.stress_period_data.mg.angrot == m.modelgrid.angrot
# get wkt text from pyproj
wkt = m.modelgrid.crs.to_wkt()
# if wkt text was fetched from pyproj
if wkt is not None:
# test default package export
shape = function_tmpdir / f"{name}_dis.shp"
m.dis.export(shape)
for suffix in [".dbf", ".prj", ".shp", ".shx"]:
part = shape.with_suffix(suffix)
assert part.exists()
if suffix == ".prj":
assert part.read_text() == wkt
part.unlink()
# test default package export to higher level dir ?
# test sparse package export
shape = function_tmpdir / f"{name}_drn_sparse.shp"
m.drn.stress_period_data.export(shape, sparse=True)
for suffix in [".dbf", ".prj", ".shp", ".shx"]:
part = shape.with_suffix(suffix)
assert part.exists()
if suffix == ".prj":
assert part.read_text() == wkt
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
@pytest.mark.parametrize("missing_arrays", [True, False])
@pytest.mark.slow
def test_disu_export(function_tmpdir, missing_arrays):
name = "export_disu"
# check that missing angldegx array is tolerated
# https://github.com/modflowpy/flopy/issues/1775
sim = disu_sim(name, function_tmpdir, missing_arrays)
m = sim.get_model(name)
# test export at model level
shpfile_path = function_tmpdir / "model.shp"
m.export(shpfile_path)
assert shpfile_path.exists()
# test export at package level
shpfile_path = function_tmpdir / "disu.shp"
m.disu.export(shpfile_path)
assert shpfile_path.exists()
# for now, test with and without a coordinate reference system
@pytest.mark.parametrize("crs", (None, 26916))
@requires_pkg("netCDF4", "pyproj")
def test_export_output(crs, function_tmpdir, example_data_path):
ml = Modflow.load("freyberg.nam", model_ws=str(example_data_path / "freyberg"))
ml.modelgrid.crs = crs
hds_pth = os.path.join(ml.model_ws, "freyberg.githds")
hds = flopy.utils.HeadFile(hds_pth)
out_pth = function_tmpdir / f"freyberg_{crs}.out.nc"
nc = flopy.export.utils.output_helper(out_pth, ml, {"freyberg.githds": hds})
var = nc.nc.variables.get("head")
arr = var[:]
ibound_mask = ml.bas6.ibound.array == 0
arr_mask = arr.mask[0]
assert np.array_equal(ibound_mask, arr_mask)
# close the netcdf file
nc.nc.close()
# verify that the CRS was written correctly
import netCDF4
import pyproj
ds = netCDF4.Dataset(out_pth)
read_crs = pyproj.CRS.from_cf(ds["latitude_longitude"].__dict__)
# currently, NetCDF files are only written
# in the 4326 coordinate reference system
# (lat/lon WGS 84)
assert read_crs == get_authority_crs(4326)
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
def test_write_gridlines_shapefile(function_tmpdir):
import shapefile
from flopy.discretization import StructuredGrid
from flopy.export.shapefile_utils import write_gridlines_shapefile
sg = StructuredGrid(
delr=np.ones(10) * 1.1,
# cell spacing along model rows
delc=np.ones(10) * 1.1,
# cell spacing along model columns
crs=26715,
)
outshp = function_tmpdir / "gridlines.shp"
write_gridlines_shapefile(outshp, sg)
for suffix in [".dbf", ".shp", ".shx"]:
assert outshp.with_suffix(suffix).exists()
assert outshp.with_suffix(".prj").exists() == HAS_PYPROJ
with shapefile.Reader(str(outshp)) as sf:
assert sf.shapeType == shapefile.POLYLINE
assert len(sf) == 22
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
def test_export_shapefile_polygon_closed(function_tmpdir):
from shapefile import Reader
xll, yll = 468970, 3478635
xur, yur = 681010, 3716462
spacing = 2000
ncol = int((xur - xll) / spacing)
nrow = int((yur - yll) / spacing)
print(nrow, ncol)
m = flopy.modflow.Modflow("test.nam", crs="EPSG:32614", xll=xll, yll=yll)
flopy.modflow.ModflowDis(m, delr=spacing, delc=spacing, nrow=nrow, ncol=ncol)
shp_file = os.path.join(function_tmpdir, "test_polygon.shp")
m.dis.export(shp_file)
shp = Reader(shp_file)
for shape in shp.iterShapes():
if len(shape.points) != 5:
raise AssertionError("Shapefile polygon is not closed!")
shp.close()
@requires_pkg("rasterio", "pyshp", "scipy", name_map={"pyshp": "shapefile"})
def test_export_array(function_tmpdir, example_data_path):
import rasterio
from scipy.ndimage import rotate
namfile = "freyberg.nam"
model_ws = example_data_path / "freyberg"
m = flopy.modflow.Modflow.load(
namfile,
model_ws=model_ws,
verbose=False,
load_only=["DIS", "BAS6"],
)
m.modelgrid.set_coord_info(angrot=45)
nodata = -9999
export_array(
m.modelgrid,
os.path.join(function_tmpdir, "fb.asc"),
m.dis.top.array,
nodata=nodata,
)
arr = np.loadtxt(function_tmpdir / "fb.asc", skiprows=6)
m.modelgrid.write_shapefile(function_tmpdir / "grid.shp")
# check bounds
with open(function_tmpdir / "fb.asc") as src:
for line in src:
if "xllcorner" in line.lower():
val = float(line.strip().split()[-1])
assert np.abs(val - m.modelgrid.extent[0]) < 1e-6
# ascii grid origin will differ if it was unrotated
# without scipy.rotate
if "yllcorner" in line.lower():
val = float(line.strip().split()[-1])
assert np.abs(val - m.modelgrid.extent[2]) < 1e-6
# without scipy.rotate
if "cellsize" in line.lower():
val = float(line.strip().split()[-1])
rot_cellsize = (
np.cos(np.radians(m.modelgrid.angrot)) * m.modelgrid.delr[0]
)
break
rotated = rotate(m.dis.top.array, m.modelgrid.angrot, cval=nodata)
assert rotated.shape == arr.shape
export_array(
m.modelgrid,
function_tmpdir / "fb.tif",
m.dis.top.array,
nodata=nodata,
)
with rasterio.open(function_tmpdir / "fb.tif") as src:
arr = src.read(1)
assert src.shape == (m.nrow, m.ncol)
assert np.abs(src.bounds[0] - m.modelgrid.extent[0]) < 1e-6
assert np.abs(src.bounds[2] - m.modelgrid.extent[1]) < 1e-6
assert np.abs(src.bounds[1] - m.modelgrid.extent[2]) < 1e-6
assert np.abs(src.bounds[3] - m.modelgrid.extent[3]) < 1e-6
@requires_pkg("netCDF4", "pyproj")
def test_netcdf_classmethods(function_tmpdir, example_data_path):
namfile = "freyberg.nam"
name = namfile.replace(".nam", "")
model_ws = example_data_path / "freyberg_multilayer_transient"
ml = flopy.modflow.Modflow.load(
namfile,
model_ws=model_ws,
check=False,
verbose=True,
load_only=[],
)
f = ml.export(function_tmpdir / "freyberg.nc")
v1_set = set(f.nc.variables.keys())
fnc = function_tmpdir / "freyberg.new.nc"
new_f = flopy.export.NetCdf.zeros_like(f, output_filename=fnc)
v2_set = set(new_f.nc.variables.keys())
diff = v1_set.symmetric_difference(v2_set)
assert len(diff) == 0, str(diff)
# close the netcdf file
f.nc.close()
new_f.nc.close()
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
def test_shapefile_ibound(function_tmpdir, example_data_path):
from shapefile import Reader
shape_name = os.path.join(function_tmpdir, "test.shp")
namfile = "freyberg.nam"
model_ws = example_data_path / "freyberg_multilayer_transient"
ml = flopy.modflow.Modflow.load(
namfile,
model_ws=model_ws,
check=False,
verbose=True,
load_only=["bas6"],
)
ml.export(shape_name)
shape = Reader(shape_name)
field_names = [item[0] for item in shape.fields][1:]
ib_idx = field_names.index("ibound_1")
txt = f"should be int instead of {type(shape.record(0)[ib_idx])}"
assert isinstance(shape.record(0)[ib_idx], int), txt
shape.close()
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
@pytest.mark.slow
@pytest.mark.parametrize("namfile", namfiles())
def test_shapefile(function_tmpdir, namfile):
from shapefile import Reader
model = flopy.modflow.Modflow.load(
namfile.name, model_ws=namfile.parent, verbose=False
)
assert model, f"Could not load namefile {namfile}"
msg = f"Could not load {namfile} model"
assert isinstance(model, flopy.modflow.Modflow), msg
fnc_name = function_tmpdir / f"{model.name}.shp"
fnc = model.export(fnc_name)
s = Reader(fnc_name)
assert s.numRecords == model.nrow * model.ncol, (
f"wrong number of records in shapefile {fnc_name}"
)
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
@pytest.mark.slow
@pytest.mark.parametrize("namfile", namfiles())
def test_shapefile_export_modelgrid_override(function_tmpdir, namfile):
from shapefile import Reader
model = flopy.modflow.Modflow.load(
namfile.name, model_ws=str(namfile.parent), verbose=False
)
grid = model.modelgrid
modelgrid = StructuredGrid(
grid.delc * 0.3048,
grid.delr * 0.3048,
grid.top,
grid.botm,
grid.idomain,
grid.lenuni,
grid.crs,
xoff=grid.xoffset,
yoff=grid.yoffset,
angrot=grid.angrot,
)
assert model, f"Could not load namefile {namfile}"
assert isinstance(model, flopy.modflow.Modflow)
fnc_name = function_tmpdir / f"{model.name}.shp"
model.export(fnc_name, modelgrid=modelgrid)
# TODO: do we want to test exports with package_names options too?
# (both currently fail)
# fnc2 = model.export(fnc_name, package_names=None)
# fnc3 = model.export(fnc_name, package_names=['DIS'])
s = Reader(fnc_name)
s.close()
@requires_pkg("netCDF4", "pyproj")
@pytest.mark.slow
@pytest.mark.parametrize("namfile", namfiles())
def test_export_netcdf(function_tmpdir, namfile):
from netCDF4 import Dataset
model = flopy.modflow.Modflow.load(
namfile.name, model_ws=namfile.parent, verbose=False
)
if model.dis.lenuni == 0:
model.dis.lenuni = 1
if model.dis.botm.shape[0] != model.nlay:
print("skipping...botm.shape[0] != nlay")
return
assert model, f"Could not load namefile {namfile}"
assert isinstance(model, flopy.modflow.Modflow)
fnc = model.export(function_tmpdir / f"{model.name}.nc")
fnc.write()
fnc_name = function_tmpdir / f"{model.name}.nc"
fnc = model.export(fnc_name)
fnc.write()
nc = Dataset(fnc_name, "r")
nc.close()
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
def test_export_array2(function_tmpdir):
nrow = 7
ncol = 11
crs = 4431
# no epsg code
modelgrid = StructuredGrid(delr=np.ones(ncol) * 1.1, delc=np.ones(nrow) * 1.1)
filename = os.path.join(function_tmpdir, "myarray1.shp")
a = np.arange(nrow * ncol).reshape((nrow, ncol))
export_array(modelgrid, filename, a)
assert os.path.isfile(filename), "did not create array shapefile"
# with modelgrid epsg code
modelgrid = StructuredGrid(
delr=np.ones(ncol) * 1.1, delc=np.ones(nrow) * 1.1, crs=crs
)
filename = os.path.join(function_tmpdir, "myarray2.shp")
a = np.arange(nrow * ncol).reshape((nrow, ncol))
export_array(modelgrid, filename, a)
assert os.path.isfile(filename), "did not create array shapefile"
# with passing in epsg code
modelgrid = StructuredGrid(delr=np.ones(ncol) * 1.1, delc=np.ones(nrow) * 1.1)
filename = os.path.join(function_tmpdir, "myarray3.shp")
a = np.arange(nrow * ncol).reshape((nrow, ncol))
export_array(modelgrid, filename, a, crs=crs)
assert os.path.isfile(filename), "did not create array shapefile"
@pytest.mark.mf6
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
def test_array3d_export_structured(function_tmpdir):
from shapefile import Reader
xll, yll = 468970, 3478635
xur, yur = 681010, 3716462
spacing = 20000
ncol = int((xur - xll) / spacing)
nrow = int((yur - yll) / spacing)
sim = flopy.mf6.MFSimulation("sim", sim_ws=function_tmpdir)
gwf = flopy.mf6.ModflowGwf(sim, modelname="array3d_export_unstructured")
flopy.mf6.ModflowGwfdis(
gwf,
nlay=3,
top=5,
botm=[4, 3, 2],
delr=spacing,
delc=spacing,
nrow=nrow,
ncol=ncol,
)
shp_file = os.path.join(function_tmpdir, "dis_botm.shp")
gwf.dis.botm.export(shp_file)
with Reader(shp_file) as shp:
assert list(shp.shapeRecord(-1).record) == [
110, # node
11, # row
10, # column
4.0, # botm_1
3.0, # botm_2
2.0, # botm_3
]
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
def test_array3d_export_unstructured(function_tmpdir):
from shapefile import Reader
name = "array3d_export_unstructured"
sim = disu_sim(name, function_tmpdir)
gwf = sim.get_model(name)
shp_file = function_tmpdir / "disu_bot.shp"
gwf.disu.bot.export(shp_file)
with Reader(shp_file) as shp:
assert list(shp.shapeRecord(-1).record) == [
1770, # node
3, # layer
0.0, # bot
]
@requires_pkg("pyshp", "shapely", name_map={"pyshp": "shapefile"})
def test_export_array_contours_structured(function_tmpdir):
nrow = 7
ncol = 11
crs = 4431
# no epsg code
modelgrid = StructuredGrid(delr=np.ones(ncol) * 1.1, delc=np.ones(nrow) * 1.1)
filename = function_tmpdir / "myarraycontours1.shp"
a = np.arange(nrow * ncol).reshape((nrow, ncol))
export_array_contours(modelgrid, filename, a)
assert os.path.isfile(filename), "did not create contour shapefile"
# with modelgrid coordinate reference
modelgrid = StructuredGrid(
delr=np.ones(ncol) * 1.1,
delc=np.ones(nrow) * 1.1,
crs=crs,
)
filename = function_tmpdir / "myarraycontours2.shp"
a = np.arange(nrow * ncol).reshape((nrow, ncol))
export_array_contours(modelgrid, filename, a)
assert os.path.isfile(filename), "did not create contour shapefile"
# with passing in coordinate reference
modelgrid = StructuredGrid(delr=np.ones(ncol) * 1.1, delc=np.ones(nrow) * 1.1)
filename = function_tmpdir / "myarraycontours3.shp"
a = np.arange(nrow * ncol).reshape((nrow, ncol))
export_array_contours(modelgrid, filename, a, crs=crs)
assert os.path.isfile(filename), "did not create contour shapefile"
@requires_pkg("pyshp", "shapely", name_map={"pyshp": "shapefile"})
def test_export_array_contours_unstructured(function_tmpdir, unstructured_grid):
from shapefile import Reader
grid = unstructured_grid
fname = function_tmpdir / "myarraycontours1.shp"
export_array_contours(grid, fname, np.arange(grid.nnodes))
assert fname.is_file(), "did not create contour shapefile"
# visual debugging
grid.plot(alpha=0.2)
with Reader(fname) as r:
shapes = r.shapes()
for s in shapes:
x = [i[0] for i in s.points[:]]
y = [i[1] for i in s.points[:]]
plt.plot(x, y)
# plt.show()
from autotest.test_gridgen import sim_disu_diff_layers
@requires_pkg("pyshp", "shapely", name_map={"pyshp": "shapefile"})
def test_export_array_contours_unstructured_diff_layers(
function_tmpdir, sim_disu_diff_layers
):
from shapefile import Reader
gwf = sim_disu_diff_layers.get_model()
grid = gwf.modelgrid
a = np.arange(grid.nnodes)
for layer in range(3):
fname = function_tmpdir / f"contours.{layer}.shp"
export_array_contours(grid, fname, a, layer=layer)
assert fname.is_file(), "did not create contour shapefile"
# visual debugging
fig, axes = plt.subplots(1, 3, subplot_kw={"aspect": "equal"})
for layer, ax in enumerate(axes):
fname = function_tmpdir / f"contours.{layer}.shp"
with Reader(fname) as r:
shapes = r.shapes()
for s in shapes:
x = [i[0] for i in s.points[:]]
y = [i[1] for i in s.points[:]]
ax.plot(x, y)
grid.plot(ax=ax, alpha=0.2, layer=layer)
# plt.show()
@requires_pkg("pyshp", "shapely", name_map={"pyshp": "shapefile"})
def test_export_contourf(function_tmpdir, example_data_path):
from shapefile import Reader
filename = function_tmpdir / "myfilledcontours.shp"
mpath = example_data_path / "freyberg"
ml = Modflow.load("freyberg.nam", model_ws=mpath)
hds_pth = Path(ml.model_ws) / "freyberg.githds"
hds = flopy.utils.HeadFile(hds_pth)
head = hds.get_data()
levels = np.arange(10, 30, 0.5)
mapview = flopy.plot.PlotMapView(model=ml)
contour_set = mapview.contour_array(
head, masked_values=[999.0], levels=levels, filled=True
)
# with pathlib.Path
export_contourf(filename, contour_set)
plt.close()
assert filename.is_file(), "did not create contourf shapefile"
# with str path
export_contourf(str(filename), contour_set)
plt.close()
assert filename.is_file(), "did not create contourf shapefile"
with Reader(filename) as r:
shapes = r.shapes()
# expect 65 with standard mpl contours (structured grids), 86 with tricontours
assert len(shapes) >= 65, "multipolygons were skipped in contourf routine"
# debugging
# for s in shapes:
# x = [i[0] for i in s.points[:]]
# y = [i[1] for i in s.points[:]]
# plt.plot(x, y)
# plt.show()
@pytest.mark.mf6
@requires_pkg("pyshp", "shapely", name_map={"pyshp": "shapefile"})
def test_export_contours(function_tmpdir, example_data_path):
from shapefile import Reader
filename = function_tmpdir / "mycontours.shp"
mpath = example_data_path / "freyberg"
ml = Modflow.load("freyberg.nam", model_ws=mpath)
hds_pth = Path(ml.model_ws) / "freyberg.githds"
hds = flopy.utils.HeadFile(hds_pth)
head = hds.get_data()
levels = np.arange(10, 30, 0.5)
mapview = flopy.plot.PlotMapView(model=ml)
contour_set = mapview.contour_array(head, masked_values=[999.0], levels=levels)
export_contours(filename, contour_set)
plt.close()
if not os.path.isfile(filename):
raise AssertionError("did not create contour shapefile")
with Reader(filename) as r:
shapes = r.shapes()
# expect 65 with standard mpl contours (structured grids), 86 with tricontours
assert len(shapes) >= 65
# debugging
# for s in shapes:
# x = [i[0] for i in s.points[:]]
# y = [i[1] for i in s.points[:]]
# plt.plot(x, y)
# plt.show()
@pytest.mark.mf6
@requires_pkg("pyshp", "shapely", name_map={"pyshp": "shapefile"})
def test_export_mf6_shp(function_tmpdir):
from shapefile import Reader
nlay = 2
nrow = 10
ncol = 10
top = 1
nper = 2
perlen = 1
nstp = 1
tsmult = 1
perioddata = [[perlen, nstp, tsmult]] * 2
botm = np.zeros((2, 10, 10))
m = flopy.modflow.Modflow(
"junk",
version="mfnwt",
model_ws=function_tmpdir,
)
dis = flopy.modflow.ModflowDis(
m,
nlay=nlay,
nrow=nrow,
ncol=ncol,
nper=nper,
perlen=perlen,
nstp=nstp,
tsmult=tsmult,
top=top,
botm=botm,
)
smg = StructuredGrid(
delc=np.ones(nrow),
delr=np.ones(ncol),
top=dis.top.array,
botm=botm,
idomain=1,
xoff=10,
yoff=10,
)
# River package (MFlist)
spd = flopy.modflow.ModflowRiv.get_empty(10)
spd["i"] = np.arange(10)
spd["j"] = [5, 5, 6, 6, 7, 7, 7, 8, 9, 9]
spd["stage"] = np.linspace(1, 0.7, 10)
spd["rbot"] = spd["stage"] - 0.1
spd["cond"] = 50.0
riv = flopy.modflow.ModflowRiv(m, stress_period_data={0: spd})
# Recharge package (transient 2d)
rech = {0: 0.001, 1: 0.002}
rch = flopy.modflow.ModflowRch(m, rech=rech)
# mf6 version of same model
mf6name = "junk6"
sim = flopy.mf6.MFSimulation(
sim_name=mf6name,
version="mf6",
exe_name="mf6",
sim_ws=function_tmpdir,
)
tdis = flopy.mf6.modflow.mftdis.ModflowTdis(
sim, pname="tdis", time_units="DAYS", nper=nper, perioddata=perioddata
)
gwf = flopy.mf6.ModflowGwf(sim, modelname=mf6name, model_nam_file=f"{mf6name}.nam")
dis6 = flopy.mf6.ModflowGwfdis(
gwf, pname="dis", nlay=nlay, nrow=nrow, ncol=ncol, top=top, botm=botm
)
# Riv6
spd6 = flopy.mf6.ModflowGwfriv.stress_period_data.empty(gwf, maxbound=len(spd))
spd6[0]["cellid"] = list(zip(spd.k, spd.i, spd.j))
for c in spd.dtype.names:
if c in spd6[0].dtype.names:
spd6[0][c] = spd[c]
riv6 = flopy.mf6.ModflowGwfriv(gwf, stress_period_data=spd6)
rch6 = flopy.mf6.ModflowGwfrcha(gwf, recharge=rech)
riv6spdarrays = dict(riv6.stress_period_data.masked_4D_arrays_itr())
rivspdarrays = dict(riv.stress_period_data.masked_4D_arrays_itr())
for k, v in rivspdarrays.items():
assert np.abs(np.nansum(v) - np.nansum(riv6spdarrays[k])) < 1e-6, (
f"variable {k} is not equal"
)
pass
m.export(function_tmpdir / "mfnwt.shp")
gwf.export(function_tmpdir / "mf6.shp")
# check that the shapefiles are the same
ra = shp2recarray(function_tmpdir / "mfnwt.shp")
ra6 = shp2recarray(function_tmpdir / "mf6.shp")
# check first and last exported cells
assert ra.geometry[0] == ra6.geometry[0]
assert ra.geometry[-1] == ra6.geometry[-1]
# fields
different_fields = list(set(ra.dtype.names).difference(ra6.dtype.names))
different_fields = [
f for f in different_fields if "thick" not in f and "rech" not in f
]
assert len(different_fields) == 0
for lay in np.arange(m.nlay) + 1:
assert np.sum(np.abs(ra[f"rech_{lay}"] - ra6[f"rechar{lay}"])) < 1e-6
common_fields = set(ra.dtype.names).intersection(ra6.dtype.names)
common_fields.remove("geometry")
# array values
for c in common_fields:
for it, it6 in zip(ra[c], ra6[c]):
if math.isnan(it):
assert math.isnan(it6)
else:
assert np.abs(it - it6) < 1e-6
# Compare exported riv shapefiles
riv.export(function_tmpdir / "riv.shp")
riv6.export(function_tmpdir / "riv6.shp")
with (
Reader(function_tmpdir / "riv.shp") as riv_shp,
Reader(function_tmpdir / "riv6.shp") as riv6_shp,
):
assert list(riv_shp.shapeRecord(-1).record) == list(
riv6_shp.shapeRecord(-1).record
)
# Check wel export with timeseries
wel_spd_0 = flopy.mf6.ModflowGwfwel.stress_period_data.empty(
gwf, maxbound=1, timeseries=True
)
wel_spd_0[0][0] = ((0, 0, 0), -99.0)
wel = flopy.mf6.ModflowGwfwel(
gwf,
maxbound=1,
stress_period_data={0: wel_spd_0[0]},
)
wel.export(function_tmpdir / "wel_test.shp")
@requires_pkg("pyshp", name_map={"pyshp": "shapefile"})
@pytest.mark.slow
def test_export_huge_shapefile(function_tmpdir):
nlay = 2
nrow = 200
ncol = 200
top = 1
nper = 2
perlen = 1
nstp = 1
tsmult = 1
botm = np.zeros((nlay, nrow, ncol))
m = flopy.modflow.Modflow("junk", version="mfnwt", model_ws=function_tmpdir)
flopy.modflow.ModflowDis(
m,
nlay=nlay,
nrow=nrow,
ncol=ncol,
nper=nper,
perlen=perlen,
nstp=nstp,
tsmult=tsmult,
top=top,
botm=botm,
)
m.export(function_tmpdir / "huge.shp")
@requires_pkg("netCDF4", "pyproj")
def test_polygon_from_ij(function_tmpdir):
"""test creation of a polygon from an i, j location using get_vertices()."""
m = Modflow("toy_model", model_ws=function_tmpdir)
botm = np.zeros((2, 10, 10))
botm[0, :, :] = 1.5
botm[1, 5, 5] = 4 # negative layer thickness!
botm[1, 6, 6] = 4
dis = ModflowDis(
nrow=10, ncol=10, nlay=2, delr=100, delc=100, top=3, botm=botm, model=m
)
fname = function_tmpdir / "toy.model.nc"
ncdf = NetCdf(fname, m)