flopy.utils.reference module

Module spatial referencing for flopy model objects

class SpatialReference(delr=array([], dtype=float64), delc=array([], dtype=float64), lenuni=2, xul=None, yul=None, xll=None, yll=None, rotation=0.0, proj4_str=None, epsg=None, prj=None, units=None, length_multiplier=None)[source]

Bases: object

a class to locate a structured model grid in x-y space

Parameters:
  • delr (numpy ndarray) – the model discretization delr vector (An array of spacings along a row)
  • delc (numpy ndarray) – the model discretization delc vector (An array of spacings along a column)
  • lenuni (int) – the length units flag from the discretization package (default 2)
  • xul (float) – the x coordinate of the upper left corner of the grid Enter either xul and yul or xll and yll.
  • yul (float) – the y coordinate of the upper left corner of the grid Enter either xul and yul or xll and yll.
  • xll (float) – the x coordinate of the lower left corner of the grid Enter either xul and yul or xll and yll.
  • yll (float) – the y coordinate of the lower left corner of the grid Enter either xul and yul or xll and yll.
  • rotation (float) – the counter-clockwise rotation (in degrees) of the grid
  • proj4_str (str) – a PROJ4 string that identifies the grid in space. warning: case sensitive!
  • units (string) – Units for the grid. Must be either feet or meters
  • epsg (int) – EPSG code that identifies the grid in space. Can be used in lieu of proj4. PROJ4 attribute will auto-populate if there is an internet connection(via get_proj4 method). See https://www.epsg-registry.org/ or spatialreference.org
  • length_multiplier (float) – multiplier to convert model units to spatial reference units. delr and delc above will be multiplied by this value. (default=1.)
xedge

array of column edges

Type:ndarray
yedge

array of row edges

Type:ndarray
xgrid

numpy meshgrid of xedges

Type:ndarray
ygrid

numpy meshgrid of yedges

Type:ndarray
xcenter

array of column centers

Type:ndarray
ycenter

array of row centers

Type:ndarray
xcentergrid

numpy meshgrid of column centers

Type:ndarray
ycentergrid

numpy meshgrid of row centers

Type:ndarray
vertices

1D array of cell vertices for whole grid in C-style (row-major) order (same as np.ravel())

Type:1D array

Notes

xul and yul can be explicitly (re)set after SpatialReference instantiation, but only before any of the other attributes and methods are accessed

static attribs_from_namfile_header(namefile)[source]
attribute_dict
bounds

Return bounding box in shapely order.

contour_array(ax, a, **kwargs)[source]

Create a QuadMesh plot of the specified array using pcolormesh

Parameters:
  • ax (matplotlib.axes.Axes) – ax to add the contours
  • a (np.ndarray) – array to contour
Returns:

contour_set

Return type:

ContourSet

defaults = {'length_multiplier': None, 'lenuni': 2, 'proj4_str': None, 'rotation': 0.0, 'source': 'defaults', 'units': None, 'xul': None, 'yul': None}
epsg
export_array(filename, a, nodata=-9999, fieldname='value', **kwargs)[source]

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

Parameters:
  • filename (str) – Path of output file. Export format is determined by file extension. ‘.asc’ Arc Ascii grid ‘.tif’ GeoTIFF (requires rasterio package) ‘.shp’ Shapefile
  • a (2D numpy.ndarray) – Array to export
  • nodata (scalar) – Value to assign to np.nan entries (default -9999)
  • fieldname (str) – 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.

export_array_contours(filename, a, fieldname='level', interval=None, levels=None, maxlevels=1000, epsg=None, prj=None, **kwargs)[source]

Contour an array using matplotlib; write shapefile of contours.

Parameters:
  • filename (str) – Path of output file with ‘.shp’ extension.
  • a (2D numpy array) – Array to contour
  • epsg (int) – EPSG code. See https://www.epsg-registry.org/ or spatialreference.org
  • prj (str) – Existing projection file to be used with new shapefile.
  • **kwargs (key-word arguments to flopy.export.shapefile_utils.recarray2shp) –
