示例#1
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)
示例#2
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
示例#3
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
示例#4
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)
    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)