Modules

Array export

mfexport.array_export.export_array(filename, a, modelgrid, nodata=-9999, fieldname='value', verbose=False, **kwargs)[source]

Write a numpy array to Arc Ascii grid or shapefile with the model reference.

Parameters:
modelgridFlopy StructuredGrid instance
filenamestr

Path of output file. Export format is determined by file extention. ‘.asc’ Arc Ascii grid ‘.tif’ GeoTIFF (requries rasterio package) ‘.shp’ Shapefile

a2D or 3D numpy.ndarray

Array to export

nodatascalar

Value to assign to np.nan entries (default -9999)

fieldnamestr

Attribute field name for array values (shapefile export only). (default ‘values’)

kwargs:

keyword arguments to np.savetxt (ascii) rasterio.open (GeoTIFF) or flopy.export.shapefile_utils.write_grid_shapefile2

Notes

Rotated grids will be either be unrotated prior to export, using scipy.ndimage.rotate (Arc Ascii format) or rotation will be included in their transform property (GeoTiff format). In either case the pixels will be displayed in the (unrotated) projected geographic coordinate system, so the pixels will no longer align exactly with the model grid (as displayed from a shapefile, for example). A key difference between Arc Ascii and GeoTiff (besides disk usage) is that the unrotated Arc Ascii will have a different grid size, whereas the GeoTiff will have the same number of rows and pixels as the original.

mfexport.array_export.export_array_contours(filename, a, modelgrid, fieldname='level', interval=None, levels=None, maxlevels=1000, crs=None, verbose=False, **kwargs)[source]

Contour an array using matplotlib; write shapefile of contours.

Parameters:
filenamestr

Path of output file with ‘.shp’ extention.

a2D numpy array

Array to contour

crsobj

A Python int, dict, str, or pyproj.crs.CRS instance passed to the pyproj.crs.CRS.from_user_input() See http://pyproj4.github.io/pyproj/stable/api/crs/crs.html#pyproj.crs.CRS.from_user_input. Can be any of:

  • PROJ string

  • Dictionary of PROJ parameters

  • PROJ keyword arguments for parameters

  • JSON string with PROJ parameters

  • CRS WKT string

  • An authority string [i.e. ‘epsg:4326’]

  • An EPSG integer code [i.e. 4326]

  • A tuple of (“auth_name”: “auth_code”) [i.e (‘epsg’, ‘4326’)]

  • An object with a to_wkt method.

  • A pyproj.crs.CRS class

**kwargskeyword arguments to matplotlib.axes.Axes.contour
mfexport.array_export.make_levels(array, interval, maxlevels=1000)[source]
mfexport.array_export.squeeze_3d(array)[source]

Squeeze a 3D array to only include the (2D) slices along the 0 axis that are different (for example, periods when a stress changes). Include the first slice (period) by default.

Parameters:
array3D numpy array

Original data

Returns:
squeezeddict

Dictionary of the 2D slices (values), keyed by period, that are different.

Budget output

mfexport.budget_output.aggregate_mf6_stress_budget(mf6_stress_budget_output, text=None, kstpkper=None)[source]

Read MODFLOW 6 budget output for a stress package into a DataFrame of one node/stress period per row, with fluxes listed by column.

Parameters:
mf6_stress_budget_outputfile path

Binary output file

textstr or list of strings

Text identifying flow term(s) (e.g. ‘FLOW-JA-FACE’, ‘GWF’, etc.). If None, all available variables are returned. (default None)

Returns:
dfDataFrame

DataFrame with flow values aggregated by node and stress period. Columns derived from FLOW-JA-FACE results are: kstpkper : (timestep, stress period) tuples time : total time in model units node : SFR reach number (zero-based) Qin : total inflows from other reaches Qout : total outflows to other reaches Qnet : net gain/loss in flow Qmean : average of inflows and outflows Any additional fluxes are listed in columns of the same name.

mfexport.budget_output.aggregate_sfr_flow_ja_face(df)[source]