export_contours(filename, contours, fieldname='level', epsg=None, prj=None, **kwargs)[source]

Convert matplotlib contour plot object to shapefile.

Parameters:
  • filename (str) – path of output shapefile
  • contours (matplotlib.contour.QuadContourSet or list of them) – (object returned by matplotlib.pyplot.contour)
  • epsg (int) – EPSG code. See https://www.epsg-registry.org/ or spatialreference.org
  • prj (str) – Existing projection file to be used with new shapefile.
  • **kwargs (key-word arguments to flopy.export.shapefile_utils.recarray2shp) –
Returns:

df

Return type:

dataframe of shapefile contents

classmethod from_gridspec(gridspec_file, lenuni=0)[source]
classmethod from_namfile(namefile)[source]
get_2d_vertex_connectivity()[source]

Create the cell 2d vertices array and the iverts index array. These are the same form as the ones used to instantiate an unstructured spatial reference.

Returns:
  • verts (ndarray) – array of x and y coordinates for the grid vertices
  • iverts (list) – a list with a list of vertex indices for each cell in clockwise order starting with the upper left corner
get_3d_shared_vertex_connectivity(nlay, botm, ibound=None)[source]
get_3d_vertex_connectivity(nlay, top, bot, ibound=None)[source]
get_extent()[source]

Get the extent of the rotated and offset grid

Return (xmin, xmax, ymin, ymax)

get_grid_line_collection(**kwargs)[source]

Get a LineCollection of the grid

get_grid_lines()[source]

Get the grid lines as a list

get_grid_map_plotter(**kwargs)[source]

Create a QuadMesh plotting object for this grid

Returns:quadmesh
Return type:matplotlib.collections.QuadMesh
get_ij(x, y)[source]

Return the row and column of a point or sequence of points in real-world coordinates.

Parameters:
  • x (scalar or sequence of x coordinates) –
  • y (scalar or sequence of y coordinates) –
Returns:

  • i (row or sequence of rows (zero-based))
  • j (column or sequence of columns (zero-based))

get_rc(x, y)[source]
get_vertices(i, j)[source]

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

get_xcenter_array()[source]

Return a numpy one-dimensional float array that has the cell center x coordinate for every column in the grid in model space - not offset or rotated.

get_xedge_array()[source]

Return a numpy one-dimensional float array that has the cell edge x coordinates for every column in the grid in model space - not offset or rotated. Array is of size (ncol + 1)

get_ycenter_array()[source]

Return a numpy one-dimensional float array that has the cell center x coordinate for every row in the grid in model space - not offset of rotated.

get_yedge_array()[source]

Return a numpy one-dimensional float array that has the cell edge y coordinates for every row in the grid in model space - not offset or rotated. Array is of size (nrow + 1)

interpolate(a, xi, method='nearest')[source]

Use the griddata method to interpolate values from an array onto the points defined in xi. For any values outside of the grid, use ‘nearest’ to find a value for them.

Parameters:
  • a (numpy.ndarray) – array to interpolate from. It must be of size nrow, ncol
  • xi (numpy.ndarray) – array containing x and y point coordinates of size (npts, 2). xi also works with broadcasting so that if a is a 2d array, then xi can be passed in as (xgrid, ygrid).
  • method ({'linear', 'nearest', 'cubic'}) – method to use for interpolation (default is ‘nearest’)
Returns:

b – array of size (npts)

Return type:

numpy.ndarray

length_multiplier

Attempt to identify multiplier for converting from model units to sr units, defaulting to 1.

lenuni
lenuni_text = {0: 'undefined', 1: 'feet', 2: 'meters', 3: 'centimeters'}
lenuni_values = {'centimeters': 3, 'feet': 1, 'meters': 2, 'undefined': 0}
classmethod load(namefile=None, reffile='usgs.model.reference')[source]

