def test_export(): fm = flopy.modflow m = fm.Modflow() dis = fm.ModflowDis(m, 1, 10, 10, lenuni=2, itmuni=4) m.sr = SpatialReference(delr=m.dis.delr.array, delc=m.dis.delc.array) m.sr.write_shapefile(os.path.join(outpath, 'grid.shp')) r, d = create_sfr_data() sfr = flopy.modflow.ModflowSfr2(m, reach_data=r, segment_data={0: d}) sfr.segment_data[0]['flow'][-1] = 1e4 sfr.stress_period_data.export(os.path.join(outpath, 'sfr.shp'), sparse=True) sfr.export_linkages(os.path.join(outpath, 'linkages.shp')) sfr.export_outlets(os.path.join(outpath, 'outlets.shp')) sfr.export_transient_variable(os.path.join(outpath, 'inlets.shp'), 'flow') from flopy.export.shapefile_utils import shp2recarray ra = shp2recarray(os.path.join(outpath, 'inlets.shp')) assert ra.flow0[0] == 1e4 ra = shp2recarray(os.path.join(outpath, 'outlets.shp')) assert ra.iseg[0] + ra.ireach[0] == 5 ra = shp2recarray(os.path.join(outpath, 'linkages.shp')) crds = np.array(list(ra.geometry[2].coords)) assert np.array_equal(crds, np.array([[2.5, 4.5], [3.5, 5.5]])) ra = shp2recarray(os.path.join(outpath, 'sfr.shp')) assert ra.iseg0.sum() == sfr.reach_data.iseg.sum() assert ra.ireach0.sum() == sfr.reach_data.ireach.sum() y = np.concatenate([np.array(g.exterior)[:, 1] for g in ra.geometry]) x = np.concatenate([np.array(g.exterior)[:, 0] for g in ra.geometry]) assert (x.min(), y.min(), x.max(), y.max()) == m.sr.bounds assert ra[(ra.iseg0 == 2) & (ra.ireach0 == 1)]['geometry'][0].bounds \ == (6.0, 2.0, 7.0, 3.0)
def test_dtypes(): ra = shp2recarray("temp/test.shp") assert "int" in ra.dtype["k"].name assert "float" in ra.dtype["stuff"].name assert "bool" in ra.dtype["stuf"].name assert "object" in ra.dtype["stf"].name assert True
def test_dtypes(): fpth = os.path.join(mpth, 'test.shp') ra = shp2recarray(fpth) assert "int" in ra.dtype['k'].name assert "float" in ra.dtype['stuff'].name assert "bool" in ra.dtype['stuf'].name assert "object" in ra.dtype['stf'].name assert True
def test_polygon_from_ij(): """test creation of a polygon from an i, j location using get_vertices().""" m = flopy.modflow.Modflow('toy_model', model_ws=mpth) botm = np.zeros((2, 10, 10)) botm[0, :, :] = 1.5 botm[1, 5, 5] = 4 # negative layer thickness! botm[1, 6, 6] = 4 dis = flopy.modflow.ModflowDis(nrow=10, ncol=10, nlay=2, delr=100, delc=100, top=3, botm=botm, model=m) m.sr = SpatialReference(delr=m.dis.delr * .3048, delc=m.dis.delc * .3048, xul=600000, yul=5170000, proj4_str='EPSG:26715', rotation=-45) recarray = np.array([(0, 5, 5, .1, True, 's0'), (1, 4, 5, .2, False, 's1'), (0, 7, 8, .3, True, 's2')], dtype=[('k', '<i8'), ('i', '<i8'), ('j', '<i8'), ('stuff', '<f4'), ('stuf', '|b1'), ('stf', np.object)]).view(np.recarray) get_vertices = m.sr.get_vertices # function to get the referenced vertices for a model cell geoms = [ Polygon(get_vertices(i, j)) for i, j in zip(recarray.i, recarray.j) ] assert geoms[0].type == 'Polygon' assert np.abs(geoms[0].bounds[-1] - 5169784.473861726) < 1e-4 fpth = os.path.join(mpth, 'test.shp') recarray2shp(recarray, geoms, fpth, epsg=26715) import epsgref reload(epsgref) from epsgref import prj assert 26715 in prj fpth = os.path.join(mpth, 'test.prj') fpth2 = os.path.join(mpth, '26715.prj') shutil.copy(fpth, fpth2) fpth = os.path.join(mpth, 'test.shp') recarray2shp(recarray, geoms, fpth, prj=fpth2) # test_dtypes fpth = os.path.join(mpth, 'test.shp') ra = shp2recarray(fpth) assert "int" in ra.dtype['k'].name assert "float" in ra.dtype['stuff'].name assert "bool" in ra.dtype['stuf'].name assert "object" in ra.dtype['stf'].name assert True
def test_polygon_from_ij(): """test creation of a polygon from an i, j location using get_vertices().""" m = flopy.modflow.Modflow('toy_model', model_ws=mpth) botm = np.zeros((2, 10, 10)) botm[0, :, :] = 1.5 botm[1, 5, 5] = 4 # negative layer thickness! botm[1, 6, 6] = 4 dis = flopy.modflow.ModflowDis(nrow=10, ncol=10, nlay=2, delr=100, delc=100, top=3, botm=botm, model=m) ncdf = NetCdf('toy.model.nc', m) ncdf.write() m.export('toy_model_two.nc') dis.export('toy_model_dis.nc') mg = m.modelgrid mg.set_coord_info(xoff=mg._xul_to_xll(600000.0, -45.0), yoff=mg._yul_to_yll(5170000, -45.0), angrot=-45.0, proj4='EPSG:26715') recarray = np.array([(0, 5, 5, .1, True, 's0'), (1, 4, 5, .2, False, 's1'), (0, 7, 8, .3, True, 's2')], dtype=[('k', '<i8'), ('i', '<i8'), ('j', '<i8'), ('stuff', '<f4'), ('stuf', '|b1'), ('stf', np.object)]).view(np.recarray) # vertices for a model cell geoms = [Polygon(m.modelgrid.get_cell_vertices(i, j)) for i, j in zip(recarray.i, recarray.j)] assert geoms[0].type == 'Polygon' assert np.abs(geoms[0].bounds[-1] - 5169292.893203464) < 1e-4 fpth = os.path.join(mpth, 'test.shp') recarray2shp(recarray, geoms, fpth, epsg=26715) ep = epsgRef() prj = ep.to_dict() assert 26715 in prj fpth = os.path.join(mpth, 'test.prj') fpth2 = os.path.join(mpth, '26715.prj') shutil.copy(fpth, fpth2) fpth = os.path.join(mpth, 'test.shp') recarray2shp(recarray, geoms, fpth, prj=fpth2) # test_dtypes fpth = os.path.join(mpth, 'test.shp') ra = shp2recarray(fpth) assert "int" in ra.dtype['k'].name assert "float" in ra.dtype['stuff'].name assert "bool" in ra.dtype['stuf'].name assert "object" in ra.dtype['stf'].name assert True
def test_export(): fm = flopy.modflow m = fm.Modflow() dis = fm.ModflowDis(m, 1, 10, 10, lenuni=2, itmuni=4) if not shapefile: return # skip m.export(os.path.join(outpath, "grid.shp")) r, d = create_sfr_data() sfr = flopy.modflow.ModflowSfr2(m, reach_data=r, segment_data={0: d}) sfr.segment_data[0]["flow"][-1] = 1e4 sfr.stress_period_data.export(os.path.join(outpath, "sfr.shp"), sparse=True) sfr.export_linkages(os.path.join(outpath, "linkages.shp")) sfr.export_outlets(os.path.join(outpath, "outlets.shp")) sfr.export_transient_variable(os.path.join(outpath, "inlets.shp"), "flow") from flopy.export.shapefile_utils import shp2recarray ra = shp2recarray(os.path.join(outpath, "inlets.shp")) assert ra.flow0[0] == 1e4 ra = shp2recarray(os.path.join(outpath, "outlets.shp")) assert ra.iseg[0] + ra.ireach[0] == 5 ra = shp2recarray(os.path.join(outpath, "linkages.shp")) crds = np.array(list(ra.geometry[2].coords)) assert np.array_equal(crds, np.array([[2.5, 4.5], [3.5, 5.5]])) ra = shp2recarray(os.path.join(outpath, "sfr.shp")) assert ra.iseg.sum() == sfr.reach_data.iseg.sum() assert ra.ireach.sum() == sfr.reach_data.ireach.sum() y = np.concatenate([np.array(g.exterior)[:, 1] for g in ra.geometry]) x = np.concatenate([np.array(g.exterior)[:, 0] for g in ra.geometry]) assert (x.min(), x.max(), y.min(), y.max()) == m.modelgrid.extent assert ra[(ra.iseg == 2) & (ra.ireach == 1)]["geometry"][0].bounds == ( 6.0, 2.0, 7.0, 3.0, )
def test_polygon_from_ij(): """test creation of a polygon from an i, j location using get_vertices().""" m = flopy.modflow.Modflow('toy_model', model_ws=mpth) botm = np.zeros((2, 10, 10)) botm[0, :, :] = 1.5 botm[1, 5, 5] = 4 # negative layer thickness! botm[1, 6, 6] = 4 dis = flopy.modflow.ModflowDis(nrow=10, ncol=10, nlay=2, delr=100, delc=100, top=3, botm=botm, model=m) m.sr = SpatialReference(delr=m.dis.delr * .3048, delc=m.dis.delc * .3048, xul=600000, yul=5170000, proj4_str='EPSG:26715', rotation=-45) recarray = np.array([(0, 5, 5, .1, True, 's0'), (1, 4, 5, .2, False, 's1'), (0, 7, 8, .3, True, 's2')], dtype=[('k', '<i8'), ('i', '<i8'), ('j', '<i8'), ('stuff', '<f4'), ('stuf', '|b1'), ('stf', np.object)]).view(np.recarray) get_vertices = m.sr.get_vertices # function to get the referenced vertices for a model cell geoms = [Polygon(get_vertices(i, j)) for i, j in zip(recarray.i, recarray.j)] assert geoms[0].type == 'Polygon' assert np.abs(geoms[0].bounds[-1] - 5169784.473861726) < 1e-4 fpth = os.path.join(mpth, 'test.shp') recarray2shp(recarray, geoms, fpth, epsg=26715) import epsgref reload(epsgref) from epsgref import prj assert 26715 in prj fpth = os.path.join(mpth, 'test.prj') fpth2 = os.path.join(mpth, '26715.prj') shutil.copy(fpth, fpth2) fpth = os.path.join(mpth, 'test.shp') recarray2shp(recarray, geoms, fpth, prj=fpth2) # test_dtypes fpth = os.path.join(mpth, 'test.shp') ra = shp2recarray(fpth) assert "int" in ra.dtype['k'].name assert "float" in ra.dtype['stuff'].name assert "bool" in ra.dtype['stuf'].name assert "object" in ra.dtype['stf'].name assert True
def test_write_shapefile(): from flopy.utils.reference import SpatialReference from flopy.export.shapefile_utils import shp2recarray from flopy.export.shapefile_utils import write_grid_shapefile, write_grid_shapefile2 sr = SpatialReference( delr=np.ones(10) * 1.1, # cell spacing along model rows delc=np.ones(10) * 1.1, # cell spacing along model columns epsg=26715, lenuni=1 # MODFLOW length units ) vrts = copy.deepcopy(sr.vertices) outshp1 = os.path.join(tpth, 'junk.shp') outshp2 = os.path.join(tpth, 'junk2.shp') write_grid_shapefile(outshp1, sr, array_dict={}) write_grid_shapefile2(outshp2, sr, array_dict={}) # test that vertices aren't getting altered by writing shapefile assert np.array_equal(vrts, sr.vertices) for outshp in [outshp1, outshp2]: # check that pyshp reads integers # this only check that row/column were recorded as "N" # not how they will be cast by python or numpy import shapefile as sf sfobj = sf.Reader(outshp) for f in sfobj.fields: if f[0] == 'row' or f[0] == 'column': assert f[1] == 'N' recs = list(sfobj.records()) for r in recs[0]: assert isinstance(r, int) # check that row and column appear as integers in recarray ra = shp2recarray(outshp) assert np.issubdtype(ra.dtype['row'], np.integer) assert np.issubdtype(ra.dtype['column'], np.integer) try: # check that fiona reads integers import fiona with fiona.open(outshp) as src: meta = src.meta assert 'int' in meta['schema']['properties']['row'] assert 'int' in meta['schema']['properties']['column'] except: pass
def test_write_shapefile(): from flopy.utils.reference import SpatialReference from flopy.export.shapefile_utils import shp2recarray from flopy.export.shapefile_utils import write_grid_shapefile, write_grid_shapefile2 sr = SpatialReference(delr=np.ones(10) *1.1, # cell spacing along model rows delc=np.ones(10) *1.1, # cell spacing along model columns epsg=26715, lenuni=1 # MODFLOW length units ) outshp1 = os.path.join(tpth, 'junk.shp') outshp2 = os.path.join(tpth, 'junk2.shp') write_grid_shapefile(outshp1, sr, array_dict={}) write_grid_shapefile2(outshp2, sr, array_dict={}) for outshp in [outshp1, outshp2]: # check that pyshp reads integers # this only check that row/column were recorded as "N" # not how they will be cast by python or numpy import shapefile as sf sfobj = sf.Reader(outshp) for f in sfobj.fields: if f[0] == 'row' or f[0] == 'column': assert f[1] == 'N' recs = list(sfobj.records()) for r in recs[0]: assert isinstance(r, int) # check that row and column appear as integers in recarray ra = shp2recarray(outshp) assert np.issubdtype(ra.dtype['row'], np.integer) assert np.issubdtype(ra.dtype['column'], np.integer) try: # check that fiona reads integers import fiona with fiona.open(outshp) as src: meta = src.meta assert 'int' in meta['schema']['properties']['row'] assert 'int' in meta['schema']['properties']['column'] except: pass
def test_get_destination_data(): m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) mg1 = m.modelgrid mg1.set_coord_info(xoff=mg1._xul_to_xll(0.0, 30.0), yoff=mg1._yul_to_yll(0.0, 30.0), angrot=30.0) mg = StructuredGrid(delc=m.dis.delc.array, delr=m.dis.delr.array) mg.set_coord_info(xoff=mg._xul_to_xll(1000.0, 30.0), yoff=mg._yul_to_yll(1000.0, 30.0), angrot=30.0) # test deprecation sr2 = SpatialReference(xll=mg.xoffset, yll=mg.yoffset, rotation=-30) if shapefile: m.dis.export(path + '/dis.shp') pthld = PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) epd = EndpointFile(os.path.join(path, 'EXAMPLE-3.endpoint')) well_epd = epd.get_destination_endpoint_data(dest_cells=[(4, 12, 12)]) well_pthld = pthld.get_destination_pathline_data(dest_cells=[(4, 12, 12)], to_recarray=True) # same particle IDs should be in both endpoint data and pathline data tval = len(set(well_epd.particleid).difference(set(well_pthld.particleid))) msg = 'same particle IDs should be in both endpoint data and pathline data' assert tval == 0, msg # check that all starting locations are included in the pathline data # (pathline data slice not just endpoints) starting_locs = ra_slice(well_epd, ['k0', 'i0', 'j0']) pathline_locs = np.array(np.array(well_pthld)[['k', 'i', 'j']].tolist(), dtype=starting_locs.dtype) assert np.all(np.in1d(starting_locs, pathline_locs)) if shapefile is None: return # skip remainder # test writing a shapefile of endpoints epd.write_shapefile(well_epd, direction='starting', shpname=os.path.join(path, 'starting_locs.shp'), mg=m.modelgrid) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', mg=m.modelgrid, shpname=fpth) fpth = os.path.join(path, 'pathlines_1per_end.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='ending', mg=m.modelgrid, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', mg=mg, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2_ll.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', mg=sr2, shpname=fpth) fpth = os.path.join(path, 'pathlines.shp') pthld.write_shapefile(well_pthld, one_per_particle=False, mg=m.modelgrid, shpname=fpth) # test that endpoints were rotated and written correctly from flopy.export.shapefile_utils import shp2recarray ra = shp2recarray(os.path.join(path, 'starting_locs.shp')) p3 = ra.geometry[ra.particleid == 4][0] xorig, yorig = m.modelgrid.get_coords(well_epd.x0[0], well_epd.y0[0]) assert p3.x - xorig + p3.y - yorig < 1e-4 xorig, yorig = mg1.xcellcenters[3, 4], mg1.ycellcenters[3, 4] assert np.abs(p3.x - xorig + p3.y - yorig) < 1e-4 # this also checks for 1-based # test that particle attribute information is consistent with pathline file ra = shp2recarray(os.path.join(path, 'pathlines.shp')) inds = (ra.particleid == 8) & (ra.i == 12) & (ra.j == 12) assert ra.time[inds][0] - 20181.7 < .1 assert ra.xloc[inds][0] - 0.933 < .01 # test that k, i, j are correct for single geometry pathlines, forwards # and backwards ra = shp2recarray(os.path.join(path, 'pathlines_1per.shp')) assert ra.i[0] == 4, ra.j[0] == 5 ra = shp2recarray(os.path.join(path, 'pathlines_1per_end.shp')) assert ra.i[0] == 13, ra.j[0] == 13 # test use of arbitrary spatial reference and offset mg1.set_coord_info(xoff=mg.xoffset, yoff=mg.yoffset, angrot=mg.angrot, epsg=mg.epsg, proj4=mg.proj4) ra = shp2recarray(os.path.join(path, 'pathlines_1per2.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] test1 = mg1.xcellcenters[3, 4] test2 = mg1.ycellcenters[3, 4] assert np.abs(p3_2.x[0] - mg1.xcellcenters[3, 4] + p3_2.y[0] - mg1.ycellcenters[3, 4]) < 1e-4 # arbitrary spatial reference with ll specified instead of ul ra = shp2recarray(os.path.join(path, 'pathlines_1per2_ll.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] #sr3 = SpatialReference(xll=sr.xll, yll=sr.yll, rotation=-30, # delc=list(m.dis.delc)) mg.set_coord_info(xoff=mg.xoffset, yoff=mg.yoffset, angrot=-30.0) assert np.abs(p3_2.x[0] - mg.xcellcenters[3, 4] + p3_2.y[0] - mg.ycellcenters[3, 4]) < 1e-4 xul = 3628793 yul = 21940389 m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) mg4 = m.modelgrid mg4.set_coord_info(xoff=mg4._xul_to_xll(xul, 0.0), yoff=mg4._yul_to_yll(yul, 0.0), angrot=0.0, epsg=mg4.epsg, proj4=mg4.proj4) fpth = os.path.join(path, 'dis2.shp') m.dis.export(fpth) pthobj = flopy.utils.PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) fpth = os.path.join(path, 'pathlines_1per3.shp') pthobj.write_shapefile(shpname=fpth, direction='ending', mg=mg4)
def test_mf6_grid_shp_export(): 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)) ogsr = OGsr(delc=np.ones(nrow), delr=np.ones(ncol), xll=10, yll=10 ) m = fm.Modflow('junk', version='mfnwt', model_ws=tmpdir) dis = fm.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 = fm.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. riv = fm.ModflowRiv(m, stress_period_data={0: spd}) # Recharge package (transient 2d) rech = {0: 0.001, 1: 0.002} rch = fm.ModflowRch(m, rech=rech) # mf6 version of same model mf6name = 'junk6' sim = fp6.MFSimulation(sim_name=mf6name, version='mf6', exe_name='mf6', sim_ws=tmpdir) tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=nper, perioddata=perioddata) gwf = fp6.ModflowGwf(sim, modelname=mf6name, model_nam_file='{}.nam'.format(mf6name)) dis6 = fp6.ModflowGwfdis(gwf, pname='dis', nlay=nlay, nrow=nrow, ncol=ncol, top=top, botm=botm) def cellid(k, i, j, nrow, ncol): return k*nrow*ncol + i*ncol + j # Riv6 spd6 = fp6.ModflowGwfriv.stress_period_data.empty(gwf, maxbound=len(spd)) #spd6[0]['cellid'] = cellid(spd.k, spd.i, spd.j, m.nrow, m.ncol) 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] # MFTransient list apparently requires entries for additional stress periods, # even if they are the same spd6[1] = spd6[0] #irch = np.zeros((nrow, ncol)) riv6 = fp6.ModflowGwfriv(gwf, stress_period_data=spd6) rch6 = fp6.ModflowGwfrcha(gwf, recharge=rech) if shapefile: #rch6.export('{}/mf6.shp'.format(tmpdir)) m.export('{}/mfnwt.shp'.format(tmpdir)) gwf.export('{}/mf6.shp'.format(tmpdir)) 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, "variable {} is not equal".format(k) pass if shapefile is None: return # skip remainder # check that the two shapefiles are the same ra = shp2recarray('{}/mfnwt.shp'.format(tmpdir)) ra6 = shp2recarray('{}/mf6.shp'.format(tmpdir)) # 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 l in np.arange(m.nlay)+1: assert np.sum(np.abs(ra['rech_{}'.format(l)] - ra6['rechar{}'.format(l)])) < 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 pass
def test_get_destination_data(): m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) m.sr = SpatialReference(delr=m.dis.delr, delc=m.dis.delc, xul=0, yul=0, rotation=30) sr = SpatialReference(delr=list(m.dis.delr), delc=list(m.dis.delc), xul=1000, yul=1000, rotation=30) sr2 = SpatialReference(xll=sr.xll, yll=sr.yll, rotation=-30) m.dis.export(path + '/dis.shp') pthld = PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) epd = EndpointFile(os.path.join(path, 'EXAMPLE-3.endpoint')) well_epd = epd.get_destination_endpoint_data(dest_cells=[(4, 12, 12)]) well_pthld = pthld.get_destination_pathline_data(dest_cells=[(4, 12, 12)], to_recarray=True) # same particle IDs should be in both endpoint data and pathline data tval = len(set(well_epd.particleid).difference(set(well_pthld.particleid))) msg = 'same particle IDs should be in both endpoint data and pathline data' assert tval == 0, msg # check that all starting locations are included in the pathline data # (pathline data slice not just endpoints) starting_locs = ra_slice(well_epd, ['k0', 'i0', 'j0']) pathline_locs = np.array(np.array(well_pthld)[['k', 'i', 'j']].tolist(), dtype=starting_locs.dtype) assert np.all(np.in1d(starting_locs, pathline_locs)) # test writing a shapefile of endpoints epd.write_shapefile(well_epd, direction='starting', shpname=os.path.join(path, 'starting_locs.shp'), sr=m.sr) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', sr=m.sr, shpname=fpth) fpth = os.path.join(path, 'pathlines_1per_end.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='ending', sr=m.sr, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', sr=sr, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2_ll.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', sr=sr2, shpname=fpth) fpth = os.path.join(path, 'pathlines.shp') pthld.write_shapefile(well_pthld, one_per_particle=False, sr=m.sr, shpname=fpth) # test that endpoints were rotated and written correctly from flopy.export.shapefile_utils import shp2recarray ra = shp2recarray(os.path.join(path, 'starting_locs.shp')) p3 = ra.geometry[ra.particleid == 4][0] xorig, yorig = m.sr.transform(well_epd.x0[0], well_epd.y0[0]) assert p3.x - xorig + p3.y - yorig < 1e-4 xorig, yorig = m.sr.xcentergrid[3, 4], m.sr.ycentergrid[3, 4] assert np.abs(p3.x - xorig + p3.y - yorig) < 1e-4 # this also checks for 1-based # test that particle attribute information is consistent with pathline file ra = shp2recarray(os.path.join(path, 'pathlines.shp')) inds = (ra.particleid == 8) & (ra.i == 12) & (ra.j == 12) assert ra.time[inds][0] - 20181.7 < .1 assert ra.xloc[inds][0] - 0.933 < .01 # test that k, i, j are correct for single geometry pathlines, forwards # and backwards ra = shp2recarray(os.path.join(path, 'pathlines_1per.shp')) assert ra.i[0] == 4, ra.j[0] == 5 ra = shp2recarray(os.path.join(path, 'pathlines_1per_end.shp')) assert ra.i[0] == 13, ra.j[0] == 13 # test use of arbitrary spatial reference and offset ra = shp2recarray(os.path.join(path, 'pathlines_1per2.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] assert np.abs(p3_2.x[0] - sr.xcentergrid[3, 4] + p3_2.y[0] - sr.ycentergrid[3, 4]) < 1e-4 # arbitrary spatial reference with ll specified instead of ul ra = shp2recarray(os.path.join(path, 'pathlines_1per2_ll.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] sr3 = SpatialReference(xll=sr.xll, yll=sr.yll, rotation=-30, delr=list(m.dis.delr), delc=list(m.dis.delc)) assert np.abs(p3_2.x[0] - sr3.xcentergrid[3, 4] + p3_2.y[0] - sr3.ycentergrid[3, 4]) < 1e-4 xul = 3628793 yul = 21940389 m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) m.sr = flopy.utils.reference.SpatialReference(delr=m.dis.delr, delc=m.dis.delc, lenuni=1, xul=xul, yul=yul, rotation=0.0) fpth = os.path.join(path, 'dis2.shp') m.dis.export(fpth) pthobj = flopy.utils.PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) fpth = os.path.join(path, 'pathlines_1per3.shp') pthobj.write_shapefile(shpname=fpth, direction='ending', sr=m.sr)
def test_get_destination_data(): m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) m.sr = SpatialReference(delr=m.dis.delr, delc=m.dis.delc, xul=0, yul=0, rotation=30) sr = SpatialReference(delr=list(m.dis.delr), delc=list(m.dis.delc), xul=1000, yul=1000, rotation=30) sr2 = SpatialReference(xll=sr.xll, yll=sr.yll, rotation=-30) m.dis.export(path + '/dis.shp') pthld = PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) epd = EndpointFile(os.path.join(path, 'EXAMPLE-3.endpoint')) well_epd = epd.get_destination_endpoint_data(dest_cells=[(4, 12, 12)]) well_pthld = pthld.get_destination_pathline_data(dest_cells=[(4, 12, 12)]) # same particle IDs should be in both endpoing data and pathline data assert len( set(well_epd.particleid).difference(set(well_pthld.particleid))) == 0 # check that all starting locations are included in the pathline data # (pathline data slice not just endpoints) starting_locs = ra_slice(well_epd, ['k0', 'i0', 'j0']) pathline_locs = np.array(well_pthld[['k', 'i', 'j']].tolist(), dtype=starting_locs.dtype) assert np.all(np.in1d(starting_locs, pathline_locs)) # test writing a shapefile of endpoints epd.write_shapefile(well_epd, direction='starting', shpname=os.path.join(path, 'starting_locs.shp'), sr=m.sr) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', sr=m.sr, shpname=fpth) fpth = os.path.join(path, 'pathlines_1per_end.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='ending', sr=m.sr, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', sr=sr, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2_ll.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', sr=sr2, shpname=fpth) fpth = os.path.join(path, 'pathlines.shp') pthld.write_shapefile(well_pthld, one_per_particle=False, sr=m.sr, shpname=fpth) # test that endpoints were rotated and written correctly from flopy.export.shapefile_utils import shp2recarray ra = shp2recarray(os.path.join(path, 'starting_locs.shp')) p3 = ra.geometry[ra.particleid == 4][0] xorig, yorig = m.sr.transform(well_epd.x0[0], well_epd.y0[0]) assert p3.x - xorig + p3.y - yorig < 1e-4 xorig, yorig = m.sr.xcentergrid[3, 4], m.sr.ycentergrid[3, 4] assert np.abs( p3.x - xorig + p3.y - yorig) < 1e-4 # this also checks for 1-based # test that particle attribute information is consistent with pathline file ra = shp2recarray(os.path.join(path, 'pathlines.shp')) inds = (ra.particleid == 8) & (ra.i == 12) & (ra.j == 12) assert ra.time[inds][0] - 20181.7 < .1 assert ra.xloc[inds][0] - 0.933 < .01 # test that k, i, j are correct for single geometry pathlines, forwards and backwards ra = shp2recarray(os.path.join(path, 'pathlines_1per.shp')) assert ra.i[0] == 4, ra.j[0] == 5 ra = shp2recarray(os.path.join(path, 'pathlines_1per_end.shp')) assert ra.i[0] == 13, ra.j[0] == 13 # test use of arbitrary spatial reference and offset ra = shp2recarray(os.path.join(path, 'pathlines_1per2.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] assert np.abs( p3_2.x[0] - sr.xcentergrid[3, 4] + p3_2.y[0] - sr.ycentergrid[ 3, 4]) < 1e-4 # arbitrary spatial reference with ll specified instead of ul ra = shp2recarray(os.path.join(path, 'pathlines_1per2_ll.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] sr3 = SpatialReference(xll=sr.xll, yll=sr.yll, rotation=-30, delr=list(m.dis.delr), delc=list(m.dis.delc)) assert np.abs( p3_2.x[0] - sr3.xcentergrid[3, 4] + p3_2.y[0] - sr3.ycentergrid[ 3, 4]) < 1e-4 xul = 3628793 yul = 21940389 m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) m.sr = flopy.utils.reference.SpatialReference(delr=m.dis.delr, delc=m.dis.delc, lenuni=1, xul=xul, yul=yul, rotation=0.0) fpth = os.path.join(path, 'dis2.shp') m.dis.export(fpth) pthobj = flopy.utils.PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) fpth = os.path.join(path, 'pathlines_1per3.shp') pthobj.write_shapefile(shpname=fpth, direction='ending', sr=m.sr)
def test_mf6_grid_shp_export(): 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)) ogsr = OGsr(delc=np.ones(nrow), delr=np.ones(ncol), xll=10, yll=10 ) m = fm.Modflow('junk', version='mfnwt', model_ws=tmpdir) dis = fm.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 = fm.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. riv = fm.ModflowRiv(m, stress_period_data={0: spd}) # Recharge package (transient 2d) rech = {0: 0.001, 1: 0.002} rch = fm.ModflowRch(m, rech=rech) # mf6 version of same model mf6name = 'junk6' sim = fp6.MFSimulation(sim_name=mf6name, version='mf6', exe_name='mf6', sim_ws=tmpdir) tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=nper, perioddata=perioddata) gwf = fp6.ModflowGwf(sim, modelname=mf6name, model_nam_file='{}.nam'.format(mf6name)) dis6 = fp6.ModflowGwfdis(gwf, pname='dis', nlay=nlay, nrow=nrow, ncol=ncol, top=top, botm=botm) def cellid(k, i, j, nrow, ncol): return k*nrow*ncol + i*ncol + j # Riv6 spd6 = fp6.ModflowGwfriv.stress_period_data.empty(gwf, maxbound=len(spd)) #spd6[0]['cellid'] = cellid(spd.k, spd.i, spd.j, m.nrow, m.ncol) 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] # MFTransient list apparently requires entries for additional stress periods, # even if they are the same spd6[1] = spd6[0] #irch = np.zeros((nrow, ncol)) riv6 = fp6.ModflowGwfriv(gwf, stress_period_data=spd6) rch6 = fp6.ModflowGwfrcha(gwf, recharge=rech) #rch6.export('{}/mf6.shp'.format(tmpdir)) m.export('{}/mfnwt.shp'.format(tmpdir)) gwf.export('{}/mf6.shp'.format(tmpdir)) 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, "variable {} is not equal".format(k) pass # check that the two shapefiles are the same ra = shp2recarray('{}/mfnwt.shp'.format(tmpdir)) ra6 = shp2recarray('{}/mf6.shp'.format(tmpdir)) # 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 l in np.arange(m.nlay)+1: assert np.sum(np.abs(ra['rech_{}'.format(l)] - ra6['rechar{}'.format(l)])) < 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 pass
def test_polygon_from_ij(): """test creation of a polygon from an i, j location using get_vertices().""" m = flopy.modflow.Modflow("toy_model", model_ws=mpth) botm = np.zeros((2, 10, 10)) botm[0, :, :] = 1.5 botm[1, 5, 5] = 4 # negative layer thickness! botm[1, 6, 6] = 4 dis = flopy.modflow.ModflowDis( nrow=10, ncol=10, nlay=2, delr=100, delc=100, top=3, botm=botm, model=m ) fname = os.path.join(mpth, "toy.model.nc") ncdf = NetCdf(fname, m) ncdf.write() fname = os.path.join(mpth, "toy_model_two.nc") m.export(fname) fname = os.path.join(mpth, "toy_model_dis.nc") dis.export(fname) mg = m.modelgrid mg.set_coord_info( xoff=mg._xul_to_xll(600000.0, -45.0), yoff=mg._yul_to_yll(5170000, -45.0), angrot=-45.0, proj4="EPSG:26715", ) recarray = np.array( [ (0, 5, 5, 0.1, True, "s0"), (1, 4, 5, 0.2, False, "s1"), (0, 7, 8, 0.3, True, "s2"), ], dtype=[ ("k", "<i8"), ("i", "<i8"), ("j", "<i8"), ("stuff", "<f4"), ("stuf", "|b1"), ("stf", object), ], ).view(np.recarray) # vertices for a model cell geoms = [ Polygon(m.modelgrid.get_cell_vertices(i, j)) for i, j in zip(recarray.i, recarray.j) ] assert geoms[0].type == "Polygon" assert np.abs(geoms[0].bounds[-1] - 5169292.893203464) < 1e-4 fpth = os.path.join(mpth, "test.shp") recarray2shp(recarray, geoms, fpth, epsg=26715) ep = EpsgReference() prj = ep.to_dict() assert 26715 in prj fpth = os.path.join(mpth, "test.prj") fpth2 = os.path.join(mpth, "26715.prj") shutil.copy(fpth, fpth2) fpth = os.path.join(mpth, "test.shp") recarray2shp(recarray, geoms, fpth, prj=fpth2) # test_dtypes fpth = os.path.join(mpth, "test.shp") ra = shp2recarray(fpth) assert "int" in ra.dtype["k"].name assert "float" in ra.dtype["stuff"].name assert "bool" in ra.dtype["stuf"].name assert "object" in ra.dtype["stf"].name assert True
def test_get_destination_data(): m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) mg1 = m.modelgrid mg1.set_coord_info(xoff=mg1._xul_to_xll(0.0, 30.0), yoff=mg1._yul_to_yll(0.0, 30.0), angrot=30.0) mg = StructuredGrid(delc=m.dis.delc.array, delr=m.dis.delr.array) mg.set_coord_info(xoff=mg._xul_to_xll(1000.0, 30.0), yoff=mg._yul_to_yll(1000.0, 30.0), angrot=30.0) # test deprecation sr2 = SpatialReference(xll=mg.xoffset, yll=mg.yoffset, rotation=-30) m.dis.export(path + '/dis.shp') pthld = PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) epd = EndpointFile(os.path.join(path, 'EXAMPLE-3.endpoint')) well_epd = epd.get_destination_endpoint_data(dest_cells=[(4, 12, 12)]) well_pthld = pthld.get_destination_pathline_data(dest_cells=[(4, 12, 12)], to_recarray=True) # same particle IDs should be in both endpoint data and pathline data tval = len(set(well_epd.particleid).difference(set(well_pthld.particleid))) msg = 'same particle IDs should be in both endpoint data and pathline data' assert tval == 0, msg # check that all starting locations are included in the pathline data # (pathline data slice not just endpoints) starting_locs = ra_slice(well_epd, ['k0', 'i0', 'j0']) pathline_locs = np.array(np.array(well_pthld)[['k', 'i', 'j']].tolist(), dtype=starting_locs.dtype) assert np.all(np.in1d(starting_locs, pathline_locs)) # test writing a shapefile of endpoints epd.write_shapefile(well_epd, direction='starting', shpname=os.path.join(path, 'starting_locs.shp'), mg=m.modelgrid) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', mg=m.modelgrid, shpname=fpth) fpth = os.path.join(path, 'pathlines_1per_end.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='ending', mg=m.modelgrid, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', mg=mg, shpname=fpth) # test writing shapefile of pathlines fpth = os.path.join(path, 'pathlines_1per2_ll.shp') pthld.write_shapefile(well_pthld, one_per_particle=True, direction='starting', mg=sr2, shpname=fpth) fpth = os.path.join(path, 'pathlines.shp') pthld.write_shapefile(well_pthld, one_per_particle=False, mg=m.modelgrid, shpname=fpth) # test that endpoints were rotated and written correctly from flopy.export.shapefile_utils import shp2recarray ra = shp2recarray(os.path.join(path, 'starting_locs.shp')) p3 = ra.geometry[ra.particleid == 4][0] xorig, yorig = m.modelgrid.get_coords(well_epd.x0[0], well_epd.y0[0]) assert p3.x - xorig + p3.y - yorig < 1e-4 xorig, yorig = mg1.xcellcenters[3, 4], mg1.ycellcenters[3, 4] assert np.abs( p3.x - xorig + p3.y - yorig) < 1e-4 # this also checks for 1-based # test that particle attribute information is consistent with pathline file ra = shp2recarray(os.path.join(path, 'pathlines.shp')) inds = (ra.particleid == 8) & (ra.i == 12) & (ra.j == 12) assert ra.time[inds][0] - 20181.7 < .1 assert ra.xloc[inds][0] - 0.933 < .01 # test that k, i, j are correct for single geometry pathlines, forwards # and backwards ra = shp2recarray(os.path.join(path, 'pathlines_1per.shp')) assert ra.i[0] == 4, ra.j[0] == 5 ra = shp2recarray(os.path.join(path, 'pathlines_1per_end.shp')) assert ra.i[0] == 13, ra.j[0] == 13 # test use of arbitrary spatial reference and offset mg1.set_coord_info(xoff=mg.xoffset, yoff=mg.yoffset, angrot=mg.angrot, epsg=mg.epsg, proj4=mg.proj4) ra = shp2recarray(os.path.join(path, 'pathlines_1per2.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] test1 = mg1.xcellcenters[3, 4] test2 = mg1.ycellcenters[3, 4] assert np.abs( p3_2.x[0] - mg1.xcellcenters[3, 4] + p3_2.y[0] - mg1.ycellcenters[ 3, 4]) < 1e-4 # arbitrary spatial reference with ll specified instead of ul ra = shp2recarray(os.path.join(path, 'pathlines_1per2_ll.shp')) p3_2 = ra.geometry[ra.particleid == 4][0] #sr3 = SpatialReference(xll=sr.xll, yll=sr.yll, rotation=-30, # delc=list(m.dis.delc)) mg.set_coord_info(xoff=mg.xoffset, yoff=mg.yoffset, angrot=-30.0) assert np.abs( p3_2.x[0] - mg.xcellcenters[3, 4] + p3_2.y[0] - mg.ycellcenters[ 3, 4]) < 1e-4 xul = 3628793 yul = 21940389 m = flopy.modflow.Modflow.load('EXAMPLE.nam', model_ws=path) mg4 = m.modelgrid mg4.set_coord_info(xoff=mg4._xul_to_xll(xul, 0.0), yoff=mg4._yul_to_yll(yul, 0.0), angrot=0.0, epsg=mg4.epsg, proj4=mg4.proj4) fpth = os.path.join(path, 'dis2.shp') m.dis.export(fpth) pthobj = flopy.utils.PathlineFile(os.path.join(path, 'EXAMPLE-3.pathline')) fpth = os.path.join(path, 'pathlines_1per3.shp') pthobj.write_shapefile(shpname=fpth, direction='ending', mg=mg4)