SFR streamflow in/out components are saved in MODFLOW 6 as FLOW-JA-FACE, where all inflows (positive values) and outflows (negative values) are listed for each stream reach (node). This method aggregates those results and returns a dataframe with one row per reach, with Qin, Qout, Qnet and Qmean_cfd and Qmean_cfs columns.

Parameters:
dfDataFrame

Dataframe produced by read_mf6_binary_stress_output. Must have columns: node : reach number (rno) kstpkper : (timestep, stress period) tuples time : total time in model units q : FLOW-JA-FACE values (+ in, - out)

Returns:
aggDataFrame

DataFrame with flow values aggregated by node, with columns: kstpkper : (timestep, stress period) tuples time : total time in model units rno : reach number (1-based) Qin : total inflows from other reaches Qout : total outflows to other reaches Qnet : net gain/loss in flow Qmean : average of inflows and outflows

mfexport.budget_output.get_bc_flux(cbbobj, txt, kstpkper=None, idx=None)[source]

Read a flow component from MODFLOW binary cell budget output;

Parameters:
cbbobjopen file handle (instance of flopy.utils.binaryfile.CellBudgetFile
txtcell budget record to read (e.g. ‘STREAM LEAKAGE’)
kstpkpertuple

(timestep, stress period) to read

idxindex of list returned by cbbobj (usually 0)
Returns:
arrndarray
mfexport.budget_output.get_flowja_face(cell_budget_file, binary_grid_file, kstpkper=(0, 0), idx=0, precision='double')[source]

Get FLOW-JA-FACE (cell by cell flows) from MODFLOW 6 budget output and binary grid file. TODO: need test for extracted flowja fluxes

mfexport.budget_output.get_intercell_connections(ia, ja, flowja)[source]
mfexport.budget_output.get_stress_budget_textlist(mf6_stress_budget_output)[source]

Get list of available variable names in a binary budget output file.

mfexport.budget_output.read_mf6_dependent_variable_output(mf6_dependent_variable_output, text='head', kstpkper=None, hdry=-1e+30)[source]

Reads dependent variable output; for example, heads from the groundwater flow solution or output from STAGE FILEOUT in the options block of the .sfr6 file). Returns a DataFrame of output values.

Parameters:
mf6_dependent_variable_outputfile path

Binary output file

textstr

Text identifying variable (e.g. ‘head’, ‘stage’, etc.)

kstpkperlist of tuples

List of zero-based (timestep, stress period) tuples. If None, all available data are returned. (default None)

hdryfloat

Value indicating dry cells.

Returns:
dfDataFrame

Table with results. Columns: node : Zero-based ID: model cell number for heads, reach number for SFR, etc. <text> : results for variable <text> kstpkper : (timestep, stress period) time : total time in model units

mfexport.budget_output.read_mf6_stress_budget_output(mf6_stress_budget_output, text='FLOW-JA-FACE', kstpkper=None)[source]

Reads budget output from any package that follows the imeth=6 structure (e.g. LAK, MAW, SFR, and UZF package(s); for example, output from BUDGET FILEOUT in the options block of the .sfr6 file).

Parameters:
mf6_stress_budget_outputfile path

Binary output file

textstr

Text identifying flow term (e.g. ‘FLOW-JA-FACE’)

Returns:
dfDataFrame

Table with flow results. Columns: node : node number (e.g. stream reach; 1-based) node2 : connecting node (e.g. up or downstream reach; 1-based) q : flow values FLOW-AREA : area of JA-FACE? kstpkper : (timestep, stress period) time : total time in model units

mfexport.budget_output.read_sfr_output(mf2005_sfr_outputfile=None, mf2005_SfrFile_instance=None, mf6_sfr_stage_file=None, mf6_sfr_budget_file=None, mf6_package_data=None, model=None, grid_type='structured')[source]

Read MF-2005 or MF-6 style SFR output; return as DataFrame.

Grid

class mfexport.grid.MFexportGrid(delc, delr, top=None, botm=None, idomain=None, laycbd=None, lenuni=None, epsg=None, proj_str=None, prj=None, wkt=None, crs=None, xoff=0.0, yoff=0.0, xul=None, yul=None, angrot=0.0)[source]