Attempts to load spatial reference information from the following files (in order): 1) usgs.model.reference 2) NAM file (header comment) 3) SpatialReference.default dictionary

model_length_units
ncol
nrow
origin_loc = 'ul'
plot_array(a, ax=None, **kwargs)[source]

Create a QuadMesh plot of the specified array using pcolormesh

Parameters:a (np.ndarray) –
Returns:quadmesh
Return type:matplotlib.collections.QuadMesh
proj4_str
static read_usgs_model_reference_file(reffile='usgs.model.reference')[source]

read spatial reference info from the usgs.model.reference file https://water.usgs.gov/ogw/policy/gw-model/modelers-setup.html

reset(**kwargs)[source]
static rotate(x, y, theta, xorigin=0.0, yorigin=0.0)[source]

Given x and y array-like values calculate the rotation about an arbitrary origin and then return the rotated coordinates. theta is in degrees.

rotation = 0.0
set_origin(xul=None, yul=None, xll=None, yll=None)[source]
set_spatialreference(xul=None, yul=None, xll=None, yll=None, rotation=0.0)[source]

set spatial reference - can be called from model instance

theta
transform(x, y, inverse=False)[source]

Given x and y array-like values, apply rotation, scale and offset, to convert them from model coordinates to real-world coordinates.

units
vertices

Returns a list of vertices for

wkt
write_gridSpec(filename)[source]

write a PEST-style grid specification file

write_shapefile(filename='grid.shp', epsg=None, prj=None)[source]

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

xcenter
xcentergrid
xedge
xgrid
xll
xul
ycenter
ycentergrid
yedge
ygrid
yll
yul
class SpatialReferenceUnstructured(xc, yc, verts, iverts, ncpl, layered=True, lenuni=1, proj4_str=None, epsg=None, units=None, length_multiplier=1.0)[source]

Bases: flopy.utils.reference.SpatialReference

a class to locate an unstructured model grid in x-y space

Parameters:
  • verts (ndarray) – 2d array of x and y points.
  • iverts (list of lists) – should be of len(ncells) with a list of vertex numbers for each cell
  • ncpl (ndarray) – array containing the number of cells per layer. ncpl.sum() must be equal to the total number of cells in the grid.
  • layered (boolean) – flag to indicated that the grid is layered. In this case, the vertices define the grid for single layer, and all layers use this same grid. In this case the ncpl value for each layer must equal len(iverts). If not layered, then verts and iverts are specified for all cells and all layers in the grid. In this case, npcl.sum() must equal len(iverts).
  • lenuni (int) – the length units flag from the discretization package
  • proj4_str (str) – a PROJ4 string that identifies the grid in space. warning: case sensitive!
  • units (string) – Units for the grid. Must be either feet or meters
  • epsg (int) – EPSG code that identifies the grid in space. Can be used in lieu of proj4. PROJ4 attribute will auto-populate if there is an internet connection(via get_proj4 method). See https://www.epsg-registry.org/ or spatialreference.org
  • length_multiplier (float) – multiplier to convert model units to spatial reference units. delr and delc above will be multiplied by this value. (default=1.)
xcenter

array of x cell centers

Type:ndarray
ycenter

array of y cell centers

Type:ndarray

Notes

contour_array(ax, a, **kwargs)[source]

Create a QuadMesh plot of the specified array using pcolormesh

Parameters:
  • ax (matplotlib.axes.Axes) – ax to add the contours
  • a (np.ndarray) – array to contour
Returns:

contour_set

Return type:

ContourSet

classmethod from_argus_export(fname, nlay=1)[source]

Create a new SpatialReferenceUnstructured grid from an Argus One Trimesh file

Parameters:
  • fname (string) – File name
  • nlay (int) – Number of layers to create
Returns:

sru

Return type:

flopy.utils.reference.SpatialReferenceUnstructured

classmethod from_gridspec(fname)[source]

