def to_shapefile(self, filename, kper=None): """ Export stress period boundary condition (MfList) data for a specified stress period Parameters ---------- filename : str Shapefile name to write kper : int MODFLOW zero-based stress period number to return. (default is None) Returns ---------- None See Also -------- Notes ----- Examples -------- >>> import flopy >>> ml = flopy.modflow.Modflow.load('test.nam') >>> ml.wel.to_shapefile('test_hk.shp', kper=1) """ if self.sr is None: raise Exception("MfList.to_shapefile: SpatialReference not set") import flopy.utils.flopy_io as fio if kper is None: keys = self.data.keys() keys.sort() else: keys = [kper] array_dict = {} for kk in keys: arrays = self.to_array(kk) for name, array in arrays.items(): for k in range(array.shape[0]): #aname = name+"{0:03d}_{1:02d}".format(kk, k) n = fio.shape_attr_name(name, length=4) aname = "{}{:03d}{:03d}".format(n, k+1, int(kk)+1) array_dict[aname] = array[k] fio.write_grid_shapefile(filename, self.sr, array_dict)
def mflist_helper(f, mfl, **kwargs): """ export helper for MfList instances Parameters ----------- f : string (filename) or existing export instance type (NetCdf only for now) mfl : MfList instance """ assert isinstance(mfl, MfList) \ , "mflist_helper only helps MfList instances" if isinstance(f, str) and f.lower().endswith(".nc"): f = NetCdf(f, mfl.model) if isinstance(f, str) and f.lower().endswith(".shp"): kper = kwargs.get("kper",None) if mfl.sr is None: raise Exception("MfList.to_shapefile: SpatialReference not set") import flopy.utils.flopy_io as fio if kper is None: keys = mfl.data.keys() keys.sort() else: keys = [kper] array_dict = {} for kk in keys: arrays = mfl.to_array(kk) for name, array in arrays.items(): for k in range(array.shape[0]): #aname = name+"{0:03d}_{1:02d}".format(kk, k) n = fio.shape_attr_name(name, length=4) aname = "{}{:03d}{:03d}".format(n, k+1, int(kk)+1) array_dict[aname] = array[k] shapefile_utils.write_grid_shapefile(f, mfl.sr, array_dict) elif isinstance(f, NetCdf) or isinstance(f,dict): base_name = mfl.package.name[0].lower() #f.log("getting 4D masked arrays for {0}".format(base_name)) #m4d = mfl.masked_4D_arrays #f.log("getting 4D masked arrays for {0}".format(base_name)) #for name, array in m4d.items(): for name, array in mfl.masked_4D_arrays_itr(): var_name = base_name + '_' + name if isinstance(f,dict): f[var_name] = array continue f.log("processing {0} attribute".format(name)) units = None if var_name in NC_UNITS_FORMAT: units = NC_UNITS_FORMAT[var_name].format(f.grid_units, f.time_units) precision_str = NC_PRECISION_TYPE[mfl.dtype[name].type] if var_name in NC_LONG_NAMES: attribs = {"long_name":NC_LONG_NAMES[var_name]} else: attribs = {"long_name":var_name} attribs["coordinates"] = "time layer latitude longitude" attribs["min"] = np.nanmin(array) attribs["max"] = np.nanmax(array) if units is not None: attribs["units"] = units try: var = f.create_variable(var_name, attribs, precision_str=precision_str, dimensions=("time", "layer", "y", "x")) except Exception as e: estr = "error creating variable {0}:\n{1}".format(var_name, str(e)) f.logger.warn(estr) raise Exception(estr) array[np.isnan(array)] = f.fillvalue try: var[:] = array except Exception as e: estr = "error setting array to variable {0}:\n{1}".format(var_name, str(e)) f.logger.warn(estr) raise Exception(estr) f.log("processing {0} attribute".format(name)) return f else: raise NotImplementedError("unrecognized export argument:{0}".format(f))
def mflist_helper(f, mfl, **kwargs): """ export helper for MfList instances Parameters ----------- f : string (filename) or existing export instance type (NetCdf only for now) mfl : MfList instance """ assert isinstance(mfl, MfList) \ , "mflist_helper only helps MfList instances" if isinstance(f, str) and f.lower().endswith(".nc"): f = NetCdf(f, mfl.model) if isinstance(f, str) and f.lower().endswith(".shp"): sparse = kwargs.get("sparse", False) kper = kwargs.get("kper", 0) squeeze = kwargs.get("squeeze", True) if mfl.sr is None: raise Exception("MfList.to_shapefile: SpatialReference not set") import flopy.utils.flopy_io as fio if kper is None: keys = mfl.data.keys() keys.sort() else: keys = [kper] if not sparse: array_dict = {} for kk in keys: arrays = mfl.to_array(kk) for name, array in arrays.items(): for k in range(array.shape[0]): # aname = name+"{0:03d}_{1:02d}".format(kk, k) n = fio.shape_attr_name(name, length=4) aname = "{}{:03d}{:03d}".format(n, k + 1, int(kk) + 1) array_dict[aname] = array[k] shapefile_utils.write_grid_shapefile(f, mfl.sr, array_dict) else: from ..export.shapefile_utils import recarray2shp from ..utils.geometry import Polygon #if np.isscalar(kper): # kper = [kper] sr = mfl.model.sr df = mfl.get_dataframe(squeeze=squeeze) if 'kper' in kwargs or df is None: ra = mfl[kper] verts = np.array(sr.get_vertices(ra.i, ra.j)) elif df is not None: verts = sr.get_vertices(df.i.values, df.j.values) ra = df.to_records(index=False) # write the projection file if sr.epsg is None: epsg = kwargs.get('epsg', None) else: epsg = sr.epsg prj = kwargs.get('prj', None) polys = np.array([Polygon(v) for v in verts]) recarray2shp(ra, geoms=polys, shpname=f, epsg=epsg, prj=prj) elif isinstance(f, NetCdf) or isinstance(f, dict): base_name = mfl.package.name[0].lower() # f.log("getting 4D masked arrays for {0}".format(base_name)) # m4d = mfl.masked_4D_arrays # f.log("getting 4D masked arrays for {0}".format(base_name)) # for name, array in m4d.items(): for name, array in mfl.masked_4D_arrays_itr(): var_name = base_name + '_' + name if isinstance(f, dict): f[var_name] = array continue f.log("processing {0} attribute".format(name)) units = None if var_name in NC_UNITS_FORMAT: units = NC_UNITS_FORMAT[var_name].format(f.grid_units, f.time_units) precision_str = NC_PRECISION_TYPE[mfl.dtype[name].type] if var_name in NC_LONG_NAMES: attribs = {"long_name": NC_LONG_NAMES[var_name]} else: attribs = {"long_name": var_name} attribs["coordinates"] = "time layer latitude longitude" attribs["min"] = np.nanmin(array) attribs["max"] = np.nanmax(array) if np.isnan(attribs["min"]) or np.isnan(attribs["max"]): raise Exception( "error processing {0}: all NaNs".format(var_name)) if units is not None: attribs["units"] = units try: var = f.create_variable(var_name, attribs, precision_str=precision_str, dimensions=("time", "layer", "y", "x")) except Exception as e: estr = "error creating variable {0}:\n{1}".format(var_name, str(e)) f.logger.warn(estr) raise Exception(estr) array[np.isnan(array)] = f.fillvalue try: var[:] = array except Exception as e: estr = "error setting array to variable {0}:\n{1}".format( var_name, str(e)) f.logger.warn(estr) raise Exception(estr) f.log("processing {0} attribute".format(name)) return f else: raise NotImplementedError("unrecognized export argument:{0}".format(f))