Exemple #1
0
def load_sr(filename):
    """Create a SpatialReference instance from model config json file."""
    cfg = load(filename)
    return SpatialReference(delr=np.ones(cfg['ncol']) * cfg['delr'],
                            delc=np.ones(cfg['nrow']) * cfg['delc'],
                            xul=cfg['xul'],
                            yul=cfg['yul'],
                            epsg=cfg['epsg'])
Exemple #2
0
def load_sr(jsonfile):
    """Create a SpatialReference instance from model config json file."""
    from flopy.utils import SpatialReference
    with open(jsonfile) as input:
        cfg = json.load(input)

    rename = {
        'xoff': 'xll',
        'yoff': 'yll',
    }
    for k, v in rename.items():
        if k in cfg:
            cfg[v] = cfg.pop(k)
    cfg['delr'] = np.ones(cfg['ncol']) * cfg['delr']
    cfg['delc'] = np.ones(cfg['nrow']) * cfg['delc']
    kwargs = get_input_arguments(cfg, SpatialReference)
    return SpatialReference(**kwargs)
Exemple #3
0
def flopy_mf2005_load(m, load_only=None, forgive=False, check=False):
    """Execute the code in flopy.modflow.Modflow.load on an existing
    flopy.modflow.Modflow instance."""
    version = m.version
    verbose = m.verbose
    model_ws = m.model_ws

    # similar to modflow command: if file does not exist , try file.nam
    namefile_path = os.path.join(model_ws, m.namefile)
    if (not os.path.isfile(namefile_path)
            and os.path.isfile(namefile_path + '.nam')):
        namefile_path += '.nam'
    if not os.path.isfile(namefile_path):
        raise IOError('cannot find name file: ' + str(namefile_path))

    files_successfully_loaded = []
    files_not_loaded = []

    # set the reference information
    ref_attributes = SpatialReference.load(namefile_path)

    # read name file
    ext_unit_dict = mfreadnam.parsenamefile(namefile_path,
                                            m.mfnam_packages,
                                            verbose=verbose)
    if m.verbose:
        print('\n{}\nExternal unit dictionary:\n{}\n{}\n'.format(
            50 * '-', ext_unit_dict, 50 * '-'))

    # create a dict where key is the package name, value is unitnumber
    ext_pkg_d = {v.filetype: k for (k, v) in ext_unit_dict.items()}

    # version is assumed to be mfnwt
    m.set_version(version)

    # reset unit number for list file
    if 'LIST' in ext_pkg_d:
        unitnumber = ext_pkg_d['LIST']
        filepth = os.path.basename(ext_unit_dict[unitnumber].filename)
        m.lst.unit_number = [unitnumber]
        m.lst.file_name = [filepth]

    # look for the free format flag in bas6
    bas_key = ext_pkg_d.get('BAS6')
    if bas_key is not None:
        bas = ext_unit_dict[bas_key]
        start = bas.filehandle.tell()
        line = bas.filehandle.readline()
        while line.startswith("#"):
            line = bas.filehandle.readline()
        if "FREE" in line.upper():
            m.free_format_input = True
        bas.filehandle.seek(start)
    if verbose:
        print("ModflowBas6 free format:{0}\n".format(m.free_format_input))

    # load dis
    dis_key = ext_pkg_d.get('DIS') or ext_pkg_d.get('DISU')
    if dis_key is None:
        raise KeyError('discretization entry not found in nam file')
    disnamdata = ext_unit_dict[dis_key]
    dis = disnamdata.package.load(disnamdata.filename,
                                  m,
                                  ext_unit_dict=ext_unit_dict,
                                  check=False)
    files_successfully_loaded.append(disnamdata.filename)
    if m.verbose:
        print('   {:4s} package load...success'.format(dis.name[0]))
    m.setup_grid()  # reset model grid now that DIS package is loaded
    assert m.pop_key_list.pop() == dis_key
    ext_unit_dict.pop(dis_key)
    start_datetime = ref_attributes.pop("start_datetime", "01-01-1970")
    itmuni = ref_attributes.pop("itmuni", 4)
    ref_source = ref_attributes.pop("source", "defaults")
    # if m.structured:
    #    # get model units from usgs.model.reference, if provided
    #    if ref_source == 'usgs.model.reference':
    #        pass
    #    # otherwise get them from the DIS file
    #    else:
    #        itmuni = dis.itmuni
    #        ref_attributes['lenuni'] = dis.lenuni
    #    sr = SpatialReference(delr=m.dis.delr.array, delc=ml.dis.delc.array,
    #                          **ref_attributes)
    # else:
    #    sr = None
    #
    dis.sr = m.sr
    dis.tr = TemporalReference(itmuni=itmuni, start_datetime=start_datetime)
    dis.start_datetime = start_datetime

    if load_only is None:
        # load all packages/files
        load_only = ext_pkg_d.keys()
    else:  # check items in list
        if not isinstance(load_only, list):
            load_only = [load_only]
        not_found = []
        for i, filetype in enumerate(load_only):
            load_only[i] = filetype = filetype.upper()
            if filetype not in ext_pkg_d:
                not_found.append(filetype)
        if not_found:
            raise KeyError("the following load_only entries were not found "
                           "in the ext_unit_dict: " + str(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:
                        package_load_args = \
                            list(inspect.getargspec(item.package.load))[0]
                        if "check" in package_load_args:
                            pck = item.package.load(
                                item.filename,
                                m,
                                ext_unit_dict=ext_unit_dict,
                                check=False)
                        else:
                            pck = item.package.load(
                                item.filename, m, ext_unit_dict=ext_unit_dict)
                        files_successfully_loaded.append(item.filename)
                        if m.verbose:
                            print('   {:4s} package load...success'.format(
                                item.filetype))
                    except Exception as e:
                        m.load_fail = True
                        if m.verbose:
                            print('   {:4s} package load...failed\n   {!s}'.
                                  format(item.filetype, e))
                        files_not_loaded.append(item.filename)
                else:
                    package_load_args = \
                        list(inspect.getargspec(item.package.load))[0]
                    if "check" in package_load_args:
                        pck = item.package.load(item.filename,
                                                m,
                                                ext_unit_dict=ext_unit_dict,
                                                check=False)
                    else:
                        pck = item.package.load(item.filename,
                                                m,
                                                ext_unit_dict=ext_unit_dict)
                    files_successfully_loaded.append(item.filename)
                    if m.verbose:
                        print('   {:4s} package load...success'.format(
                            item.filetype))
            else:
                if m.verbose:
                    print('   {:4s} package load...skipped'.format(
                        item.filetype))
                files_not_loaded.append(item.filename)
        elif "data" not in item.filetype.lower():
            files_not_loaded.append(item.filename)
            if m.verbose:
                print('   {:4s} package load...skipped'.format(item.filetype))
        elif "data" in item.filetype.lower():
            if m.verbose:
                print('   {} file load...skipped\n      {}'.format(
                    item.filetype, os.path.basename(item.filename)))
            if key not in m.pop_key_list:
                # do not add unit number (key) if it already exists
                if key not in m.external_units:
                    m.external_fnames.append(item.filename)
                    m.external_units.append(key)
                    m.external_binflag.append(
                        "binary" in item.filetype.lower())
                    m.external_output.append(False)
        else:
            raise KeyError('unhandled case: {}, {}'.format(key, item))

    # pop binary output keys and any external file units that are now
    # internal
    for key in m.pop_key_list:
        try:
            m.remove_external(unit=key)
            ext_unit_dict.pop(key)
        except KeyError:
            if m.verbose:
                print('Warning: external file unit {} does not exist in '
                      'ext_unit_dict.'.format(key))

    # write message indicating packages that were successfully loaded
    if m.verbose:
        print('')
        print('   The following {0} packages were successfully loaded.'.format(
            len(files_successfully_loaded)))
        for fname in files_successfully_loaded:
            print('      ' + os.path.basename(fname))
        if len(files_not_loaded) > 0:
            print('   The following {0} packages were not loaded.'.format(
                len(files_not_loaded)))
            for fname in files_not_loaded:
                print('      ' + os.path.basename(fname))
    if check:
        m.check(f='{}.chk'.format(m.name), verbose=m.verbose, level=0)

    # return model object
    return m
Exemple #4
0
    def load(
        f,
        version="mfnwt",
        exe_name="mfnwt.exe",
        verbose=False,
        model_ws=".",
        load_only=None,
        forgive=False,
        check=True,
        control_file=None,
    ):
        """
        Load an existing MODFLOW model.

        Parameters
        ----------
        f : str
            Path to MODFLOW name file to load.
        version : str, optional
            MODFLOW version. Default 'mf2005', although can be modified on
            loading packages unique to different MODFLOW versions.
        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.
        load_only : list, str or None
            List of case insensitive filetypes to load, e.g. ["bas6", "lpf"].
            One package can also be specified, e.g. "rch". Default is None,
            which attempts to load all files. An empty list [] will not load
            any additional packages than is necessary. At a minimum, "dis" or
            "disu" is always loaded.
        forgive : bool, optional
            Option to raise exceptions on package load failure, which can be
            useful for debugging. Default False.
        check : boolean, optional
            Check model input for common errors. Default True.
        control_file : str, optional
            For using GSFLOW, providing a control file helps to adjust the paths on
            the fly

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

        Examples
        --------

        >>> import flopy
        >>> ml = flopy.modflow.Modflow.load('model.nam')

        """

        # similar to modflow command: if file does not exist , try file.nam
        namefile_path = os.path.join(model_ws, f)
        if not os.path.isfile(namefile_path) and os.path.isfile(namefile_path +
                                                                ".nam"):
            namefile_path += ".nam"
        if not os.path.isfile(namefile_path):
            raise IOError("cannot find name file: " + str(namefile_path))

        # Determine model name from 'f', without any extension or path
        modelname = os.path.splitext(os.path.basename(f))[0]

        # if model_ws is None:
        #    model_ws = os.path.dirname(f)
        if verbose:
            print("\nCreating new model with name: {}\n{}\n".format(
                modelname, 50 * "-"))
        ml = Modflow(
            modelname,
            version=version,
            exe_name=exe_name,
            verbose=verbose,
            model_ws=model_ws,
        )

        files_successfully_loaded = []
        files_not_loaded = []

        # set the reference information
        ref_attributes = SpatialReference.load(namefile_path)

        # read name file
        ext_unit_dict = mfreadnam.parsenamefile(
            namefile_path,
            ml.mfnam_packages,
            control_file=control_file,
            verbose=verbose,
        )
        if ml.verbose:
            print("\n{}\nExternal unit dictionary:\n{}\n{}\n".format(
                50 * "-", ext_unit_dict, 50 * "-"))

        # create a dict where key is the package name, value is unitnumber
        ext_pkg_d = {v.filetype: k for (k, v) in ext_unit_dict.items()}

        # reset version based on packages in the name file
        if "NWT" in ext_pkg_d or "UPW" in ext_pkg_d:
            version = "mfnwt"
        if "GLOBAL" in ext_pkg_d:
            version = "mf2k"
        if "SMS" in ext_pkg_d:
            version = "mfusg"
        if "DISU" in ext_pkg_d:
            version = "mfusg"
            ml.structured = False
        # update the modflow version
        ml.set_version(version)

        # reset unit number for glo file
        if version == "mf2k":
            if "GLOBAL" in ext_pkg_d:
                unitnumber = ext_pkg_d["GLOBAL"]
                filepth = os.path.basename(ext_unit_dict[unitnumber].filename)
                ml.glo.unit_number = [unitnumber]
                ml.glo.file_name = [filepth]
            else:
                ml.glo.unit_number = [0]
                ml.glo.file_name = [""]

        # reset unit number for list file
        if "LIST" in ext_pkg_d:
            unitnumber = ext_pkg_d["LIST"]
            filepth = os.path.basename(ext_unit_dict[unitnumber].filename)
            ml.lst.unit_number = [unitnumber]
            ml.lst.file_name = [filepth]

        # look for the free format flag in bas6
        bas_key = ext_pkg_d.get("BAS6")
        if bas_key is not None:
            bas = ext_unit_dict[bas_key]
            start = bas.filehandle.tell()
            line = bas.filehandle.readline()
            while line.startswith("#"):
                line = bas.filehandle.readline()
            if "FREE" in line.upper():
                ml.free_format_input = True
            bas.filehandle.seek(start)
        if verbose:
            print("ModflowBas6 free format:{0}\n".format(ml.free_format_input))

        # load dis
        dis_key = ext_pkg_d.get("DIS") or ext_pkg_d.get("DISU")
        if dis_key is None:
            raise KeyError("discretization entry not found in nam file")
        disnamdata = ext_unit_dict[dis_key]
        dis = disnamdata.package.load(disnamdata.filename,
                                      ml,
                                      ext_unit_dict=ext_unit_dict,
                                      check=False)
        files_successfully_loaded.append(disnamdata.filename)
        if ml.verbose:
            print("   {:4s} package load...success".format(dis.name[0]))
        assert ml.pop_key_list.pop() == dis_key
        ext_unit_dict.pop(dis_key)
        start_datetime = ref_attributes.pop("start_datetime", "01-01-1970")
        itmuni = ref_attributes.pop("itmuni", 4)
        ref_source = ref_attributes.pop("source", "defaults")
        if ml.structured:
            # get model units from usgs.model.reference, if provided
            if ref_source == "usgs.model.reference":
                pass
            # otherwise get them from the DIS file
            else:
                itmuni = dis.itmuni
                ref_attributes["lenuni"] = dis.lenuni
            sr = SpatialReference(delr=ml.dis.delr.array,
                                  delc=ml.dis.delc.array,
                                  **ref_attributes)
        else:
            sr = None

        dis.sr = sr
        dis.tr = TemporalReference(itmuni=itmuni,
                                   start_datetime=start_datetime)
        dis.start_datetime = start_datetime

        if load_only is None:
            # load all packages/files
            load_only = ext_pkg_d.keys()
        else:  # check items in list
            if not isinstance(load_only, list):
                load_only = [load_only]
            not_found = []
            for i, filetype in enumerate(load_only):
                load_only[i] = filetype = filetype.upper()
                if filetype not in ext_pkg_d:
                    not_found.append(filetype)
            if not_found:
                raise KeyError(
                    "the following load_only entries were not found "
                    "in the ext_unit_dict: " + str(not_found))

        # zone, mult, pval
        if "PVAL" in ext_pkg_d:
            ml.mfpar.set_pval(ml, ext_unit_dict)
            assert ml.pop_key_list.pop() == ext_pkg_d.get("PVAL")
        if "ZONE" in ext_pkg_d:
            ml.mfpar.set_zone(ml, ext_unit_dict)
            assert ml.pop_key_list.pop() == ext_pkg_d.get("ZONE")
        if "MULT" in ext_pkg_d:
            ml.mfpar.set_mult(ml, ext_unit_dict)
            assert ml.pop_key_list.pop() == ext_pkg_d.get("MULT")

        # 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:
                            package_load_args = list(
                                inspect.getargspec(item.package.load))[0]
                            if "check" in package_load_args:
                                pck = item.package.load(
                                    item.filename,
                                    ml,
                                    ext_unit_dict=ext_unit_dict,
                                    check=False,
                                )
                            else:
                                pck = item.package.load(
                                    item.filename,
                                    ml,
                                    ext_unit_dict=ext_unit_dict,
                                )
                            files_successfully_loaded.append(item.filename)
                            if ml.verbose:
                                print("   {:4s} package load...success".format(
                                    item.filetype))
                        except Exception as e:
                            ml.load_fail = True
                            if ml.verbose:
                                print("{:4s} package load...failed\n   {!s}".
                                      format(item.filetype, e))
                            files_not_loaded.append(item.filename)
                    else:
                        package_load_args = list(
                            inspect.getargspec(item.package.load))[0]
                        if "check" in package_load_args:
                            pck = item.package.load(
                                item.filename,
                                ml,
                                ext_unit_dict=ext_unit_dict,
                                check=False,
                            )
                        else:
                            pck = item.package.load(
                                item.filename, ml, ext_unit_dict=ext_unit_dict)
                        files_successfully_loaded.append(item.filename)
                        if ml.verbose:
                            print("   {:4s} package load...success".format(
                                item.filetype))
                else:
                    if ml.verbose:
                        print("   {:4s} package load...skipped".format(
                            item.filetype))
                    files_not_loaded.append(item.filename)
            elif "data" not in item.filetype.lower():
                files_not_loaded.append(item.filename)
                if ml.verbose:
                    print("   {:4s} package load...skipped".format(
                        item.filetype))
            elif "data" in item.filetype.lower():
                if ml.verbose:
                    print("   {} file load...skipped\n      {}".format(
                        item.filetype, os.path.basename(item.filename)))
                if key not in ml.pop_key_list:
                    # do not add unit number (key) if it already exists
                    if key not in ml.external_units:
                        ml.external_fnames.append(item.filename)
                        ml.external_units.append(key)
                        ml.external_binflag.append(
                            "binary" in item.filetype.lower())
                        ml.external_output.append(False)
            else:
                raise KeyError("unhandled case: {}, {}".format(key, item))

        # pop binary output keys and any external file units that are now
        # internal
        for key in ml.pop_key_list:
            try:
                ml.remove_external(unit=key)
                ext_unit_dict.pop(key)
            except KeyError:
                if ml.verbose:
                    print("Warning: external file unit {} does not exist in "
                          "ext_unit_dict.".format(key))

        # write message indicating packages that were successfully loaded
        if ml.verbose:
            print("")
            print(
                "The following {0} packages were successfully loaded.".format(
                    len(files_successfully_loaded)))
            for fname in files_successfully_loaded:
                print("      " + os.path.basename(fname))
            if len(files_not_loaded) > 0:
                print("   The following {0} packages were not loaded.".format(
                    len(files_not_loaded)))
                for fname in files_not_loaded:
                    print("      " + os.path.basename(fname))
        if check:
            ml.check(f="{}.chk".format(ml.name), verbose=ml.verbose, level=0)

        # return model object
        return ml