Bases: StructuredGrid

property bbox

Shapely polygon bounding box of the model grid.

property bounds

Grid bounding box in order used by shapely.

property crs

pyproj.crs.CRS instance describing the coordinate reference system for the model grid.

property dataframe

Pandas DataFrame of grid cell polygons with i, j locations.

get_dataframe(layers=True)[source]

Get a pandas DataFrame of grid cell polygons with i, j locations.

Parameters:
layersbool

If True, return a row for each k, i, j location and a ‘k’ column; if False, only return i, j locations with no ‘k’ column. By default, True

Returns:
layersDataFrame

Pandas Dataframe with k, i, j and geometry column with a shapely polygon representation of each model cell.

get_vertices(i, j)[source]

Get vertices for a single cell or sequence if i, j locations.

property length_multiplier
property length_units
property polygons

Vertices for grid cell polygons.

property rotation
property size
property transform

Rasterio Affine object (same as transform attribute of rasters).

property vertices

Vertices for grid cell polygons.

write_bbox_shapefile(filename='grid_bbox.shp')[source]
write_shapefile(filename='grid.shp')[source]

Write a shapefile of the grid with just the row and column attributes.

property xul
property yul
mfexport.grid.get_crs(crs=None, epsg=None, prj=None, wkt=None, proj_str=None)[source]

Get a pyproj CRS instance from various CRS representations.

mfexport.grid.get_crs_length_units(crs)[source]
mfexport.grid.get_grid_bounding_box(modelgrid)[source]

Get bounding box of potentially rotated modelgrid as a shapely Polygon object.

Parameters:
modelgridflopy.discretization.StructuredGrid instance
mfexport.grid.get_kij_from_node3d(node3d, nrow, ncol)[source]

For a consecutive cell number in row-major order (row, column, layer), get the zero-based row, column position.

mfexport.grid.load_modelgrid(filename)[source]

Create a MFsetupGrid instance from model config json file.

mfexport.grid.write_bbox_shapefile(modelgrid, outshp)[source]

Tabular data export

mfexport.list_export.get_tl_variables(mftransientlist)[source]

Get variable names in a flopy.utils.MFList or flopy.mf6.data.mfdatalist.MFTransientList instance

mfexport.list_export.mftransientlist_to_dataframe(mftransientlist, squeeze=True)[source]

Cast a MFTransientList of stress period data into single dataframe containing all stress periods. Output data are aggregated (summed) to the model cell level, to avoid issues with non-unique row indices.

Parameters:
mftransientlistflopy.mf6.data.mfdatalist.MFTransientList instance
squeezebool

Reduce number of columns in dataframe to only include stress periods where a variable changes.

Returns:
dfdataframe

Dataframe of shape nrow = ncells, ncol = nvar x nper. If the squeeze option is chosen, nper is the number of stress periods where at least one cell is different, otherwise it is equal to the number of keys in MfList.data.

mfexport.list_export.squeeze_columns(df, fillna=0.0)[source]

Drop columns where the forward difference (along axis 1, the column axis) is 0 in all rows. In other words, only retain columns where the data changed in at least one row.

Parameters:
dfDataFrame

Containing homogenous data to be differenced (e.g., just flux values, no id or other ancillary information)

fillnafloat

Value for nan values in DataFrame

Returns
——-
squeezedDataFrame

Listing file

Functions for exporting results from the MODFLOW listing file

mfexport.listfile.get_budget_keys(listfile, key_suffix='BUDGET FOR ENTIRE MODEL')[source]
mfexport.listfile.get_listfile_data(listfile, model_start_datetime=None, budgetkey=None)[source]
mfexport.listfile.get_listfile_model_version(listfile)[source]
mfexport.listfile.plot_budget_summary(df, title_prefix='', title_suffix='', date_index_fmt='%Y-%m', term_nets=False, model_length_units=None, model_time_units=None, secondary_axis_units=None, xtick_stride=6, plot_start_date=None, plot_end_date=None, plot_pcts=False, annual_sums=False, special_column_renames=None)[source]

