コード例 #1
0
ファイル: t007_test.py プロジェクト: yinzongmin/flopy
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)
コード例 #2
0
ファイル: t007_test.py プロジェクト: yinzongmin/flopy
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
コード例 #3
0
ファイル: t007_test.py プロジェクト: modflowpy/flopy
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)
コード例 #4
0
ファイル: t007_test.py プロジェクト: yinzongmin/flopy
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
コード例 #5
0
    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
コード例 #6
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)
コード例 #7
0
ファイル: t007_test.py プロジェクト: modflowpy/flopy
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
コード例 #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 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
コード例 #10
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
コード例 #11
0
ファイル: t007_test.py プロジェクト: yinzongmin/flopy
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
コード例 #12
0
ファイル: t009_test.py プロジェクト: spaulins-usgs/flopy
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)
コード例 #13
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
コード例 #14
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)
コード例 #15
0
ファイル: t031_test.py プロジェクト: modflowpy/flopy
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)
コード例 #16
0
ファイル: t007_test.py プロジェクト: yinzongmin/flopy
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)
コード例 #17
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)
コード例 #18
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
コード例 #19
0
class Mt3dms(fp.mt3d.Mt3dms):
    """
    Override of the flopy mt3ms class until the modelgrid issues
    are fixed
    """
    def __init__(self,
                 modelname='mt3dtest',
                 namefile_ext='nam',
                 modflowmodel=None,
                 ftlfilename="mt3d_link.ftl",
                 ftlfree=False,
                 version='mt3dms',
                 exe_name='mt3dms.exe',
                 structured=True,
                 listunit=None,
                 ftlunit=None,
                 model_ws='.',
                 external_path=None,
                 verbose=False,
                 load=True,
                 silent=0):

        super(Mt3dms, self).__init__(modelname=modelname,
                                     namefile_ext=namefile_ext,
                                     modflowmodel=modflowmodel,
                                     ftlfilename=ftlfilename,
                                     ftlfree=ftlfree,
                                     version=version,
                                     exe_name=exe_name,
                                     structured=structured,
                                     listunit=listunit,
                                     ftlunit=ftlunit,
                                     model_ws=model_ws,
                                     external_path=external_path,
                                     verbose=verbose,
                                     load=load,
                                     silent=silent)

        self._mg_resync = True

    @property
    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

    @staticmethod
    def load(f,
             version='mt3dms',
             exe_name='mt3dms.exe',
             verbose=False,
             model_ws='.',
             load_only=None,
             forgive=False,
             modflowmodel=None):
        """
        Load an existing model.

        Parameters
        ----------
        f : string
            Full path and name of MT3D name file.

        version : string
            The version of MT3D (mt3dms, or mt3d-usgs)
            (default is mt3dms)

        exe_name : string
            The name of the executable to use if this loaded model is run.
            (default is mt3dms.exe)

        verbose : bool
            Write information on the load process if True.
            (default is False)

        model_ws : string
            The path for the model workspace.
            (default is the current working directory '.')

        load_only : list of strings
            Filetype(s) to load (e.g. ['btn', 'adv'])
            (default is None, which means that all will be loaded)

        modflowmodel : flopy.modflow.mf.Modflow
            This is a flopy Modflow model object upon which this Mt3dms
            model is based. (the default is None)

        Returns
        -------
        mt : flopy.mt3d.mt.Mt3dms
            flopy Mt3d model object

        Notes
        -----
        The load method does not retain the name for the MODFLOW-generated
        FTL file.  This can be added manually after the MT3D model has been
        loaded.  The syntax for doing this manually is
        mt.ftlfilename = 'example.ftl'

        Examples
        --------

        >>> import mf2web
        >>> f = 'example.nam'
        >>> mt = mf2web.mt3d.Mt3dms.load(f)
        >>> mt.ftlfilename = 'example.ftl'

        """
        # test if name file is passed with extension (i.e., is a valid file)
        modelname_extension = None
        if os.path.isfile(os.path.join(model_ws, f)):
            modelname = f.rpartition('.')[0]
            modelname_extension = f.rpartition('.')[2]
        else:
            modelname = f

        if verbose:
            sys.stdout.write(
                '\nCreating new model with name: {}\n{}\n\n'.format(
                    modelname, 50 * '-'))
        mt = Mt3dms(modelname=modelname,
                    namefile_ext=modelname_extension,
                    version=version,
                    exe_name=exe_name,
                    verbose=verbose,
                    model_ws=model_ws,
                    modflowmodel=modflowmodel)

        files_successfully_loaded = []
        files_not_loaded = []

        # read name file
        try:
            # namefile_path = os.path.join(mt.model_ws, mt.namefile)
            # namefile_path = f
            namefile_path = os.path.join(mt.model_ws, f)
            ext_unit_dict = mfreadnam.parsenamefile(namefile_path,
                                                    mt.mfnam_packages,
                                                    verbose=verbose)
        except Exception as e:
            # print("error loading name file entries from file")
            # print(str(e))
            # return None
            raise Exception("error loading name file entries from file:\n" +
                            str(e))

        if mt.verbose:
            print('\n{}\nExternal unit dictionary:\n{}\n{}\n'.format(
                50 * '-', ext_unit_dict, 50 * '-'))

        # reset unit number for list file
        unitnumber = None
        for key, value in ext_unit_dict.items():
            if value.filetype == 'LIST':
                unitnumber = key
                filepth = os.path.basename(value.filename)
        if unitnumber == 'LIST':
            unitnumber = 16
        if unitnumber is not None:
            mt.lst.unit_number = [unitnumber]
            mt.lst.file_name = [filepth]

        # set ftl information
        unitnumber = None
        for key, value in ext_unit_dict.items():
            if value.filetype == 'FTL':
                unitnumber = key
                filepth = os.path.basename(value.filename)
        if unitnumber == 'FTL':
            unitnumber = 10
        if unitnumber is not None:
            mt.ftlunit = unitnumber
            mt.ftlfilename = filepth

        # load btn
        btn = None
        btn_key = None
        for key, item in ext_unit_dict.items():
            if item.filetype.lower() == "btn":
                btn = item
                btn_key = key
                break

        if btn is None:
            return None

        try:
            pck = btn.package.load(btn.filename,
                                   mt,
                                   ext_unit_dict=ext_unit_dict)
        except Exception as e:
            raise Exception('error loading BTN: {0}'.format(str(e)))
        files_successfully_loaded.append(btn.filename)
        if mt.verbose:
            sys.stdout.write('   {:4s} package load...success\n'.format(
                pck.name[0]))
        ext_unit_dict.pop(btn_key)

        if load_only is None:
            load_only = []
            for key, item in ext_unit_dict.items():
                load_only.append(item.filetype)
        else:
            if not isinstance(load_only, list):
                load_only = [load_only]
            not_found = []
            for i, filetype in enumerate(load_only):
                filetype = filetype.upper()
                if filetype != 'BTN':
                    load_only[i] = filetype
                    found = False
                    for key, item in ext_unit_dict.items():
                        if item.filetype == filetype:
                            found = True
                            break
                    if not found:
                        not_found.append(filetype)
            if len(not_found) > 0:
                raise Exception(
                    "the following load_only entries were not found "
                    "in the ext_unit_dict: " + ','.join(not_found))

        # try loading packages in ext_unit_dict
        for key, item in ext_unit_dict.items():
            if item.package is not None:
                if item.filetype in load_only:
                    if forgive:
                        try:
                            pck = item.package.load(
                                item.filename, mt, ext_unit_dict=ext_unit_dict)
                            files_successfully_loaded.append(item.filename)
                            if mt.verbose:
                                sys.stdout.write(
                                    '   {:4s} package load...success\n'.format(
                                        pck.name[0]))
                        except BaseException as o:
                            if mt.verbose:
                                sys.stdout.write(
                                    '   {:4s} package load...failed\n   {!s}\n'
                                    .format(item.filetype, o))
                            files_not_loaded.append(item.filename)
                    else:
                        pck = item.package.load(item.filename,
                                                mt,
                                                ext_unit_dict=ext_unit_dict)
                        files_successfully_loaded.append(item.filename)
                        if mt.verbose:
                            sys.stdout.write(
                                '   {:4s} package load...success\n'.format(
                                    pck.name[0]))
                else:
                    if mt.verbose:
                        sys.stdout.write(
                            '   {:4s} package load...skipped\n'.format(
                                item.filetype))
                    files_not_loaded.append(item.filename)
            elif "data" not in item.filetype.lower():
                files_not_loaded.append(item.filename)
                if mt.verbose:
                    sys.stdout.write(
                        '   {:4s} package load...skipped\n'.format(
                            item.filetype))
            elif "data" in item.filetype.lower():
                if mt.verbose:
                    sys.stdout.write(
                        '   {} file load...skipped\n      {}\n'.format(
                            item.filetype, os.path.basename(item.filename)))
                if key not in mt.pop_key_list:
                    mt.external_fnames.append(item.filename)
                    mt.external_units.append(key)
                    mt.external_binflag.append(
                        "binary" in item.filetype.lower())
                    mt.external_output.append(False)

        # pop binary output keys and any external file units that are now
        # internal
        for key in mt.pop_key_list:
            try:
                mt.remove_external(unit=key)
                ext_unit_dict.pop(key)
            except:
                if mt.verbose:
                    sys.stdout.write('Warning: external file unit " +\
                        "{} does not exist in ext_unit_dict.\n'.format(key))

        # write message indicating packages that were successfully loaded
        if mt.verbose:
            print(1 * '\n')
            s = '   The following {0} packages were successfully loaded.' \
                .format(len(files_successfully_loaded))
            print(s)
            for fname in files_successfully_loaded:
                print('      ' + os.path.basename(fname))
            if len(files_not_loaded) > 0:
                s = '   The following {0} packages were not loaded.'.format(
                    len(files_not_loaded))
                print(s)
                for fname in files_not_loaded:
                    print('      ' + os.path.basename(fname))
                print('\n')

        # return model object
        return mt
