flopy.utils.binaryfile module

Module to read MODFLOW binary output files. The module contains four important classes that can be accessed by the user.

  • HeadFile (Binary head file. Can also be used for drawdown)

  • HeadUFile (Binary MODFLOW-USG unstructured head file)

  • UcnFile (Binary concentration file from MT3DMS)

  • CellBudgetFile (Binary cell-by-cell flow file)

class BinaryHeader(bintype=None, precision='single')[source]

Bases: Header

Represents data headers for binary output files.

Parameters:
  • bintype (str) – Type of file being opened. Accepted values are ‘head’ and ‘ucn’.

  • precision (str) – Precision of floating point data in the file.

static create(bintype=None, precision='single', **kwargs)[source]

Create a binary header

static set_dtype(bintype=None, precision='single')[source]

Set the dtype

set_values(**kwargs)[source]

Set values using kwargs

class BinaryLayerFile(filename: str | PathLike, precision, verbose, kwargs)[source]

Bases: LayerFile

The BinaryLayerFile class is a parent class from which concrete classes inherit. This class should not be instantiated directly.

Notes

The BinaryLayerFile class is built on a record array consisting of headers, which are record arrays of the modflow header information (kstp, kper, pertim, totim, text, nrow, ncol, ilay), and long ints pointing to the 1st byte of data for the corresponding data arrays.

get_databytes(header)[source]
Parameters:

header (datafile.Header) – header object

Returns:

databytes – size of the data array, in bytes, following the header

Return type:

int

get_ts(idx)[source]

Get a time series from the binary file.

Parameters:

idx (tuple of ints, or a list of a tuple of ints) – idx can be (layer, row, column) or it can be a list in the form [(layer, row, column), (layer, row, column), …]. The layer, row, and column values must be zero based.

Returns:

out – Array has size (ntimes, ncells + 1). The first column in the data array will contain time (totim).

Return type:

numpy array

Notes

The layer, row, and column values must be zero-based, and must be within the following ranges: 0 <= k < nlay; 0 <= i < nrow; 0 <= j < ncol

Examples

exception BudgetIndexError[source]

Bases: Exception

class CellBudgetFile(filename: str | PathLike, precision='auto', verbose=False, **kwargs)[source]

Bases: object

The CellBudgetFile class provides convenient ways to retrieve and manipulate budget data from a binary cell budget file. A utility method is also provided to reverse the budget records for particle tracking simulations in which particles are tracked backwards from terminating to release locations (e.g., to compute capture zones).

Parameters:
  • filename (str or PathLike) – Path of the cell budget file.

  • precision (string) – Precision of floating point budget data in the file. Accepted values are ‘single’ or ‘double’. Default is ‘single’.

  • verbose (bool) – Toggle logging output. Default is False.

Examples

>>> import flopy.utils.binaryfile as bf
>>> cbb = bf.CellBudgetFile('mymodel.cbb')
>>> cbb.list_records()
>>> rec = cbb.get_data(kstpkper=(0,0), text='RIVER LEAKAGE')
close()[source]

Close the file handle

get_data(idx=None, kstpkper=None, totim=None, text=None, paknam=None, paknam2=None, full3D=False) List | ndarray[source]

Get data from the binary budget file.

Parameters:
  • idx (int or list) – The zero-based record number. The first record is record 0.

  • kstpkper (tuple of ints) – A tuple containing the time step and stress period (kstp, kper). The kstp and kper values are zero based.

  • totim (float) – The simulation time.

  • text (str) – The text identifier for the record. Examples include ‘RIVER LEAKAGE’, ‘STORAGE’, ‘FLOW RIGHT FACE’, etc.

  • paknam (str) – The from package name for the record.

  • paknam2 (str) – The to package name for the record. This argument can be useful for MODFLOW 6 budget files if multiple packages of the same type are specified. The paknam2 argument can be specified as the package name (not the package type) in order to retrieve budget data for a specific named package.

  • full3D (boolean) – If true, then return the record as a three dimensional numpy array, even for those list-style records written as part of a ‘COMPACT BUDGET’ MODFLOW budget file. (Default is False.)

Returns:

recordlist – A list of budget objects. The structure of the returned object depends on the structure of the data in the cbb file.

If full3D is True, then this method will return a numpy masked array of size (nlay, nrow, ncol) for those list-style ‘COMPACT BUDGET’ records written by MODFLOW.

Return type:

list of records

Notes

Examples

get_indices(text=None)[source]

Get a list of indices for a selected record name

Parameters:

text (str) – The text identifier for the record. Examples include ‘RIVER LEAKAGE’, ‘STORAGE’, ‘FLOW RIGHT FACE’, etc.

Returns:

out – indices of selected record name in budget file.

Return type:

tuple

get_kstpkper()[source]

Get a list of unique tuples (stress period, time step) in the file. Indices are 0-based, use the kstpkper attribute for 1-based.