Plot a stacked bar chart summary of a MODFLOW listing file budget dataframe.

Parameters:
dfDataFrame

Table of listing file budget results produced by flopy; typically the flux (not volume) terms (see example below). The DataFrame needs to have a datetime index.

title_prefixstr, optional

Prefix to insert at the begining of the title, for example the model name. by default ‘’

title_suffixstr, optional

Suffix to insert at the end of the title, by default ‘’

date_index_fmtstr, optional

Date format for the plot x-axis, by default ‘%Y-%m’

term_netsbool, optional

Option to only plot net quantities for each stress period. For example if the inflows and outflows for the WEL package were +10 and -10, a bar of zero height would be plotted. by default False

model_length_unitsstr, optional

Length units of the model, for labeling and conversion to secondary_axis_units, by default None

model_time_unitsstr, optional

Time units of the model, for labeling and conversion to secondary_axis_units, by default None

secondary_axis_unitsstr, optional

Option to include a secondary y-axis on the right with another unit, for example ‘mgal/day’ for million gallons per day. Requires model_length_units and model_time_units. by default None

xtick_strideint, optional

Spacing between x-ticks. May be useful for models with many stress periods. by default 6

plot_start_datestr, optional

Minimum date to plot on the x-axis, in a string format recognizable by pandas (if df has a datetime index) or a numeric value (if df has a numeric index). by default None (plot all dates)

plot_end_datestr, optional

Maximum date to plot on the x-axis, in a string format recognizable by pandas (if df has a datetime index) or a numeric value (if df has a numeric index). by default None (plot all dates)

plot_pctsbool

Option to include the percentage of each flux. by default, False

annual_sumsbool

Option to summarize budget by year (e.g. using pandas.DataFrame.groupby()). Requires that df have a valid datetime index. by default, False

Returns:
axmatplotlib axes subplot instance

Examples

from mfexport.listfile import get_listfile_data, plot_budget_summary
df = get_listfile_data(listfile='model.list', model_start_datetime='2000-01-01')
plot_budget_summary(df)
mfexport.listfile.plot_budget_term(df, term, title_prefix='', title_suffix='', model_length_units=None, model_time_units=None, secondary_axis_units=None, xtick_stride=None, plot_start_date=None, plot_end_date=None, datetime_xaxis=True)[source]

Make a timeseries plot of an individual MODFLOW listing file budget term.

Parameters:
dfDataFrame

Table of listing file budget results produced by flopy; typically the flux (not volume) terms (see example below).

title_prefixstr, optional

Prefix to insert at the begining of the title, for example the model name. by default ‘’

title_suffixstr, optional

Suffix to insert at the end of the title, by default ‘’

model_length_unitsstr, optional

Length units of the model, for labeling and conversion to secondary_axis_units, by default None

model_time_unitsstr, optional

Time units of the model, for labeling and conversion to secondary_axis_units, by default None

secondary_axis_unitsstr, optional

Option to include a secondary y-axis on the right with another unit, for example ‘mgal/day’ for million gallons per day. Requires model_length_units and model_time_units. by default None

xtick_strideint, optional

Spacing between x-ticks. May be useful for models with many stress periods. by default 6

plot_start_datestr, optional

Minimum date to plot on the x-axis, in a string format recognizable by pandas (if df has a datetime index) or a numeric value (if df has a numeric index). May be useful if the model has long spinup period(s) that would obscure later periods of interest when datetime_xaxis=True. by default None (plot all dates)

plot_end_datestr, optional

Maximum date to plot on the x-axis, in a string format recognizable by pandas (if df has a datetime index) or a numeric value (if df has a numeric index). by default None (plot all dates)

datetime_xaxisbool

Plot budget values as a function of time. If False, plot as a function of stress period. by default, True

Returns:
axmatplotlib axes subplot instance

Examples