コード例 #20
0
class Modflow88(BaseModel):
    """
    MODFLOW 88 model object

    Parameters
    ----------

    modelname : str
        name of the model

    scriptfile_ext : str
        extension of the scriptfile

    exe_name : basestring
        name of the modflow executable

    model_ws : str
        path to the model workspace

    verbose : bool
        is mf88 going to be verbose?
    """
    def __init__(self,
                 modelname="modflowtest",
                 scriptfile_ext=".sh",
                 exe_name="mf88.exe",
                 model_ws=".",
                 verbose=False,
                 lenuni=0,
                 **kwargs):

        super(Modflow88, self).__init__(modelname,
                                        scriptfile_ext,
                                        exe_name,
                                        model_ws,
                                        structured=True,
                                        verbose=verbose,
                                        **kwargs)

        self.__LENUNI = {'u': 0, "f": 1, "m": 2, "c": 3}
        self.array_format = "modflow"
        self.load_fail = False
        self._next_ext_unit = 91

        self.external_path = "."
        self.verbose = verbose

        self.hext = 'hds'
        self.cext = 'cbc'

        self.hpth = None
        self.cpath = None

        self._lenuni = lenuni
        if isinstance(lenuni, str):
            self._lenuni = self.__LENUNI[lenuni.lower()[0]]

        # Create a dictionary to map package with the iunit location.
        # This is used for loading models.
        self.mfnam_packages = {
            "BAS": mf2web.mf88.Modflow88Bas,
            0: mf2web.mf88.Modflow88Bcf,
            1: mf2web.mf88.Modflow88Wel,
            2: mf2web.mf88.Modflow88Drn,
            3: mf2web.mf88.Modflow88Riv,
            4: mf2web.mf88.Modflow88Evt,
            5: mf2web.mf88.Modflow88Hfb,
            6: mf2web.mf88.Modflow88Ghb,
            7: mf2web.mf88.Modflow88Rch,
            8: mf2web.mf88.Modflow88Sip,
            9: None,
            10: mf2web.mf88.Modflow88Sor,
            11: mf2web.mf88.Modflow88Oc,
            12: None,
            13: None,
            14: None,
            15: None,
            16: None,
            17: None,
            18: None,
            19: None,
            20: None,
            21: None,
            22: None,
            23: None
        }

    def __repr__(self):
        nrow, ncol, nlay, nper = self.get_nrow_ncol_nlay_nper()
        s = ""
        if nrow is not None:
            # structured case
            s = ('MODFLOW-88 {} layer(s) {} row(s) {} column(s) '
                 '{} stress period(s)'.format(nlay, nrow, ncol, nper))
        return s

    @property
    def lenuni(self):
        return self._lenuni

    @lenuni.setter
    def lenuni(self, lenuni):
        if isinstance(lenuni, str):
            self._lenuni = self.__LENUNI[lenuni.lower()[0]]
        elif lenuni is None:
            self._lenuni = 0
        else:
            self._lenuni = lenuni

        if self.bas is not None:
            self.bas.lenuni = self._lenuni

    @property
    def modeltime(self):
        # build model time
        data_frame = {
            'perlen': self.bas.perlen.array,
            'nstp': self.bas.nstp.array,
            'tsmult': self.bas.tsmult.array
        }
        self._model_time = ModelTime(data_frame,
                                     self.bas.itmuni_dict[self.dis.itmuni],
                                     self.bas.start_datetime)
        return self._model_time

    @property
    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

    @modelgrid.setter
    def modelgrid(self, value):
        self._modelgrid = value

    @property
    def solver_tols(self):
        if self.sor is not None:
            return self.sor.hclose, -999
        elif self.sip is not None:
            return self.sip.hclose, -999
        return None

    @property
    def nlay(self):
        if (self.bas):
            return self.bas.nlay
        else:
            return 0

    @property
    def nrow(self):
        if (self.bas):
            return self.bas.nrow
        else:
            return 0

    @property
    def ncol(self):
        if (self.bas):
            return self.bas.ncol
        else:
            return 0

    @property
    def nper(self):
        if (self.bas):
            return self.bas.nper
        else:
            return 0

    @property
    def ncpl(self):
        if (self.bas):
            return self.bas.nrow * self.bas.ncol
        else:
            return 0

    @property
    def nrow_ncol_nlay_nper(self):
        return self.nrow, self.ncol, self.nlay, self.nper

    def _set_name(self, value):
        pass

    def write_name_file(self):
        pass

    def set_model_units(self, iunit0=None):
        pass

    def load_results(self, **kwargs):
        pass

    def __getattr__(self, item):
        """
        __getattr__ - syntactic sugar

        Parameters
        ----------
        item : str
            3 character package name (case insensitive) or "sr" to access
            the SpatialReference instance of the ModflowDis object


        Returns
        -------
        sr : SpatialReference instance
        pp : Package object
            Package object of type :class:`flopy.pakbase.Package`

        Note
        ----
        if self.dis is not None, then the spatial reference instance is updated
        using self.dis.delr, self.dis.delc, and self.dis.lenuni before being
        returned
        """
        if item == 'sr':
            return None
        if item == 'tr':
            return None
        if item == "start_datetime":
            if self.bas is not None:
                return self.bas.start_datetime
            else:
                return None

        return self.get_package(item)

    @staticmethod
    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
コード例 #21
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