예제 #1
0
def test_export_array_contours():
    from flopy.discretization import StructuredGrid
    from flopy.export.utils import export_array_contours
    nrow = 7
    ncol = 11
    epsg = 4111

    # no epsg code
    modelgrid = StructuredGrid(delr=np.ones(ncol) * 1.1,
                               delc=np.ones(nrow) * 1.1)
    filename = os.path.join(spth, '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 epsg code
    modelgrid = StructuredGrid(delr=np.ones(ncol) * 1.1,
                               delc=np.ones(nrow) * 1.1,
                               epsg=epsg)
    filename = os.path.join(spth, '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 epsg code
    modelgrid = StructuredGrid(delr=np.ones(ncol) * 1.1,
                               delc=np.ones(nrow) * 1.1)
    filename = os.path.join(spth, 'myarraycontours3.shp')
    a = np.arange(nrow * ncol).reshape((nrow, ncol))
    export_array_contours(modelgrid, filename, a, epsg=epsg)
    assert os.path.isfile(filename), 'did not create contour shapefile'
    return
예제 #2
0
    def __new__(cls, ax=None, model=None, dis=None, line=None,
                xul=None, yul=None, rotation=None, extent=None):

        from flopy.plot.plotbase import DeprecatedCrossSection
        from flopy.discretization import StructuredGrid

        err_msg = "ModelCrossSection will be replaced by " +\
            "PlotCrossSection(), Calling PlotCrossSection()"
        warnings.warn(err_msg, PendingDeprecationWarning)

        modelgrid = None
        if model is not None:
            if (xul, yul, rotation) != (None, None, None):
                modelgrid = plotutil._set_coord_info(model.modelgrid,
                                                     xul, yul, None, None,
                                                     rotation)

        elif dis is not None:
            modelgrid = StructuredGrid(delr=dis.delr.array,
                                       delc=dis.delc.array,
                                       top=dis.top.array,
                                       botm=dis.botm.array)

        if (xul, yul, rotation) != (None, None, None):
            modelgrid = plotutil._set_coord_info(modelgrid,
                                          xul, yul, None, None,
                                          rotation)


        return DeprecatedCrossSection(ax=ax, model=model,
                                      modelgrid=modelgrid,
                                      line=line, extent=extent)
예제 #3
0
def test_get_vertices():
    from flopy.utils.reference import SpatialReference
    from flopy.discretization import StructuredGrid
    m = flopy.modflow.Modflow(rotation=20.)
    nrow, ncol = 40, 20
    dis = flopy.modflow.ModflowDis(m,
                                   nlay=1,
                                   nrow=nrow,
                                   ncol=ncol,
                                   delr=250.,
                                   delc=250.,
                                   top=10,
                                   botm=0)
    xul, yul = 500000, 2934000
    sr = SpatialReference(delc=m.dis.delc.array,
                          xul=xul,
                          yul=yul,
                          rotation=45.)
    mg = StructuredGrid(delc=m.dis.delc.array,
                        delr=m.dis.delr.array,
                        xoff=sr.xll,
                        yoff=sr.yll,
                        angrot=sr.rotation)

    xgrid = mg.xvertices
    ygrid = mg.yvertices
    # a1 = np.array(mg.xyvertices)
    a1 = np.array([[xgrid[0, 0], ygrid[0, 0]], [xgrid[0, 1], ygrid[0, 1]],
                   [xgrid[1, 1], ygrid[1, 1]], [xgrid[1, 0], ygrid[1, 0]]])

    a2 = np.array(mg.get_cell_vertices(0, 0))
    assert np.array_equal(a1, a2)
    def load_with_crs(path, xll, yll, epsg=4326, rot=None):
        try:
            instance = InowasModflowReadAdapter.load(path)

            # Transform to UTM with WGS84 as intermediate
            tf = Transformer.from_crs(epsg, 4326, always_xy=True, skip_equivalent=True)
            wgs84_xll, wgs84_yll = tf.transform(xll, yll)

            # Calculate the UTM-EPSG to use with pyproj
            _, _, zone_number, _ = utm.from_latlon(wgs84_yll, wgs84_xll)
            utm_epsg = f"326{zone_number:02d}" if wgs84_yll >= 0 else f"327{zone_number:02d}"

            tf = Transformer.from_crs(4326, int(utm_epsg), always_xy=True, skip_equivalent=True)
            xoff, yoff = tf.transform(wgs84_xll, wgs84_yll)

            modelgrid = instance._mf.modelgrid
            updated_modelgrid = StructuredGrid(
                modelgrid.delc,
                modelgrid.delr,
                modelgrid.top,
                modelgrid.botm,
                modelgrid.idomain,
                modelgrid.lenuni,
                epsg=utm_epsg,
                xoff=xoff,
                yoff=yoff,
                angrot=rot if not None else modelgrid.angrot
            )

            instance._mf.modelgrid = updated_modelgrid
            return instance

        except:
            raise
예제 #5
0
def test_read_usgs_model_reference():
    nlay, nrow, ncol = 1, 30, 5
    delr, delc = 250, 500
    #xll, yll = 272300, 5086000
    model_ws = os.path.join('temp', 't007')
    mrf = os.path.join(model_ws, 'usgs.model.reference')
    shutil.copy('../examples/data/usgs.model.reference', mrf)
    fm = flopy.modflow
    m = fm.Modflow(modelname='junk', model_ws=model_ws)
    # feet and days
    dis = fm.ModflowDis(m,
                        nlay=nlay,
                        nrow=nrow,
                        ncol=ncol,
                        delr=delr,
                        delc=delc,
                        lenuni=1,
                        itmuni=4)
    m.write_input()

    # test reading of SR information from usgs.model.reference
    m2 = fm.Modflow.load('junk.nam', model_ws=os.path.join('temp', 't007'))
    from flopy.discretization import StructuredGrid
    mg = StructuredGrid(delr=dis.delr.array, delc=dis.delc.array)
    mg.read_usgs_model_reference_file(mrf)
    m2.modelgrid = mg

    assert m2.modelgrid.xoffset == mg.xoffset
    assert m2.modelgrid.yoffset == mg.yoffset
    assert m2.modelgrid.angrot == mg.angrot
    assert m2.modelgrid.epsg == mg.epsg

    # test reading non-default units from usgs.model.reference
    shutil.copy(mrf, mrf + '_copy')
    with open(mrf + '_copy') as src:
        with open(mrf, 'w') as dst:
            for line in src:
                if 'epsg' in line:
                    line = line.replace("102733", '4326')
                dst.write(line)

    m2 = fm.Modflow.load('junk.nam', model_ws=os.path.join('temp', 't007'))
    m2.modelgrid.read_usgs_model_reference_file(mrf)

    assert m2.modelgrid.epsg == 4326
    # have to delete this, otherwise it will mess up other tests
    to_del = glob.glob(mrf + '*')
    for f in to_del:
        if os.path.exists(f):
            os.remove(os.path.join(f))
    assert True
예제 #6
0
def test_const():

    fm = flopy.modflow
    m = fm.Modflow()
    dis = fm.ModflowDis(m, 1, 10, 10, lenuni=2, itmuni=4)
    m.modelgrid = StructuredGrid(delc=dis.delc.array,
                                 delr=dis.delr.array,)
    r, d = create_sfr_data()
    sfr = flopy.modflow.ModflowSfr2(m, reach_data=r, segment_data={0: d})
    assert sfr.const == 86400.
    m.dis.itmuni = 1.
    m.sfr.const = None
    assert sfr.const == 1.
    m.dis.lenuni = 1.
    m.sfr.const = None
    assert sfr.const == 1.486
    m.dis.itmuni = 4.
    m.sfr.const = None
    assert sfr.const == 1.486 * 86400.
    assert True
예제 #7
0
def test_write_shapefile():
    from flopy.discretization import StructuredGrid
    from flopy.export.shapefile_utils import shp2recarray
    from flopy.export.shapefile_utils import write_grid_shapefile, write_grid_shapefile2

    sg = StructuredGrid(
        delr=np.ones(10) * 1.1,  # cell spacing along model rows
        delc=np.ones(10) * 1.1,  # cell spacing along model columns
        epsg=26715)
    outshp1 = os.path.join(tpth, 'junk.shp')
    outshp2 = os.path.join(tpth, 'junk2.shp')
    write_grid_shapefile(outshp1, sg, array_dict={})
    write_grid_shapefile2(outshp2, sg, array_dict={})

    # test that vertices aren't getting altered by writing shapefile
    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
예제 #8
0
    def modelgrid(self):
        if not self._mg_resync:
            return self._modelgrid

        bas = self.mf.get_package("BAS6")
        if bas is not None:
            ibound = self.btn.icbund.array
        else:
            ibound = None
        # build grid
        self._modelgrid = StructuredGrid(delc=self.mf.dis.delc.array,
                                         delr=self.mf.dis.delr.array,
                                         top=self.mf.dis.top.array,
                                         botm=self.mf.dis.botm.array,
                                         idomain=ibound,
                                         proj4=self._modelgrid.proj4,
                                         epsg=self._modelgrid.epsg,
                                         xoff=self._modelgrid.xoffset,
                                         yoff=self._modelgrid.yoffset,
                                         angrot=self._modelgrid.angrot)

        # resolve offsets
        xoff = self._modelgrid.xoffset
        if xoff is None:
            if self._xul is not None:
                xoff = self._modelgrid._xul_to_xll(self._xul)
            else:
                xoff = 0.0
        yoff = self._modelgrid.yoffset
        if yoff is None:
            if self._yul is not None:
                yoff = self._modelgrid._yul_to_yll(self._yul)
            else:
                yoff = 0.0
        self._modelgrid.set_coord_info(xoff, yoff, self._modelgrid.angrot,
                                       self._modelgrid.epsg,
                                       self._modelgrid.proj4)

        return self._modelgrid
예제 #9
0
def test_export():
    fm = flopy.modflow
    m = fm.Modflow()
    dis = fm.ModflowDis(m, 1, 10, 10, lenuni=2, itmuni=4)
    sr = SpatialReference(xul=0.0, yul=0.0, delc=m.dis.delc.array)
    m.modelgrid = StructuredGrid(delc=m.dis.delc.array,
                                 delr=m.dis.delr.array,
                                 xoff=sr.xll,
                                 yoff=sr.yll)
    # m.sr.origin_loc = "ll"
    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)
예제 #10
0
    def modelgrid(self):
        if not self._mg_resync:
            return self._modelgrid

        if self.bas is not None:
            ibound = self.bas.ibound.array
        else:
            ibound = None

        self._modelgrid = StructuredGrid(self.bcf.delc.array,
                                         self.bcf.delr.array,
                                         None,
                                         None,
                                         ibound,
                                         self.bas.lenuni,
                                         proj4=self._modelgrid.proj4,
                                         epsg=self._modelgrid.epsg,
                                         xoff=self._modelgrid.xoffset,
                                         yoff=self._modelgrid.yoffset,
                                         angrot=self._modelgrid.angrot)
        # resolve offsets
        xoff = self._modelgrid.xoffset
        if xoff is None:
            if self._xul is not None:
                xoff = self._modelgrid._xul_to_xll(self._xul)
            else:
                xoff = 0.0
        yoff = self._modelgrid.yoffset
        if yoff is None:
            if self._yul is not None:
                yoff = self._modelgrid._yul_to_yll(self._yul)
            else:
                yoff = 0.0
        self._modelgrid.set_coord_info(xoff, yoff, self._modelgrid.angrot,
                                       self._modelgrid.epsg,
                                       self._modelgrid.proj4)
        return self._modelgrid
예제 #11
0
def test_structured_thick():
    nlay, nrow, ncol = 3, 2, 3
    delc = 1.0 * np.ones(nrow, dtype=float)
    delr = 1.0 * np.ones(ncol, dtype=float)
    top = 10.0 * np.ones((nrow, ncol), dtype=float)
    botm = np.zeros((nlay, nrow, ncol), dtype=float)
    botm[0, :, :] = 5.0
    botm[1, :, :] = 0.0
    botm[2, :, :] = -5.0
    grid = StructuredGrid(
        nlay=nlay,
        nrow=nrow,
        ncol=ncol,
        delc=delc,
        delr=delr,
        top=top,
        botm=botm,
    )
    thick = grid.thick
    assert np.allclose(thick, 5.0), "thicknesses != 5."

    sat_thick = grid.saturated_thick(grid.botm + 10.0)
    assert np.allclose(sat_thick, thick), "saturated thicknesses != 5."

    sat_thick = grid.saturated_thick(grid.botm + 5.0)
    assert np.allclose(sat_thick, thick), "saturated thicknesses != 5."

    sat_thick = grid.saturated_thick(grid.botm + 2.5)
    assert np.allclose(sat_thick, 2.5), "saturated thicknesses != 2.5"

    sat_thick = grid.saturated_thick(grid.botm)
    assert np.allclose(sat_thick, 0.0), "saturated thicknesses != 0."

    sat_thick = grid.saturated_thick(grid.botm - 100.0)
    assert np.allclose(sat_thick, 0.0), "saturated thicknesses != 0."

    return
예제 #12
0
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)
예제 #13
0
def test_freyberg_export():
    from flopy.discretization import StructuredGrid
    namfile = 'freyberg.nam'

    # steady state
    model_ws = '../examples/data/freyberg'
    m = flopy.modflow.Modflow.load(namfile,
                                   model_ws=model_ws,
                                   check=False,
                                   verbose=False)
    # test export at model, package and object levels
    m.export('{}/model.shp'.format(spth))
    m.wel.export('{}/wel.shp'.format(spth))
    m.lpf.hk.export('{}/hk.shp'.format(spth))
    m.riv.stress_period_data.export('{}/riv_spd.shp'.format(spth))

    # transient
    # (doesn't work at model level because the total size of
    #  the attribute fields exceeds the shapefile limit)
    model_ws = '../examples/data/freyberg_multilayer_transient/'
    m = flopy.modflow.Modflow.load(
        namfile,
        model_ws=model_ws,
        verbose=False,
        load_only=['DIS', 'BAS6', 'NWT', 'OC', 'RCH', 'WEL', 'DRN', 'UPW'])
    # test export without instantiating an sr
    outshp = os.path.join(spth, namfile[:-4] + '_drn_sparse.shp')
    m.drn.stress_period_data.export(outshp, sparse=True)
    assert os.path.exists(outshp)
    remove_shp(outshp)
    m.modelgrid = StructuredGrid(delc=m.dis.delc.array,
                                 delr=m.dis.delr.array,
                                 epsg=5070)
    # test export with an sr, regardless of whether or not wkt was found
    m.drn.stress_period_data.export(outshp, sparse=True)
    assert os.path.exists(outshp)
    remove_shp(outshp)
    m.modelgrid = StructuredGrid(delc=m.dis.delc.array,
                                 delr=m.dis.delr.array,
                                 epsg=3070)
    # verify that attributes have same sr as parent
    assert m.drn.stress_period_data.mg.epsg == m.modelgrid.epsg
    assert m.drn.stress_period_data.mg.proj4 == m.modelgrid.proj4
    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

    # if wkt text was fetched from spatialreference.org
    if m.sr.wkt is not None:
        # test default package export
        outshp = os.path.join(spth, namfile[:-4] + '_dis.shp')
        m.dis.export(outshp)
        prjfile = outshp.replace('.shp', '.prj')
        with open(prjfile) as src:
            prjtxt = src.read()
        assert prjtxt == m.sr.wkt
        remove_shp(outshp)

        # test default package export to higher level dir
        outshp = os.path.join(spth, namfile[:-4] + '_dis.shp')
        m.dis.export(outshp)
        prjfile = outshp.replace('.shp', '.prj')
        with open(prjfile) as src:
            prjtxt = src.read()
        assert prjtxt == m.sr.wkt
        remove_shp(outshp)

        # test sparse package export
        outshp = os.path.join(spth, namfile[:-4] + '_drn_sparse.shp')
        m.drn.stress_period_data.export(outshp, sparse=True)
        prjfile = outshp.replace('.shp', '.prj')
        assert os.path.exists(prjfile)
        with open(prjfile) as src:
            prjtxt = src.read()
        assert prjtxt == m.sr.wkt
        remove_shp(outshp)