from mfexport.listfile import get_listfile_data, plot_budget_summary
df = get_listfile_data(listfile='model.list', model_start_datetime='2000-01-01')
plot_budget_term(df, 'WELLS')
mfexport.listfile.plot_list_budget(listfile, model_name=None, model_start_datetime=None, output_path='postproc', model_length_units=None, model_time_units=None, secondary_axis_units=None, xtick_stride=6, plot_start_date=None, plot_end_date=None, plot_pcts=False, datetime_xaxis=True)[source]

Model input

mfexport.inputs.export(model, modelgrid, packages=None, variables=None, output_path='postproc', contours=False, include_inactive_cells=False, gis=True, pdfs=True, **kwargs)[source]
mfexport.inputs.export_sfr(package, modelgrid, gis=True, pdfs=False, shapefile_outfolder='.', pdf_outfolder='.', filenames=None)[source]

Export an SFR package

mfexport.inputs.export_thickness(top_array, botm_array, modelgrid, filenames, rasters_dir, shps_dir, pdfs_dir, gis=True, pdfs=True, contours=True, include_inactive_cells=True, inactive_cells=None, **kwargs)[source]
mfexport.inputs.export_variable(variable, package, modelgrid, inactive_cells, inactive_cells2d, filenames, rasters_dir, shps_dir, pdfs_dir, gis=True, pdfs=True, contours=False, include_inactive_cells=False, **kwargs)[source]
mfexport.inputs.get_inactive_cells_mask(model)[source]
mfexport.inputs.get_package_list(model)[source]
mfexport.inputs.get_variable_list(variables)[source]
mfexport.inputs.summarize(model, packages=None, variables=None, output_path=None, include_inactive_cells=False, verbose=False, **kwargs)[source]
mfexport.inputs.summarize_variable(variable, package, inactive_cells, inactive_cells2d, summarized, include_inactive_cells=False, verbose=False, **kwargs)[source]

PDF export

mfexport.pdf_export.export_pdf(filename, array, text, nodata=None, mfarray_type='array2d', float_fmt='{:.2f}', verbose=False)[source]
mfexport.pdf_export.export_pdf_bar_summary(filename, array, title=None, xlabel='Stress Period', method='mean')[source]
mfexport.pdf_export.sfr_baseflow_pdf(outfile, df, pointsize=0.5, verbose=False)[source]

make a scatter plot of base flow (with point size proportional to Q)

mfexport.pdf_export.sfr_qaquifer_pdf(outfile, df, pointsize=0.5, verbose=False)[source]

make a scatter plot of Qaquifer (with color proportional to flux, scaled to largest gaining flow)

Model results

mfexport.results.export_cell_budget(cell_budget_file, grid, binary_grid_file=None, kstpkper=None, text=None, idx=0, precision='single', output_path='postproc', suffix='')[source]

Read a flow component from MODFLOW binary cell budget output; write to raster.

Parameters:
cell_budget_filemodflow binary cell budget output
gridrOpen.modflow.grid instance
textcell budget record to read (e.g. ‘STREAM LEAKAGE’)
kstpkpertuple

(timestep, stress period) to read

idxindex of list returned by cbbobj (usually 0)
outfolderwhere to write raster
mfexport.results.export_drawdown(heads_file, grid, hdry, hnflo, kstpkper0=None, kstpkper1=None, levels=None, interval=None, export_water_table=True, export_layers=False, output_path='postproc', suffix='')[source]

Export MODFLOW binary head output to rasters and shapefiles.

Parameters:
modelnamestr

model base name

gridrOpen.modflow.grid instance
hdryhdry value from UPW package
hnflohnflo value from BAS package
levels1D numpy array

Values of equal interval contours to write.

shps_outfolderwhere to write shapefiles
rasters_outfolderwhere to write rasters
mfexport.results.export_heads(heads_file, grid, hdry, hnflo, kstpkper=(0, 0), levels=None, interval=None, export_water_table=True, export_depth_to_water=False, export_layers=False, land_surface_elevations=None, output_path='postproc', suffix='')[source]

Export MODFLOW binary head output to rasters and shapefiles.

Parameters:
modelnamestr

model base name

gridrOpen.modflow.grid instance
hdryhdry value from UPW package
hnflohnflo value from BAS package
levels1D numpy array