Returns:

List of unique combinations of stress period & time step indices (0-based) in the binary file

Return type:

list of (kstp, kper) tuples

get_nrecords()[source]

Return the number of records in the file

Returns:

out – Number of records in the file.

Return type:

int

get_position(idx, header=False)[source]

Get the starting position of the data or header for a specified record number in the binary budget file.

Parameters:
  • idx (int) – The zero-based record number. The first record is record 0.

  • header (bool) – If True, the position of the start of the header data is returned. If False, the position of the start of the data is returned (default is False).

Returns:

ipos – The position of the start of the data in the cell budget file or the start of the header.

Return type:

int64

get_record(idx, full3D=False)[source]

Get a single data record from the budget file.

Parameters:
  • idx (int) – The zero-based record number. The first record is record 0.

  • full3D (boolean) – If true, then return the record as a three dimensional numpy array, even for those list-style records written as part of a ‘COMPACT BUDGET’ MODFLOW budget file. (Default is False.)

Returns:

record – The structure of the returned object depends on the structure of the data in the cbb file. Compact list data are returned as

If full3D is True, then this method will return a numpy masked array of size (nlay, nrow, ncol) for those list-style ‘COMPACT BUDGET’ records written by MODFLOW.

Return type:

a single data record

Notes

Examples

get_residual(totim, scaled=False)[source]

Return an array the size of the model grid containing the flow residual calculated from the budget terms. Residual will not be correct unless all flow terms are written to the budget file.

Parameters:
  • totim (float) – Simulation time for which to calculate the residual. This value must be precise, so it is best to get it from the get_times method.

  • scaled (bool) – If True, then divide the residual by the total cell inflow

Returns:

residual – The flow residual for the cell of shape (nlay, nrow, ncol)

Return type:

np.ndarray

get_times()[source]

Get a list of unique times in the file

Returns:

out – List contains unique simulation times (totim) in binary file.

Return type:

list of floats

get_ts(idx, text=None, times=None)[source]

Get a time series from the binary budget file.

Parameters:
  • idx (tuple of ints, or a list of a tuple of ints) – idx can be (layer, row, column) or it can be a list in the form [(layer, row, column), (layer, row, column), …]. The layer, row, and column values must be zero based.

  • text (str) – The text identifier for the record. Examples include ‘RIVER LEAKAGE’, ‘STORAGE’, ‘FLOW RIGHT FACE’, etc.

  • times (iterable of floats) – List of times to from which to get time series.

Returns:

out – Array has size (ntimes, ncells + 1). The first column in the data array will contain time (totim).

Return type:

numpy array

Notes

The layer, row, and column values must be zero-based, and must be within the following ranges: 0 <= k < nlay; 0 <= i < nrow; 0 <= j < ncol

Examples

get_unique_package_names(decode=False, to=False)[source]

Get a list of unique package names in the file

Parameters:

decode (bool) – Optional boolean used to decode byte strings (default is False).

Returns:

names – List of unique package names in the binary file.

Return type:

list of strings

get_unique_record_names(decode=False)[source]

Get a list of unique record names in the file

Parameters:

decode (bool) – Optional boolean used to decode byte strings (default is False).

Returns:

names – List of unique text names in the binary file.

Return type:

list of strings

list_records()[source]

Print a list of all of the records in the file

list_unique_packages(to=False)[source]

Print a list of unique package names

list_unique_records()[source]

Print a list of unique record names

reverse(filename: PathLike | None = None)[source]

Write a binary cell budget file with the records in reverse order. If a new filename is not provided, or if the filename is the same as the existing filename, the file will be overwritten and data reloaded from the rewritten/reversed file.

Parameters:

filename (str or PathLike, optional) – Path of the new reversed binary cell budget file to create.

class HeadFile(filename: str | PathLike, text='head', precision='auto', verbose=False, **kwargs)[source]

Bases: BinaryLayerFile

The HeadFile class provides simple ways to retrieve and manipulate 2D or 3D head arrays, or time series arrays for one or more cells, from a binary head output file. A utility method is also provided to reverse the order of head data, for use with particle tracking simulations in which particles are tracked backwards in time from terminating to release locations (e.g., to compute capture zones).

Parameters:
  • filename (str or PathLike) – Path of the head file.

  • text (string) – Name of the text string in the head file. Default is ‘head’.

  • precision (string) – Precision of floating point head data in the value. Accepted values are ‘auto’, ‘single’ or ‘double’. Default is ‘auto’, which enables automatic detection of precision.

  • verbose (bool) – Toggle logging output. Default is False.

Examples

>>> import flopy.utils.binaryfile as bf
>>> hdobj = bf.HeadFile('model.hds', precision='single')
>>> hdobj.list_records()
>>> rec = hdobj.get_data(kstpkper=(0, 49))
>>> ddnobj = bf.HeadFile('model.ddn', text='drawdown', precision='single')
>>> ddnobj.list_records()
>>> rec = ddnobj.get_data(totim=100.)
reverse(filename: PathLike | None = None)[source]