예제 #14
0
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
예제 #15
0
    def load(f,
             exe_name='mf88.exe',
             verbose=False,
             model_ws='.',
             forgive=True,
             lenuni=0):
        """
        Load an existing MODFLOW model.

        Parameters
        ----------
        f : str
            Path to MODFLOW script file to load.
        exe_name : str, optional
            MODFLOW executable name. Default 'mf2005.exe'.
        verbose : bool, optional
            Show messages that can be useful for debugging. Default False.
        model_ws : str
            Model workspace path. Default '.' or current directory.
        forgive : bool, optional
            Option to raise exceptions on package load failure, which can be
            useful for debugging. Default False.
        lenuni : int, str
            length unit for model. Not in mf88 but useful for exporting


        Returns
        -------
        ml : Modflow object

        Examples
        --------

        >>> import mf2web
        >>> ml = mf2web.mf88.Modflow88.load('model.sh')

        """
        scriptfile_path = os.path.join(model_ws, f)
        modelname = os.path.splitext(os.path.basename(f))[0]

        if verbose:
            print('\nCreating new model with name: {}\n{}\n'.format(
                modelname, 50 * '-'))

        ml = Modflow88(modelname,
                       exe_name=exe_name,
                       verbose=verbose,
                       model_ws=model_ws)

        # create utility to parse the script file!
        ext_unit_dict = parse_scriptfile(scriptfile_path, model_ws)

        basfile = ext_unit_dict.pop("BAS")
        pak = ml.mfnam_packages["BAS"]
        bas = pak.load(os.path.join(model_ws, basfile.filename),
                       ml,
                       ext_unit_dict=ext_unit_dict)

        # get active packages!
        ml.lenuni = lenuni
        iunit = bas.iunit

        for pos, unit in enumerate(iunit):

            if unit > 0:
                if forgive:
                    try:
                        pak = ml.mfnam_packages[pos]
                        fname = ext_unit_dict.pop(unit)
                        pak.load(os.path.join(model_ws, fname.filename),
                                 ml,
                                 ext_unit_dict=ext_unit_dict)
                    except Exception as e:
                        print("Package load error: iunit position {}".format(
                            pos + 1))

                else:
                    pak = ml.mfnam_packages[pos]
                    if pak is None:
                        print("iunit position not implemented {}".format(pos +
                                                                         1))
                        continue
                    fname = ext_unit_dict.pop(unit)
                    pak.load(os.path.join(model_ws, fname.filename),
                             ml,
                             ext_unit_dict=ext_unit_dict)

            else:
                pass

        ml._modelgrid = StructuredGrid(ml.bcf.delc.array, ml.bcf.delr.array,
                                       None, None, ml.bas.ibound,
                                       ml.bas.lenuni)

        return ml