Values of equal interval contours to write.

shps_outfolderwhere to write shapefiles
rasters_outfolderwhere to write rasters
mfexport.results.export_sfr_results(mf2005_sfr_outputfile=None, mf2005_SfrFile_instance=None, mf6_sfr_stage_file=None, mf6_sfr_budget_file=None, mf6_package_data=None, model=None, model_top=None, grid=None, kstpkper=(0, 0), sfrlinesfile=None, pointsize=0.5, model_length_units=None, model_time_units=None, output_length_units='feet', output_time_units='seconds', gis=True, pdfs=True, output_path='postproc', suffix='', verbose=False)[source]

Shapefile export

mfexport.shapefile_export.export_shapefile(filename, data, modelgrid, kper=None, squeeze=True, epsg=None, proj_str=None, prj=None, verbose=False)[source]

Units conversion

Stuff for handling units

mfexport.units.convert_flux_units(input_length_units, input_time_units, output_length_units, output_time_units)[source]
mfexport.units.convert_length_units(lenuni1, lenuni2)[source]

Convert length units, takes MODFLOW-2005 style lenuni numbers or MF-6 style text.

Parameters:
lenuni1int or str

Convert from.

lenuni2int or str

Convert to.

Returns:
multfloat

Multiplier to convert from lenuni1 to lenuni2.

mfexport.units.convert_temperature_units(input_temp_units, output_temp_units)[source]
mfexport.units.convert_time_units(itmuni1, itmuni2)[source]

Convert time units, takes MODFLOW-2005 style itmuni numbers or MF-6 style text.

Parameters:
itmuni1int or str

Convert from.

itmuni2int or str

Convert to.

Returns:
multfloat

Multiplier to convert from itmuni1 to itmuni2.

mfexport.units.convert_volume_units(input_volume_units, output_volume_units)[source]
mfexport.units.get_figure_label_unit_text(length_unit, time_unit=None, length_unit_exp=None)[source]

Get text abbreviation for common units. Needs to be filled out more.

mfexport.units.get_length_conversions()[source]
mfexport.units.get_length_units(model)[source]

Return length units for model as text.

mfexport.units.get_time_units(model)[source]

Return time units for model as text.

mfexport.units.get_unit_text(length_unit, time_unit, length_unit_exp)[source]

Get text abbreviation for common units. Needs to be filled out more.

mfexport.units.get_volume_conversions()[source]
mfexport.units.parse_flux_units(text)[source]
mfexport.units.parse_length_units(text, text_output=True)[source]

Utility functions

mfexport.utils.get_flopy_package_fname(package)[source]
mfexport.utils.get_input_arguments(kwargs, function, warn=True)[source]

Return subset of keyword arguments in kwargs dict that are valid parameters to a function or method.

Parameters:
kwargsdict (parameter names, values)
functionfunction of class method
Returns:
input_kwargsdict
mfexport.utils.get_water_table(heads, nodata, valid_min=-0.0001, valid_max=30000.0)[source]

Get a 2D array representing the water table elevation for each stress period in heads array.

Parameters:
heads3 or 4-D np.ndarray

Heads array.

nodatareal

HDRY value indicating dry cells.

valid_minfloat (optional)

The lowest value regarded as valid, regardless of nodata value. By default, -1e4

valid_maxfloat (optional)

The highest value regarded as valid, regardless of nodata value. By default, 3e4

Returns:
wt2 or 3-D np.ndarray of water table elevations

for each stress period.

mfexport.utils.load(filename)[source]

Load a configuration file.

mfexport.utils.load_json(jsonfile)[source]

Convenience function to load a json file; replacing some escaped characters.

mfexport.utils.load_yaml(yml_file)[source]

Load yaml file into a dictionary.

mfexport.utils.make_output_folders(output_path='postproc')[source]
mfexport.utils.print_item(k, v)[source]

Zone budget

Functions for working with zone budget.

mfexport.zbud.write_zonebudget6_input(zones, budgetfile, binary_grid_file=None, zone_arrays_subfolder='external', outname=None)[source]