Write a new binary head file with the records in reverse order. If a new filename is not provided, or if the filename is the same as the existing filename, the file will be overwritten and data reloaded from the rewritten/reversed file.

Parameters:

filename (str or PathLike) – Path of the new reversed binary file to create.

class HeadUFile(filename: str | PathLike, text='headu', precision='auto', verbose=False, **kwargs)[source]

Bases: BinaryLayerFile

The HeadUFile class provides simple ways to retrieve a list of head arrays from a MODFLOW-USG binary head file and time series arrays for one or more cells.

Parameters:
  • filename (str or PathLike) – Path of the head file

  • text (string) – Name of the text string in the head file. Default is ‘headu’.

  • precision (string) – Precision of the floating point head data in the file. Accepted values are ‘auto’, ‘single’ or ‘double’. Default is ‘auto’, which enables precision to be automatically detected.

  • verbose (bool) – Toggle logging output. Default is False.

Notes

The BinaryLayerFile class is built on a record array consisting of headers, which are record arrays of the modflow header information (kstp, kper, pertim, totim, text, nrow, ncol, ilay), and long ints pointing to the 1st byte of data for the corresponding data arrays. This class overrides methods in the parent class so that the proper sized arrays are created: for unstructured grids, nrow and ncol are the starting and ending node numbers for layer, ilay.

When the get_data method is called for this class, a list of one-dimensional arrays will be returned, where each array is the head array for a layer. If the heads for a layer were not saved, then None will be returned for that layer.

Examples

>>> import flopy.utils.binaryfile as bf
>>> hdobj = bf.HeadUFile('model.hds')
>>> hdobj.list_records()
>>> usgheads = hdobj.get_data(kstpkper=(0, 49))
get_databytes(header)[source]
Parameters:

header (datafile.Header) – header object

Returns:

databytes – size of the data array, in bytes, following the header

Return type:

int

get_ts(idx)[source]

Get a time series from the binary HeadUFile

Parameters:

idx (int or list of ints) – idx can be nodenumber or it can be a list in the form [nodenumber, nodenumber, …]. The nodenumber, values must be zero based.

Returns:

out – Array has size (ntimes, ncells + 1). The first column in the data array will contain time (totim).

Return type:

numpy array

class UcnFile(filename, text='concentration', precision='auto', verbose=False, **kwargs)[source]

Bases: BinaryLayerFile

UcnFile Class.

Parameters:
  • filename (string) – Name of the concentration file

  • text (string) – Name of the text string in the ucn file. Default is ‘CONCENTRATION’

  • precision (string) – ‘auto’, ‘single’ or ‘double’. Default is ‘auto’.

  • verbose (bool) – Write information to the screen. Default is False.

Notes

The UcnFile class provides simple ways to retrieve 2d and 3d concentration arrays from a MT3D binary head file and time series arrays for one or more cells.

The BinaryLayerFile class is built on a record array consisting of headers, which are record arrays of the modflow header information (kstp, kper, pertim, totim, text, nrow, ncol, ilay) and long integers, which are pointers to first bytes of data for the corresponding data array.

Examples

>>> import flopy.utils.binaryfile as bf
>>> ucnobj = bf.UcnFile('MT3D001.UCN', precision='single')
>>> ucnobj.list_records()
>>> rec = ucnobj.get_data(kstpkper=(0, 0))
binaryread(file, vartype, shape=(1,), charlen=16)[source]
Uses numpy to read from binary file. This was found to be faster than the

struct approach and is used as the default.

binaryread_struct(file, vartype, shape=(1,), charlen=16)[source]

Read text, a scalar value, or an array of values from a binary file.

filefile object

is an open file object

vartypetype

is the return variable type: str, numpy.int32, numpy.float32, or numpy.float64

shapetuple

is the shape of the returned array (shape(1, ) returns a single value) for example, shape = (nlay, nrow, ncol)

charlenint

is the length of the text string. Note that string arrays cannot be returned, only multi-character strings. Shape has no affect on strings.

get_headfile_precision(filename: str | PathLike)[source]

Determine precision of a MODFLOW head file.

Parameters:
  • filename (str or PathLike) –

  • precision. (Path of binary MODFLOW file to determine) –

Returns:

  • result (str)

  • Result will be unknown, single, or double

join_struct_arrays(arrays)[source]

Simple function that can join two numpy structured arrays.

write_budget(fbin, data, kstp=1, kper=1, text='    FLOW-JA-FACE', imeth=1, delt=1.0, pertim=1.0, totim=1.0, text1id1='           GWF-1', text2id1='           GWF-1', text1id2='           GWF-1', text2id2='             NPF')[source]
write_head(fbin, data, kstp=1, kper=1, pertim=1.0, totim=1.0, text='            HEAD', ilay=1)[source]