예제 #16
0
    def __new__(cls,
                sr=None,
                ax=None,
                model=None,
                dis=None,
                layer=0,
                extent=None,
                xul=None,
                yul=None,
                xll=None,
                yll=None,
                rotation=None,
                length_multiplier=None):

        from ..utils.reference import SpatialReferenceUnstructured
        from ..plot.plotbase import DeprecatedMapView

        err_msg = "ModelMap will be replaced by " \
                  "PlotMapView(); Calling PlotMapView()"
        warnings.warn(err_msg, PendingDeprecationWarning)

        modelgrid = None
        if model is not None:
            if (xul, yul, xll, yll, rotation) != (None, None, None, None,
                                                  None):
                modelgrid = plotutil._set_coord_info(model.modelgrid, xul, yul,
                                                     xll, yll, rotation)
        elif sr is not None:
            if length_multiplier is not None:
                sr.length_multiplier = length_multiplier

            if (xul, yul, xll, yll, rotation) != (None, None, None, None,
                                                  None):
                sr.set_spatialreference(xul, yul, xll, yll, rotation)

            if isinstance(sr, SpatialReferenceUnstructured):
                if dis is not None:
                    modelgrid = UnstructuredGrid(vertices=sr.verts,
                                                 iverts=sr.iverts,
                                                 xcenters=sr.xc,
                                                 ycenters=sr.yc,
                                                 top=dis.top.array,
                                                 botm=dis.botm.array,
                                                 ncpl=sr.ncpl)
                else:
                    modelgrid = UnstructuredGrid(vertices=sr.verts,
                                                 iverts=sr.iverts,
                                                 xcenters=sr.xc,
                                                 ycenters=sr.yc,
                                                 ncpl=sr.ncpl)

            elif dis is not None:
                modelgrid = StructuredGrid(delc=sr.delc,
                                           delr=sr.delr,
                                           top=dis.top.array,
                                           botm=dis.botm.array,
                                           xoff=sr.xll,
                                           yoff=sr.yll,
                                           angrot=sr.rotation)
            else:
                modelgrid = StructuredGrid(delc=sr.delc,
                                           delr=sr.delr,
                                           xoff=sr.xll,
                                           yoff=sr.yll,
                                           angrot=sr.rotation)

        else:
            pass

        return DeprecatedMapView(model=model,
                                 modelgrid=modelgrid,
                                 ax=ax,
                                 layer=layer,
                                 extent=extent)