Create a new SpatialReferenceUnstructured grid from an PEST grid specification file

Parameters:fname (string) – File name for grid specification file
Returns:sru
Return type:flopy.utils.reference.SpatialReferenceUnstructured
get_extent()[source]

Get the extent of the grid

Returns:extent – min and max grid coordinates
Return type:tuple
get_grid_line_collection(**kwargs)[source]

Get a patch collection of the grid

get_xcenter_array()[source]

Return a numpy one-dimensional float array that has the cell center x coordinate for every cell in the grid in model space - not offset or rotated.

get_ycenter_array()[source]

Return a numpy one-dimensional float array that has the cell center x coordinate for every cell in the grid in model space - not offset of rotated.

grid_type
plot_array(a, ax=None)[source]

Create a QuadMesh plot of the specified array using patches

Parameters:a (np.ndarray) –
Returns:quadmesh
Return type:matplotlib.collections.QuadMesh
write_gridSpec(filename)[source]

Write a PEST-style grid specification file

Parameters:filename (string) – filename for grid specification file
write_shapefile(filename='grid.shp')[source]

Write shapefile of the grid

Parameters:filename (string) – filename for shapefile
class TemporalReference(itmuni=4, start_datetime=None)[source]

Bases: object

For now, just a container to hold start time and time units files outside of DIS package.

defaults = {'itmuni': 4, 'start_datetime': '01-01-1970'}
itmuni_text = {0: 'undefined', 1: 'seconds', 2: 'minutes', 3: 'hours', 4: 'days', 5: 'years'}
itmuni_values = {'days': 4, 'hours': 3, 'minutes': 2, 'seconds': 1, 'undefined': 0, 'years': 5}
model_time_units
class crs(prj=None, esri_wkt=None, epsg=None)[source]

Bases: object

Container to parse and store coordinate reference system parameters, and translate between different formats.

crs

Dict mapping crs attributes to proj4 parameters

grid_mapping_attribs

Map parameters for CF Grid Mappings http://http://cfconventions.org/cf-conventions/cf-conventions.html, Appendix F: Grid Mappings

parse_wkt()[source]
proj4

Not implemented yet

class epsgRef[source]

Bases: object

Sets up a local database of text representations of coordinate reference systems, keyed by EPSG code.

The database is epsgref.json, located in the user’s data directory. If optional ‘appdirs’ package is available, this is in the platform-dependent user directory, otherwise in the user’s ‘HOME/.flopy’ directory.

add(epsg, prj)[source]

add an epsg code to epsgref.json

get(epsg)[source]

returns prj from a epsg code, otherwise None if not found

remove(epsg)[source]

removes an epsg entry from epsgref.json

reset(verbose=True)[source]
static show()[source]
to_dict()[source]

Returns dict with EPSG code integer key, and WKT CRS text

get_spatialreference(epsg, text='esriwkt')[source]

Gets text for given epsg code and text format from spatialreference.org

Fetches the reference text using the url:
https://spatialreference.org/ref/epsg/<epsg code>/<text>/

See: https://www.epsg-registry.org/

Parameters:
  • epsg (int) – epsg code for coordinate system
  • text (str) – string added to url
Returns:

url

Return type:

str

getprj(epsg, addlocalreference=True, text='esriwkt')[source]

Gets projection file (.prj) text for given epsg code from spatialreference.org

Parameters:
  • epsg (int) – epsg code for coordinate system
  • addlocalreference (boolean) – adds the projection file text associated with epsg to a local database, epsgref.json, located in the user’s data directory.

References

https://www.epsg-registry.org/

Returns:prj – text for a projection (*.prj) file.
Return type:str
getproj4(epsg)[source]

Get projection file (.prj) text for given epsg code from spatialreference.org. See: https://www.epsg-registry.org/

Parameters:epsg (int) – epsg code for coordinate system
Returns:prj – text for a projection (*.prj) file.
Return type:str