landlab

Base Class (ModelGrid)

General class methods and attributes of the landlab.grid.base module

Python implementation of ModelGrid, a base class used to create and manage grids for 2D numerical models.

Do NOT add new documentation here. Grid documentation is now built in a semi- automated fashion. To modify the text seen on the web, edit the files docs/text_for_[gridfile].py.txt.

Indicates a link is active, and can carry flux

BAD_INDEX_VALUE = -1

Indicates an index is, in some way, bad.

CLOSED_BOUNDARY = 4

Indicates a boundary node is closed

CORE_NODE = 0

Indicates a node is core.

FIXED_GRADIENT_BOUNDARY = 2

Indicates a boundary node is has a fixed gradient.

Indicates a link has a fixed (gradient) value, & behaves as a boundary

FIXED_VALUE_BOUNDARY = 1

Indicates a boundary node is has a fixed values.

Indicates a link is inactive, and cannot carry flux

LOOPED_BOUNDARY = 3

Indicates a boundary node is wrap-around.

class ModelGrid(**kwds)[source]

Bases: landlab.field.field_mixin.ModelDataFieldsMixIn

Base class for 2D structured or unstructured grids for numerical models.

The idea is to have at least two inherited classes, RasterModelGrid and DelaunayModelGrid, that can create and manage grids. To this might be added a GenericModelGrid, which would be an unstructured polygonal grid that doesn’t necessarily obey or understand the Delaunay triangulation, but rather simply accepts an input grid from the user. Also a HexModelGrid for hexagonal.

Attributes

axis_name Get the name of each coordinate axis.
axis_units Get units for each axis.
at_node (dict-like) Values at nodes.
at_cell (dict-like) Values at cells.
at_link (dict-like) Values at links.
at_face (dict-like) Values at faces.
at_grid: dict-like Global values
Other Parameters  
   
active_faces

Get array of active faces.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.active_faces
array([0, 1, 2, 3, 4, 5, 6])
>>> from landlab import CLOSED_BOUNDARY
>>> grid.status_at_node[6] = CLOSED_BOUNDARY
>>> grid.active_faces
array([0, 2, 5])

LLCATS: FINF BC

Get the active link that connects a pair of nodes.

Note

This method is deprecated as of Landlab version 1.0.

Use no replacement() instead.

Returns the ID number of the active link that connects the given pair of nodes, or BAD_INDEX_VALUE if not found. This method is slow, and can only take single ints as node1 and node2. It should ideally be overridden for optimal functionality in more specialized grid modules (e.g., raster).

Examples

>>> import landlab as ll
>>> rmg = ll.RasterModelGrid((4, 5))
>>> rmg.active_link_connecting_node_pair(8, 3)
array([2])

LLCATS: DEPR LINF NINF CONN

Link flux directions at each node: 1=incoming flux, -1=outgoing flux, 0=no flux. Note that inactive links receive zero, but active and fixed links are both reported normally.

Returns:

(NODES, LINKS) ndarray of int

Link directions relative to the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. A zero indicates no link at this position.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> grid = RasterModelGrid((4, 3))
>>> grid.status_at_node[grid.nodes_at_left_edge] = CLOSED_BOUNDARY
>>> grid.active_link_dirs_at_node 
array([[ 0,  0,  0,  0], [ 0, -1,  0,  0], [ 0,  0,  0,  0],
       [ 0,  0,  0,  0], [-1, -1,  0,  1], [ 0,  0,  1,  0],
       [ 0,  0,  0,  0], [-1, -1,  0,  1], [ 0,  0,  1,  0],
       [ 0,  0,  0,  0], [ 0,  0,  0,  1], [ 0,  0,  0,  0]],
       dtype=int8)

LLCATS: NINF LINF CONN

Get array of active links.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.active_links
array([ 4,  5,  7,  8,  9, 11, 12])

LLCATS: LINF BC

active_neighbors_at_node

Get list of neighbor node IDs.

Return lists of neighbor nodes, where the neighbor is connected by an active link. For each node, the list gives neighbor ids as [right, top, left, bottom]. Nodes at the end of inactive links or nodes in missing positions get BAD_INDEX_VALUE.

Examples

>>> from landlab.grid.base import BAD_INDEX_VALUE as X
>>> from landlab import RasterModelGrid, HexModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((4, 5))
>>> np.array_equal(rmg.active_neighbors_at_node[[-1, 6, 2]],
...     [[X, X, X, X], [ 7, 11,  5,  1], [X,  7,  X, X]])
True
>>> rmg.active_neighbors_at_node[7]
array([ 8, 12,  6,  2])
>>> rmg.active_neighbors_at_node[2]
array([-1,  7, -1, -1])
>>> hmg = HexModelGrid(3, 2)
>>> hmg.status_at_node[0] = CLOSED_BOUNDARY
>>> hmg.active_neighbors_at_node
array([[-1, -1, -1, -1, -1, -1],
       [-1,  3, -1, -1, -1, -1],
       [ 3, -1, -1, -1, -1, -1],
       [ 4,  6,  5,  2, -1,  1],
       [-1,  3, -1, -1, -1, -1],
       [-1, -1,  3, -1, -1, -1],
       [-1,  3, -1, -1, -1, -1]])

LLCATS: NINF CONN BC

all_node_azimuths_map

Get azimuths from every node to every other node.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> angles = grid.all_node_azimuths_map

The shape of the array is number_of_nodes by number_of_nodes and azimuth from a node to itself is zero.

>>> angles.shape == (grid.number_of_nodes, grid.number_of_nodes)
True
>>> angles.diagonal()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

Angles are measured in radians and increase clockwise starting at north.

>>> angles *= 180. / np.pi
>>> angles[0, :4]
array([  0.,  90.,  90.,  90.])
>>> angles[0, ::4]
array([ 0.,  0.,  0.])
>>> angles[0, ::5]
array([  0.,  45.,  45.])

LLCATS: NINF MEAS

all_node_distances_map

Get distances from every node to every other node.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> distances = grid.all_node_distances_map

The shape of the array is number_of_nodes by number_of_nodes and distance from a node to itself is zero.

>>> distances.shape == (grid.number_of_nodes, grid.number_of_nodes)
True
>>> distances.diagonal()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

The distances from the first node to all nodes in its row and all the nodes in its column.

>>> distances[0, :4]
array([ 0.,  1.,  2.,  3.])
>>> distances[0, ::4]
array([ 0.,  1.,  2.])

LLCATS: NINF MEAS

Find and return the angle of a link about the node at the link tail.

Examples

>>> from landlab import HexModelGrid
>>> mg = HexModelGrid(3, 2)
>>> mg.angle_of_link / np.pi * 3.  # 60 degree segments
array([ 0.,  2.,  1.,  2.,  1.,  0.,  0.,  1.,  2.,  1.,  2.,  0.])

LLCATS: LINF MEAS

Find and return the angle of a link about the node at the link head.

Because links have direction, their angle can be specified as an angle about either the node at the link head, or the node at the link tail. The default behaviour of angle_of_link is to return the angle about the link tail, but this method gives the angle about the link head.

Examples

>>> from landlab import HexModelGrid
>>> mg = HexModelGrid(3, 2)
>>> mg.angle_of_link_about_head[:3] / np.pi * 3.  # 60 deg segments
array([ 3.,  5.,  4.])

LLCATS: LINF MEAS

area_of_cell

Get areas of grid cells.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5), spacing=(2, 3))
>>> grid.area_of_cell 
array([ 6.,  6.,  6.,
        6.,  6.,  6.])

LLCATS: CINF MEAS

at_cell = {}
at_corner = {}
at_face = {}
at_node = {}
at_patch = {}
axis_name

Get the name of each coordinate axis.

Returns:

tuple of str

The names of each axis.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.axis_name
('y', 'x')
>>> grid.axis_name = ('lon', 'lat')
>>> grid.axis_name
('lon', 'lat')

LLCATS: GINF

axis_units

Get units for each axis.

Returns:

tuple of str

The units (as a string) for each of a grid’s coordinates.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.axis_units
('-', '-')
>>> mg.axis_units = ('km', 'km')
>>> mg.axis_units
('km', 'km')

LLCATS: GINF

boundary_nodes

Get array of boundary nodes.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.boundary_nodes
array([ 0,  1,  2,  3,  4,  5,  9, 10, 14, 15, 16, 17, 18, 19])

LLCATS: NINF BC

calc_aspect_at_node(grid, slope_component_tuple=None, elevs='topographic__elevation', unit='degrees', ignore_closed_nodes=True)

Get array of aspect of a surface.

Calculates at returns the aspect of a surface. Aspect is returned as radians clockwise of north, unless input parameter units is set to ‘degrees’.

If slope_component_tuple is provided, i.e., (slope_x, slope_y), the aspect will be calculated from these data.

If it is not, it will be derived from elevation data at the nodes, which can either be a string referring to a grid field (default: ‘topographic__elevation’), or an nnodes-long numpy array of the values themselves.

If ignore_closed_nodes is False, all proximal elevation values will be used in the calculation. If True, only unclosed nodes are used.

Parameters:

slope_component_tuple : (slope_x_array, slope_y_array) (optional)

Tuple of components of slope in the x and y directions, defined on nodes, if already known. If not, provide elevs.

elevs : str or array (optional)

Node field name or node array of elevations. If slope_component_tuple is not provided, must be set, but unused otherwise.

unit : {‘degrees’, ‘radians’}

Controls the unit that the aspect is returned as.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 4))
>>> z = mg.node_x ** 2 + mg.node_y ** 2
>>> mg.calc_aspect_at_node(elevs=z)
array([ 225.        ,  240.16585039,  255.2796318 ,  258.69006753,
        209.83414961,  225.        ,  243.54632481,  248.77808974,
        194.7203682 ,  206.45367519,  225.        ,  231.94498651,
        191.30993247,  201.22191026,  218.05501349,  225.        ])
>>> z = z.max() - z
>>> mg.calc_aspect_at_node(elevs=z)
array([ 45.        ,  60.16585039,  75.2796318 ,  78.69006753,
        29.83414961,  45.        ,  63.54632481,  68.77808974,
        14.7203682 ,  26.45367519,  45.        ,  51.94498651,
        11.30993247,  21.22191026,  38.05501349,  45.        ])
>>> mg = RasterModelGrid((4, 4), (2., 3.))
>>> z = mg.node_x ** 2 + mg.node_y ** 2
>>> mg.calc_aspect_at_node(elevs=z)
array([ 236.30993247,  247.52001262,  259.97326008,  262.40535663,
        220.75264634,  234.41577266,  251.13402374,  255.29210302,
        201.54258265,  215.47930877,  235.73541937,  242.24162456,
        196.69924423,  209.43534223,  229.19345757,  236.30993247])

Note that a small amount of asymmetry arises at the grid edges due to the “missing” nodes beyond the edge of the grid.

LLCATS: NINF SURF

Calculate differences of node values over links.

Calculates the difference in quantity node_values at each link in the grid.

Construction:

grid.calc_diff_at_link(node_values, out=None)
Parameters:

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray

Differences across links.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 3))
>>> z = np.zeros(9)
>>> z[4] = 1.
>>> rmg.calc_diff_at_link(z)
array([ 0.,  0.,  0.,  1.,  0.,  1., -1.,  0., -1.,  0.,  0.,  0.])

LLCATS: LINF GRAD

calc_distances_of_nodes_to_point(coord, get_az=None, node_subset=None, out_distance=None, out_azimuth=None)[source]

Get distances for nodes to a given point.

Returns an array of distances for each node to a provided point. If “get_az” is set to ‘angles’, returns both the distance array and an array of azimuths from up/north. If it is set to ‘displacements’, it returns the azimuths as a 2xnnodes array of x and y displacements. If it is not set, returns just the distance array.

If “node_subset” is set as an ID, or list/array/etc of IDs method returns just the distance (and optionally azimuth) for that node. Point is provided as a tuple (x,y).

If out_distance (& out_azimuth) are provided, these arrays are used to store the outputs. This is recommended for memory management reasons if you are working with node subsets.

Note

Angles are returned in radians but measured clockwise from north.

Parameters:

coord : tuple of float

Coodinates of point as (x, y).

get_az: {None, ‘angles’, ‘displacements’}, optional

Optionally calculate azimuths as either angles or displacements. The calculated values will be returned along with the distances as the second item of a tuple.

node_subset : array_like, optional

Calculate distances on a subset of grid nodes. The default is to calculate distances from the provided points to all nodes.

out_distance : array_like, optional

If provided, put the calculated distances here. Otherwise, create a new array.

out_azimuth : array_like, optional

If provided, put the calculated distances here. Otherwise, create a new array.

Returns:

ndarray or tuple of ndarray

If get_az is None return the array of distances. Otherwise, return a tuple of distances and azimuths.

Notes

Once you start working with node subsets in Landlab, which can change size between loops, it’s quite possible for Python’s internal memory management to crap out after large numbers of loops (~>10k). This is to do with the way it block allocates memory for arrays of differing lengths, then cannot free this memory effectively. The solution - as implemented here - is to pre-allocate all arrays as nnodes long, then only work with the first [len_subset] entries by slicing (in a pseudo-C-style). Care has to be taken not to “accidentally” allow Python to allocate a new array you don’t have control over. Then, to maintain efficient memory allocation, we create some “dummy” nnode-long arrays to store intermediate parts of the solution in.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))

Calculate distances from point at (2., 1.) to a subset of nodes on the grid.

>>> grid.calc_distances_of_nodes_to_point((2, 1),
...     node_subset=(2, 6, 7, 8, 12))
array([ 1.,  1.,  0.,  1.,  1.])

Calculate distances from a point to all nodes on the grid.

>>> dist = grid.calc_distances_of_nodes_to_point((2, 1))
>>> dist.shape == (grid.number_of_nodes, )
True
>>> dist.take((2, 6, 7, 8, 12))
array([ 1.,  1.,  0.,  1.,  1.])

Put the distances into a buffer.

>>> out = np.empty(grid.number_of_nodes, dtype=float)
>>> dist = grid.calc_distances_of_nodes_to_point((2, 1),
...     out_distance=out)
>>> out is dist
True
>>> out.take((2, 6, 7, 8, 12))
array([ 1.,  1.,  0.,  1.,  1.])

Calculate azimuths along with distances. The azimuths are calculated in radians but measured clockwise from north.

>>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1),
...     get_az='angles')
>>> azim.take((2, 6, 7, 8, 12)) * 180. / np.pi
array([ 180.,  270.,    0.,   90.,    0.])
>>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1),
...     get_az='angles', node_subset=(1, 3, 11, 13))
>>> azim * 180. / np.pi
array([ 225.,  135.,  315.,   45.])

When calculating displacements, the first row contains displacements in x and the second displacements in y.

>>> (_, azim) = grid.calc_distances_of_nodes_to_point((2, 1),
...     get_az='displacements', node_subset=(2, 6, 7, 8, 12))
>>> azim
array([[ 0., -1.,  0.,  1.,  0.],
       [-1.,  0.,  0.,  0.,  1.]])

LLCATS: NINF MEAS

calc_flux_div_at_cell(grid, vals, *args, **kwds)

Calculate divergence of link-based fluxes at cells.

This function is very similar to the function calc_flux_div_at_node.

Given a flux per unit width across each cell face in the grid, calculate the net outflux (or influx, if negative) divided by cell area, at each cell.

Construction:

grid.calc_flux_div_at_cell(unit_flux_at_links_across_faces, out=None)
Parameters:

unit_flux_at_links_across_faces : ndarray or field name

Flux per unit width along links at faces (x number of faces) or link field.

Returns:

ndarray (x number of cells)

Flux divergence at cells.

Notes

Performs a numerical flux divergence operation at cells.

LLCATS: NINF GRAD

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> from landlab.grid.divergence import calc_flux_div_at_cell
>>> rg = RasterModelGrid(3, 4, 10.0)
>>> import numpy as np
>>> z = rg.add_zeros('node', 'topographic__elevation')
>>> z[5] = 50.0
>>> z[6] = 36.0
>>> lg = rg.calc_grad_at_link(z)  # there are 17 links
>>> lg
array([ 0. ,  0. ,  0. ,  0. ,  5. ,  3.6,  0. ,  5. , -1.4, -3.6,  0. ,
       -5. , -3.6,  0. ,  0. ,  0. ,  0. ])
>>> fg = lg[rg.link_at_face]  # there are 7 faces
>>> fg
array([ 5. ,  3.6,  5. , -1.4, -3.6, -5. , -3.6])
>>> calc_flux_div_at_cell(rg, -fg)
array([ 1.64,  0.94])
>>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)
>>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)
>>> unit_flux_at_faces = np.zeros(rg.number_of_faces)
>>> unit_flux_at_faces[rg.active_faces] = -fg[rg.active_faces]
>>> calc_flux_div_at_cell(rg, unit_flux_at_faces)
array([ 1.14,  0.22])
>>> _ = rg.add_field('neg_grad_at_link', -lg, at = 'link')
>>> calc_flux_div_at_cell(rg, 'neg_grad_at_link')
array([ 1.64,  0.94])
calc_flux_div_at_node(grid, vals, *args, **kwds)

Calculate divergence of link-based fluxes at nodes.

Given a flux per unit width across each face in the grid, calculate the net outflux (or influx, if negative) divided by cell area, at each node (zero or “out” value for nodes without cells).

Construction:

grid.calc_flux_div_at_node(unit_flux_at_links, out=None)
Parameters:

unit_flux : ndarray or field name

Flux per unit width along links (x number of links).

Returns:

ndarray (x number of nodes)

Flux divergence at nodes.

Notes

Performs a numerical flux divergence operation on nodes.

LLCATS: NINF GRAD

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> from landlab.grid.divergence import calc_flux_div_at_node
>>> rg = RasterModelGrid(3, 4, 10.0)
>>> z = rg.add_zeros('node', 'topographic__elevation')
>>> z[5] = 50.0
>>> z[6] = 36.0
>>> lg = rg.calc_grad_at_link(z)  # there are 17 links
>>> lg
array([ 0. ,  0. ,  0. ,  0. ,  5. ,  3.6,  0. ,  5. , -1.4, -3.6,  0. ,
       -5. , -3.6,  0. ,  0. ,  0. ,  0. ])
>>> calc_flux_div_at_node(rg, -lg)
array([ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  1.64,  0.94,  0.  ,  0.  ,
        0.  ,  0.  ,  0.  ])
>>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)
>>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)
>>> unit_flux_at_links = np.zeros(rg.number_of_links)
>>> unit_flux_at_links[rg.active_links] = -lg[rg.active_links]
>>> calc_flux_div_at_node(rg, unit_flux_at_links)
array([ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  1.14,  0.22,  0.  ,  0.  ,
        0.  ,  0.  ,  0.  ])
>>> _ = rg.add_field('neg_grad_at_link', -lg, at = 'link')
>>> calc_flux_div_at_node(rg, 'neg_grad_at_link')
array([ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  1.64,  0.94,  0.  ,  0.  ,
        0.  ,  0.  ,  0.  ])

Calculate gradients of node values over active links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_grad_at_link() instead.

Calculates the gradient in quantity node values at each active link in the grid.

Construction:

grid.calc_grad_at_active_link(node_values, out=None)
Parameters:

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray

Gradients across active links.

LLCATS: DEPR LINF GRAD

Calculate gradients of node values at links.

Calculates the gradient in node_values at each link in the grid, returning an array of length number_of_links.

Construction:

grid.calc_grad_at_link(node_values, out=None)
Parameters:

node_values : ndarray or field name (x number of nodes)

Values at grid nodes.

out : ndarray, optional (x number of links)

Buffer to hold the result.

Returns:

ndarray

Gradients across active links.

Examples

>>> from landlab import RasterModelGrid
>>> rg = RasterModelGrid(3, 4, 10.0)
>>> z = rg.add_zeros('node', 'topographic__elevation')
>>> z[5] = 50.0
>>> z[6] = 36.0
>>> calc_grad_at_link(rg, z)  # there are 17 links
array([ 0. ,  0. ,  0. ,  0. ,  5. ,  3.6,  0. ,  5. , -1.4, -3.6,  0. ,
       -5. , -3.6,  0. ,  0. ,  0. ,  0. ])
>>> from landlab import HexModelGrid
>>> hg = HexModelGrid(3, 3, 10.0)
>>> z = hg.add_zeros('node', 'topographic__elevation', noclobber=False)
>>> z[4] = 50.0
>>> z[5] = 36.0
>>> calc_grad_at_link(hg, z)  # there are 11 faces
array([ 0. ,  0. ,  0. ,  5. ,  5. ,  3.6,  3.6,  0. ,  5. , -1.4, -3.6,
        0. , -5. , -5. , -3.6, -3.6,  0. ,  0. ,  0. ])

LLCATS: LINF GRAD

calc_grad_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, unit_normal=None, slope_magnitude=None)

Calculate the components of the gradient at each patch.

If ignore_closed_nodes is True, closed nodes do not affect gradient calculations. If a closed node is present in a patch, the patch gradient is set to zero in both x and y directions.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

unit_normal : array with shape (num_patches, 3) (optional)

The unit normal vector to each patch, if already known.

slope_magnitude : array with size num_patches (optional)

The slope of each patch, if already known.

Returns:

gradient_tuple : (x_component_at_patch, y_component_at_patch)

Len-2 tuple of arrays giving components of gradient in the x and y directions, in the units of units.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_y
>>> (x_grad, y_grad) = mg.calc_grad_at_patch(elevs=z)
>>> np.allclose(y_grad, np.pi / 4.)
True
>>> np.allclose(x_grad, 0.)
True

LLCATS: PINF GRAD

Calculate gradients at active links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_grad_at_link() instead.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> z = np.array([0., 0., 0., 0.,
...               1., 1., 1., 1.,
...               3., 3., 3., 3.])
>>> grid.calc_grad_of_active_link(z)
array([ 1.,  1.,  0.,  0.,  0.,  2.,  2.])

This method is deprecated. Instead, use calc_grad_at_link.

>>> vals = grid.calc_grad_at_link(z)
>>> vals[grid.active_links]
array([ 1.,  1.,  0.,  0.,  0.,  2.,  2.])

LLCATS: DEPR

calc_hillshade_at_node(alt=45.0, az=315.0, slp=None, asp=None, unit='degrees', elevs='topographic__elevation')[source]

Get array of hillshade.

Code author: Katy Barnhart <katherine.barnhart@colorado.edu>

Parameters:

alt : float

Sun altitude (from horizon) - defaults to 45 degrees

az : float

Sun azimuth (CW from north) - defaults to 315 degrees

slp : float

slope of cells at surface - optional

asp : float

aspect of cells at surface (from north) - optional (with slp)

unit : string

‘degrees’ (default) or ‘radians’ - only needed if slp and asp

are not provided

If slp and asp are both not specified, ‘elevs’ must be provided as

a grid field name (defaults to ‘topographic__elevation’) or an

nnodes-long array of elevation values. In this case, the method will

calculate local slopes and aspects internally as part of the hillshade

production.

Returns:

ndarray of float

Hillshade at each cell.

Notes

code taken from GeospatialPython.com example from December 14th, 2014 DEJH found what looked like minor sign problems, and adjusted to follow the ArcGIS algorithm: http://help.arcgis.com/en/arcgisdesktop/10.0/ help/index.html#/How_Hillshade_works/009z000000z2000000/ .

Remember when plotting that bright areas have high values. cmap=’Greys’ will give an apparently inverted color scheme. cmap=’gray’ has white associated with the high values, so is recommended for plotting.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((5, 5), 1.)
>>> z = mg.x_of_node * np.tan(60. * np.pi / 180.)
>>> mg.calc_hillshade_at_node(elevs=z, alt=30., az=210.)
array([ 0.625,  0.625,  0.625,  0.625,  0.625,  0.625,  0.625,  0.625,
        0.625,  0.625,  0.625,  0.625,  0.625,  0.625,  0.625,  0.625,
        0.625,  0.625,  0.625,  0.625,  0.625,  0.625,  0.625,  0.625,
        0.625])

LLCATS: NINF SURF

calc_net_flux_at_node(grid, vals, *args, **kwds)

Calculate net link fluxes at nodes.

Given a flux per unit width along each link in the grid, calculate the net outflux (or influx, if negative) at each node. Fluxes are treated as zero for links that have no faces, and net fluxes are treated as zero for nodes that have no cell.

Construction:

grid.calc_net_flux_at_node(unit_flux_at_links, out=None)
Parameters:

unit_flux_at_links : ndarray or field name

Flux per unit width associated with links.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray (x number of cells)

Net flux at nodes.

Notes

This is essentially a line integral for the fluxes along the boundaries of each cell. Hence, the resulting output has dimensions of total flux (so, if the unit flux happens to be mass per time per face width, the output will be in mass per unit time). Because a line integral is undefined where there are no cells (i.e., perimeter nodes), the result is given as zeros for these nodes. The current algorithm uses fancy indexing (calling _calc_net_face_flux_at_cells) and could probably be made faster.

LLCATS: NINF GRAD

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rg = RasterModelGrid(3, 4, 10.0)
>>> z = rg.add_zeros('node', 'topographic__elevation')
>>> z[5] = 50.0
>>> z[6] = 36.0
>>> lg = rg.calc_grad_at_link(z)  # there are 17 links
>>> lg
array([ 0. ,  0. ,  0. ,  0. ,  5. ,  3.6,  0. ,  5. , -1.4, -3.6,  0. ,
       -5. , -3.6,  0. ,  0. ,  0. ,  0. ])
>>> calc_net_flux_at_node(rg, -lg)
array([   0.,    0.,    0.,    0.,    0.,  164.,   94.,    0.,    0.,
          0.,    0.,    0.])
>>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)
>>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)
>>> unit_flux_at_links = np.zeros(rg.number_of_links)
>>> unit_flux_at_links[rg.active_links] = -lg[rg.active_links]
>>> nlfn = calc_net_flux_at_node(rg, unit_flux_at_links)
>>> np.round(nlfn)
array([   0.,    0.,    0.,    0.,    0.,  114.,   22.,    0.,    0.,
          0.,    0.,    0.])
>>> from landlab import HexModelGrid
>>> hg = HexModelGrid(3, 3, 10.0)
>>> z = hg.add_zeros('node', 'topographic__elevation', noclobber=False)
>>> z[4] = 50.0
>>> z[5] = 36.0
>>> lg = hg.calc_grad_at_link(z)  # there are ? links
>>> lg
array([ 0. ,  0. ,  0. ,  5. ,  5. ,  3.6,  3.6,  0. ,  5. , -1.4, -3.6,
        0. , -5. , -5. , -3.6, -3.6,  0. ,  0. ,  0. ])
>>> nlfn = calc_net_flux_at_node(hg, -lg)
>>> np.round(nlfn)
array([   0.,    0.,    0.,    0.,  152.,   96.,    0.,    0.,    0.,    0.])
calc_slope_at_node(grid, elevs='topographic__elevation', method='patch_mean', ignore_closed_nodes=True, return_components=False, **kwds)

Array of slopes at nodes, averaged over neighboring patches.

Produces a value for node slope (i.e., mean gradient magnitude) at each node in a manner analogous to a GIS-style slope map. It averages the gradient on each of the patches surrounding the node, creating a value for node slope that better incorporates nonlocal elevation information. Directional information can still be returned through use of the return_components keyword.

Note that under these definitions, it is not always true that:

mag, cmp = mg.calc_slope_at_node(z)
mag ** 2 == cmp[0] ** 2 + cmp[1] ** 2  # not always true

If ignore_closed_nodes is False, all proximal elevation values will be used in the calculation. If True, only unclosed nodes are used.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

method : {‘patch_mean’, ‘Horn’}

By equivalence to the raster version, ‘patch_mean’ returns a scalar mean on the patches; ‘Horn’ returns a vector mean on the patches.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

return_components : bool

If True, return a tuple, (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If false, return an array of floats of the slope magnitude.

Returns:

float array or length-2 tuple of float arrays

If return_components, returns (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If not return_components, returns an array of slope magnitudes.

Examples

>>> import numpy as np
>>> from landlab import RadialModelGrid, RasterModelGrid
>>> mg = RasterModelGrid((4, 5), 1.)
>>> z = mg.node_x
>>> slopes = mg.calc_slope_at_node(elevs=z)
>>> np.allclose(slopes, 45. / 180. * np.pi)
True
>>> mg = RasterModelGrid((4, 5), 1.)
>>> z = - mg.node_y
>>> slope_mag, cmp = mg.calc_slope_at_node(elevs=z,
...                                        return_components=True)
>>> np.allclose(slope_mag, np.pi / 4.)
True
>>> np.allclose(cmp[0], 0.)
True
>>> np.allclose(cmp[1], - np.pi / 4.)
True
>>> mg = RadialModelGrid(num_shells=9)
>>> z = mg.radius_at_node
>>> slopes = mg.calc_slope_at_node(elevs=z)
>>> mean_ring_slope = []
>>> for i in range(10):
...     mean_ring_slope.append(
...         slopes[np.isclose(mg.radius_at_node, i)].mean())

Notice the small amounts of numerical error here:

>>> target_mean_ring_slope = [0.85707194785013108, 0.79363155567711452,
...                           0.77922185867135429, 0.78359813570962411,
...                           0.78433070957439543, 0.78452745144699965,
...                           0.78477643475446901, 0.78506472422668094,
...                           0.78505793680521629, 0.78661256633611021]
>>> np.allclose(mean_ring_slope, target_mean_ring_slope)
True

LLCATS: NINF GRAD SURF

calc_slope_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, unit_normal=None)

Calculate the slope (positive magnitude of gradient) at patches.

If ignore_closed_nodes is True, closed nodes do not affect slope calculations. If a closed node is present in a patch, the patch slope is set to zero.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

unit_normal : array with shape (num_patches, 3) (optional)

The unit normal vector to each patch, if already known.

Returns:

slopes_at_patch : n_patches-long array

The slope (positive gradient magnitude) of each patch.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_x
>>> S = mg.calc_slope_at_patch(elevs=z)
>>> S.size == mg.number_of_patches
True
>>> np.allclose(S, np.pi / 4.)
True

LLCATS: PINF GRAD

calc_unit_normal_at_patch(grid, elevs='topographic__elevation')

Calculate and return the unit normal vector <a, b, c> to a patch.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

Returns:

nhat : num-patches x length-3 array

The unit normal vector <a, b, c> to each patch.

Examples

>>> from landlab import HexModelGrid
>>> mg = HexModelGrid(3, 3)
>>> z = mg.node_x * 3. / 4.
>>> mg.calc_unit_normal_at_patch(z)
array([[-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8]])

LLCATS: PINF GRAD

Calculate differences of node values over active links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_diff_at_link() instead.

Calculates the difference in quantity node_values at each active link in the grid.

Construction:

grid.calculate_diff_at_active_links(node_values, out=None)
Parameters:

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray

Differences across active links.

LLCATS: DEPR LINF GRAD

Calculate differences of node values over links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_diff_at_link() instead.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> z = np.zeros(9)
>>> z[4] = 1.
>>> grid.calculate_diff_at_links(z)
array([ 0.,  0.,  0.,  1.,  0.,  1., -1.,  0., -1.,  0.,  0.,  0.])
>>> grid.calc_diff_at_link(z)
array([ 0.,  0.,  0.,  1.,  0.,  1., -1.,  0., -1.,  0.,  0.,  0.])

LLCATS: DEPR LINF GRAD

calculate_flux_divergence_at_core_nodes(*args, **kwargs)[source]

Get array of flux divergence for core nodes.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_flux_div_at_node() instead.

Given an array of fluxes along links, computes the net total flux within each cell, divides by cell area, and stores the result in net_unit_flux.

The function works by calling calculate_flux_divergence_at_nodes, then slicing out only the values at core nodes. Therefore, it is slower than calculate_flux_divergence_at_nodes, even though it returns a shorter list of numbers.

The input active_link_flux should be flux of something (e.g., mass, momentum, energy) per unit face width, positive if flowing in the same direction as its link, and negative otherwise. There should be one value per active link. Returns an array of net total flux per unit area, one value per core node (creates this array if it is not given as an argument).

By convention, divergence is positive for net outflow, and negative for net outflow. That’s why we add outgoing flux and subtract incoming flux. This makes net_unit_flux have the same sign and dimensions as a typical divergence term in a conservation equation.

In general, for a polygonal cell with N sides of lengths Li and with surface area A, the net influx divided by cell area would be:

\[{Q_{net} \over A} = {1 \over A} \sum{q_i L_i}\]

For a square cell, which is what we have in RasterModelGrid, the sum is over 4 sides of length dx, and \(A = dx^2\), so:

\[{Q_{net} \over A} = {1 \over dx} \sum{q_i}\]

Note

The net flux is defined as positive outward, negative inward. In a diffusion problem, for example, one would use:

\[{du \over dt} = \text{source} - \text{fd}\]

where fd is “flux divergence”.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5), 1.0)
>>> u = [0., 1., 2., 3., 0.,
...      1., 2., 3., 2., 3.,
...      0., 1., 2., 1., 2.,
...      0., 0., 2., 2., 0.]
>>> u = np.array(u)
>>> grad = rmg.calc_grad_at_link(u)[rmg.active_links]
>>> grad
array([ 1.,  1., -1.,  1.,  1., -1.,  1., -1., -1., -1.,  1.,  1., -1.,
        1., -1.,  0.,  1.])
>>> flux = - grad    # downhill flux proportional to gradient
>>> divflux = rmg.calculate_flux_divergence_at_core_nodes(flux)
>>> divflux
array([ 2.,  4., -2.,  0.,  1., -4.])

If calculate_gradients_at_core_nodes is called inside a loop, you can improve speed slightly by creating an array outside the loop. For example, do this once, before the loop:

>>> divflux = np.zeros(rmg.number_of_core_cells) # outside loop

Then do this inside the loop:

>>> divflux = rmg.calculate_flux_divergence_at_core_nodes(
...     flux, divflux)

In this case, the function will not have to create the divflux array.

Note this method is untested with looped boundary conditions.

LLCATS: DEPR NINF GRAD

calculate_flux_divergence_at_nodes(*args, **kwargs)[source]

Flux divergence at nodes.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_flux_div_at_node() instead.

Same as calculate_flux_divergence_at_active_cells, but works with and returns a list of net unit fluxes that corresponds to all nodes, rather than just active cells.

Note that we don’t compute net unit fluxes at boundary nodes (which don’t have active cells associated with them, and often don’t have cells of any kind, because they are on the perimeter), but simply return zeros for these entries. The advantage is that the caller can work with node-based arrays instead of active-cell-based arrays.

This method is untested with looped boundary conditions.

LLCATS: DEPR NINF GRAD

calculate_gradients_at_faces(*args, **kwargs)

Calculate gradients of node values over faces.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_grad_at_link() instead.

Calculate and return gradient in node_values at each face in the grid. Gradients are calculated from the nodes at either end of the link that crosses each face.

Construction:

grid.calculate_gradients_at_faces(node_values, out=None)
Parameters:

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray (x number of faces)

Gradients across faces.

Examples

>>> from landlab import RasterModelGrid
>>> rg = RasterModelGrid(3, 4, 10.0)
>>> z = rg.add_zeros('node', 'topographic__elevation')
>>> z[5] = 50.0
>>> z[6] = 36.0
>>> calculate_gradients_at_faces(rg, z)  # there are 7 faces
array([ 5. ,  3.6,  5. , -1.4, -3.6, -5. , -3.6])
>>> from landlab import HexModelGrid
>>> hg = HexModelGrid(3, 3, 10.0)
>>> z = hg.add_zeros('node', 'topographic__elevation', noclobber=False)
>>> z[4] = 50.0
>>> z[5] = 36.0
>>> calculate_gradients_at_faces(hg, z)  # there are 11 faces
array([ 5. ,  5. ,  3.6,  3.6,  5. , -1.4, -3.6, -5. , -5. , -3.6, -3.6])

LLCATS: DEPR GRAD

cell_area_at_node

Cell areas in a nnodes-long array.

Zeros are entered at all perimeter nodes, which lack cells.

Returns:

ndarray

Cell areas as an n_nodes-long array.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5), spacing=(3, 4))
>>> grid.status_at_node[7] = CLOSED_BOUNDARY
>>> grid.cell_area_at_node
array([  0.,   0.,   0.,   0.,   0.,
         0.,  12.,  12.,  12.,   0.,
         0.,  12.,  12.,  12.,   0.,
         0.,   0.,   0.,   0.,   0.])
LLCATS: CINF NINF CONN
cell_at_node

Node ID associated with grid cells.

Examples

>>> from landlab import RasterModelGrid, BAD_INDEX_VALUE
>>> grid = RasterModelGrid((4, 5))
>>> ids = grid.cell_at_node
>>> ids[ids == BAD_INDEX_VALUE] = -1
>>> ids 
array([-1, -1, -1, -1, -1,
       -1,  0,  1,  2, -1,
       -1,  3,  4,  5, -1,
       -1, -1, -1, -1, -1])

LLCATS: CINF NINF CONN

closed_boundary_nodes

Get array of closed boundary nodes.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY
>>> mg.closed_boundary_nodes
array([15, 16, 17, 18, 19])

LLCATS: NINF BC

core_cells

Get array of core cells.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.status_at_node[8] = CLOSED_BOUNDARY
>>> mg.core_cells
array([0, 1, 3, 4, 5])

LLCATS: CINF BC

core_nodes

Get array of core nodes.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.core_nodes
array([ 6,  7,  8, 11, 12, 13])

LLCATS: NINF BC

display_grid(*args, **kwargs)[source]

Display the grid.

Note

This method is deprecated as of Landlab version 1.0.

Use plot.imshow_grid() instead.

LLCATS: DEPR GINF

Return an (nnodes, X) shape array of link IDs of which links are downwind of each node, according to values (array or field).

X is the maximum downwind links at any node. Nodes with fewer downwind links than this have additional slots filled with bad_index. Links are ordered anticlockwise from east.

Parameters:

values : str or array

Name of variable field defined at links, or array of values at links.

bad_index : int

Index to place in array indicating no link.

Returns:

ndarray

Array of upwind link IDs

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid, BAD_INDEX_VALUE
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                 -2., -3., -4., -5.,
...                                 -1., -2., -1.,
...                                 -1., -2., -3., -4.,
...                                 -1., -2., -1.])
>>> rmg.downwind_links_at_node('grad', bad_index=BAD_INDEX_VALUE)
array([[ 0,  3],
       [ 1,  4],
       [ 2,  5],
       [ 6, -1],
       [ 7, 10],
       [ 8, 11],
       [ 9, 12],
       [13, -1],
       [14, -1],
       [15, -1],
       [16, -1],
       [-1, -1]])

LLCATS: LINF NINF CONN

Get array of faces associated with links.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid, BAD_INDEX_VALUE
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.face_at_link[5:7]
array([0, 1])
>>> np.all(mg.face_at_link[:5]==BAD_INDEX_VALUE)
True

LLCATS: FINF LINF CONN

face_width

Note

This method is deprecated as of Landlab version 1.0.

Use width_of_face() instead.

LLCATS: DEPR FINF MEAS

faces_at_cell

Return array containing face IDs at each cell.

Creates array if it doesn’t already exist.

LLCATS: FINF CINF CONN

fixed_gradient_boundary_node_anchor_node

Returns the node at the other end of the fixed link for a fixed gradient boundary node.

Degenerate FIXED_GRADIENT_BOUNDARY nodes (e.g., corners) are handled as in fixed_gradient_boundary_node_fixed_link(), by pointing to a neighboring FIXED_GRADIENT_BOUNDARY node.

Examples

>>> from landlab import RasterModelGrid
>>> from landlab import FIXED_GRADIENT_BOUNDARY
>>> grid = RasterModelGrid((3, 4))
>>> leftedge = grid.nodes_at_left_edge
>>> grid.status_at_node[leftedge] = FIXED_GRADIENT_BOUNDARY
>>> grid.fixed_gradient_boundary_nodes
array([0, 4, 8])
>>> grid.fixed_gradient_boundary_node_fixed_link
array([ 3,  7, 10])
>>> grid.fixed_gradient_boundary_node_anchor_node
array([4, 5, 4])

An array of the fixed_links connected to fixed gradient boundary nodes.

Note that on a raster, some nodes (notably the corners) can be FIXED_GRADIENT_BOUNDARY, but not have a true FIXED_LINK neighboring link. In such cases, the link returned will be a closed link joining the corner node to a neighboring FIXED_GRADIENT_BOUNDARY node (see example).

An AssertionError will be raised if for some reason a FIXED_GRADIENT_BOUNDARY node exists which has neither a FIXED_GRADIENT_BOUNDARY neighbor, or a FIXED_LINK.

Examples

>>> from landlab import RasterModelGrid
>>> from landlab import FIXED_GRADIENT_BOUNDARY
>>> grid = RasterModelGrid((3, 4))
>>> leftedge = grid.nodes_at_left_edge
>>> grid.status_at_node[leftedge] = FIXED_GRADIENT_BOUNDARY
>>> grid.fixed_gradient_boundary_nodes
array([0, 4, 8])
>>> grid.fixed_gradient_boundary_node_fixed_link
array([ 3,  7, 10])
fixed_gradient_boundary_nodes

Get array of fixed gradient boundary nodes.

Examples

>>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.status_at_node[mg.nodes_at_top_edge] = FIXED_GRADIENT_BOUNDARY
>>> mg.fixed_gradient_boundary_nodes
array([15, 16, 17, 18, 19])

LLCATS: NINF BC

Get array of fixed links.

Examples

>>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY
>>> grid = RasterModelGrid((3, 4))
>>> grid.status_at_node 
array([1, 1, 1, 1,
       1, 0, 0, 1,
       1, 1, 1, 1], dtype=int8)
>>> grid.fixed_links.size
0
>>> grid.status_at_node[:4] = FIXED_GRADIENT_BOUNDARY
>>> grid.status_at_node 
array([2, 2, 2, 2,
       1, 0, 0, 1,
       1, 1, 1, 1], dtype=int8)
>>> grid.fixed_links
array([4, 5])

LLCATS: LINF BC

fixed_value_boundary_nodes

Get array of fixed value boundary nodes.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge,
...              mg.nodes_at_bottom_edge):
...     mg.status_at_node[edge] = CLOSED_BOUNDARY
>>> mg.fixed_value_boundary_nodes
array([16, 17, 18])

LLCATS: NINF BC

classmethod from_dict(params)[source]
classmethod from_file(file_like)[source]
is_boundary(*args, **kwargs)[source]

Note

This method is deprecated as of Landlab version 1.0.

Use node_is_boundary() instead.

LLCATS: DEPR NINF BC

Get lengths of links.

Returns:

ndarray

Lengths of all links, in ID order.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.length_of_link
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.])
>>> len(grid.length_of_link) == grid.number_of_links
True

LLCATS: LINF MEAS

Get links associated with faces.

Returns an array of the link IDs for the links that intersect faces.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 4))
>>> mg.link_at_face
array([ 4,  5,  7,  8,  9, 11, 12])

LLCATS: LINF FINF MEAS

Return a boolean the same shape as links_at_node() which flags links which are downwind of the node as True.

link_at_node_is_downwind iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node. It then return a boolean array the same shape as links_at_node flagging these links. e.g., for a raster, the returned array will be shape (nnodes, 4).

Parameters:

values : str or array

Name of variable field defined at links, or array of values at links.

out
: ndarray, optional

Buffer to place mapped values into or None to create a new array. Must be correct shape and boolean dtype.

Returns:

ndarray

Boolean of which links are downwind at nodes.

LLCATS: LINF NINF CONN

Return a boolean the same shape as links_at_node() which flags links which are upwind of the node as True.

link_at_node_is_upwind iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node. It then return a boolean array the same shape as links_at_node flagging these links. e.g., for a raster, the returned array will be shape (nnodes, 4).

Parameters:

values : str or array

Name of variable field defined at links, or array of values at links.

out
: ndarray, optional

Buffer to place mapped values into or None to create a new array. Must be correct shape and boolean dtype.

Returns:

ndarray

Boolean of which links are upwind at nodes.

LLCATS: LINF NINF CONN

Link directions at each node: 1=incoming, -1=outgoing, 0=none.

Returns:

(NODES, LINKS) ndarray of int

Link directions relative to the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. A zero indicates no link at this position.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 3))
>>> grid.link_dirs_at_node 
array([[-1, -1,  0,  0], [-1, -1,  1,  0], [ 0, -1,  1,  0],
       [-1, -1,  0,  1], [-1, -1,  1,  1], [ 0, -1,  1,  1],
       [-1, -1,  0,  1], [-1, -1,  1,  1], [ 0, -1,  1,  1],
       [-1,  0,  0,  1], [-1,  0,  1,  1], [ 0,  0,  1,  1]],
       dtype=int8)
>>> grid.link_dirs_at_node[4]
array([-1, -1,  1,  1], dtype=int8)
>>> grid.link_dirs_at_node[(4, 7), :]
array([[-1, -1,  1,  1],
       [-1, -1,  1,  1]], dtype=int8)

LLCATS: NINF LINF CONN

Note

This method is deprecated as of Landlab version 1.0.

Use length_of_link() instead.

LLCATS: DEPR LINF MEAS

Note

This method is deprecated as of Landlab version 0.5.

Use unit_vector_xcomponent_at_link() instead.

LLCATS: DEPR LINF MEAS

Note

This method is deprecated as of Landlab version 0.5.

Use unit_vector_xcomponent_at_link() instead.

LLCATS: DEPR LINF MEAS

Get links of nodes.

Returns:

(NODES, LINKS) ndarray of int

Link for the nodes of a grid. The shape of the matrix will be number of nodes rows by max number of links per node. Order is anticlockwise from east.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 3))
>>> grid.links_at_node 
array([[ 0,  2, -1, -1], [ 1,  3,  0, -1], [-1,  4,  1, -1],
       [ 5,  7, -1,  2], [ 6,  8,  5,  3], [-1,  9,  6,  4],
       [10, 12, -1,  7], [11, 13, 10,  8], [-1, 14, 11,  9],
       [15, -1, -1, 12], [16, -1, 15, 13], [-1, -1, 16, 14]])
>>> grid.links_at_node[4]
array([6, 8, 5, 3])
>>> grid.links_at_node[(4, 7), :]
array([[ 6,  8,  5,  3], [11, 13, 10, 8]])

LLCATS: NINF LINF CONN

Map the largest magnitude of the links carrying flux from the node to the node.

map_downwind_node_link_max_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node, then maps the maximum magnitude of ‘var_name’ found on these links onto the node. If no downwind link is found, the value will be recorded as zero.

Construction:

grid.map_downwind_node_link_max_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_downwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> map_downwind_node_link_max_to_node(rmg, 'grad')
array([ 1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_downwind_node_link_max_to_node(rmg, 'grad',
...                                        out=values_at_nodes)
>>> values_at_nodes
array([ 1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the mean magnitude of the links carrying flux out of the node to the node.

map_downwind_node_link_mean_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node, then maps the mean magnitude of ‘var_name’ found on these links onto the node. Links with zero values are not included in the means, and zeros are returned if no upwind links are found.

Construction:

grid.map_downwind_node_link_mean_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_downwind_node_link_mean_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                 -2., -3., -4., -5.,
...                                 -1., -2., -1.,
...                                 -1., -2., -3., -4.,
...                                 -1., -2., -1.])
>>> map_downwind_node_link_mean_to_node(rmg, 'grad')
array([ 1.5,  2.5,  2.5,  5. ,
        1. ,  2. ,  2. ,  4. ,
        1. ,  2. ,  1. ,  0. ])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_downwind_node_link_mean_to_node(rmg, 'grad',
...                                         out=values_at_nodes)
>>> values_at_nodes
array([ 1.5,  2.5,  2.5,  5. ,
        1. ,  2. ,  2. ,  4. ,
        1. ,  2. ,  1. ,  0. ])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map values from a link head nodes to links.

Iterate over a grid and identify the node at the head. For each link, the value of var_name at the head node is mapped to the corresponding link.

In a RasterModelGrid, each one node has two adjacent “link heads”. This means each node value is mapped to two corresponding links.

Construction:

grid.map_link_head_node_to_link(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_link_head_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['z'] = np.array([ 0,  1,  2,  3,
...                               4,  5,  6,  7,
...                               8,  9, 10, 11])
>>> map_link_head_node_to_link(rmg, 'z')
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   5.,   6.,   7.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_link_head_node_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   5.,   6.,   7.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map values from a link tail nodes to links.

map_link_tail_node_to_link iterates across the grid and identifies the node at the “tail”, or the “from” node for each link. For each link, the value of ‘var_name’ at the “from” node is mapped to the corresponding link.

In a RasterModelGrid, each one node has two adjacent “link tails”. This means each node value is mapped to two corresponding links.

Construction:

grid.map_link_tail_node_to_link(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_link_tail_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['z'] = np.array([ 0,  1,  2,  3,
...                               4,  5,  6,  7,
...                               8,  9, 10, 11])
>>> map_link_tail_node_to_link(rmg, 'z')
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   4.,   5.,   6.,   4.,
         5.,   6.,   7.,   8.,   9.,  10.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_link_tail_node_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   4.,   5.,   6.,   4.,
         5.,   6.,   7.,   8.,   9.,  10.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map the vector sum of links around a patch to the patch.

The resulting vector is returned as a length-2 list, with the two items being arrays of the x component and the y component of the resolved vectors at the patches, respectively.

Construction:

grid.map_link_vector_sum_to_patch(var_name, ignore_inctive_links=True,
                                  out=None)
Parameters:

var_name : array or field name

Values defined at links.

ignore_inactive_links : bool

If True, do not incorporate inactive links into calc. If all links are inactive at a patch, record zero if out is None or leave the existing value if out.

out : len-2 list of npatches-long arrays, optional

Buffer to place mapped values into or None to create a new array.

Returns:

len-2 list of arrays

[x_component_of_link_vals_at_patch, y_component_of_link_vals_at_patch].

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_link_vector_sum_to_patch
>>> from landlab import HexModelGrid
>>> from landlab import CLOSED_BOUNDARY, CORE_NODE, INACTIVE_LINK
>>> mg = HexModelGrid(4, 3)
>>> interior_nodes = mg.status_at_node == CORE_NODE
>>> exterior_nodes = mg.status_at_node != CORE_NODE

Add a ring of closed nodes at the edge:

>>> mg.status_at_node[exterior_nodes] = CLOSED_BOUNDARY

This gives us 5 core nodes, 7 active links, and 3 present patches

>>> (mg.number_of_core_nodes == 5 and mg.number_of_active_links == 7)
True
>>> A = mg.add_ones('link', 'vals')
>>> A.fill(9.)  # any old values on the inactive links
>>> A[mg.active_links] = np.array([ 1., -1.,  1., -1., -1., -1., -1.])

This setup should give present patch 0 pure east, patch 1 zero (vorticity), and patch 2 westwards and downwards components.

>>> xcomp, ycomp = map_link_vector_sum_to_patch(mg, 'vals')
>>> np.allclose(xcomp[[6, 9, 10]], [2., 0., -1])
True
>>> np.allclose(ycomp[[6, 9, 10]]/np.sqrt(3.), [0., 0., -1.])
True

These are the patches with INACTIVE_LINKs on all three sides:

>>> absent_patches = np.array([0, 1, 2, 4, 8, 11, 12, 15, 16, 17, 18])
>>> np.allclose(xcomp[absent_patches], 0.)
True
>>> np.allclose(ycomp[absent_patches], 0.)
True

Now demonstrate the remaining functionality:

>>> A = mg.at_link['vals'].copy()
>>> A.fill(1.)
>>> _ = map_link_vector_sum_to_patch(mg, A, ignore_inactive_links=False,
...                                  out=[xcomp, ycomp])
>>> np.allclose(xcomp[absent_patches], 0.)
False
>>> np.allclose(ycomp[absent_patches], 0.)
False

LLCATS: PINF LINF MAP

Map data defined on links to nodes.

Given a variable defined on links, breaks it into x and y components and assigns values to nodes by averaging each node’s attached links.

Parameters:

q : ndarray of floats (1D, length = number of links in grid)

Variable defined on links

Returns:

ndarray, ndarray

x and y components of variable mapped to nodes (1D, length = number of nodes)

See also

_create_link_unit_vectors
sets up unit vectors at links and unit-vector sums at nodes

Notes

THIS ALGORITHM IS NOT CORRECT AND NEEDS TO BE CHANGED!

The concept here is that q contains a vector variable that is defined at each link. The magnitude is given by the value of q, and the direction is given by the orientation of the link, as described by its unit vector.

To map the link-vector values to the nodes, we break the values into x- and y-components according to each link’s unit vector. The x-component of q at a node is a weighted sum of the x-components of the links that are attached to that node. A good way to appreciate this is by example. Consider a 3x4 raster grid:

8--14---9--15--10--16--11
|       |       |       |
4       5       6       7
|       |       |       |
4--11---5---12--6---13--7
|       |       |       |
0       1       2       3
|       |       |       |
0---8---1---9---2--10---3

Imagine that for each node, we were to add up the unit vector components for each connected link; in other words, add up all the x components of the unit vectors associated with each link, and add up all the y components. Here’s what that would look like for the above grid (“vsx” and “vsy” stand for “vector sum x” and “vector sum y”):

  • Corner nodes (0, 3, 8, 11): vsx = 1, vsy = 1
  • Bottom and top nodes (1-2, 9-10): vsx = 2, vsy = 1
  • Left and right nodes (4, 7): vsx = 1, vsy = 2
  • All others: vsx = 2, vsy = 2

The process of creating unit-vector sums at nodes is handled by ModelGrid._create_link_unit_vectors() (and, for raster grids, by the overriding method RasterModelGrid._create_link_unit_vectors()). The node unit-vector sums are then stored in self.node_unit_vector_sum_x and self.node_unit_vector_sum_y.

How would you use this? Suppose you have a vector variable q defined at links. What’s the average at the nodes? We’ll define the average as follows. The terminology here is: \(q = (u,v)\) represents the vector quantity defined at links, \(Q = (U,V)\) represents its definition at nodes, \((m,n)\) represents the unit vector components at a link, and \((S_x,S_y)\) represents the unit-vector sum at a given node.

\[U_i = \sum_{j=1}^{L_i} q_j m_j / S_{xi} V_i = \sum_{j=1}^{L_i} q_j n_j / S_{yi}\]

Suppose that the vector q is uniform and equal to one. Then, at node 0 in the above grid, this works out to:

U_0 = (q_0 m_0) / 1 + (q_8 m_8) / 1 = (1 0)/ 1 + (1 1)/1 = 1
V_0 = (q_0 n_0) / 1 + (q_8 n_8) / 1 = (1 1) / 1 + (1 0) / 1 = 1

At node 1, in the bottom row but not a corner, we add up the values of q associated with THREE links. The x-vector sum of these links is 2 because there are two horizontal links, each with an x- unit vector value of unity. The y-vector sum is 1 because only one of the three (link #1) has a non-zero y component (equal to one). Here is how the numbers work out:

U_1 = (q_1 m_1) / 2 + (q_8 m_8) / 2 + (q_9 m_9) / 2
    = (1 0) / 2 + (1 1) / 2 + (1 1) / 2 = 1
V_1 = (q_1 n_1) / 1 + (q_8 n_8) / 1 + (q_9 n_9) / 1
    = (1 1) / 1 + (1 0) / 1 + (1 0) / 1 = 1

At node 5, in the interior, there are four connected links (two in-links and two out-links; two horizontal and two vertical). So, we add up the q values associated with all four:

U_5 = (q_1 m_1) / 2 + (q_5 m_5) / 2 + (q_11 m_11) / 2 + (q_12 m_12) / 2
    = (1 0) / 2 + (1 0) / 2 + (1 1) / 2 + (1 1) / 2 = 1

V_5 = (q_1 n_1) / 2 + (q_5 n_5) / 2 + (q_11 n_11) / 2 + (q_12 n_12) / 2
    = (1 1) / 2 + (1 1) / 2 + (1 0) / 2 + (1 0) / 2 = 1

To do this calculation efficiently, we use the following algorithm:

FOR each row in _node_inlink_matrix (representing one inlink @ each
node)
    Multiply the link's q value by its unit x component ...
    ... divide by node's unit vector sum in x ...
    ... and add it to the node's total q_x
    Multiply the link's q value by its unit y component ...
    ... divide by node's unit vector sum in y ...
    ... and add it to the node's total q_y

Examples

Example 1

q[:] = 1. Vector magnitude is \(\sqrt{2}\), direction is \((1,1)\).

>>> import numpy as np
>>> import landlab as ll
>>> rmg = ll.RasterModelGrid((3, 4), spacing=(2., 2.))
>>> rmg.node_unit_vector_sum_x
array([ 1.,  2.,  2.,  1.,  1.,  2.,  2.,  1.,  1.,  2.,  2.,  1.])
>>> rmg.node_unit_vector_sum_y
array([ 1.,  1.,  1.,  1.,  2.,  2.,  2.,  2.,  1.,  1.,  1.,  1.])
>>> q = np.ones(rmg.number_of_links)
>>> nvx, nvy = rmg.map_link_vector_to_nodes(q)
>>> nvx
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
>>> nvy
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

Example 2

Vector magnitude is 5, angle is 30 degrees from horizontal, forming a 3-4-5 triangle.

>>> q = np.array([4., 4., 4., 3., 3., 3., 3.,
...               4., 4., 4., 3., 3., 3., 3.,
...               4., 4., 4])
>>> nvx, nvy = rmg.map_link_vector_to_nodes(q)
>>> nvx
array([ 4.,  4.,  4.,  4.,  4.,  4.,  4.,  4.,  4.,  4.,  4.,  4.])
>>> nvy
array([ 3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.,  3.])

..todo:

Fix and finish example 3 below.

Example 3: Hexagonal grid with vector as above. Here, q is pre-calculated to have the right values to represent a uniform vector with magnitude 5 and orientation 30 degrees counter-clockwise from horizontal.

LLCATS: NINF LINF CONN MAP

Map the maximum of a link’s nodes to the link.

map_max_of_link_nodes_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘var_name’ at both the “to” and “from” node. The maximum value of the two node values is then mapped to the link.

Construction:

grid.map_max_of_link_nodes_to_link(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_max_of_link_nodes_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[0, 1, 2, 3],
...                    [7, 6, 5, 4],
...                    [8, 9, 10, 11]])
>>> map_max_of_link_nodes_to_link(rmg, 'z')
array([  1.,   2.,   3.,   7.,   6.,   5.,   4.,   7.,   6.,   5.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_max_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  1.,   2.,   3.,   7.,   6.,   5.,   4.,   7.,   6.,   5.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map the maximum value of a nodes’ links to the node.

map_max_of_node_links_to_node iterates across the grid and identifies the link values at each link connected to a node. This function finds the maximum value of ‘var_name’ of each set of links, and then maps this value to the node. Note no attempt is made to honor the directionality of the links.

Construction:

grid.map_max_of_node_links_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_max_of_node_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.arange(rmg.number_of_links)
>>> map_max_of_node_links_to_node(rmg, 'grad')
array([  3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.,
        14.,  15.,  16.,  16.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_max_of_node_links_to_node(rmg, 'grad', out=values_at_nodes)
>>> values_at_nodes
array([  3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.,
        14.,  15.,  16.,  16.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

map_max_of_patch_nodes_to_patch(grid, var_name, ignore_closed_nodes=True, out=None)

Map the maximum value of nodes around a patch to the patch.

Construction:

grid.map_max_of_patch_nodes_to_patch(var_name,
                                     ignore_closed_nodes=True, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

ignore_closed_nodes : bool

If True, do not incorporate closed nodes into calc. If all nodes are masked at a patch, record zero if out is None or leave the existing value if out.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at patches.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_max_of_patch_nodes_to_patch
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 3., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> map_max_of_patch_nodes_to_patch(rmg, 'vals')
array([ 5., 4., 3.,
        4., 4., 3.])
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 3., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> rmg.status_at_node[rmg.node_x > 1.5] = CLOSED_BOUNDARY
>>> ans = np.zeros(6, dtype=float)
>>> _ = map_max_of_patch_nodes_to_patch(rmg, 'vals', out=ans)
>>> ans 
array([ 5., 4., 0.,
        4., 4., 0.])

LLCATS: PINF NINF MAP

Map the mean of a link’s nodes to the link.

map_mean_of_link_nodes_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function takes the sum of the two values of ‘var_name’ at both the “to” and “from” node. The average value of the two node values of ‘var_name’ is then mapped to the link.

Construction:

grid.map_mean_of_link_nodes_to_link(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_mean_of_link_nodes_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['z'] = np.array([ 0,  1,  2,  3,
...                               4,  5,  6,  7,
...                               8,  9, 10, 11])
>>> map_mean_of_link_nodes_to_link(rmg, 'z')
array([  0.5,   1.5,   2.5,   2. ,   3. ,   4. ,   5. ,   4.5,   5.5,
         6.5,   6. ,   7. ,   8. ,   9. ,   8.5,   9.5,  10.5])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_mean_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  0.5,   1.5,   2.5,   2. ,   3. ,   4. ,   5. ,   4.5,   5.5,
         6.5,   6. ,   7. ,   8. ,   9. ,   8.5,   9.5,  10.5])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

map_mean_of_patch_nodes_to_patch(grid, var_name, ignore_closed_nodes=True, out=None)

Map the mean value of nodes around a patch to the patch.

Construction:

grid.map_mean_of_patch_nodes_to_patch(var_name,
                                      ignore_closed_nodes=True, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

ignore_closed_nodes : bool

If True, do not incorporate closed nodes into calc. If all nodes are masked at a patch, record zero if out is None or leave the existing value if out.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at patches.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_mean_of_patch_nodes_to_patch
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> map_mean_of_patch_nodes_to_patch(rmg, 'vals')
array([ 4.5, 3.5, 2.5,
        3.5, 2.5, 1.5])
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> rmg.status_at_node[rmg.node_x > 1.5] = CLOSED_BOUNDARY
>>> ans = np.zeros(6, dtype=float)
>>> _ = map_mean_of_patch_nodes_to_patch(rmg, 'vals', out=ans)
>>> ans 
array([ 4.5, 4. , 0. ,
        3.5, 3. , 0. ])

LLCATS: PINF NINF MAP

Map the minimum of a link’s nodes to the link.

map_min_of_link_nodes_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘var_name’ at both the “to” and “from” node. The minimum value of the two node values is then mapped to the link.

Construction:

grid.map_min_of_link_nodes_to_link(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_min_of_link_nodes_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[ 0,  1,  2,  3],
...                    [ 7,  6,  5,  4],
...                    [ 8,  9, 10, 11]])
>>> map_min_of_link_nodes_to_link(rmg, 'z')
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   6.,   5.,   4.,   7.,
         6.,   5.,   4.,   8.,   9.,  10.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_min_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   6.,   5.,   4.,   7.,
         6.,   5.,   4.,   8.,   9.,  10.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map the minimum value of a nodes’ links to the node.

map_min_of_node_links_to_node iterates across the grid and identifies the link values at each link connected to a node. This function finds the minimum value of ‘var_name’ of each set of links, and then maps this value to the node. Note no attempt is made to honor the directionality of the links.

Construction:

grid.map_min_of_node_links_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_min_of_node_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.arange(rmg.number_of_links)
>>> map_min_of_node_links_to_node(rmg, 'grad')
array([  0.,   0.,   1.,   2.,
         3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_min_of_node_links_to_node(rmg, 'grad', out=values_at_nodes)
>>> values_at_nodes
array([  0.,   0.,   1.,   2.,
         3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

map_min_of_patch_nodes_to_patch(grid, var_name, ignore_closed_nodes=True, out=None)

Map the minimum value of nodes around a patch to the patch.

Construction:

grid.map_min_of_patch_nodes_to_patch(var_name,
                                     ignore_closed_nodes=True, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

ignore_closed_nodes : bool

If True, do not incorporate closed nodes into calc. If all nodes are masked at a patch, record zero if out is None or leave the existing value if out.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at patches.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_min_of_patch_nodes_to_patch
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> map_min_of_patch_nodes_to_patch(rmg, 'vals')
array([ 4., 3., 2.,
        2., 1., 0.])
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> rmg.status_at_node[rmg.node_x > 1.5] = CLOSED_BOUNDARY
>>> ans = np.zeros(6, dtype=float)
>>> _ = map_min_of_patch_nodes_to_patch(rmg, 'vals', out=ans)
>>> ans 
array([ 4., 4., 0.,
        2., 2., 0.])

LLCATS: PINF NINF MAP

map_node_to_cell(grid, var_name, out=None)

Map values for nodes to cells.

map_node_to_cell iterates across the grid and identifies the all node values of ‘var_name’.

This function takes node values of ‘var_name’ and mapes that value to the corresponding cell area for each node.

Construction:

grid.map_node_to_cell(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at cells.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_node_to_cell
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z', np.arange(12.))
>>> map_node_to_cell(rmg, 'z')
array([ 5.,  6.])
>>> values_at_cells = rmg.empty(at='cell')
>>> rtn = map_node_to_cell(rmg, 'z', out=values_at_cells)
>>> values_at_cells
array([ 5.,  6.])
>>> rtn is values_at_cells
True

LLCATS: CINF NINF MAP

Map the largest magnitude of the links bringing flux into the node to the node.

map_upwind_node_link_max_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node, then maps the maximum magnitude of ‘var_name’ found on these links onto the node. If no upwind link is found, the value will be recorded as zero.

Construction:

grid.map_upwind_node_link_max_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_upwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> map_upwind_node_link_max_to_node(rmg, 'grad')
array([ 0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_upwind_node_link_max_to_node(rmg, 'grad',
...                                        out=values_at_nodes)
>>> values_at_nodes
array([ 0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the mean magnitude of the links bringing flux into the node to the node.

map_upwind_node_link_mean_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node, then maps the mean magnitude of ‘var_name’ found on these links onto the node. Links with zero values are not included in the means, and zeros are returned if no upwind links are found.

Construction:

grid.map_upwind_node_link_mean_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_upwind_node_link_mean_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                 -2., -3., -4., -5.,
...                                 -1., -2., -1.,
...                                 -1., -2., -3., -4.,
...                                 -1., -2., -1.])
>>> map_upwind_node_link_mean_to_node(rmg, 'grad')
array([ 0. ,  1. ,  2. ,  1. ,
        2. ,  2. ,  3. ,  3. ,
        1. ,  1.5,  2.5,  2.5])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_upwind_node_link_mean_to_node(rmg, 'grad',
...                                         out=values_at_nodes)
>>> values_at_nodes
array([ 0. ,  1. ,  2. ,  1. ,
        2. ,  2. ,  3. ,  3. ,
        1. ,  1.5,  2.5,  2.5])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the the value found in one link array to a node, based on the largest magnitude value of links carrying fluxes out of the node, found in a second node array or field.

map_downwind_node_link_max_to_node iterates across the grid and identifies the link control_values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node, then identifies the link with the maximum magnitude. The value of the second field ‘value_name’ at these links is then mapped onto the node. If no downwind link is found, the value will be recorded as zero.

Construction:

grid.map_value_at_downwind_node_link_max_to_node(control_name,
                                                 value_name, out=None)
Parameters:

control_name : array or field name

Values defined at nodes that dictate which end of the link to draw values from.

value_name : array or field name

Values defined at nodes from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_downwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> rmg.at_link['vals'] = np.arange(rmg.number_of_links, dtype=float)
>>> map_value_at_downwind_node_link_max_to_node(rmg, 'grad', 'vals')
array([  0.,   1.,   2.,   0.,
         7.,   8.,   9.,   0.,
        14.,  15.,  16.,   0.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_value_at_downwind_node_link_max_to_node(rmg, 'grad', 'vals',
...                                                   out=values_at_nodes)
>>> values_at_nodes
array([  0.,   1.,   2.,   0.,
         7.,   8.,   9.,   0.,
        14.,  15.,  16.,   0.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the the value found in one node array to a link, based on the maximum value found in a second node field or array.

map_value_at_max_node_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘control_name’ at both the “to” and “from” node. The value of ‘value_name’ at the node with the maximum value of the two values of ‘control_name’ is then mapped to the link.

Construction:

grid.map_value_at_max_node_to_link(control_name, value_name,
                                   out=None)
Parameters:

control_name : array or field name

Name of field defined at nodes or a node array that dictates which end of the link to draw values from.

value_name : array or field name

Name of field defined at nodes or node array from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_max_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[0, 1, 2, 3],
...                    [7, 6, 5, 4],
...                    [8, 9, 10, 11]])
>>> _ = rmg.add_field('node', 'vals_to_map',
...                   [[0, 10, 20, 30],
...                    [70, 60, 50, 40],
...                    [80, 90, 100, 110]])
>>> map_value_at_max_node_to_link(rmg, 'z', 'vals_to_map')
array([  10.,   20.,   30.,   70.,   60.,   50.,   40.,   70.,   60.,
         50.,   80.,   90.,  100.,  110.,   90.,  100.,  110.])

LLCATS: NINF LINF MAP

Map the the value found in one node array to a link, based on the minimum value found in a second node field or array.

map_value_at_min_node_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘control_name’ at both the “to” and “from” node. The value of ‘value_name’ at the node with the minimum value of the two values of ‘control_name’ is then mapped to the link.

Construction:

grid.map_value_at_min_node_to_link(control_name, value_name,
                                   out=None)
Parameters:

control_name : array or field name

Name of field defined at nodes or a node array that dictates which end of the link to draw values from.

value_name : array or field name

Name of field defined at nodes or node array from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_min_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[0, 1, 2, 3],
...                    [7, 6, 5, 4],
...                    [8, 9, 10, 11]])
>>> _ = rmg.add_field('node', 'vals_to_map',
...                   [[0, 10, 20, 30],
...                    [70, 60, 50, 40],
...                    [80, 90, 100, 110]])
>>> map_value_at_min_node_to_link(rmg, 'z', 'vals_to_map')
array([   0.,   10.,   20.,    0.,   10.,   20.,   30.,   60.,   50.,
         40.,   70.,   60.,   50.,   40.,   80.,   90.,  100.])

LLCATS: NINF LINF MAP

Map the the value found in one link array to a node, based on the largest magnitude value of links bringing fluxes into the node, found in a second node array or field.

map_upwind_node_link_max_to_node iterates across the grid and identifies the link control_values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node, then identifies the link with the maximum magnitude. The value of the second field ‘value_name’ at these links is then mapped onto the node. If no upwind link is found, the value will be recorded as zero.

Construction:

grid.map_value_at_upwind_node_link_max_to_node(control_name,
                                               value_name, out=None)
Parameters:

control_name : array or field name

Values defined at nodes that dictate which end of the link to draw values from.

value_name : array or field name

Values defined at nodes from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_upwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> rmg.at_link['vals'] = np.arange(rmg.number_of_links, dtype=float)
>>> map_value_at_upwind_node_link_max_to_node(rmg, 'grad', 'vals')
array([  0.,   0.,   1.,   2.,
         0.,   7.,   8.,   9.,
         0.,  14.,  15.,  16.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_value_at_upwind_node_link_max_to_node(rmg, 'grad', 'vals',
...                                                 out=values_at_nodes)
>>> values_at_nodes
array([  0.,   0.,   1.,   2.,
         0.,   7.,   8.,   9.,
         0.,  14.,  15.,  16.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Maximum value at the end of links.

Note

This method is deprecated as of Landlab version 1.0.

Use map_max_of_link_nodes_to_link() instead.

For each active link, finds and returns the maximum value of node_data at either of the two ends. Use this, for example, if you want to find the maximum value of water depth at linked pairs of nodes (by passing in an array of water depth values at nodes).

Parameters:

node_data : ndarray

Values at grid nodes.

Returns:

ndarray :

Maximum values whose length is the number of active links.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4), spacing=(1., 1.))
>>> h = np.array([ 2., 2., 8., 0.,
...                8., 0., 3., 0.,
...                5., 6., 8., 3.])
>>> grid.max_of_link_end_node_values(h)
array([ 2.,  8.,  8.,  3.,  3.,  6.,  8.])

Note that this method is deprecatd. The alternative is to use map_max_of_link_nodes_to_link.

>>> vals = grid.map_max_of_link_nodes_to_link(h)
>>> vals[grid.active_links]
array([ 2.,  8.,  8.,  3.,  3.,  6.,  8.])

LLCATS: DEPR LINF NINF CONN

move_origin(origin)[source]

Changes the x, y values of all nodes. Initially a grid will have an origin of 0,0, and all x,y values will be relative to 0,0. This will add origin[0] to all x values and origin[1] to all y values.

Note this is most likely useful when importing a DEM that has an absolute location, however it can be used generally.

Parameters:

origin : list of two float values, can be negative.

[x,y], where x is the value to add to all x values and y is the value to add to all y values

Examples

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 3), 1.0) # rows, columns, spacing
>>> rmg.node_x
array([ 0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.])
>>> rmg.node_y
array([ 0.,  0.,  0.,  1.,  1.,  1.,  2.,  2.,  2.,  3.,  3.,  3.])
>>> rmg.move_origin((5,1.5))
>>> rmg.node_x
array([ 5.,  6.,  7.,  5.,  6.,  7.,  5.,  6.,  7.,  5.,  6.,  7.])
>>> rmg.node_y
array([ 1.5,  1.5,  1.5,  2.5,  2.5,  2.5,  3.5,  3.5,  3.5,  4.5,  4.5,
4.5])

LLCATS: GINF MEAS

ndim

Number of spatial dimensions of the grid.

LLCATS: GINF

neighbors_at_node

Get neighboring nodes.

LLCATS: NINF CONN

node_at_cell

Node ID associated with grid cells.

Examples

>>> from landlab import RasterModelGrid, BAD_INDEX_VALUE
>>> grid = RasterModelGrid((4, 5))
>>> grid.node_at_cell 
array([ 6,  7,  8,
       11, 12, 13])

LLCATS: NINF CINF CONN

node_at_core_cell

Get array of nodes associated with core cells.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.status_at_node[8] = CLOSED_BOUNDARY
>>> mg.node_at_core_cell
array([ 6,  7, 11, 12, 13])

LLCATS: NINF CINF BC CONN

Get array of the node at each link head (to-node).

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.node_at_link_head[:5]
array([1, 2, 3, 4, 5])

LLCATS: NINF LINF CONN

Get array of the node at each link tail (from-node).

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.node_at_link_tail[:5]
array([0, 1, 2, 3, 0])

LLCATS: NINF LINF CONN

node_axis_coordinates(*args, **kwds)[source]

Get the coordinates of nodes along a particular axis.

Return node coordinates from a given axis (defaulting to 0). Axis numbering is the same as that for numpy arrays. That is, the zeroth axis is along the rows, and the first along the columns.

Parameters:

axis : int, optional

Coordinate axis.

Returns:

ndarray

Coordinates of nodes for a given axis.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.node_axis_coordinates(0) 
array([ 0., 0., 0., 0., 0.,
        1., 1., 1., 1., 1.,
        2., 2., 2., 2., 2.,
        3., 3., 3., 3., 3.])
>>> grid.node_axis_coordinates(1) 
array([ 0., 1., 2., 3., 4.,
        0., 1., 2., 3., 4.,
        0., 1., 2., 3., 4.,
        0., 1., 2., 3., 4.])

LLCATS: GINF NINF MEAS

node_is_boundary(ids, boundary_flag=None)[source]

Check if nodes are boundary nodes.

Check if nodes at given ids are boundary nodes. Use the boundary_flag to specify a particular boundary type status flag.

Parameters:

ids : ndarray

Node IDs to check.

boundary_flag : int, optional

A boundary type to check for.

Returns:

ndarray

Array of booleans indicating if nodes are boundary nodes.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5))
>>> mg.node_is_boundary([0, 6])
array([ True, False], dtype=bool)
>>> mg.node_is_boundary([0, 6], boundary_flag=CLOSED_BOUNDARY)
array([False, False], dtype=bool)

LLCATS: NINF BC

node_unit_vector_sum_x

Note

This method is deprecated as of Landlab version 0.5.

Use unit_vector_sum_xcomponent_at_node() instead.

LLCATS: DEPR NINF MEAS

node_unit_vector_sum_y

Note

This method is deprecated as of Landlab version 0.5.

Use unit_vector_sum_ycomponent_at_node() instead.

LLCATS: DEPR NINF MEAS

node_x

Get array of the x-coordinates of nodes.

See also

x_of_node
Exquivalent method.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.node_x.reshape((4, 5))
array([[  0.,   3.,   6.,   9.,  12.],
       [  0.,   3.,   6.,   9.,  12.],
       [  0.,   3.,   6.,   9.,  12.],
       [  0.,   3.,   6.,   9.,  12.]])

LLCATS: NINF MEAS

node_y

Get array of the y-coordinates of nodes.

LLCATS: NINF MEAS

nodes

Get node ids for the grid.

Examples

>>> from landlab import RadialModelGrid
>>> mg = RadialModelGrid(num_shells=1)
>>> mg.nodes
array([0, 1, 2, 3, 4, 5, 6])

LLCATS: NINF

number_of_active_faces

Total number of active faces.

Returns:

int

Total number of active faces in the grid.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.number_of_active_faces
7

The number of active faces is updated when a node status changes.

>>> from landlab import CLOSED_BOUNDARY
>>> grid.status_at_node[6] = CLOSED_BOUNDARY
>>> grid.number_of_active_faces
3

LLCATS: FINF BC

Number of active links.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.number_of_active_links
17
>>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge,
...              mg.nodes_at_bottom_edge):
...     mg.status_at_node[edge] = CLOSED_BOUNDARY
>>> mg.number_of_active_links
10

LLCATS: LINF BC

number_of_cells

Total number of cells.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_cells
6

LLCATS: CINF

number_of_core_cells

Number of core cells.

A core cell excludes all boundary cells.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_core_cells
6
>>> grid.status_at_node[7] = CLOSED_BOUNDARY
>>> grid.number_of_core_cells
5

LLCATS: CINF BC

number_of_core_nodes

Number of core nodes.

The number of core nodes on the grid (i.e., excluding all boundary nodes).

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_core_nodes
6
>>> grid.status_at_node[7] = CLOSED_BOUNDARY
>>> grid.number_of_core_nodes
5

LLCATS: NINF BC

number_of_corners

Total number of corners.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_corners
12

LLCATS: CNINF

number_of_elements(name)[source]

Number of instances of an element.

Get the number of instances of a grid element in a grid.

Parameters:

name : {‘node’, ‘cell’, ‘link’, ‘face’, ‘core_node’, ‘core_cell’,

‘active_link’, ‘active_face’}

Name of the grid element.

Returns:

int

Number of elements in the grid.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.number_of_elements('node')
20
>>> mg.number_of_elements('core_cell')
6
>>> mg.number_of_elements('link')
31
>>> mg.number_of_elements('active_link')
17
>>> mg.status_at_node[8] = CLOSED_BOUNDARY
>>> mg.number_of_elements('link')
31
>>> mg.number_of_elements('active_link')
13

LLCATS: GINF

number_of_faces

Total number of faces.

Returns:

int

Total number of faces in the grid.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.number_of_faces
7

LLCATS: FINF

number_of_faces_at_cell()[source]

Number of faces attached to each cell.

Examples

>>> from landlab import HexModelGrid
>>> hg = HexModelGrid(3, 3)
>>> hg.number_of_faces_at_cell()
array([6, 6])

LLCATS: FINF CINF CONN

Number of fixed links.

Examples

>>> from landlab import RasterModelGrid, FIXED_GRADIENT_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.number_of_fixed_links
0
>>> mg.status_at_node[mg.nodes_at_top_edge] = FIXED_GRADIENT_BOUNDARY
>>> mg.number_of_fixed_links
3

LLCATS: LINF BC

Total number of links.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.number_of_links
17

LLCATS: LINF

Number of links connected to each node.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 4))
>>> mg.number_of_links_at_node
array([2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2])

LLCATS: LINF NINF CONN

number_of_nodes

Total number of nodes.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_nodes
20

LLCATS: NINF

Return the number of patches at a link without a closed node.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((3, 3))
>>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY
>>> mg.patches_present_at_link
array([[ True, False],
       [ True, False],
       [ True, False],
       [ True,  True],
       [ True, False],
       [ True, False],
       [ True, False],
       [False, False],
       [False, False],
       [False, False],
       [False, False],
       [False, False]], dtype=bool)
>>> mg.number_of_patches_present_at_link
array([1, 1, 1, 2, 1, 1, 1, 0, 0, 0, 0, 0])

LLCATS: PINF LINF BC

number_of_patches_present_at_node

Return the number of patches at a node without a closed node.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((3, 3))
>>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY
>>> mg.patches_present_at_node
array([[ True, False, False, False],
       [ True,  True, False, False],
       [False,  True, False, False],
       [False, False, False,  True],
       [False, False,  True,  True],
       [False, False,  True, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False]], dtype=bool)
>>> mg.number_of_patches_present_at_node
array([1, 2, 1, 1, 2, 1, 0, 0, 0])

LLCATS: PINF NINF BC

open_boundary_nodes

Get array of open boundary nodes.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((4, 5), 1.)
>>> for edge in (mg.nodes_at_left_edge, mg.nodes_at_right_edge,
...              mg.nodes_at_bottom_edge):
...     mg.status_at_node[edge] = CLOSED_BOUNDARY
>>> mg.open_boundary_nodes
array([16, 17, 18])

LLCATS: NINF BC

A boolean array, False where a patch has a closed node or is missing.

The array is the same shape as patches_at_link(), and is designed to mask it.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((3, 3))
>>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY
>>> mg.patches_at_link
array([[ 0, -1],
       [ 1, -1],
       [ 0, -1],
       [ 0,  1],
       [ 1, -1],
       [ 0,  2],
       [ 1,  3],
       [ 2, -1],
       [ 2,  3],
       [ 3, -1],
       [ 2, -1],
       [ 3, -1]])
>>> mg.patches_present_at_link
array([[ True, False],
       [ True, False],
       [ True, False],
       [ True,  True],
       [ True, False],
       [ True, False],
       [ True, False],
       [False, False],
       [False, False],
       [False, False],
       [False, False],
       [False, False]], dtype=bool)
>>> 1 in mg.patches_at_link * mg.patches_present_at_link
True
>>> 2 in mg.patches_at_link * mg.patches_present_at_link
False

LLCATS: PINF LINF

patches_present_at_node

A boolean array, False where a patch has a closed node or is missing.

The array is the same shape as patches_at_node(), and is designed to mask it.

Note that in cases where patches may have more than 3 nodes (e.g., rasters), a patch is considered still present as long as at least 3 open nodes are present.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> mg = RasterModelGrid((3, 3))
>>> mg.status_at_node[mg.nodes_at_top_edge] = CLOSED_BOUNDARY
>>> mg.patches_at_node
array([[ 0, -1, -1, -1],
       [ 1,  0, -1, -1],
       [-1,  1, -1, -1],
       [ 2, -1, -1,  0],
       [ 3,  2,  0,  1],
       [-1,  3,  1, -1],
       [-1, -1, -1,  2],
       [-1, -1,  2,  3],
       [-1, -1,  3, -1]])
>>> mg.patches_present_at_node
array([[ True, False, False, False],
       [ True,  True, False, False],
       [False,  True, False, False],
       [False, False, False,  True],
       [False, False,  True,  True],
       [False, False,  True, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False]], dtype=bool)
>>> 1 in mg.patches_at_node * mg.patches_present_at_node
True
>>> 2 in mg.patches_at_node * mg.patches_present_at_node
False

LLCATS: PINF NINF

Resolve the xy-components of active links.

Note

This method is deprecated as of Landlab version 1.0.

Use no replacement() instead.

Resolves values provided defined on active links into the x and y directions. Returns values_along_x, values_along_y

LLCATS: LINF

Resolve the xy-components of links.

Resolves values provided defined on links into the x and y directions. Returns values_along_x, values_along_y

LLCATS: LINF

set_closed_nodes(*args, **kwargs)[source]

Make nodes closed boundaries.

Note

This method is deprecated as of Landlab version 1.0.

Use status_at_node() instead.

Sets the given nodes’ boundary condition statuses to CLOSED_BOUNDARY (==4), and resets the list of active links to reflect any changes.

LLCATS: DEPR NINF BC

set_nodata_nodes_to_closed(node_data, nodata_value)[source]

Make no-data nodes closed boundaries.

Sets node status to CLOSED_BOUNDARY for all nodes whose value of node_data is equal to the nodata_value.

Any links connected to CLOSED_BOUNDARY nodes are automatically set to INACTIVE_LINK boundary.

Parameters:

node_data : ndarray

Data values.

nodata_value : float

Value that indicates an invalid value.

Examples

The following example uses the following grid:

*--I--->o------>o------>o
^       ^       ^       ^
I       I       |       |
|       |       |       |
*--I--->*--I--->o------>o
^       ^       ^       ^
I       I       I       I
|       |       |       |
*--I--->*--I--->*--I--->*

Note

Links set to ACTIVE_LINK are not shown in this diagram.

* indicates the nodes that are set to CLOSED_BOUNDARY

o indicates the nodes that are set to CORE_NODE

I indicates the links that are set to INACTIVE_LINK

>>> import numpy as np
>>> import landlab as ll
>>> mg = ll.RasterModelGrid((3, 4), 1.0)
>>> mg.status_at_node
array([1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8)
>>> h = np.array([-9999, -9999, -9999, -9999, -9999, -9999, 12345.,
...     0., -9999, 0., 0., 0.])
>>> mg.set_nodata_nodes_to_closed(h, -9999)
>>> mg.status_at_node
array([4, 4, 4, 4, 4, 4, 0, 1, 4, 1, 1, 1], dtype=int8)

LLCATS: BC NINF

set_nodata_nodes_to_fixed_gradient(node_data, nodata_value)[source]

Make no-data nodes fixed gradient boundaries.

Set node status to FIXED_GRADIENT_BOUNDARY for all nodes whose value of node_data is equal to nodata_value.

Any links between FIXED_GRADIENT_BOUNDARY nodes and CORE_NODES are automatically set to FIXED_LINK boundary status.

Parameters:

node_data : ndarray

Data values.

nodata_value
: float

Value that indicates an invalid value.

LLCATS: BC NINF

set_nodata_nodes_to_inactive(*args, **kwargs)[source]

Make no-data nodes inactive.

Note

This method is deprecated as of Landlab version 0.2.

Set the status to CLOSED_BOUNDARY for all nodes whose value of node_data is equal to the nodata_value.

Parameters:

node_data : ndarray

Data values.

nodata_value
: float

Value that indicates an invalid value.

LLCATS: DEPR NINF BC

Get array of the status of all links.

LLCATS: BC LINF

status_at_node

Get array of the boundary status for each node.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> from landlab import FIXED_GRADIENT_BOUNDARY, FIXED_LINK
>>> mg = RasterModelGrid((4, 5), 1.)
>>> mg.status_at_node.reshape((4, 5))
array([[1, 1, 1, 1, 1],
       [1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1],
       [1, 1, 1, 1, 1]], dtype=int8)
>>> np.any(mg.status_at_link == FIXED_LINK)
False
>>> mg.status_at_node[mg.nodes_at_left_edge] = FIXED_GRADIENT_BOUNDARY
>>> mg.status_at_node.reshape((4, 5))
array([[2, 1, 1, 1, 1],
       [2, 0, 0, 0, 1],
       [2, 0, 0, 0, 1],
       [2, 1, 1, 1, 1]], dtype=int8)
>>> np.any(mg.status_at_link == FIXED_LINK)  # links auto-update
True

LLCATS: NINF BC

unit_vector_sum_xcomponent_at_node

Get array of x-component of unit vector sums at each node.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> len(grid.unit_vector_sum_xcomponent_at_node) == grid.number_of_nodes
True
>>> grid.unit_vector_sum_xcomponent_at_node
array([ 1.,  2.,  1.,  1.,  2.,  1.,  1.,  2.,  1.])

LLCATS: NINF MEAS

unit_vector_sum_ycomponent_at_node

Get array of y-component of unit vector sums at each node.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> len(grid.unit_vector_sum_ycomponent_at_node) == grid.number_of_nodes
True
>>> grid.unit_vector_sum_ycomponent_at_node
array([ 1.,  1.,  1.,  2.,  2.,  2.,  1.,  1.,  1.])

LLCATS: NINF MEAS

Get array of x-component of unit vector for links.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> len(grid.unit_vector_xcomponent_at_link) == grid.number_of_links + 1
True
>>> grid.unit_vector_xcomponent_at_link 
array([ 1.,  1.,  0.,  0.,  0.,
        1.,  1.,  0.,  0.,  0.,  1.,  1.,  0.])

LLCATS: LINF MEAS

Get array of y-component of unit vector for links.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> len(grid.unit_vector_ycomponent_at_link) == grid.number_of_links + 1
True
>>> grid.unit_vector_ycomponent_at_link 
array([ 0.,  0.,  1.,  1.,  1.,
        0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.])

LLCATS: LINF MEAS

Return an (nnodes, X) shape array of link IDs of which links are upwind of each node, according to values (field or array).

X is the maximum upwind links at any node. Nodes with fewer upwind links than this have additional slots filled with bad_index. Links are ordered anticlockwise from east.

Parameters:

values : str or array

Name of variable field defined at links, or array of values at links.

bad_index
: int

Index to place in array indicating no link.

Returns:

ndarray

Array of upwind link IDs

LLCATS: LINF NINF CONN

width_of_face

Width of grid faces.

Examples

>>> from landlab import RasterModelGrid, HexModelGrid
>>> mg = RasterModelGrid((3, 4), (1., 2.))
>>> mg.width_of_face
array([ 2.,  2.,  2.,  1.,  1.,  1.,  1.])
>>> mg = HexModelGrid(3, 3)
>>> np.allclose(mg.width_of_face, 0.57735027)
True

LLCATS: FINF MEAS

x_of_cell

Get array of the x-coordinates of nodes at cells.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.x_of_cell.reshape((2, 3))
array([[  3.,   6.,   9.],
       [  3.,   6.,   9.]])

LLCATS: CINF MEAS

x_of_face

Get array of the x-coordinates of face midpoints.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.x_of_face 
array([  3. ,   6. ,   9. ,   1.5,   4.5,   7.5,  10.5,
         3. ,   6. ,   9. ,   1.5,   4.5,   7.5,  10.5,
         3. ,   6. ,   9. ])

LLCATS: FINF MEAS

Get array of the x-coordinates of link midpoints.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.x_of_link 
array([  1.5,   4.5,   7.5,  10.5,   0. ,   3. ,   6. ,   9. ,  12. ,
         1.5,   4.5,   7.5,  10.5,   0. ,   3. ,   6. ,   9. ,  12. ,
         1.5,   4.5,   7.5,  10.5,   0. ,   3. ,   6. ,   9. ,  12. ,
         1.5,   4.5,   7.5,  10.5])

LLCATS: LINF MEAS

x_of_node

Get array of the x-coordinates of nodes.

LLCATS: NINF MEAS

y_of_cell

Get array of the y-coordinates of nodes at cells.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.y_of_cell.reshape((2, 3))
array([[ 2.,  2.,  2.],
       [ 4.,  4.,  4.]])

LLCATS: CINF MEAS

y_of_face

Get array of the y-coordinates of face midpoints.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.y_of_face 
array([ 1.,  1.,  1.,  2.,  2.,  2.,  2.,  3.,  3.,  3.,
        4.,  4.,  4.,  4.,  5.,  5.,  5.])

LLCATS: FINF MEAS

Get array of the y-coordinates of link midpoints.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.y_of_link 
array([ 0.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,
        2.,  2.,  2.,  2.,  3.,  3.,  3.,  3.,  3.,
        4.,  4.,  4.,  4.,  5.,  5.,  5.,  5.,  5.,
        6.,  6.,  6.,  6.])

LLCATS: LINF MEAS

y_of_node

Get array of the y-coordinates of nodes.

See also

node_y
Exquivalent method.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5), (2., 3.))
>>> mg.y_of_node.reshape((4, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 4.,  4.,  4.,  4.,  4.],
       [ 6.,  6.,  6.,  6.,  6.]])

LLCATS: NINF MEAS

Separate a pair of links with vector values into x and y components.

The concept here is that a pair of adjacent links attached to a node are projections of a ‘true’ but unknown vector. This function finds and returns the x and y components of this true vector. The trivial case is the situation in which the two links are orthogonal and aligned with the grid axes, in which case the vectors of these two links are the x and y components.

Parameters:

L1, L2 : float

Values (magnitudes) associated with the two links

b1x, b1y, b2x, b2y : float

Unit vectors of the two links

Returns:

ax, ay : float

x and y components of the ‘true’ vector

Notes

The function does an inverse vector projection. Suppose we have a given ‘true’ vector \(a\), and we want to project it onto two other lines with unit vectors (b1x,b1y) and (b2x,b2y). In the context of Landlab, the ‘true’ vector is some unknown vector quantity, which might for example represent the local water flow velocity. The lines represent two adjacent links in the grid.

Let \(\mathbf{a}\) be the true vector, \(\mathbf{B}\) be a different vector with unit vector \(\mathbf{b}\), and \(L\) be the scalar projection of a onto B. Then,

..math:

L = \mathbf{a} \dot \mathbf{b} = a_x b_x + a_y b_y,

where \((a_x,a_y)\) are the components of a and \((b_x,b_y)\) are the components of the unit vector b.

In this case, we know b (the link unit vector), and we want to know the x and y components of a. The problem is that we have one equation and two unknowns (\(a_x\) and \(a_y\)). But we can solve this if we have two vectors, both of which are projections of a. Using the subscripts 1 and 2 to denote the two vectors, we can obtain equations for both \(a_x\) and \(a_y\):

..math:

a_x = L_1 / b_{1x} - a_y b_{1y} / b_{1x}

a_y = L_2 / b_{2y} - a_x b_{2x} / b_{2y}

Substituting the second into the first,

..math:

a_x = [L_1/b_{1x}-L_2 b_{1y}/(b_{1x} b_{2y})] / [1-b_{1y} b_{2x}/(b_{1x} b_{2y})]

Hence, we find the original vector \((a_x,a_y)\) from two links with unit vectors \((b_{1x},b_{1y})\) and \((b_{2x},b_{2y})\) and associated values \(L_1\) and \(L_2\).

Note that the above equations require that \(b_{1x}>0\) and \(b_{2y}>0\). If this isn’t the case, we invert the order of the two links, which requires \(b_{2x}>0\) and \(b_{1y}>0\). If none of these conditions is met, then we have a degenerate case.

Examples

The following example represents the active links in a 7-node hexagonal grid, with just one core node. The ‘true’ vector has a magnitude of 5 units and an orientation of 30 degrees, pointing up and to the right (i.e., the postive-x and postive-y quadrant), so that its vector components are 4 (x) and 3 (y) (in other words, it is a 3-4-5 triangle). The values assigned to L below are the projection of that true vector onto the six link vectors. The algorithm should recover the correct vector component values of 4 and 3. The FOR loop examines each pair of links in turn.

>>> import numpy as np
>>> from landlab.grid.base import find_true_vector_from_link_vector_pair
>>> bx = np.array([0.5, -0.5, -1., -0.5, 1., 0.5])
>>> by = np.array([0.866, 0.866, 0., -0.866, 0., -0.866])
>>> L = np.array([4.6, 0.6, -4., -4.6, 4., -0.6])
>>> for i in range(5):
...     ax, ay = find_true_vector_from_link_vector_pair(
...         L[i], L[i+1], bx[i], by[i], bx[i+1], by[i+1])
...     round(ax,1), round(ay,1)
(4.0, 3.0)
(4.0, 3.0)
(4.0, 3.0)
(4.0, 3.0)
(4.0, 3.0)

Mapping data between different grid elements

Map values from one grid element to another.

Grid mapping functions

map_link_head_node_to_link(grid, var_name[, out]) Map values from a link head nodes to links.
map_link_tail_node_to_link(grid, var_name[, out]) Map values from a link tail nodes to links.
map_min_of_link_nodes_to_link(grid, var_name) Map the minimum of a link’s nodes to the link.
map_max_of_link_nodes_to_link(grid, var_name) Map the maximum of a link’s nodes to the link.
map_mean_of_link_nodes_to_link(grid, var_name) Map the mean of a link’s nodes to the link.
map_value_at_min_node_to_link(grid, ...[, out]) Map the the value found in one node array to a link, based on the minimum value found in a second node field or array.
map_value_at_max_node_to_link(grid, ...[, out]) Map the the value found in one node array to a link, based on the maximum value found in a second node field or array.
map_node_to_cell(grid, var_name[, out]) Map values for nodes to cells.
map_min_of_node_links_to_node(grid, var_name) Map the minimum value of a nodes’ links to the node.
map_max_of_node_links_to_node(grid, var_name) Map the maximum value of a nodes’ links to the node.
map_upwind_node_link_max_to_node(grid, var_name) Map the largest magnitude of the links bringing flux into the node to the node.
map_downwind_node_link_max_to_node(grid, ...) Map the largest magnitude of the links carrying flux from the node to the node.
map_upwind_node_link_mean_to_node(grid, var_name) Map the mean magnitude of the links bringing flux into the node to the node.
map_downwind_node_link_mean_to_node(grid, ...) Map the mean magnitude of the links carrying flux out of the node to the node.
map_value_at_upwind_node_link_max_to_node(...) Map the the value found in one link array to a node, based on the largest magnitude value of links bringing fluxes into the node, found in a second node array or field.
map_value_at_downwind_node_link_max_to_node(...) Map the the value found in one link array to a node, based on the largest magnitude value of links carrying fluxes out of the node, found in a second node array or field.
dummy_func_to_demonstrate_docstring_modification(...) A dummy function to demonstrate automated docstring changes.

Each link has a tail and head node. The tail nodes are located at the start of a link, while the head nodes are located at end of a link.

Below, the numbering scheme for links in RasterModelGrid is illustrated with an example of a four-row by five column grid (4x5). In this example, each * (or X) is a node, the lines represent links, and the ^ and > symbols indicate the direction and head of each link. Link heads in the RasterModelGrid always point in the cardinal directions North (N) or East (E).:

 *--27-->*--28-->*--29-->*--30-->*
 ^       ^       ^       ^       ^
22      23      24      25      26
 |       |       |       |       |
 *--18-->*--19-->*--20-->*--21-->*
 ^       ^       ^       ^       ^
 13      14      15      16     17
 |       |       |       |       |
 *---9-->*--10-->X--11-->*--12-->*
 ^       ^       ^       ^       ^
 4       5       6       7       8
 |       |       |       |       |
 *--0--->*---1-->*--2--->*---3-->*

For example, node ‘X’ has four link-neighbors. From south and going clockwise, these neighbors are [6, 10, 15, 11]. Both link 6 and link 10 have node ‘X’ as their ‘head’ node, while links 15 and 11 have node ‘X’ as their tail node.

dummy_func_to_demonstrate_docstring_modification(grid, some_arg)[source]

A dummy function to demonstrate automated docstring changes.

Construction:

dummy_func_to_demonstrate_docstring_modification(grid, some_arg)
Parameters:

grid : ModelGrid

A Landlab modelgrid.

some_arg : whatever

A dummy argument.

Examples

...

LLCATS: DEPR MAP

Map the largest magnitude of the links carrying flux from the node to the node.

map_downwind_node_link_max_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node, then maps the maximum magnitude of ‘var_name’ found on these links onto the node. If no downwind link is found, the value will be recorded as zero.

Construction:

map_downwind_node_link_max_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_downwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> map_downwind_node_link_max_to_node(rmg, 'grad')
array([ 1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_downwind_node_link_max_to_node(rmg, 'grad',
...                                        out=values_at_nodes)
>>> values_at_nodes
array([ 1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.,
        1.,  2.,  1.,  0.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the mean magnitude of the links carrying flux out of the node to the node.

map_downwind_node_link_mean_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node, then maps the mean magnitude of ‘var_name’ found on these links onto the node. Links with zero values are not included in the means, and zeros are returned if no upwind links are found.

Construction:

map_downwind_node_link_mean_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_downwind_node_link_mean_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                 -2., -3., -4., -5.,
...                                 -1., -2., -1.,
...                                 -1., -2., -3., -4.,
...                                 -1., -2., -1.])
>>> map_downwind_node_link_mean_to_node(rmg, 'grad')
array([ 1.5,  2.5,  2.5,  5. ,
        1. ,  2. ,  2. ,  4. ,
        1. ,  2. ,  1. ,  0. ])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_downwind_node_link_mean_to_node(rmg, 'grad',
...                                         out=values_at_nodes)
>>> values_at_nodes
array([ 1.5,  2.5,  2.5,  5. ,
        1. ,  2. ,  2. ,  4. ,
        1. ,  2. ,  1. ,  0. ])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map values from a link head nodes to links.

Iterate over a grid and identify the node at the head. For each link, the value of var_name at the head node is mapped to the corresponding link.

In a RasterModelGrid, each one node has two adjacent “link heads”. This means each node value is mapped to two corresponding links.

Construction:

map_link_head_node_to_link(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_link_head_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['z'] = np.array([ 0,  1,  2,  3,
...                               4,  5,  6,  7,
...                               8,  9, 10, 11])
>>> map_link_head_node_to_link(rmg, 'z')
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   5.,   6.,   7.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_link_head_node_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   5.,   6.,   7.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map values from a link tail nodes to links.

map_link_tail_node_to_link iterates across the grid and identifies the node at the “tail”, or the “from” node for each link. For each link, the value of ‘var_name’ at the “from” node is mapped to the corresponding link.

In a RasterModelGrid, each one node has two adjacent “link tails”. This means each node value is mapped to two corresponding links.

Construction:

map_link_tail_node_to_link(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_link_tail_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['z'] = np.array([ 0,  1,  2,  3,
...                               4,  5,  6,  7,
...                               8,  9, 10, 11])
>>> map_link_tail_node_to_link(rmg, 'z')
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   4.,   5.,   6.,   4.,
         5.,   6.,   7.,   8.,   9.,  10.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_link_tail_node_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   4.,   5.,   6.,   4.,
         5.,   6.,   7.,   8.,   9.,  10.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map the vector sum of links around a patch to the patch.

The resulting vector is returned as a length-2 list, with the two items being arrays of the x component and the y component of the resolved vectors at the patches, respectively.

Construction:

map_link_vector_sum_to_patch(grid, var_name, ignore_inctive_links=True,
                             out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

ignore_inactive_links : bool

If True, do not incorporate inactive links into calc. If all links are inactive at a patch, record zero if out is None or leave the existing value if out.

out : len-2 list of npatches-long arrays, optional

Buffer to place mapped values into or None to create a new array.

Returns:

len-2 list of arrays

[x_component_of_link_vals_at_patch, y_component_of_link_vals_at_patch].

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_link_vector_sum_to_patch
>>> from landlab import HexModelGrid
>>> from landlab import CLOSED_BOUNDARY, CORE_NODE, INACTIVE_LINK
>>> mg = HexModelGrid(4, 3)
>>> interior_nodes = mg.status_at_node == CORE_NODE
>>> exterior_nodes = mg.status_at_node != CORE_NODE

Add a ring of closed nodes at the edge:

>>> mg.status_at_node[exterior_nodes] = CLOSED_BOUNDARY

This gives us 5 core nodes, 7 active links, and 3 present patches

>>> (mg.number_of_core_nodes == 5 and mg.number_of_active_links == 7)
True
>>> A = mg.add_ones('link', 'vals')
>>> A.fill(9.)  # any old values on the inactive links
>>> A[mg.active_links] = np.array([ 1., -1.,  1., -1., -1., -1., -1.])

This setup should give present patch 0 pure east, patch 1 zero (vorticity), and patch 2 westwards and downwards components.

>>> xcomp, ycomp = map_link_vector_sum_to_patch(mg, 'vals')
>>> np.allclose(xcomp[[6, 9, 10]], [2., 0., -1])
True
>>> np.allclose(ycomp[[6, 9, 10]]/np.sqrt(3.), [0., 0., -1.])
True

These are the patches with INACTIVE_LINKs on all three sides:

>>> absent_patches = np.array([0, 1, 2, 4, 8, 11, 12, 15, 16, 17, 18])
>>> np.allclose(xcomp[absent_patches], 0.)
True
>>> np.allclose(ycomp[absent_patches], 0.)
True

Now demonstrate the remaining functionality:

>>> A = mg.at_link['vals'].copy()
>>> A.fill(1.)
>>> _ = map_link_vector_sum_to_patch(mg, A, ignore_inactive_links=False,
...                                  out=[xcomp, ycomp])
>>> np.allclose(xcomp[absent_patches], 0.)
False
>>> np.allclose(ycomp[absent_patches], 0.)
False

LLCATS: PINF LINF MAP

Map the maximum of a link’s nodes to the link.

map_max_of_link_nodes_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘var_name’ at both the “to” and “from” node. The maximum value of the two node values is then mapped to the link.

Construction:

map_max_of_link_nodes_to_link(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_max_of_link_nodes_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[0, 1, 2, 3],
...                    [7, 6, 5, 4],
...                    [8, 9, 10, 11]])
>>> map_max_of_link_nodes_to_link(rmg, 'z')
array([  1.,   2.,   3.,   7.,   6.,   5.,   4.,   7.,   6.,   5.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_max_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  1.,   2.,   3.,   7.,   6.,   5.,   4.,   7.,   6.,   5.,   8.,
         9.,  10.,  11.,   9.,  10.,  11.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map the maximum value of a nodes’ links to the node.

map_max_of_node_links_to_node iterates across the grid and identifies the link values at each link connected to a node. This function finds the maximum value of ‘var_name’ of each set of links, and then maps this value to the node. Note no attempt is made to honor the directionality of the links.

Construction:

map_max_of_node_links_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_max_of_node_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.arange(rmg.number_of_links)
>>> map_max_of_node_links_to_node(rmg, 'grad')
array([  3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.,
        14.,  15.,  16.,  16.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_max_of_node_links_to_node(rmg, 'grad', out=values_at_nodes)
>>> values_at_nodes
array([  3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.,
        14.,  15.,  16.,  16.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

map_max_of_patch_nodes_to_patch(grid, var_name, ignore_closed_nodes=True, out=None)[source]

Map the maximum value of nodes around a patch to the patch.

Construction:

map_max_of_patch_nodes_to_patch(grid, var_name,
                                ignore_closed_nodes=True, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

ignore_closed_nodes : bool

If True, do not incorporate closed nodes into calc. If all nodes are masked at a patch, record zero if out is None or leave the existing value if out.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at patches.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_max_of_patch_nodes_to_patch
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 3., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> map_max_of_patch_nodes_to_patch(rmg, 'vals')
array([ 5., 4., 3.,
        4., 4., 3.])
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 3., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> rmg.status_at_node[rmg.node_x > 1.5] = CLOSED_BOUNDARY
>>> ans = np.zeros(6, dtype=float)
>>> _ = map_max_of_patch_nodes_to_patch(rmg, 'vals', out=ans)
>>> ans 
array([ 5., 4., 0.,
        4., 4., 0.])

LLCATS: PINF NINF MAP

Map the mean of a link’s nodes to the link.

map_mean_of_link_nodes_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function takes the sum of the two values of ‘var_name’ at both the “to” and “from” node. The average value of the two node values of ‘var_name’ is then mapped to the link.

Construction:

map_mean_of_link_nodes_to_link(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_mean_of_link_nodes_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['z'] = np.array([ 0,  1,  2,  3,
...                               4,  5,  6,  7,
...                               8,  9, 10, 11])
>>> map_mean_of_link_nodes_to_link(rmg, 'z')
array([  0.5,   1.5,   2.5,   2. ,   3. ,   4. ,   5. ,   4.5,   5.5,
         6.5,   6. ,   7. ,   8. ,   9. ,   8.5,   9.5,  10.5])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_mean_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  0.5,   1.5,   2.5,   2. ,   3. ,   4. ,   5. ,   4.5,   5.5,
         6.5,   6. ,   7. ,   8. ,   9. ,   8.5,   9.5,  10.5])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

map_mean_of_patch_nodes_to_patch(grid, var_name, ignore_closed_nodes=True, out=None)[source]

Map the mean value of nodes around a patch to the patch.

Construction:

map_mean_of_patch_nodes_to_patch(grid, var_name,
                                 ignore_closed_nodes=True, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

ignore_closed_nodes : bool

If True, do not incorporate closed nodes into calc. If all nodes are masked at a patch, record zero if out is None or leave the existing value if out.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at patches.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_mean_of_patch_nodes_to_patch
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> map_mean_of_patch_nodes_to_patch(rmg, 'vals')
array([ 4.5, 3.5, 2.5,
        3.5, 2.5, 1.5])
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> rmg.status_at_node[rmg.node_x > 1.5] = CLOSED_BOUNDARY
>>> ans = np.zeros(6, dtype=float)
>>> _ = map_mean_of_patch_nodes_to_patch(rmg, 'vals', out=ans)
>>> ans 
array([ 4.5, 4. , 0. ,
        3.5, 3. , 0. ])

LLCATS: PINF NINF MAP

Map the minimum of a link’s nodes to the link.

map_min_of_link_nodes_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘var_name’ at both the “to” and “from” node. The minimum value of the two node values is then mapped to the link.

Construction:

map_min_of_link_nodes_to_link(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_min_of_link_nodes_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[ 0,  1,  2,  3],
...                    [ 7,  6,  5,  4],
...                    [ 8,  9, 10, 11]])
>>> map_min_of_link_nodes_to_link(rmg, 'z')
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   6.,   5.,   4.,   7.,
         6.,   5.,   4.,   8.,   9.,  10.])
>>> values_at_links = rmg.empty(at='link')
>>> rtn = map_min_of_link_nodes_to_link(rmg, 'z', out=values_at_links)
>>> values_at_links
array([  0.,   1.,   2.,   0.,   1.,   2.,   3.,   6.,   5.,   4.,   7.,
         6.,   5.,   4.,   8.,   9.,  10.])
>>> rtn is values_at_links
True

LLCATS: NINF LINF MAP

Map the minimum value of a nodes’ links to the node.

map_min_of_node_links_to_node iterates across the grid and identifies the link values at each link connected to a node. This function finds the minimum value of ‘var_name’ of each set of links, and then maps this value to the node. Note no attempt is made to honor the directionality of the links.

Construction:

map_min_of_node_links_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_min_of_node_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.arange(rmg.number_of_links)
>>> map_min_of_node_links_to_node(rmg, 'grad')
array([  0.,   0.,   1.,   2.,
         3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_min_of_node_links_to_node(rmg, 'grad', out=values_at_nodes)
>>> values_at_nodes
array([  0.,   0.,   1.,   2.,
         3.,   4.,   5.,   6.,
        10.,  11.,  12.,  13.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

map_min_of_patch_nodes_to_patch(grid, var_name, ignore_closed_nodes=True, out=None)[source]

Map the minimum value of nodes around a patch to the patch.

Construction:

map_min_of_patch_nodes_to_patch(grid, var_name,
                                ignore_closed_nodes=True, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

ignore_closed_nodes : bool

If True, do not incorporate closed nodes into calc. If all nodes are masked at a patch, record zero if out is None or leave the existing value if out.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at patches.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_min_of_patch_nodes_to_patch
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> map_min_of_patch_nodes_to_patch(rmg, 'vals')
array([ 4., 3., 2.,
        2., 1., 0.])
>>> rmg.at_node['vals'] = np.array([5., 4., 3., 2.,
...                                 5., 4., 3., 2.,
...                                 3., 2., 1., 0.])
>>> rmg.status_at_node[rmg.node_x > 1.5] = CLOSED_BOUNDARY
>>> ans = np.zeros(6, dtype=float)
>>> _ = map_min_of_patch_nodes_to_patch(rmg, 'vals', out=ans)
>>> ans 
array([ 4., 4., 0.,
        2., 2., 0.])

LLCATS: PINF NINF MAP

map_node_to_cell(grid, var_name, out=None)[source]

Map values for nodes to cells.

map_node_to_cell iterates across the grid and identifies the all node values of ‘var_name’.

This function takes node values of ‘var_name’ and mapes that value to the corresponding cell area for each node.

Construction:

map_node_to_cell(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at nodes.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at cells.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_node_to_cell
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z', np.arange(12.))
>>> map_node_to_cell(rmg, 'z')
array([ 5.,  6.])
>>> values_at_cells = rmg.empty(at='cell')
>>> rtn = map_node_to_cell(rmg, 'z', out=values_at_cells)
>>> values_at_cells
array([ 5.,  6.])
>>> rtn is values_at_cells
True

LLCATS: CINF NINF MAP

Map the largest magnitude of the links bringing flux into the node to the node.

map_upwind_node_link_max_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node, then maps the maximum magnitude of ‘var_name’ found on these links onto the node. If no upwind link is found, the value will be recorded as zero.

Construction:

map_upwind_node_link_max_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_upwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> map_upwind_node_link_max_to_node(rmg, 'grad')
array([ 0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_upwind_node_link_max_to_node(rmg, 'grad',
...                                        out=values_at_nodes)
>>> values_at_nodes
array([ 0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.,
        0.,  1.,  2.,  1.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the mean magnitude of the links bringing flux into the node to the node.

map_upwind_node_link_mean_to_node iterates across the grid and identifies the link values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node, then maps the mean magnitude of ‘var_name’ found on these links onto the node. Links with zero values are not included in the means, and zeros are returned if no upwind links are found.

Construction:

map_upwind_node_link_mean_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_upwind_node_link_mean_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                 -2., -3., -4., -5.,
...                                 -1., -2., -1.,
...                                 -1., -2., -3., -4.,
...                                 -1., -2., -1.])
>>> map_upwind_node_link_mean_to_node(rmg, 'grad')
array([ 0. ,  1. ,  2. ,  1. ,
        2. ,  2. ,  3. ,  3. ,
        1. ,  1.5,  2.5,  2.5])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_upwind_node_link_mean_to_node(rmg, 'grad',
...                                         out=values_at_nodes)
>>> values_at_nodes
array([ 0. ,  1. ,  2. ,  1. ,
        2. ,  2. ,  3. ,  3. ,
        1. ,  1.5,  2.5,  2.5])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the the value found in one link array to a node, based on the largest magnitude value of links carrying fluxes out of the node, found in a second node array or field.

map_downwind_node_link_max_to_node iterates across the grid and identifies the link control_values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links carrying flux out of the node, then identifies the link with the maximum magnitude. The value of the second field ‘value_name’ at these links is then mapped onto the node. If no downwind link is found, the value will be recorded as zero.

Construction:

map_value_at_downwind_node_link_max_to_node(grid, control_name,
                                            value_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

control_name : array or field name

Values defined at nodes that dictate which end of the link to draw values from.

value_name : array or field name

Values defined at nodes from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_downwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> rmg.at_link['vals'] = np.arange(rmg.number_of_links, dtype=float)
>>> map_value_at_downwind_node_link_max_to_node(rmg, 'grad', 'vals')
array([  0.,   1.,   2.,   0.,
         7.,   8.,   9.,   0.,
        14.,  15.,  16.,   0.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_value_at_downwind_node_link_max_to_node(rmg, 'grad', 'vals',
...                                                   out=values_at_nodes)
>>> values_at_nodes
array([  0.,   1.,   2.,   0.,
         7.,   8.,   9.,   0.,
        14.,  15.,  16.,   0.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Map the the value found in one node array to a link, based on the maximum value found in a second node field or array.

map_value_at_max_node_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘control_name’ at both the “to” and “from” node. The value of ‘value_name’ at the node with the maximum value of the two values of ‘control_name’ is then mapped to the link.

Construction:

map_value_at_max_node_to_link(grid, control_name, value_name,
                              out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

control_name : array or field name

Name of field defined at nodes or a node array that dictates which end of the link to draw values from.

value_name : array or field name

Name of field defined at nodes or node array from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_max_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[0, 1, 2, 3],
...                    [7, 6, 5, 4],
...                    [8, 9, 10, 11]])
>>> _ = rmg.add_field('node', 'vals_to_map',
...                   [[0, 10, 20, 30],
...                    [70, 60, 50, 40],
...                    [80, 90, 100, 110]])
>>> map_value_at_max_node_to_link(rmg, 'z', 'vals_to_map')
array([  10.,   20.,   30.,   70.,   60.,   50.,   40.,   70.,   60.,
         50.,   80.,   90.,  100.,  110.,   90.,  100.,  110.])

LLCATS: NINF LINF MAP

Map the the value found in one node array to a link, based on the minimum value found in a second node field or array.

map_value_at_min_node_to_link iterates across the grid and identifies the node values at both the “head” and “tail” of a given link. This function evaluates the value of ‘control_name’ at both the “to” and “from” node. The value of ‘value_name’ at the node with the minimum value of the two values of ‘control_name’ is then mapped to the link.

Construction:

map_value_at_min_node_to_link(grid, control_name, value_name,
                              out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

control_name : array or field name

Name of field defined at nodes or a node array that dictates which end of the link to draw values from.

value_name : array or field name

Name of field defined at nodes or node array from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at links.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_min_node_to_link
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('node', 'z',
...                   [[0, 1, 2, 3],
...                    [7, 6, 5, 4],
...                    [8, 9, 10, 11]])
>>> _ = rmg.add_field('node', 'vals_to_map',
...                   [[0, 10, 20, 30],
...                    [70, 60, 50, 40],
...                    [80, 90, 100, 110]])
>>> map_value_at_min_node_to_link(rmg, 'z', 'vals_to_map')
array([   0.,   10.,   20.,    0.,   10.,   20.,   30.,   60.,   50.,
         40.,   70.,   60.,   50.,   40.,   80.,   90.,  100.])

LLCATS: NINF LINF MAP

Map the the value found in one link array to a node, based on the largest magnitude value of links bringing fluxes into the node, found in a second node array or field.

map_upwind_node_link_max_to_node iterates across the grid and identifies the link control_values at each link connected to a node. It then uses the link_dirs_at_node data structure to identify links bringing flux into the node, then identifies the link with the maximum magnitude. The value of the second field ‘value_name’ at these links is then mapped onto the node. If no upwind link is found, the value will be recorded as zero.

Construction:

map_value_at_upwind_node_link_max_to_node(grid, control_name,
                                          value_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

control_name : array or field name

Values defined at nodes that dictate which end of the link to draw values from.

value_name : array or field name

Values defined at nodes from which values are drawn, based on control_name.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.mappers import map_value_at_upwind_node_link_max_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> rmg.at_link['grad'] = np.array([-1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.,
...                                  0.,  0.,  0.,  0.,
...                                 -1., -2., -1.])
>>> rmg.at_link['vals'] = np.arange(rmg.number_of_links, dtype=float)
>>> map_value_at_upwind_node_link_max_to_node(rmg, 'grad', 'vals')
array([  0.,   0.,   1.,   2.,
         0.,   7.,   8.,   9.,
         0.,  14.,  15.,  16.])
>>> values_at_nodes = rmg.add_empty('node', 'z')
>>> rtn = map_value_at_upwind_node_link_max_to_node(rmg, 'grad', 'vals',
...                                                 out=values_at_nodes)
>>> values_at_nodes
array([  0.,   0.,   1.,   2.,
         0.,   7.,   8.,   9.,
         0.,  14.,  15.,  16.])
>>> rtn is values_at_nodes
True

LLCATS: NINF LINF MAP

Gradient calculation functions

Calculate gradients of quantities over links.

Gradient calculation functions

calc_grad_at_active_link(\*args, \*\*kwargs) Calculate gradients of node values over active links.
calc_grad_at_link(grid, vals, \*args, \*\*kwds) Calculate gradients of node values at links.
calculate_gradients_at_faces(\*args, \*\*kwargs) Calculate gradients of node values over faces.
calculate_diff_at_links(\*args, \*\*kwargs) Calculate differences of node values over links.
calculate_diff_at_active_links(\*args, \*\*kwargs) Calculate differences of node values over active links.
calc_aspect_at_node(grid, slope_component_tuple=None, elevs='topographic__elevation', unit='degrees', ignore_closed_nodes=True)[source]

Get array of aspect of a surface.

Calculates at returns the aspect of a surface. Aspect is returned as radians clockwise of north, unless input parameter units is set to ‘degrees’.

If slope_component_tuple is provided, i.e., (slope_x, slope_y), the aspect will be calculated from these data.

If it is not, it will be derived from elevation data at the nodes, which can either be a string referring to a grid field (default: ‘topographic__elevation’), or an nnodes-long numpy array of the values themselves.

If ignore_closed_nodes is False, all proximal elevation values will be used in the calculation. If True, only unclosed nodes are used.

Parameters:

grid : ModelGrid

A ModelGrid.

slope_component_tuple : (slope_x_array, slope_y_array) (optional)

Tuple of components of slope in the x and y directions, defined on nodes, if already known. If not, provide elevs.

elevs : str or array (optional)

Node field name or node array of elevations. If slope_component_tuple is not provided, must be set, but unused otherwise.

unit : {‘degrees’, ‘radians’}

Controls the unit that the aspect is returned as.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 4))
>>> z = mg.node_x ** 2 + mg.node_y ** 2
>>> mg.calc_aspect_at_node(elevs=z)
array([ 225.        ,  240.16585039,  255.2796318 ,  258.69006753,
        209.83414961,  225.        ,  243.54632481,  248.77808974,
        194.7203682 ,  206.45367519,  225.        ,  231.94498651,
        191.30993247,  201.22191026,  218.05501349,  225.        ])
>>> z = z.max() - z
>>> mg.calc_aspect_at_node(elevs=z)
array([ 45.        ,  60.16585039,  75.2796318 ,  78.69006753,
        29.83414961,  45.        ,  63.54632481,  68.77808974,
        14.7203682 ,  26.45367519,  45.        ,  51.94498651,
        11.30993247,  21.22191026,  38.05501349,  45.        ])
>>> mg = RasterModelGrid((4, 4), (2., 3.))
>>> z = mg.node_x ** 2 + mg.node_y ** 2
>>> mg.calc_aspect_at_node(elevs=z)
array([ 236.30993247,  247.52001262,  259.97326008,  262.40535663,
        220.75264634,  234.41577266,  251.13402374,  255.29210302,
        201.54258265,  215.47930877,  235.73541937,  242.24162456,
        196.69924423,  209.43534223,  229.19345757,  236.30993247])

Note that a small amount of asymmetry arises at the grid edges due to the “missing” nodes beyond the edge of the grid.

LLCATS: NINF SURF

Calculate differences of node values over links.

Calculates the difference in quantity node_values at each link in the grid.

Construction:

calc_diff_at_link(grid, node_values, out=None)
Parameters:

grid : ModelGrid

A ModelGrid.

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray

Differences across links.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 3))
>>> z = np.zeros(9)
>>> z[4] = 1.
>>> rmg.calc_diff_at_link(z)
array([ 0.,  0.,  0.,  1.,  0.,  1., -1.,  0., -1.,  0.,  0.,  0.])

LLCATS: LINF GRAD

Calculate gradients of node values over active links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_grad_at_link() instead.

Calculates the gradient in quantity node values at each active link in the grid.

Construction:

calc_grad_at_active_link(grid, node_values, out=None)
Parameters:

grid : ModelGrid

A ModelGrid.

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray

Gradients across active links.

LLCATS: DEPR LINF GRAD

Calculate gradients of node values at links.

Calculates the gradient in node_values at each link in the grid, returning an array of length number_of_links.

Construction:

calc_grad_at_link(grid, node_values, out=None)
Parameters:

grid : ModelGrid

A ModelGrid.

node_values : ndarray or field name (x number of nodes)

Values at grid nodes.

out : ndarray, optional (x number of links)

Buffer to hold the result.

Returns:

ndarray

Gradients across active links.

Examples

>>> from landlab import RasterModelGrid
>>> rg = RasterModelGrid(3, 4, 10.0)
>>> z = rg.add_zeros('node', 'topographic__elevation')
>>> z[5] = 50.0
>>> z[6] = 36.0
>>> calc_grad_at_link(rg, z)  # there are 17 links
array([ 0. ,  0. ,  0. ,  0. ,  5. ,  3.6,  0. ,  5. , -1.4, -3.6,  0. ,
       -5. , -3.6,  0. ,  0. ,  0. ,  0. ])
>>> from landlab import HexModelGrid
>>> hg = HexModelGrid(3, 3, 10.0)
>>> z = hg.add_zeros('node', 'topographic__elevation', noclobber=False)
>>> z[4] = 50.0
>>> z[5] = 36.0
>>> calc_grad_at_link(hg, z)  # there are 11 faces
array([ 0. ,  0. ,  0. ,  5. ,  5. ,  3.6,  3.6,  0. ,  5. , -1.4, -3.6,
        0. , -5. , -5. , -3.6, -3.6,  0. ,  0. ,  0. ])

LLCATS: LINF GRAD

calc_grad_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, unit_normal=None, slope_magnitude=None)[source]

Calculate the components of the gradient at each patch.

If ignore_closed_nodes is True, closed nodes do not affect gradient calculations. If a closed node is present in a patch, the patch gradient is set to zero in both x and y directions.

Parameters:

grid : ModelGrid

A ModelGrid.

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

unit_normal : array with shape (num_patches, 3) (optional)

The unit normal vector to each patch, if already known.

slope_magnitude : array with size num_patches (optional)

The slope of each patch, if already known.

Returns:

gradient_tuple : (x_component_at_patch, y_component_at_patch)

Len-2 tuple of arrays giving components of gradient in the x and y directions, in the units of units.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_y
>>> (x_grad, y_grad) = mg.calc_grad_at_patch(elevs=z)
>>> np.allclose(y_grad, np.pi / 4.)
True
>>> np.allclose(x_grad, 0.)
True

LLCATS: PINF GRAD

Calculate gradients at active links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_grad_at_link() instead.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> z = np.array([0., 0., 0., 0.,
...               1., 1., 1., 1.,
...               3., 3., 3., 3.])
>>> grid.calc_grad_of_active_link(z)
array([ 1.,  1.,  0.,  0.,  0.,  2.,  2.])

This method is deprecated. Instead, use calc_grad_at_link.

>>> vals = grid.calc_grad_at_link(z)
>>> vals[grid.active_links]
array([ 1.,  1.,  0.,  0.,  0.,  2.,  2.])

LLCATS: DEPR

calc_slope_at_node(grid, elevs='topographic__elevation', method='patch_mean', ignore_closed_nodes=True, return_components=False, **kwds)[source]

Array of slopes at nodes, averaged over neighboring patches.

Produces a value for node slope (i.e., mean gradient magnitude) at each node in a manner analogous to a GIS-style slope map. It averages the gradient on each of the patches surrounding the node, creating a value for node slope that better incorporates nonlocal elevation information. Directional information can still be returned through use of the return_components keyword.

Note that under these definitions, it is not always true that:

mag, cmp = mg.calc_slope_at_node(z)
mag ** 2 == cmp[0] ** 2 + cmp[1] ** 2  # not always true

If ignore_closed_nodes is False, all proximal elevation values will be used in the calculation. If True, only unclosed nodes are used.

Parameters:

grid : ModelGrid

A ModelGrid.

elevs : str or ndarray, optional

Field name or array of node values.

method : {‘patch_mean’, ‘Horn’}

By equivalence to the raster version, ‘patch_mean’ returns a scalar mean on the patches; ‘Horn’ returns a vector mean on the patches.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

return_components : bool

If True, return a tuple, (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If false, return an array of floats of the slope magnitude.

Returns:

float array or length-2 tuple of float arrays

If return_components, returns (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If not return_components, returns an array of slope magnitudes.

Examples

>>> import numpy as np
>>> from landlab import RadialModelGrid, RasterModelGrid
>>> mg = RasterModelGrid((4, 5), 1.)
>>> z = mg.node_x
>>> slopes = mg.calc_slope_at_node(elevs=z)
>>> np.allclose(slopes, 45. / 180. * np.pi)
True
>>> mg = RasterModelGrid((4, 5), 1.)
>>> z = - mg.node_y
>>> slope_mag, cmp = mg.calc_slope_at_node(elevs=z,
...                                        return_components=True)
>>> np.allclose(slope_mag, np.pi / 4.)
True
>>> np.allclose(cmp[0], 0.)
True
>>> np.allclose(cmp[1], - np.pi / 4.)
True
>>> mg = RadialModelGrid(num_shells=9)
>>> z = mg.radius_at_node
>>> slopes = mg.calc_slope_at_node(elevs=z)
>>> mean_ring_slope = []
>>> for i in range(10):
...     mean_ring_slope.append(
...         slopes[np.isclose(mg.radius_at_node, i)].mean())

Notice the small amounts of numerical error here:

>>> target_mean_ring_slope = [0.85707194785013108, 0.79363155567711452,
...                           0.77922185867135429, 0.78359813570962411,
...                           0.78433070957439543, 0.78452745144699965,
...                           0.78477643475446901, 0.78506472422668094,
...                           0.78505793680521629, 0.78661256633611021]
>>> np.allclose(mean_ring_slope, target_mean_ring_slope)
True

LLCATS: NINF GRAD SURF

calc_slope_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, unit_normal=None)[source]

Calculate the slope (positive magnitude of gradient) at patches.

If ignore_closed_nodes is True, closed nodes do not affect slope calculations. If a closed node is present in a patch, the patch slope is set to zero.

Parameters:

grid : ModelGrid

A ModelGrid.

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

unit_normal : array with shape (num_patches, 3) (optional)

The unit normal vector to each patch, if already known.

Returns:

slopes_at_patch : n_patches-long array

The slope (positive gradient magnitude) of each patch.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_x
>>> S = mg.calc_slope_at_patch(elevs=z)
>>> S.size == mg.number_of_patches
True
>>> np.allclose(S, np.pi / 4.)
True

LLCATS: PINF GRAD

calc_unit_normal_at_patch(grid, elevs='topographic__elevation')[source]

Calculate and return the unit normal vector <a, b, c> to a patch.

Parameters:

grid : ModelGrid

A ModelGrid.

elevs : str or ndarray, optional

Field name or array of node values.

Returns:

nhat : num-patches x length-3 array

The unit normal vector <a, b, c> to each patch.

Examples

>>> from landlab import HexModelGrid
>>> mg = HexModelGrid(3, 3)
>>> z = mg.node_x * 3. / 4.
>>> mg.calc_unit_normal_at_patch(z)
array([[-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8],
       [-0.6,  0. ,  0.8]])

LLCATS: PINF GRAD

Calculate differences of node values over active links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_diff_at_link() instead.

Calculates the difference in quantity node_values at each active link in the grid.

Construction:

calculate_diff_at_active_links(grid, node_values, out=None)
Parameters:

grid : ModelGrid

A ModelGrid.

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray

Differences across active links.

LLCATS: DEPR LINF GRAD

Calculate differences of node values over links.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_diff_at_link() instead.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> z = np.zeros(9)
>>> z[4] = 1.
>>> grid.calculate_diff_at_links(z)
array([ 0.,  0.,  0.,  1.,  0.,  1., -1.,  0., -1.,  0.,  0.,  0.])
>>> grid.calc_diff_at_link(z)
array([ 0.,  0.,  0.,  1.,  0.,  1., -1.,  0., -1.,  0.,  0.,  0.])

LLCATS: DEPR LINF GRAD

calculate_gradients_at_faces(*args, **kwargs)[source]

Calculate gradients of node values over faces.

Note

This method is deprecated as of Landlab version 1.0beta.

Use calc_grad_at_link() instead.

Calculate and return gradient in node_values at each face in the grid. Gradients are calculated from the nodes at either end of the link that crosses each face.

Construction:

calculate_gradients_at_faces(grid, node_values, out=None)
Parameters:

grid : ModelGrid

A ModelGrid.

node_values : ndarray or field name

Values at grid nodes.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray (x number of faces)

Gradients across faces.

Examples

>>> from landlab import RasterModelGrid
>>> rg = RasterModelGrid(3, 4, 10.0)
>>> z = rg.add_zeros('node', 'topographic__elevation')
>>> z[5] = 50.0
>>> z[6] = 36.0
>>> calculate_gradients_at_faces(rg, z)  # there are 7 faces
array([ 5. ,  3.6,  5. , -1.4, -3.6, -5. , -3.6])
>>> from landlab import HexModelGrid
>>> hg = HexModelGrid(3, 3, 10.0)
>>> z = hg.add_zeros('node', 'topographic__elevation', noclobber=False)
>>> z[4] = 50.0
>>> z[5] = 36.0
>>> calculate_gradients_at_faces(hg, z)  # there are 11 faces
array([ 5. ,  5. ,  3.6,  3.6,  5. , -1.4, -3.6, -5. , -5. , -3.6, -3.6])

LLCATS: DEPR GRAD

Miscellaneous functions

Utility functions that operate on landlab grids.

calculate_flux_divergence_at_nodes(grid, active_link_flux, out=None)[source]

Calculate flux divergence at grid nodes.

Same as calculate_flux_divergence_at_active_cells, but works with and returns a list of net unit fluxes that corresponds to all nodes, rather than just active cells.

Note that we don’t compute net unit fluxes at boundary nodes (which don’t have active cells associated with them, and often don’t have cells of any kind, because they are on the perimeter), but simply return zeros for these entries. The advantage is that the caller can work with node-based arrays instead of active-cell-based arrays.

Parameters:

grid : ModelGrid

A ModelGrid.

active_link_flux : ndarray

Fluxes at active links.

out : ndarray, optional

Buffer to hold the result.

Returns:

ndarray

Net unit fluxes at nodes.

Examples

>>> from landlab import RasterModelGrid
>>> from landlab.grid.grid_funcs import calculate_flux_divergence_at_nodes
>>> grid = RasterModelGrid((4, 5))
>>> link_flux = np.ones(grid.number_of_active_links, dtype=float)
>>> flux_at_node = calculate_flux_divergence_at_nodes(grid, link_flux)
...     
>>> flux_at_node
array([ 0.,  1.,  1.,  1.,  0.,
        1.,  0.,  0.,  0., -1.,
        1.,  0.,  0.,  0., -1.,
        0., -1., -1., -1.,  0.])
>>> flux_at_node[grid.core_nodes]
array([ 0., 0., 0., 0., 0., 0.])

This is deprecated. Instead use ``calc_flux_div_at_node`. Notice that fluxes at non-core nodes are handled differently. However, these boundary nodes don’t have “flux” anyway and so should be ignored.

>>> grid = RasterModelGrid((4, 5))
>>> link_flux = grid.zeros(at='link')
>>> link_flux[grid.active_links] = 1.
>>> flux_at_node = grid.calc_flux_div_at_node(link_flux)
>>> flux_at_node
array([ 0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.])
>>> flux_at_node[grid.core_nodes]
array([ 0., 0., 0., 0., 0., 0.])

Resolve active-link values into x and y directions.

Takes a set of values defined on active links, and returns those values resolved into the x and y directions. Two link arrays are returned: x, then y.

Parameters:

grid : ModelGrid

A ModelGrid.

active_link_values : ndarray

Values on active links.

Returns:

tuple of ndarray

Values resolved into x-component and y-component.

Resolve link values into x and y directions.

Takes a set of values defined on active links, and returns those values resolved into the x and y directions. Two link arrays are returned: x, then y.

Parameters:

grid : ModelGrid

A ModelGrid.

link_values : ndarray

Values on links.

Returns:

tuple of ndarray

Values resolved into x-component and y-component.

Grid creation from a formatted input file

Create landlab model grids.

exception BadGridTypeError(grid_type)[source]

Bases: landlab.grid.create.Error

Raise this error for a bad grid type.

exception Error[source]

Bases: exceptions.Exception

Base class for exceptions from this module.

create_and_initialize_grid(input_source)[source]

Create and initialize a grid from a file.

Creates, initializes, and returns a new grid object using parameters specified in input_source. input_source is either a ModelParameterDictionary instance (or, really, just dict-like) or a named input file.

Parameters:

input_source : str or dict

Input file or dict of parameter values.

Raises:

KeyError

If missing a key from the input file.

Examples

>>> from six import StringIO
>>> test_file = StringIO('''
... GRID_TYPE:
... raster
... NUM_ROWS:
... 4
... NUM_COLS:
... 5
... GRID_SPACING:
... 2.5
... ''')
>>> from landlab import create_and_initialize_grid
>>> grid = create_and_initialize_grid(test_file)
>>> grid.number_of_nodes
20

Function/method decorators

This module defines decorators used with ModelGrid objects.

Grid decorators

override_array_setitem_and_reset(reset) Decorator that calls a grid method after setting array values.
return_id_array(func) Decorate a function to return an array of ids.
return_readonly_id_array(func) Decorate a function to return a read-only array of ids.
class override_array_setitem_and_reset(reset)[source]

Bases: object

Decorator that calls a grid method after setting array values.

This decorator wraps ModelGrid methods that return a numpy array so that it returns a wrapped array that overrides the numpy array __setitem__, __setslice__, and itemset methods. The wrapped methods set values in the array but then also call a grid method that resets some state variables of the grid.

Parameters:

reset : str

The name of the grid method to call after setting values. The corresponding method must take no arguments.

return_id_array(func)[source]

Decorate a function to return an array of ids.

Parameters:

func : function

A function that returns a numpy array.

Returns:

func

A wrapped function that returns an id array.

return_readonly_id_array(func)[source]

Decorate a function to return a read-only array of ids.

Parameters:

func : function

A function that returns a numpy array.

Returns:

func

A wrapped function that returns an id array.

Regular Rectilinear Grids (RasterModelGrid)

Inherits from ModelGrid and adds:

A class used to create and manage regular raster grids for 2D numerical models in Landlab.

Do NOT add new documentation here. Grid documentation is now built in a semi- automated fashion. To modify the text seen on the web, edit the files docs/text_for_[gridfile].py.txt.

class RasterModelGrid(*args, **kwds)[source]

Bases: landlab.grid.base.ModelGrid, landlab.grid.raster.RasterModelGridPlotter

A 2D uniform rectilinear grid.

Create a uniform rectilinear grid that has num_rows and num_cols of grid nodes, with a row and column spacing of dx.

Use the bc keyword to specify boundary_conditions along the edge nodes of the grid. bc is a dict whose keys indicate edge location (as “bottom”, “left”, “top”, “right”) and values must be one of “open”, or “closed”. If an edge location key is missing, that edge is assumed to be open.

Parameters:

shape : tuple of int

Shape of the grid in nodes.

spacing : float, optional

Row and column node spacing.

bc : dict, optional

Edge boundary conditions.

Notes

The option for NOT giving rows, cols, and dx no longer works, because the field init requires num_active_cells, etc., to be defined. Either we force users to give arguments on instantiation, or set it up such that one can create a zero-node grid.

Examples

Create a uniform rectilinear grid that has 4 rows and 5 columns of nodes. Nodes along the edges will be open. That is, links connecting these nodes to core nodes are active.

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5), 1.0)
>>> rmg.number_of_node_rows, rmg.number_of_node_columns
(4, 5)
>>> rmg.number_of_active_links
17

Set the nodes along the top edge of the grid to be closed boundaries. This means that any links touching these nodes will be inactive.

>>> rmg = RasterModelGrid((4, 5), 1.0, bc={'top': 'closed'})
>>> rmg.number_of_node_rows, rmg.number_of_node_columns
(4, 5)
>>> rmg.number_of_active_links
14

A RasterModelGrid can have different node spacings in the x and y directions.

>>> grid = RasterModelGrid((4, 5), spacing=(1, 2))
>>> grid.dy, grid.dx
(1.0, 2.0)
>>> grid.node_y 
array([ 0., 0., 0., 0., 0.,
        1., 1., 1., 1., 1.,
        2., 2., 2., 2., 2.,
        3., 3., 3., 3., 3.])
>>> grid.node_x 
array([ 0., 2., 4., 6., 8.,
        0., 2., 4., 6., 8.,
        0., 2., 4., 6., 8.,
        0., 2., 4., 6., 8.])
are_all_core(*args, **kwargs)[source]

Note

This method is deprecated as of Landlab version 1.0.

Use nodes_are_all_core() instead.

LLCATS: DEPR NINF BC

are_all_interior(*args, **kwargs)[source]

Check if nodes are interior.

Note

This method is deprecated as of Landlab version 1.0.

Use nodes_are_all_core() instead.

Returns a single boolean truth value, True if all nodes with IDs are interior nodes, False if not.

LLCATS: DEPR NINF BC

calc_aspect_at_cell_subtriangles(grid, elevs='topographic__elevation', subtriangle_unit_normals=None, unit='degrees')

Get tuple of arrays of aspect of each of the eight cell subtriangles.

Aspect is returned as radians clockwise of north, unless input parameter units is set to ‘degrees’.

If subtriangle_unit_normals is provided the aspect will be calculated from these data.

If it is not, it will be derived from elevation data at the nodes, which can either be a string referring to a grid field (default: ‘topographic__elevation’), or an nnodes-long numpy array of the values themselves.

Parameters:

elevs : str or array (optional)

Node field name or node array of elevations. If subtriangle_unit_normals is not provided, must be set, but unused otherwise.

subtriangle_unit_normals : tuple of 8 (ncels, 3) arrays (optional)

The unit normal vectors for the eight subtriangles of each cell, if already known. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

unit : {‘degrees’, ‘radians’}

Controls the unit that the aspect is returned as.

Returns:

(a_ENE, a_NNE, a_NNW, a_WNW, a_WSW, a_SSW, a_SSE, a_ESE) :

each a length num-cells array

Len-8 tuple of the aspect of each of the eight cell subtriangles. Aspect is returned as angle clockwise of north. Units are given as radians unless input parameter units is set to ‘degrees’. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> z = np.array([1., 0., 1., 0., 0., 0., 1., 0., 1.])
>>> eight_tris = mg.calc_unit_normals_at_cell_subtriangles(z)
>>> A = mg.calc_aspect_at_cell_subtriangles(z, eight_tris)
>>> A0 = mg.calc_aspect_at_cell_subtriangles(z)
>>> np.allclose(A, A0)
True
>>> type(A) is tuple
True
>>> len(A)
8
>>> len(A[0]) == mg.number_of_cells
True
>>> A0  
(array([ 180.]), array([ 270.]), array([ 90.]), array([ 180.]),
 array([ 0.]), array([ 90.]), array([ 270.]), array([ 0.]))

LLCATS: CINF SURF

calc_grad_across_cell_corners(grid, vals, *args, **kwds)

Get gradients to diagonally opposite nodes.

Calculate gradient of the value field provided by node_values to the values at diagonally opposite nodes. The returned gradients are ordered as upper-right, upper-left, lower-left and lower-right.

Construction:

grid.calc_grad_across_cell_corners(node_values, [cell_ids],
                                            out=None)
Parameters:

node_values : array_like or field name

Quantity to take the gradient of defined at each node.

cell_ids : array_like, optional

If provided, cell ids to measure gradients. Otherwise, find gradients for all cells.

out : array_like, optional

Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.

Returns:

(N, 4) ndarray

Gradients to each diagonal node.

Examples

Create a grid with two cells.

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(3, 4)
>>> x = np.array([1., 0., 0., 1.,
...               0., 0., 1., 1.,
...               3., 3., 3., 3.])

A decrease in quantity to a diagonal node is a negative gradient.

>>> from math import sqrt
>>> grid.calc_grad_across_cell_corners(x) * sqrt(2.)
array([[ 3.,  3.,  1.,  0.],
       [ 2.,  2., -1.,  0.]])
>>> grid = RasterModelGrid((3, 4), spacing=(3, 4))
>>> grid.calc_grad_across_cell_corners(x)
array([[ 0.6,  0.6,  0.2,  0. ],
       [ 0.4,  0.4, -0.2,  0. ]])

LLCATS: CNINF GRAD

calc_grad_across_cell_faces(grid, vals, *args, **kwds)

Get gradients across the faces of a cell.

Calculate gradient of the value field provided by node_values across each of the faces of the cells of a grid. The returned gradients are ordered as right, top, left, and bottom.

Note that the returned gradients are masked to exclude neighbor nodes which are closed. Beneath the mask is the value -1.

Construction:

grid.calc_grad_across_cell_faces(node_values, [cell_ids],
                                          out=None)
Parameters:

node_values : array_like or field name

Quantity to take the gradient of defined at each node.

cell_ids : array_like, optional

If provided, cell ids to measure gradients. Otherwise, find gradients for all cells.

out : array_like, optional

Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.

Returns:

(N, 4) Masked ndarray

Gradients for each face of the cell.

Examples

Create a grid with two cells.

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(3, 4)
>>> x = np.array([0., 0., 0., 0.,
...               0., 0., 1., 1.,
...               3., 3., 3., 3.])

A decrease in quantity across a face is a negative gradient.

>>> grid.calc_grad_across_cell_faces(x) 
masked_array(data =
 [[ 1.  3.  0.  0.]
 [ 0.  2. -1. -1.]],
             mask =
 False,
       fill_value = 1e+20)
>>> grid = RasterModelGrid((3, 4), spacing=(2, 1))
>>> grid.calc_grad_across_cell_faces(x) 
masked_array(data =
 [[ 1.   1.5  0.   0. ]
 [ 0.   1.  -1.  -0.5]],
              mask =
 False,
       fill_value = 1e+20)

LLCATS: FINF GRAD

Get gradients along links touching a node.

Calculate gradient of the value field provided by node_values across each of the faces of the nodes of a grid. The returned gradients are ordered as right, top, left, and bottom. All returned values follow our standard sign convention, where a link pointing N or E and increasing in value is positive, a link pointing S or W and increasing in value is negative.

Note that the returned gradients are masked to exclude neighbor nodes which are closed. Beneath the mask is the value -1.

Construction:

grid.calc_grad_along_node_links(node_values, [cell_ids],
                                         out=None)
Parameters:

node_values : array_like or field name

Quantity to take the gradient of defined at each node.

node_ids : array_like, optional

If provided, node ids to measure gradients. Otherwise, find gradients for all nodes.

out : array_like, optional

Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.

Returns:

(N, 4) Masked ndarray

Gradients for each link of the node. Ordering is E,N,W,S.

Examples

Create a grid with nine nodes.

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(3, 3)
>>> x = np.array([0., 0., 0.,
...               0., 1., 2.,
...               2., 2., 2.])

A decrease in quantity across a face is a negative gradient.

>>> grid.calc_grad_along_node_links(x) 
masked_array(data =
 [[-- -- -- --]
 [-- 1.0 -- --]
 [-- -- -- --]
 [1.0 -- -- --]
 [1.0 1.0 1.0 1.0]
 [-- -- 1.0 --]
 [-- -- -- --]
 [-- -- -- 1.0]
 [-- -- -- --]],
             mask =
 [[ True  True  True  True]
 [ True False  True  True]
 [ True  True  True  True]
 [False  True  True  True]
 [False False False False]
 [ True  True False  True]
 [ True  True  True  True]
 [ True  True  True False]
 [ True  True  True  True]],
       fill_value = 1e+20)
>>> grid = RasterModelGrid((3, 3), spacing=(2, 4))
>>> grid.calc_grad_along_node_links(x) 
masked_array(data =
 [[-- -- -- --]
 [-- 0.5 -- --]
 [-- -- -- --]
 [0.25 -- -- --]
 [0.25 0.5 0.25 0.5]
 [-- -- 0.25 --]
 [-- -- -- --]
 [-- -- -- 0.5]
 [-- -- -- --]],
             mask =
 [[ True  True  True  True]
 [ True False  True  True]
 [ True  True  True  True]
 [False  True  True  True]
 [False False False False]
 [ True  True False  True]
 [ True  True  True  True]
 [ True  True  True False]
 [ True  True  True  True]],
       fill_value = 1e+20)

LLCATS: NINF LINF GRAD

Calculate gradients over active links.

Deprecated since version 0.1: Use calc_grad_across_cell_faces() or calc_grad_across_cell_corners() instead

Calculates the gradient in quantity s at each active link in the grid. This is nearly identical to the method of the same name in ModelGrid, except that it uses a constant node spacing for link length to improve efficiency.

Note that a negative gradient corresponds to a lower node in the direction of the link.

Returns:

ndarray

Gradients of the nodes values for each link.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(4, 5, 1.0)
>>> u = [0., 1., 2., 3., 0.,
...      1., 2., 3., 2., 3.,
...      0., 1., 2., 1., 2.,
...      0., 0., 2., 2., 0.]
>>> grad = grid.calc_grad_at_active_link(u)
>>> grad 
array([ 1.,  1., -1.,
        1.,  1., -1.,  1.,
       -1., -1., -1.,
        1.,  1., -1.,  1.,
       -1.,  0.,  1.])

For greater speed, sending a pre-created numpy array as an argument avoids having to create a new one with each call:

>>> grad = np.empty(grid.number_of_active_links)
>>> rtn = grid.calc_grad_at_active_link(u, out=grad)
>>> grad 
array([ 1.,  1., -1.,
        1.,  1., -1.,  1.,
       -1., -1., -1.,
        1.,  1., -1.,  1.,
       -1.,  0.,  1.])
>>> rtn is grad
True
>>> grid = RasterModelGrid((3, 3), spacing=(1, 2))
>>> node_values = [0., 0., 0.,
...                1., 3., 1.,
...                2., 2., 2.]
>>> grid.calc_grad_at_active_link(node_values)
array([ 3.,  1., -1., -1.])

This function is deprecated. Instead, use calc_grad_at_link.

>>> grid = RasterModelGrid((3, 3), spacing=(1, 2))
>>> node_values = [0., 0., 0.,
...                1., 3., 1.,
...                2., 2., 2.]
>>> grid.calc_grad_at_link(node_values)[grid.active_links]
array([ 3.,  1., -1., -1.])

LLCATS: LINF GRAD

Calculate gradients in node_values at links.

Construction:

grid.calc_grad_at_link(node_values, out=None)
Parameters:

node_values : array_like or field name

Values at nodes.

out : ndarray, optional

Buffer to hold result. If None, create a new array.

Returns:

ndarray

Gradients of the nodes values for each link.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> node_values = [0., 0., 0.,
...                1., 3., 1.,
...                2., 2., 2.]
>>> grid.calc_grad_at_link(node_values)
array([ 0.,  0.,  1.,  3.,  1.,  2., -2.,  1., -1.,  1.,  0.,  0.])
>>> out = np.empty(grid.number_of_links, dtype=float)
>>> rtn = grid.calc_grad_at_link(node_values, out=out)
>>> rtn is out
True
>>> out
array([ 0.,  0.,  1.,  3.,  1.,  2., -2.,  1., -1.,  1.,  0.,  0.])
>>> grid = RasterModelGrid((3, 3), spacing=(1, 2))
>>> grid.calc_grad_at_link(node_values)
array([ 0.,  0.,  1.,  3.,  1.,  1., -1.,  1., -1.,  1.,  0.,  0.])
>>> _ = grid.add_field('node', 'elevation', node_values)
>>> grid.calc_grad_at_link('elevation')
array([ 0.,  0.,  1.,  3.,  1.,  1., -1.,  1., -1.,  1.,  0.,  0.])

LLCATS: LINF GRAD

calc_grad_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, subtriangle_unit_normals=None, slope_magnitude=None)

Calculate the components of the gradient of each raster patch.

Returns the mean gradient of the four possible patch subtriangles, in radians.

If ignore_closed_nodes is True, closed nodes do not affect gradient calculations. If more than one closed node is present in a patch, the patch gradients in both x and y directions are set to zero.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

subtriangle_unit_normals : tuple of 4 (npatches, 3) arrays (optional)

The unit normal vectors for the four subtriangles of each patch, if already known. Order is TR, TL, BL, BR.

slope_magnitude : array with size num_patches (optional)

The mean slope of each patch, if already known. Units must be the same as provided here!

Returns:

gradient_tuple : (x_component_at_patch, y_component_at_patch)

Len-2 tuple of arrays giving components of gradient in the x and y directions, in the units of radians.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_y
>>> (x_grad, y_grad) = mg.calc_grad_at_patch(elevs=z)
>>> np.allclose(y_grad, np.pi/4.)
True
>>> np.allclose(x_grad, 0.)
True
>>> from landlab import CLOSED_BOUNDARY, FIXED_VALUE_BOUNDARY
>>> z = mg.node_x.copy()
>>> mg.set_closed_boundaries_at_grid_edges(True, True, True, True)
>>> mg.status_at_node[11] = CLOSED_BOUNDARY
>>> mg.status_at_node[[9, 2]] = FIXED_VALUE_BOUNDARY
>>> z[11] = 100.  # this should get ignored now
>>> z[9] = 2.  # this should be felt by patch 7 only
>>> z[2] = 1.  # should be felt by patches 1 and 2
>>> xgrad, ygrad = mg.calc_grad_at_patch(
...     elevs=z, ignore_closed_nodes=True)
>>> (xgrad.reshape((3, 4)) * 4./np.pi)[1, 1:]
array([ 1.,  1., -1.])
>>> np.allclose(ygrad[1:3], xgrad[1:3])
True

LLCATS: PINF GRAD

calc_slope_at_cell_subtriangles(grid, elevs='topographic__elevation', subtriangle_unit_normals=None)

Calculate the slope (positive magnitude of gradient) at each of the eight cell subtriangles.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

subtriangle_unit_normals : tuple of 8 (ncells, 3) arrays (optional)

The unit normal vectors for the eight subtriangles of each cell, if already known. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Returns:

(s_ENE, s_NNE, s_NNW, s_WNW, s_WSW, s_SSW, s_SSE, s_ESE) :

each a length num-cells array Len-8 tuple of the slopes (positive gradient magnitude) of each of the eight cell subtriangles, in radians. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> z = np.array([np.sqrt(3.), 0., 4./3.,
...               0., 0., 0.,
...               1., 0., 1./np.sqrt(3.)])
>>> eight_tris = mg.calc_unit_normals_at_cell_subtriangles(z)
>>> S = mg.calc_slope_at_cell_subtriangles(z, eight_tris)
>>> S0 = mg.calc_slope_at_cell_subtriangles(z)
>>> np.allclose(S, S0)
True
>>> type(S) is tuple
True
>>> len(S)
8
>>> len(S[0]) == mg.number_of_cells
True
>>> np.allclose(S[0], S[1])
True
>>> np.allclose(S[2], S[3])
True
>>> np.allclose(S[4], S[5])
True
>>> np.allclose(S[6], S[7])
True
>>> np.allclose(np.rad2deg(S[0])[0], 30.)
True
>>> np.allclose(np.rad2deg(S[2])[0], 45.)
True
>>> np.allclose(np.rad2deg(S[4])[0], 60.)
True
>>> np.allclose(np.cos(S[6])[0], 3./5.)
True

LLCATS: CINF GRAD

calc_slope_at_node(grid, elevs='topographic__elevation', method='patch_mean', ignore_closed_nodes=True, return_components=False)

Array of slopes at nodes, averaged over neighboring patches.

Produces a value for node slope (i.e., mean gradient magnitude) at each node in a manner analogous to a GIS-style slope map. If method==’patch_mean’, it averages the gradient on each of the patches surrounding the node; if method==’Horn’, it returns the resolved slope direction. Directional information can still be returned through use of the return_components keyword. All values are returned in radians, including the components; take the tan to recover the rise/run.

Note that under these definitions, it is not always true that:

mag, cmp = mg.calc_slope_at_node(z)
mag**2 == cmp[0]**2 + cmp[1]**2  # only if method=='Horn'

If ignore_closed_nodes is False, all proximal elevation values will be used in the calculation. If True, only unclosed nodes are used.

This is a verion of this code specialized for a raster. It subdivides the four square patches around each node into subtriangles, in order to ensure more correct solutions that incorporate equally weighted information from all surrounding nodes on rough surfaces.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

method : {‘patch_mean’, ‘Horn’}

Controls the slope algorithm. Current options are ‘patch_mean’, which takes the mean slope of each pf the four neighboring square patches, and ‘Horn’, which is the standard ArcGIS slope algorithm. These produce very similar solutions; the Horn method gives a vector mean and the patch_mean gives a scalar mean.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

return_components : bool

If True, return a tuple, (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If false, return an array of floats of the slope magnitude.

Returns:

float array or length-2 tuple of float arrays

If return_components, returns (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If not return_components, returns an array of slope magnitudes.

Examples

>>> import numpy as np
>>> from landlab import RadialModelGrid, RasterModelGrid
>>> mg = RasterModelGrid((5, 5), 1.)
>>> z = mg.node_x
>>> slopes = mg.calc_slope_at_node(elevs=z)
>>> np.allclose(slopes, np.pi / 4.)
True
>>> mg = RasterModelGrid((4, 5), 2.)
>>> z = - mg.node_y
>>> slope_mag, cmp = mg.calc_slope_at_node(elevs=z,
...                                        return_components=True)
>>> np.allclose(slope_mag, np.pi / 4.)
True
>>> np.allclose(cmp[0], 0.)
True
>>> np.allclose(cmp[1], - np.pi / 4.)
True
>>> mg = RasterModelGrid((4, 4))
>>> z = mg.node_x ** 2 + mg.node_y ** 2
>>> slopes, cmp = mg.calc_slope_at_node(z, return_components=True)
>>> slopes
array([ 0.95531662,  1.10991779,  1.32082849,  1.37713803,  1.10991779,
        1.20591837,  1.3454815 ,  1.38904403,  1.32082849,  1.3454815 ,
        1.39288142,  1.41562833,  1.37713803,  1.38904403,  1.41562833,
        1.43030663])
>>> np.allclose(cmp[0].reshape((4, 4))[:, 0],
...             cmp[1].reshape((4, 4))[0, :])  # test radial symmetry
True

LLCATS: NINF GRAD SURF

calc_slope_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, subtriangle_unit_normals=None)

Calculate the slope (positive magnitude of gradient) at raster patches.

Returns the mean of the slopes of the four possible patch subtriangles.

If ignore_closed_nodes is True, closed nodes do not affect slope calculations. If more than one closed node is present in a patch, the patch slope is set to zero.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

subtriangle_unit_normals : tuple of 4 (npatches, 3) arrays (optional)

The unit normal vectors for the four subtriangles of each patch, if already known. Order is TR, TL, BL, BR.

Returns:

slopes_at_patch : n_patches-long array

The slope (positive gradient magnitude) of each patch, in radians.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_x
>>> S = mg.calc_slope_at_patch(elevs=z)
>>> S.size == mg.number_of_patches
True
>>> np.allclose(S, np.pi/4.)
True
>>> z = mg.node_y**2
>>> mg.calc_slope_at_patch(elevs=z).reshape((3, 4))
array([[ 0.78539816,  0.78539816,  0.78539816,  0.78539816],
       [ 1.24904577,  1.24904577,  1.24904577,  1.24904577],
       [ 1.37340077,  1.37340077,  1.37340077,  1.37340077]])
>>> from landlab import CLOSED_BOUNDARY, FIXED_VALUE_BOUNDARY
>>> z = mg.node_x.copy()
>>> mg.set_closed_boundaries_at_grid_edges(True, True, True, True)
>>> mg.status_at_node[11] = CLOSED_BOUNDARY
>>> mg.status_at_node[9] = FIXED_VALUE_BOUNDARY
>>> z[11] = 100.  # this should get ignored now
>>> z[9] = 2.  # this should be felt by patch 7 only
>>> mg.calc_slope_at_patch(elevs=z, ignore_closed_nodes=True).reshape(
...     (3, 4)) * 4./np.pi
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.]])

LLCATS: PINF GRAD

calc_unit_normal_at_patch(elevs='topographic__elevation')[source]

Calculate and return the unit normal vector <a, b, c> to a patch.

This method is not defined on a raster, as there is no unique unit normal for a square patch. Use _calc_unit_normals_to_patch_subtriangles instead.

LLCATS: PINF GRAD

calc_unit_normals_at_cell_subtriangles(grid, elevs='topographic__elevation')

Calculate unit normals on a cell.

Calculate the eight unit normal vectors <a, b, c> to the eight subtriangles of a four-cornered (raster) cell.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

Returns:

(n_ENE, n_NNE, n_NNW, n_WNW, n_WSW, n_SSW, n_SSE, n_ESE) :

each a num-cells x length-3 array Len-8 tuple of the eight unit normal vectors <a, b, c> for the eight subtriangles in the cell. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> z = mg.node_x ** 2
>>> eight_tris = mg.calc_unit_normals_at_cell_subtriangles(z)
>>> type(eight_tris) is tuple
True
>>> len(eight_tris)
8
>>> eight_tris[0].shape == (mg.number_of_cells, 3)
True
>>> eight_tris
(array([[-0.9486833 ,  0.        ,  0.31622777]]),
 array([[-0.9486833 ,  0.        ,  0.31622777]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.9486833 ,  0.        ,  0.31622777]]),
 array([[-0.9486833 ,  0.        ,  0.31622777]]))

LLCATS: CINF GRAD

calc_unit_normals_at_patch_subtriangles(grid, elevs='topographic__elevation')

Calculate unit normals on a patch.

Calculate the four unit normal vectors <a, b, c> to the four possible subtriangles of a four-cornered (raster) patch.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

Returns:

(n_TR, n_TL, n_BL, n_BR) : each a num-patches x length-3 array

Len-4 tuple of the four unit normal vectors <a, b, c> for the four possible subtriangles in the patch. Order is (topright, topleft, bottomleft, bottomright).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_x ** 2
>>> four_tris = mg.calc_unit_normals_at_patch_subtriangles(z)
>>> type(four_tris) is tuple
True
>>> len(four_tris)
4
>>> np.allclose(four_tris[0], four_tris[1])
True
>>> np.allclose(four_tris[2], four_tris[3])
True
>>> np.allclose(four_tris[0], four_tris[2])
True
>>> np.allclose(np.square(four_tris[0]).sum(axis=1), 1.)
True
>>> four_tris[0]
array([[-0.70710678,  0.        ,  0.70710678],
       [-0.9486833 ,  0.        ,  0.31622777],
       [-0.98058068,  0.        ,  0.19611614],
       [-0.98994949,  0.        ,  0.14142136],
       [-0.70710678,  0.        ,  0.70710678],
       [-0.9486833 ,  0.        ,  0.31622777],
       [-0.98058068,  0.        ,  0.19611614],
       [-0.98994949,  0.        ,  0.14142136],
       [-0.70710678,  0.        ,  0.70710678],
       [-0.9486833 ,  0.        ,  0.31622777],
       [-0.98058068,  0.        ,  0.19611614],
       [-0.98994949,  0.        ,  0.14142136]])

LLCATS: PINF GRAD

calculate_aspect_at_nodes_bestFitPlane(*args, **kwargs)[source]

Aspect at nodes.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_aspect_at_node() instead.

Code author: Katy Barnhart <katherine.barnhart@colorado.edu>

Calculates the aspect at each node based on the elevation of the node and its neighbors using a best fit plane calculated using single value decomposition.

Parameters:

id : array-like

ID of nodes at which to calculate the aspect.

val : ndarray

Elevation at all nodes

Returns:

ndarray

Aspect at the nodes given by id

LLCATS: DEPR NINF SURF

calculate_flux_divergence(*args, **kwargs)[source]

Flux divergence.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_flux_div_at_node() instead.

Candidate for depreciation, DEJH 5/14

Todo

UPDATE THIS TO USE NEW DATA STRUCTURES!

This is like calculate_flux_divergences (plural!), but only does it for cell “id”.

LLCATS: DEPR NINF GRAD

calculate_flux_divergence_at_nodes(*args, **kwargs)[source]

Flux divergence at nodes.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_flux_div_at_node() instead.

Same as calculate_flux_divergence_at_active_cells, but works with and returns a list of net unit fluxes that corresponds to all nodes, rather than just active cells.

Note that we DO compute net unit fluxes at boundary nodes (even though these don’t have active cells associated with them, and often don’t have cells of any kind, because they are on the perimeter). It’s up to the user to decide what to do with these boundary values.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5), 1.0)
>>> u = [0., 1., 2., 3., 0.,
...      1., 2., 3., 2., 3.,
...      0., 1., 2., 1., 2.,
...      0., 0., 2., 2., 0.]
>>> u = np.array(u)
>>> grad = rmg.calc_grad_at_link(u)[rmg.active_links]
>>> grad
array([ 1.,  1., -1.,  1.,  1., -1.,  1., -1., -1., -1.,  1.,  1., -1.,
        1., -1.,  0.,  1.])
>>> flux = -grad    # downhill flux proportional to gradient
>>> df = rmg.calculate_flux_divergence_at_nodes(flux)
>>> df
array([ 0., -1., -1.,  1.,  0., -1.,  2.,  4., -2.,  1., -1.,  0.,  1.,
       -4.,  1.,  0., -1.,  0.,  1.,  0.])

If calculate_gradients_at_nodes is called inside a loop, you can improve speed by creating an array outside the loop. For example, do this once, before the loop:

>>> df = rmg.zeros(centering='node') # outside loop
>>> rmg.number_of_nodes
20

Then do this inside the loop:

>>> df = rmg.calculate_flux_divergence_at_nodes(flux, df)

In this case, the function will not have to create the df array.

LLCATS: DEPR NINF GRAD

calculate_slope_aspect_at_nodes_best_fit_plane(*args, **kwargs)[source]

Calculate slope aspect.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_slope_at_node, calc_aspect_at_node() instead.

Slope aspect of best-fit plane at nodes.

Code author: Katy Barnhart <katherine.barnhart@colorado.edu>

Note

THIS CODE HAS ISSUES (SN 25-Sept-14): This code didn’t perform well on a NS facing elevation profile. Please check slope_aspect_routines_comparison.py under landlabexamples before using this. Suggested alternative: calculate_slope_aspect_at_nodes_burrough

Calculates both the slope and aspect at each node based on the elevation of the node and its neighbors using a best fit plane calculated using single value decomposition.

Parameters:

nodes : array-like

ID of nodes at which to calculate the aspect

val : ndarray

Elevation at all nodes

Returns:

(slope, aspect) : tuple of floats

Tuple containing (slope, aspect)

LLCATS: DEPR NINF GRAD SURF

calculate_slope_aspect_at_nodes_burrough(*args, **kwargs)[source]

Calculate topographic slope.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_slope_at_node, calc_aspect_at_node() instead.

Calculates the local topographic slope (i.e., the down-dip slope, and presented as positive), and the aspect (dip direction in degrees clockwise from north), at the given nodes, ids. All ids must be of core nodes. This method uses Burrough’s 1998 Pg. 190 method similar to the methods used by ArcMap to calculate slope and aspect.

If ids is not provided, the slope will be returned for nodes at all cells.

vals is either the name of an existing grid field from which to draw topographic data, or an array of values to use. If an array of values is passed, it must be nnodes long. If vals is not provided, this method will default to trying to use the field ‘Elevation’.

Returns:

(slope, aspect) : tuple of float

slope, a len(ids) array of slopes at each node provided. aspect, a len(ids) array of aspects at each node provided.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4), (4, 4))
>>> z = np.array([0., 0., 0., 0.,
...               3., 3., 3., 3,
...               6., 6., 6., 6.])
>>> (slope,
...  aspect) = grid.calculate_slope_aspect_at_nodes_burrough(vals=z)
>>> np.tan(slope)
array([ 0.75,  0.75])
>>> np.degrees(aspect)
array([ 180.,  180.])

This method is deprecated. Use calc_slope_at_node and calc_aspect_at_node instead. Notice that calc_slope_at_node and calc_aspect_at_node return values for all nodes, not just core nodes. In addition, calc_aspect_at_node returns compass-style angles in degrees.

>>> np.tan(grid.calc_slope_at_node(elevs=z)[grid.core_nodes])
array([ 0.75,  0.75])
>>> grid.calc_aspect_at_node(elevs=z)[grid.core_nodes]
array([ 180.,  180.])

LLCATS: DEPR NINF SURF GRAD

calculate_slope_at_nodes_bestFitPlane(*args, **kwargs)[source]

Slope of best-fit plane at nodes.

Note

This method is deprecated as of Landlab version 1.0.

Use calc_slope_at_node() instead.

Code author: Katy Barnhart <katherine.barnhart@colorado.edu>

Calculates the slope at each node based on the elevation of the node and its neighbors using a best fit plane calculated using single value decomposition.

Parameters:

id : array-like

ID of nodes at which to calculate the aspect

val : ndarray

Elevation at all nodes

Returns:

ndarray

Slope at the nodes given by id

LLCATS: DEPR NINF GRAD SURF

cell_grid_shape

Get the shape of the cellular grid (grid with only cells).

Returns:

shape : tuple of ints

The shape of the cellular grid as number of cell rows and cell columns.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.cell_grid_shape
(1, 2)

LLCATS: GINF CINF

cell_vector_to_raster(u, flip_vertically=False)[source]

Unravel a 1D array.

Converts cell vector u to a 2D array and returns it, so that it can be plotted, output, etc.

If the optional argument flip_vertically=True, the function returns an array that has the rows in reverse order, for use in plot commands (such as the image display functions) that put the (0,0) axis at the top left instead of the bottom left.

LLCATS: GINF CINF

cells_at_corners_of_grid

Get array of cells in cellular grid (grid with only cells) corners.

Return the IDs to the corner cells of the cellular grid, sorted by ID.

Returns:

(4, ) ndarray

Array of corner node IDs.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.cells_at_corners_of_grid
array([0, 2, 3, 5])

LLCATS: GINF CINF SUBSET

corner_cells

Note

This method is deprecated as of Landlab version 1.0.

Use cells_at_corners_of_grid() instead.

LLCATS: DEPR GINF CINF SUBSET

corner_nodes

Note

This method is deprecated as of Landlab version 1.0.

Use nodes_at_corners_of_grid() instead.

LLCATS: DEPR GINF NINF SUBSET

dx

Get node spacing in the column direction.

Returns:

float

Spacing of node columns.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.dx
1.0
>>> grid = RasterModelGrid((4, 5), 2.0)
>>> grid.dx
2.0

LLCATS: GINF MEAS

dy

Get node spacing in the row direction.

Note in a RasterModelGrid, dy==dx.

Returns:

float

Spacing of node rows.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.dy
1.0
>>> grid = RasterModelGrid((4, 5), spacing=(2, 4))
>>> grid.dy
2.0

LLCATS: GINF MEAS

extent

Extent of the grid in the y and x-dimensions.

Return the y and x-dimension of the grid. Because boundary nodes don’t have cells, the dimension of the grid is ((num_rows - 1) * dy, (num_columns - 1) * dx), not (num_rows * dy, num_cols * dx).

Returns:

(y_extent, x_extent) : tuple of float

Length of the grid in the y and x-dimensions.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.extent
(3.0, 4.0)
>>> grid = RasterModelGrid((4, 5), 2.)
>>> grid.extent
(6.0, 8.0)
>>> grid = RasterModelGrid((4, 5), spacing=(2, 3))
>>> grid.extent
(6.0, 12.0)

LLCATS: GINF MEAS

face_connecting_cell_pair(*args, **kwargs)[source]

Get the face that connects two cells.

Note

This method is deprecated as of Landlab version 1.0.

Use no replacement() instead.

Returns an array of face indices that cell_a and cell_b share. If the cells do not share any faces, returns an empty array.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> mg.face_connecting_cell_pair(0, 1)
array([4])
>>> mg.face_connecting_cell_pair(0, 2).size  # empty array returned
0

LLCATS: DEPR FINF CINF CONN

find_nearest_node(coords, mode='raise')[source]

Node nearest a point.

Find the index to the node nearest the given x, y coordinates. Coordinates are provided as numpy arrays in the coords tuple.

Use the mode keyword to specify what to do if the given coordinates are out-of-bounds. See np.ravel_multi_index() for a description of possible values for mode. Note that a coordinate is out-of-bounds if it is beyond one half the node spacing from the exterior nodes.

Returns the indices of the nodes nearest the given coordinates.

Parameters:

coords : tuple of array-like

Coordinates of points.

mode : {‘raise’, ‘wrap’, ‘clip’}, optional

What to do if a point is off the grid.

Returns:

array-like

IDs of the nearest nodes.

Notes

For coordinates that are equidistant to two or more nodes, see the rounding rules for numpy.around().

Examples

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5))
>>> rmg.find_nearest_node([0.2, 0.2])
0
>>> rmg.find_nearest_node((np.array([1.6, 3.6]), np.array([2.3, .7])))
array([12,  9])
>>> rmg.find_nearest_node((-.4999, 1.))
5

LLCATS: NINF SUBSET

classmethod from_dict(params)[source]

Create a RasterModelGrid from a dictionary.

Parameters:

params : dict_like

Initialization parameters for a RasterModelGrid.

Returns:

RasterModelGrid

A newly-created grid.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid.from_dict(
...     {'shape': (3, 4), 'bc': {'top': 'closed'}})
>>> grid.number_of_nodes
12

LLCATS: GINF

grid_coords_to_node_id(*args, **kwds)[source]

Convert node indices to node ID.

Returns the ID of the node at the specified row and col of the raster grid. Since this is a wrapper for the numpy ravel_multi_index function, the keyword arguments are the same as that function. In addition, row and col can both be either scalars or arrays (of the same length) to get multiple ids.

As with ravel_multi_index use the mode keyword to change the behavior of the method when passed an out-of-range row or col. The default is to raise ValueError (not IndexError, as you might expect).

Note

The syntax assumes that first row and column are 0, so max entry for a mg with 4 rows and 5 cols is row=3, col=4

Parameters:

row : array-like

Row of node.

col : array-like

Column of node.

Returns:

ndarray

Node IDs.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> mg.grid_coords_to_node_id(2, 3)
13
>>> mg.grid_coords_to_node_id([2, 0], [3, 4])
array([13,  4])

LLCATS: NINF SUBSET MEAS

grid_xdimension

Length of the grid in the x-dimension.

Return the x-dimension of the grid. Because boundary nodes don’t have cells, the dimension of the grid is num_cols-1, not num_cols.

Returns:

float

Length of the grid in the x-dimension.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.grid_xdimension
4.0
>>> grid = RasterModelGrid((4, 5), 0.5)
>>> grid.grid_xdimension
2.0
>>> grid = RasterModelGrid((4, 5), spacing=(2, 3))
>>> grid.grid_xdimension
12.0

LLCATS: GINF MEAS

grid_ydimension

Length of the grid in the y-dimension.

Return the y-dimension of the grid. Because boundary nodes don’t have cells, the dimension of the grid is num_rows-1, not num_rows.

Returns:

float

Length of the grid in the y-dimension.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.grid_ydimension
3.0
>>> grid = RasterModelGrid((4, 5), 0.5)
>>> grid.grid_ydimension
1.5
>>> grid = RasterModelGrid((4, 5), spacing=(2, 3))
>>> grid.grid_ydimension
6.0

LLCATS: GINF MEAS

has_boundary_neighbor(*args, **kwargs)[source]

Note

This method is deprecated as of Landlab version 1.0.

Use node_has_boundary_neighbor() instead.

LLCATS: DEPR NINF CONN BC

LLCATS: LINF

is_core(*args, **kwargs)[source]

Note

This method is deprecated as of Landlab version 1.0.

Use node_is_core() instead.

LLCATS: DEPR NINF BC

is_interior([ids])[source]

Check of a node is an interior node.

Note

This method is deprecated as of Landlab version 0.5.

Use node_is_core() instead.

Returns an boolean array of truth values for each node ID provided; True if the node is an interior node, False otherwise. If no IDs are provided, method returns a boolean array for every node.

(Interior status is typically indicated by a value of 0 in node_status.)

LLCATS: DEPR NINF BC

is_point_on_grid(xcoord, ycoord)[source]

Check if a point is on the grid.

This method takes x, y coordinates and tests whether they lie within the grid. The limits of the grid are taken to be links connecting the boundary nodes. We perform a special test to detect looped boundaries.

Coordinates can be ints or arrays of ints. If arrays, will return an array of the same length of boolean truth values.

Parameters:

xcoord : float or array_like

The point’s x-coordinate.

ycoord : float or array_like

The point’s y-coordinate.

Returns:

bool

True if the point is on the grid. Otherwise, False.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5), spacing=(2, 1))
>>> grid.is_point_on_grid(1, 1)
True
>>> grid.is_point_on_grid((1, 1, 1,), (1, 3.1, 6.1))
array([ True,  True, False], dtype=bool)
>>> grid.is_point_on_grid((-.1, .1, 3.9, 4.1), (1, 1, 1, 1))
array([False,  True,  True, False], dtype=bool)

LLCATS: GINF MEAS SUBSET

Get lengths of links.

Return the link lengths in the grid, as a nlinks-long array.

Returns:

(4, N) ndarray

Link lengths.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3), spacing=(3, 4))
>>> grid.length_of_link
array([ 4.,  4.,  3.,  3.,  3.,  4.,  4.,  3.,  3.,  3.,  4.,  4.])

Since LL version 1, this method is unaffected by the existance or otherwise of diagonal links on the grid:

>>> grid = RasterModelGrid((3, 3), spacing=(4, 3))
>>> _ = grid._diagonal_links_at_node
>>> grid.length_of_link 
array([ 3.,  3.,  4.,  4.,  4.,  3.,  3.,  4.,  4.,  4.,  3.,  3.])

LLCATS: LINF MEAS

Get array of links defining each patch.

Examples

>>> mg = RasterModelGrid((3, 4))
>>> mg.links_at_patch
array([[ 4,  7,  3,  0],
       [ 5,  8,  4,  1],
       [ 6,  9,  5,  2],
       [11, 14, 10,  7],
       [12, 15, 11,  8],
       [13, 16, 12,  9]])

LLCATS: PINF LINF CONN

looped_neighbors_at_cell

For each cell in a raster, return the D8 neighboring cells, looping across grid boundaries as necessary.

Returns lists of looped neighbor cell IDs of given cell ids. If cell ids are not given, it returns a 2D array of size (self.number_of_cells, 8). Order or neighbors is [ E, NE, N, NW, W, SW, S, SE ]

Output is looped, regardless of boundary conditions! (see examples)

Returns:

ndarray (num_cells, 8)

The eight neighbors of each cell.

LLCATS: DEPR CINF CONN BC

Map the maximum of links entering a node to the node.

map_max_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. it finds the maximum value at the the inlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_max_of_inlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_max_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_max_of_inlinks_to_node(rmg, 'z')
array([  0.,   0.,   1.,   2.,
         3.,   7.,   8.,   9.,
        10.,  14.,  15.,  16.])

LLCATS: NINF LINF MAP

Map the max of links leaving a node to the node.

map_max_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. it finds the maximum value at the the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_max_of_outlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_max_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_max_of_outlinks_to_node(rmg, 'z')
array([  3.,   4.,   5.,   6.,  10.,  11.,  12.,  13.,  14.,  15.,  16.,
         0.])

LLCATS: NINF LINF MAP

Map the mean of active links in the x direction touching node to the node.

map_mean_of_horizontal_active_links_to_node takes an array at the links and finds the average of all horizontal (x-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. If a node has no active links, it receives 0. Note that here a positive returned value means flux to the east, and a negative to the west.

Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_horizontal_active_links_to_node
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', -np.arange(17, dtype=float))
>>> rmg.status_at_node[rmg.nodes_at_left_edge] = CLOSED_BOUNDARY
>>> map_mean_of_horizontal_active_links_to_node(rmg, 'z')
array([ 0. ,  0. ,  0. ,  0. ,  0. , -8. , -8.5, -9. ,  0. ,  0. ,  0. ,
        0. ])

LLCATS: NINF LINF MAP

Map the mean of links in the x direction touching a node to the node.

map_mean_of_horizontal_links_to_node takes an array at the links and finds the average of all horizontal (x-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. Note that here a positive returned value means flux to the east, and a negative to the west.

Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_horizontal_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_horizontal_links_to_node(rmg, 'z')
array([  0. ,   0.5,   1.5,   2. ,   7. ,   7.5,   8.5,   9. ,  14. ,
        14.5,  15.5,  16. ])

LLCATS: NINF LINF MAP

Map the mean of links entering a node to the node.

map_mean_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. It finds the average of the inlinks and returns values at the nodes.

This considers all inactive links to have a value of 0.

Construction:

grid.map_mean_of_inlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_inlinks_to_node(rmg, 'z')
array([  0. ,   0. ,   0.5,   1. ,   1.5,   5.5,   6.5,   7.5,   5. ,
        12.5,  13.5,  14.5])

LLCATS: NINF LINF MAP

Map the mean of links touching a node to the node.

map_mean_all_links_to_node takes an array at the links and finds the average of all ~existing~ link neighbor values for each node in the grid. it returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_mean_of_links_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_links_to_node(rmg, 'z')
array([  1.5       ,   1.66666667,   2.66666667,   4.        ,
         6.66666667,   7.5       ,   8.5       ,   9.33333333,
        12.        ,  13.33333333,  14.33333333,  14.5       ])

LLCATS: NINF LINF MAP

Map the mean of links leaving a node to the node.

map_mean_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. it finds the average of the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_mean_of_outlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_outlinks_to_node(rmg, 'z')
array([  1.5,   2.5,   3.5,   3. ,   8.5,   9.5,  10.5,   6.5,   7. ,
         7.5,   8. ,   0. ])

LLCATS: NINF LINF MAP

Map the mean of active links in the y direction touching node to the node.

map_mean_of_vertical_active_links_to_node takes an array at the links and finds the average of all vertical (y-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. If a node has no active links, it receives 0. Note that here a positive returned value means flux to the north, and a negative to the south.

Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_vertical_active_links_to_node
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', -np.arange(17, dtype=float))
>>> rmg.status_at_node[rmg.nodes_at_bottom_edge] = CLOSED_BOUNDARY
>>> map_mean_of_vertical_active_links_to_node(rmg, 'z')
array([  0.,   0.,   0.,   0.,   0., -11., -12.,   0.,   0., -11., -12.,
         0.])

LLCATS: NINF LINF MAP

Map the mean of links in the y direction touching a node to the node.

map_mean_of_vertical_links_to_node takes an array at the links and finds the average of all vertical (y-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. Note that here a positive returned value means flux to the north, and a negative to the south.

Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_vertical_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_vertical_links_to_node(rmg, 'z')
array([  3. ,   4. ,   5. ,   6. ,   6.5,   7.5,   8.5,   9.5,  10. ,
        11. ,  12. ,  13. ])

LLCATS: NINF LINF MAP

Map the minimum of links entering a node to the node.

map_min_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. it finds the minimum value at the the inlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_min_of_inlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_min_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_min_of_inlinks_to_node(rmg, 'z')
array([  0.,   0.,   0.,   0.,   0.,   4.,   5.,   6.,   0.,  11.,  12.,
        13.])

LLCATS: NINF LINF MAP

Map the min of links leaving a node to the node.

map_min_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. It finds the minimum value at the the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_min_of_outlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_min_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_min_of_outlinks_to_node(rmg, 'z')
array([ 0.,  1.,  2.,  0.,  7.,  8.,  9.,  0.,  0.,  0.,  0.,  0.])

LLCATS: NINF LINF MAP

Map the sum of links entering a node to the node.

map_sum_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. it sums the inlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_sum_of_inlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_sum_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_sum_of_inlinks_to_node(rmg, 'z')
array([  0.,   0.,   1.,   2.,   3.,  11.,  13.,  15.,  10.,  25.,  27.,
        29.])

LLCATS: NINF LINF MAP

Map the sum of links leaving a node to the node.

map_sum_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. it sums the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

grid.map_sum_of_outlinks_to_node(var_name, out=None)
Parameters:

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_sum_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_sum_of_outlinks_to_node(rmg, 'z')
array([  3.,  5.,  7.,   6.,  17.,  19.,  21.,  13.,  14.,  15.,  16.,
         0.])

LLCATS: NINF LINF MAP

node_has_boundary_neighbor(ids, method='d8')[source]

Check if nodes have neighbors that are boundary nodes.

Checks to see if one of the eight neighbor nodes of node(s) with id has a boundary node. Returns True if a node has a boundary node, False if all neighbors are interior.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((5, 5))
>>> mg.node_has_boundary_neighbor(6)
True
>>> mg.node_has_boundary_neighbor(12)
False
>>> mg.node_has_boundary_neighbor([12, -1])
array([False,  True], dtype=bool)
>>> mg.node_has_boundary_neighbor(25)
Traceback (most recent call last):
    ...
IndexError: index 25 is out of bounds for axis 0 with size 25

LLCATS: NINF CONN BC

node_is_core([ids])[source]

Check if a node is a core node.

Returns an boolean array of truth values for each node ID provided; True if the node is a core node, False otherwise. If no IDs are provided, method returns a boolean array for every node.

(Core status is typically indicated by a value of 0 in node_status.)

LLCATS: NINF BC

node_spacing

Spacing betweem node rows and columns.

Note

This method is deprecated as of Landlab version 0.5.

Use dx() instead.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.node_spacing
1.0
>>> grid = RasterModelGrid((4, 5), 3.0)
>>> grid.node_spacing
3.0

LLCATS: DEPR GINF NINF MEAS

node_vector_to_raster(u, flip_vertically=False)[source]

Unravel an array of node values.

Converts node vector u to a 2D array and returns it, so that it can be plotted, output, etc.

If the flip_vertically keyword is True, this function returns an array that has the rows in reverse order. This is useful for use in plot commands (such as the image display functions) that puts the first row at the top of the image. In the landlab coordinate system, the first row is thought to be at the bottom. Thus, a flipped matrix will plot in the landlab style with the first row at the bottom.

The returned array is a view of u, not a copy.

LLCATS: GINF NINF

nodes

Get a shaped array of nodes.

Returns:

ndarray

Node IDs in an array shaped as number_of_node_rows by number_of_node_columns.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.nodes
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

You can’t change node ids.

>>> grid.nodes[0] = 99 
Traceback (most recent call last):
ValueError: assignment destination is read-only

LLCATS: NINF

nodes_are_all_core(ids)[source]

Check if nodes are all core.

Returns a single boolean truth value, True if all nodes with IDs are core nodes, False if not.

Parameters:

ids : array-like

Grid nodes.

Returns:

boolean

True if all the given nodes are core nodes.

LLCATS: NINF BC

nodes_around_point(xcoord, ycoord)[source]

Get the nodes surrounding a point.

Return IDs of the four nodes of the area around a point with coordinates xcoord, ycoord. Node IDs are returned counter-clockwise order starting from the southwest node.

If either xcoord or ycoord are arrays the usual numpy broadcasting rules apply.

Parameters:

xcoord : float, array-like

x-coordinate of point

ycoord : float, array-like

y-coordinate of point

Returns:

(4, N) ndarray

IDs of nodes around the point.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.nodes_around_point(.4, 1.2)
array([4, 8, 9, 5])
>>> grid.nodes_around_point([.9, 1.1], 1.2)
array([[ 4,  5],
       [ 8,  9],
       [ 9, 10],
       [ 5,  6]])
>>> grid = RasterModelGrid((3, 4), spacing=(2, 1))
>>> grid.nodes_around_point(.5, 1.5)
array([0, 4, 5, 1])
>>> grid = RasterModelGrid((3, 4))
>>> grid.nodes_around_point(.5, 1.5)
array([4, 8, 9, 5])

LLCATS: NINF SUBSET

nodes_at_bottom_edge

Get nodes along the bottom edge of a grid.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> vals = np.array([ 0,  1,  2,  3,
...                   4,  5,  6,  7,
...                   8,  9, 10, 11])
>>> vals[grid.nodes_at_bottom_edge]
array([0, 1, 2, 3])

LLCATS: NINF BC SUBSET

nodes_at_corners_of_grid

Get array of the nodes in grid corners.

Return the IDs to the corner nodes of the grid, sorted by ID.

Returns:

(4, ) ndarray

Array of corner node IDs.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.nodes_at_corners_of_grid
array([ 0,  4, 15, 19])

LLCATS: GINF NINF SUBSET

nodes_at_edge(edge)[source]

Get edge nodes by edge name.

Parameters:

edge : {‘right’, ‘top’, ‘left’, ‘bottom’}

Edge location.

Returns:

slice

Slice of the nodes on an edge.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> vals = np.array([ 0,  1,  2,  3,
...                   4,  5,  6,  7,
...                   8,  9, 10, 11])
>>> vals[grid.nodes_at_edge('left')]
array([0, 4, 8])

LLCATS: NINF BC SUBSET

nodes_at_left_edge

Get nodes along the left edge of a grid.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> vals = np.array([ 0,  1,  2,  3,
...                   4,  5,  6,  7,
...                   8,  9, 10, 11])
>>> vals[grid.nodes_at_left_edge]
array([0, 4, 8])

LLCATS: NINF BC SUBSET

nodes_at_patch

Get array of nodes of a patch.

Returns the four nodes at the corners of each patch in a regular grid. Shape of the returned array is (nnodes, 4). Returns in order CCW from east, i.e., [NE, NW, SW, SE].

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> mg.nodes_at_patch
array([[4, 3, 0, 1],
       [5, 4, 1, 2],
       [7, 6, 3, 4],
       [8, 7, 4, 5]])

LLCATS: NINF PINF CONN

nodes_at_right_edge

Get nodes along the right edge of a grid.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> vals = np.array([ 0,  1,  2,  3,
...                   4,  5,  6,  7,
...                   8,  9, 10, 11])
>>> vals[grid.nodes_at_right_edge]
array([ 3,  7, 11])

LLCATS: NINF BC SUBSET

nodes_at_top_edge

Get nodes along the top edge of a grid.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> vals = np.array([ 0,  1,  2,  3,
...                   4,  5,  6,  7,
...                   8,  9, 10, 11])
>>> vals[grid.nodes_at_top_edge]
array([ 8,  9, 10, 11])

LLCATS: NINF BC SUBSET

number_of_cell_columns

Number of cell columns.

Returns the number of columns, including boundaries.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_cell_columns
3

LLCATS: GINF NINF

number_of_cell_rows

Number of cell rows.

Returns the number of rows, including boundaries.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_cell_rows
2

LLCATS: GINF CINF

number_of_interior_nodes

Number of interior nodes.

Returns the number of interior nodes on the grid, i.e., non-perimeter nodes. Compare self.number_of_core_nodes.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_interior_nodes
6

LLCATS: NINF

number_of_node_columns

Number of node columns.

Returns the number of columns, including boundaries.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_node_columns
5

LLCATS: GINF NINF

number_of_node_rows

Number of node rows.

Returns the number of rows, including boundaries.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_node_rows
4

LLCATS: GINF NINF

number_of_patches

Number of patches.

Returns the number of patches over the grid.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((4, 5))
>>> grid.number_of_patches
12

LLCATS: PINF

Get array of patches adjoined to each link.

Missing paches are indexed as -1.

Examples

>>> mg = RasterModelGrid((3, 4))
>>> mg.patches_at_link
array([[ 0, -1],
       [ 1, -1],
       [ 2, -1],
       [ 0, -1],
       [ 0,  1],
       [ 1,  2],
       [ 2, -1],
       [ 0,  3],
       [ 1,  4],
       [ 2,  5],
       [ 3, -1],
       [ 3,  4],
       [ 4,  5],
       [ 5, -1],
       [ 3, -1],
       [ 4, -1],
       [ 5, -1]])

LLCATS: PINF LINF CONN

patches_at_node

Get array of patches attached to nodes.

Returns a (N, 4) array of the patches associated with each node in the grid. The four possible patches are returned in order CCW from east, i.e., NE, NW, SW, SE.

Missing patches are indexed -1.

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> mg.patches_at_node
array([[ 0, -1, -1, -1],
       [ 1,  0, -1, -1],
       [-1,  1, -1, -1],
       [ 2, -1, -1,  0],
       [ 3,  2,  0,  1],
       [-1,  3,  1, -1],
       [-1, -1, -1,  2],
       [-1, -1,  2,  3],
       [-1, -1,  3, -1]])

LLCATS: PINF NINF CONN

roll_nodes_ud(data_name, shift, interior_only=False)[source]

Roll (shift) specified data on nodes up or down in a raster grid.

Similar to the Numpy roll() function, in that it shifts node values up by shift rows, wrapping the data in the top row(s) around to the bottom. If the interior_only is set, data along the left and right grid edges are not changed.

Note that the contents of the data_name field are changed.

Parameters:

data_name : string

Name of node-data item attached to grid.

shift : int

Number of rows to shift upward.

interior_only : bool, optional

If True, data along left and right edges are not shifted

Examples

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 3), 1.)
>>> data = rmg.add_zeros('test_data', at='node')
>>> data[:] = np.arange(12)
>>> rmg.roll_nodes_ud('test_data', 1)
>>> data 
array([ 9.,  10.,  11.,   0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,
        8.])
>>> rmg.roll_nodes_ud('test_data', 2)
>>> data 
array([ 3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,   0.,   1.,
        2.])
>>> rmg.roll_nodes_ud('test_data', 1, interior_only=True)
>>> data 
array([ 3.,   1.,   5.,   6.,   4.,   8.,   9.,   7.,  11.,   0.,  10.,
        2.])

LLCATS: NINF

save(path, names=None, format=None, at=None)[source]

Save a grid and fields.

If more than one field name is specified for names when saving to ARC ascii, multiple files will be produced, suffixed with the field names.

When saving to netCDF (.nc), the fields are incorporated into the single named .nc file.

Parameters:

path : str

Path to output file.

names : iterable of strings, optional

List of field names to save, defaults to all if not specified.

format : {‘netcdf’, ‘esri-ascii’}, optional

Output file format. Guess from file extension if not given.

at : str

Grid element where values are defined.

Examples

>>> from landlab import RasterModelGrid
>>> import os
>>> rmg = RasterModelGrid((4, 5))
>>> rmg.save('./mysave.nc')
>>> os.remove('mysave.nc') #to remove traces of this test

LLCATS: GINF

second_ring_looped_neighbors_at_cell

Get list of second ring looped neighbor cell IDs (all 16 neighbors).

Returns lists of looped second ring neighbor cell IDs of given cell ids. If cell ids are not given, it returns a 2D array of size ( self.number_of_cells, 16 ).

The cells are the 16 which encircle the nine true neighbor cells. Order of neighbors: Starts with E and goes counter clockwise

Examples

>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((10, 10))
>>> mg.second_ring_looped_neighbors_at_cell[36, :]
array([38, 46, 54, 53, 52, 51, 50, 42, 34, 26, 18, 19, 20, 21, 22, 30])
>>> mg.second_ring_looped_neighbors_at_cell[8, :]
array([10, 18, 26, 25, 24, 31, 30, 22, 14,  6, 62, 63, 56, 57, 58,  2])

...take a look at the cell grid to understand why: [56, 57, 58, 59, 60, 61, 62, 63] [48, 49, 50, 51, 52, 53, 54, 55] [40, 41, 42, 43, 44, 45, 46, 47] [32, 33, 34, 35, 36, 37, 38, 39] [24, 25, 26, 27, 28, 29, 30, 31] [16, 17, 18, 19, 20, 21, 22, 23] [ 8, 9, 10, 11, 12, 13, 14, 15] [ 0, 1, 2, 3, 4, 5, 6, 7]

LLCATS: CINF CONN BC

set_closed_boundaries_at_grid_edges(right_is_closed, top_is_closed, left_is_closed, bottom_is_closed)[source]

Set boundary not to be closed.

Sets the status of nodes along the specified side(s) of a raster grid (bottom, right, top, and/or left) to CLOSED_BOUNDARY.

Arguments are booleans indicating whether the bottom, left, top, and right are closed (True) or not (False).

For a closed boundary:

  • the nodes are flagged CLOSED_BOUNDARY (status type 4)
  • all links that connect to a CLOSED_BOUNDARY node are flagged as inactive (so they appear on link-based lists, but not active_link-based lists)

This means that if you call the calc_grad_at_active_link method, links connecting to closed boundaries will be ignored: there can be no gradients or fluxes calculated, because the links that connect to that edge of the grid are not included in the calculation. So, setting a grid edge to CLOSED_BOUNDARY is a convenient way to impose a no-flux boundary condition. Note, however, that this applies to the grid as a whole, rather than a particular variable that you might use in your application. In other words, if you want a no-flux boundary in one variable but a different boundary condition for another, then use another method.

This method is a replacement for the now-deprecated method set_inactive_boundaries(). Unlike that method, this one ONLY sets nodes to CLOSED_BOUNDARY; it does not set any nodes to FIXED_VALUE_BOUNDARY.

Parameters:

right_is_closed : boolean

If True right-edge nodes are closed boundaries.

top_is_closed
: boolean

If True top-edge nodes are closed boundaries.

left_is_closed
: boolean

If True left-edge nodes are closed boundaries.

bottom_is_closed
: boolean

If True bottom-edge nodes are closed boundaries.

Notes

Note that the four corners are treated as follows:

  • bottom left = BOTTOM
  • bottom right = BOTTOM
  • top right = TOP
  • top left = TOP

This scheme is necessary for internal consistency with looped boundaries.

LLCATS: BC SUBSET

Create fixed link boundaries at the grid edges.

Sets the status of links along the specified side(s) of a raster grid— bottom vertical links, right horizontal, top vertical links, and/or left horizontal links —to FIXED_LINK.

By definition, fixed links exist between fixed gradient nodes (status_at_node == 2) and core nodes (status_at_node == 0). Because the outer ring of nodes are fixed gradient (status_at_node == 2), the links between them are inactive (status_at_link == 4) and are not set using this function (the inactive links are the top and bottom horizontal edge links, and left and right edge vertical edge links.)

Arguments are booleans indicating whether the bottom, right, top, and left sides are to be set (True) or not (False).

node_value controls what values are held constant at the fixed gradient nodes (status_at_node == 2). It can be either a float, an array of length number_of_fixed_nodes or number_of_nodes (total), or left blank. If left blank, the values will be set from the those already in the grid fields, according to ‘fixed_node_value_of’.

link_value controls what values are held constant at the fixed links (status_at_link == 2). It can be either a float, an array of length number_of_fixed_links or number_of_links (total), or left blank. If left blank, the values will be set from the those already in the grid fields, according to ‘fixed_link_value_of’.

fixed_node_value_of controls the name of the model field that contains the node values. Remember, if you don’t set value, the fixed gradient node values will be set from the field values *at the time you call this method*. If no values are present in the field, the module will complain but accept this, warning that it will be unable to automatically update boundary conditions (and such methods, e.g., RasterModelGrid.update_boundary_nodes(), will raise exceptions if you try).

fixed_link_value_of controls the name of the model field that contains the fixed link values. Remember, if you don’t set value, the fixed link values will be set from the field values *at the time you call this method*. If no values are present in the field, the module will complain but accept this, warning that it will be unable to automatically update boundary conditions (and such methods, e.g., RasterModelGrid.update_boundary_nodes(), will raise exceptions if you try).

The following example sets the bottom and right link boundaries as fixed-value in a four-row by nine-column grid that initially has all boundaries set to fixed_gradient (nodes, i.e. flagged at (status_at_node == 2) and fixed_link (links, i.e., flagged as (status_at_link == 2).

Parameters:

right_is_fixed : boolean

Set right edge horizontal links as fixed boundary.

top_is_fixed : boolean

Set top edge vertical links as fixed boundary.

left_is_fixed : boolean

Set left edge horizontal links as fixed boundary.

bottom_is_fixed : boolean

Set bottom edge vertical links as fixed boundary.

link_value : float, array or None (default).

Override value to be kept constant at links.

node_value : float, array or None (default).

Override value to be kept constant at nodes.

fixed_node_value_of : string.

The name of the grid field containing the values of interest at nodes.

fixed_link_value_of : string.

The name of the grid field containing the values of interest at links.

Examples

The following grid is used in the example:

*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*
^       ^       ^       ^       ^       ^       ^       ^       ^
I       X       X       X       X       X       X       X       I
|       |       |       |       |       |       |       |       |
*--X--->o       o       o       o       o       o       o--X--->*
^       ^       ^       ^       ^       ^       ^       ^       ^
I       |       |       |       |       |       |       |       I
|       |       |       |       |       |       |       |       |
*--X--->o       o       o       o       o       o       o--X--->*
^       ^       ^       ^       ^       ^       ^       ^       ^
I       X       X       X       X       X       X       X       I
|       |       |       |       |       |       |       |       |
*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*--I--->*

Note

Links set to ACTIVE_LINK are not indicated in this diagram.

* indicates the nodes that are set to FIXED_GRADIENT BOUNDARY

o indicates the nodes that are set to CORE_NODE

I indicates the links that are set to INACTIVE_LINK

X indicates the links that are set to FIXED_LINK

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 9), 1.0) # rows, columns, spacing
>>> import numpy as np
>>> z = np.arange(0, rmg.number_of_nodes)
>>> s = np.arange(0, rmg.number_of_links)
>>> rmg['node']['topographic__elevation'] = z
>>> rmg['link']['topographic__slope'] = s
>>> rmg.set_fixed_link_boundaries_at_grid_edges(True, True, True, True)
>>> rmg.status_at_node 
array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0,
       0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int8)
>>> rmg.status_at_link 
array([4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2, 0, 0, 0,
       0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 4, 2, 0, 0, 0, 0, 0, 0, 2,
       4, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4])
>>> rmg.fixed_link_properties['fixed_gradient_of']
'topographic__slope'
>>> rmg.fixed_gradient_node_properties['fixed_gradient_of']
'topographic__elevation'

LLCATS: BC SUBSET

set_fixed_value_boundaries_at_grid_edges(right_is_fixed_val, top_is_fixed_val, left_is_fixed_val, bottom_is_fixed_val, value=None, value_of='topographic__elevation')[source]

Create fixed values boundaries.

Sets the status of nodes along the specified side(s) of a raster grid—bottom, right, top, and/or left—to FIXED_VALUE_BOUNDARY.

Arguments are booleans indicating whether the bottom, right, top, and left sides are to be set (True) or not (False).

value controls what values are held constant at these nodes. It can be either a float, an array of length number_of_fixed_nodes or number_of_nodes (total), or left blank. If left blank, the values will be set from the those already in the grid fields, according to ‘value_of’.

value_of controls the name of the model field that contains the values. Remember, if you don’t set value, the fixed values will be set from the field values *at the time you call this method*. If no values are present in the field, the module will complain but accept this, warning that it will be unable to automatically update boundary conditions (and such methods, e.g., RasterModelGrid.update_boundary_nodes(), will raise exceptions if you try).

The status of links (active or inactive) is automatically updated to reflect the changes.

The following example sets the bottom and right boundaries as fixed-value in a four-row by five-column grid that initially has all boundaries closed (i.e., flagged as node_status=4):

Parameters:

bottom_is_fixed_val : boolean

Set bottom edge as fixed boundary.

left_is_fixed_val : boolean

Set left edge as fixed boundary.

top_is_fixed_val : boolean

Set top edge as fixed boundary.

right_is_fixed_val : boolean

Set right edge as fixed boundary.

value : float, array or None (default).

Override value to be kept constant at nodes.

value_of : string.

The name of the grid field containing the values of interest.

Examples

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5), spacing=(1, 1))
>>> rmg.number_of_active_links
17

Put some arbitrary values in the grid fields:

>>> import numpy as np
>>> rmg.at_node['topographic__elevation'] = np.random.rand(20)
>>> rmg.set_closed_boundaries_at_grid_edges(True, True, True, True)
>>> rmg.status_at_node 
array([4, 4, 4, 4, 4,
       4, 0, 0, 0, 4,
       4, 0, 0, 0, 4,
       4, 4, 4, 4, 4], dtype=int8)
>>> rmg.set_fixed_value_boundaries_at_grid_edges(
...     True, True, False, False)
>>> rmg.number_of_active_links
12
>>> rmg.status_at_node 
array([4, 4, 4, 4, 4,
       4, 0, 0, 0, 1,
       4, 0, 0, 0, 1,
       1, 1, 1, 1, 1], dtype=int8)

Note that the four corners are treated as follows:

  • bottom left = BOTTOM
  • bottom right = BOTTOM
  • top right = TOP
  • top left = TOP

This scheme is necessary for internal consistency with looped boundaries.

LLCATS: BC SUBSET

set_inactive_boundaries(*args, **kwargs)[source]

Set boundary nodes to be inactive.

Note

This method is deprecated as of Landlab version 0.5.

Use set_closed_boundaries_at_grid_edges() instead.

Handles boundary conditions by setting each of the four sides of the rectangular grid to either ‘inactive’ or ‘active (fixed value)’ status. Arguments are booleans indicating whether the bottom, right, top, and left are inactive (True) or not (False).

For an inactive boundary:

  • the nodes are flagged CLOSED_BOUNDARY (normally status type 4)
  • the links between them and the adjacent interior nodes are inactive (so they appear on link-based lists, but not active_link-based lists)

This means that if you call the calc_grad_at_active_link method, the inactive boundaries will be ignored: there can be no gradients or fluxes calculated, because the links that connect to that edge of the grid are not included in the calculation. So, setting a grid edge to CLOSED_BOUNDARY is a convenient way to impose a no-flux boundary condition. Note, however, that this applies to the grid as a whole, rather than a particular variable that you might use in your application. In other words, if you want a no-flux boundary in one variable but a different boundary condition for another, then use another method.

Notes

The four corners are treated as follows:

  • bottom left = BOTTOM
  • bottom right = BOTTOM
  • top right = TOP
  • top left = TOP

This scheme is necessary for internal consistency with looped boundaries.

LLCATS: DEPR BC SUBSET

Examples

The following example sets the top and left boundaries as inactive in a four-row by five-column grid that initially has all boundaries active and all boundary nodes coded as FIXED_VALUE_BOUNDARY (=1):

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5), 1.0) # rows, columns, spacing
>>> rmg.number_of_active_links
17
>>> rmg.status_at_node 
array([1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1],
      dtype=int8)
>>> rmg.set_inactive_boundaries(False, True, True, False)
>>> rmg.number_of_active_links
12
>>> rmg.status_at_node 
array([1, 1, 1, 1, 1, 4, 0, 0, 0, 1, 4, 0, 0, 0, 1, 4, 4, 4, 4, 4],
      dtype=int8)
set_looped_boundaries(top_bottom_are_looped, sides_are_looped)[source]

Create wrap-around boundaries.

Handles boundary conditions by setting corresponding parallel grid edges as looped “tracks_cell” (==3) status, linked to each other. If top_bottom_are_looped is True, the top and bottom edges will link to each other. If sides_are_looped is True, the left and right edges will link to each other.

Looped boundaries are experimental, and not as yet well integrated into the Landlab framework. Many functions may not recognise them, or silently create unforeseen errors. Use at your own risk!

Note that because of the symmetries this BC implies, the corner nodes are all paired with the bottom/top edges, not the sides.

Parameters:

top_bottom_are_looped : bool

Top and bottom are wrap-around.

sides_are_looped : bool

Left and right sides are wrap-around.

Examples

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5), 1.0) # rows, columns, spacing
>>> rmg.number_of_active_links
17
>>> rmg.status_at_node 
array([1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1],
      dtype=int8)
>>> rmg.add_zeros('topographic__elevation', at='node')
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> rmg.set_looped_boundaries(True, True)
>>> rmg.looped_node_properties['boundary_node_IDs']
array([ 0,  1,  2,  3,  4,  5,  9, 10, 14, 15, 16, 17, 18, 19])
>>> rmg.looped_node_properties['linked_node_IDs']
array([10, 11, 12, 13, 14,  8,  6, 13, 11,  5,  6,  7,  8,  9])

LLCATS: BC SUBSET

set_open_nodes_disconnected_from_watershed_to_closed(node_data, outlet_id=None, nodata_value=-9999.0, adjacency_method='D8')[source]

Identifys all non-closed nodes that are disconnected from the node given in outlet_id and sets them as closed.

If outlet_id is not given, the outlet will be identified as the node for which the status at the node is FIXED_VALUE_BOUNDARY. If more than one node has this value, the algorithm will fail.

If outlet_id is given, the algorithm will check that it is not a node with status of CLOSED_BOUNDARY.

The method supports both D4 and D8 (default) neighborhood evaluation in determining if a node is connected. This can be modified with the flag adjacency_method.

This function can be run directly, or by setting the flag remove_disconnected to True in set_watershed_boundary_condition

Parameters:

node_data : ndarray

Data values.

outlet_id : one element numpy array, optional.

The node ID of the outlet that all open nodes must be connected to. If a node ID is provided, it does not need have the status FIXED_VALUE_BOUNDARY. However, it must not have the status of CLOSED_BOUNDARY.

nodata_value : float, optional, default is -9999.

Value that indicates an invalid value.

adjacency_method : string, optional. Default is ‘D8’.

Sets the connection method.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg1 = RasterModelGrid((4,6))
>>> z1 = np.array([-9999., -9999., -9999.,  -9999., -9999., -9999.,
...                -9999.,    67.,    67.,  -9999.,    50., -9999.,
...                -9999.,    67.,     0.,  -9999., -9999., -9999.,
...                -9999., -9999., -9999.,  -9999., -9999., -9999.])
>>> mg2 = RasterModelGrid((4,6))
>>> z2 = np.array([-9999., -9999., -9999.,  -9999., -9999., -9999.,
...                -9999.,    67.,    67.,  -9999.,    50., -9999.,
...                -9999.,    67.,     0.,  -9999., -9999., -9999.,
...                -9999., -9999., -9999.,  -9999., -9999., -9999.])
>>> mg1.set_watershed_boundary_condition(z1, remove_disconnected=True)
>>> mg2.set_watershed_boundary_condition(z2)
>>> mg2.status_at_node.reshape(mg2.shape)
array([[4, 4, 4, 4, 4, 4],
      [4, 0, 0, 4, 0, 4],
      [4, 0, 1, 4, 4, 4],
      [4, 4, 4, 4, 4, 4]], dtype=int8)
>>> mg2.set_open_nodes_disconnected_from_watershed_to_closed(z2)
>>> np.allclose(mg1.status_at_node, mg2.status_at_node)
True
>>> np.allclose(z1, z2)
True
>>> mg2.status_at_node.reshape(mg2.shape)
array([[4, 4, 4, 4, 4, 4],
       [4, 0, 0, 4, 4, 4],
       [4, 0, 1, 4, 4, 4],
       [4, 4, 4, 4, 4, 4]], dtype=int8)
>>> z1.reshape(mg1.shape)
array([[-9999., -9999., -9999., -9999., -9999., -9999.],
       [-9999.,    67.,    67., -9999., -9999., -9999.],
       [-9999.,    67.,     0., -9999., -9999., -9999.],
       [-9999., -9999., -9999., -9999., -9999., -9999.]])

LLCATS: BC

set_status_at_node_on_edges(grid, right=None, top=None, left=None, bottom=None)

Set node status on grid edges.

Parameters:

right : int, optional

Node status along right edge.

top : int, optional

Node status along top edge.

left : int, optional

Node status along left edge.

bottom : int, optional

Node status along bottom edge.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> grid = RasterModelGrid((3, 4))
>>> grid.status_at_node 
array([1, 1, 1, 1,
       1, 0, 0, 1,
       1, 1, 1, 1], dtype=int8)
>>> grid.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)
>>> grid.status_at_node 
array([1, 1, 1, 4,
       1, 0, 0, 4,
       1, 1, 1, 4], dtype=int8)
>>> from landlab import FIXED_GRADIENT_BOUNDARY
>>> grid = RasterModelGrid((3, 4))

The status of a corner is set along with its clockwise edge. That is, if setting the status for the top and right edges, the upper-right corner has the status of the right edge.

>>> grid.set_status_at_node_on_edges(top=CLOSED_BOUNDARY,
...     right=FIXED_GRADIENT_BOUNDARY)
>>> grid.status_at_node 
array([1, 1, 1, 2,
       1, 0, 0, 2,
       4, 4, 4, 2], dtype=int8)

In the above example, if you wanted the corner to have the status of the top edge, you need to make two calls to set_status_at_node_on_edges,

>>> grid = RasterModelGrid((3, 4))
>>> grid.set_status_at_node_on_edges(right=FIXED_GRADIENT_BOUNDARY)
>>> grid.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)
>>> grid.status_at_node 
array([1, 1, 1, 2,
       1, 0, 0, 2,
       4, 4, 4, 4], dtype=int8)

An example that sets all of the edges shows how corners are set.

>>> grid.set_status_at_node_on_edges(right=1, top=2, left=3, bottom=4)
>>> grid.status_at_node 
array([3, 4, 4, 4,
       3, 0, 0, 1,
       2, 2, 2, 1], dtype=int8)

LLCATS: BC

set_watershed_boundary_condition(node_data, nodata_value=-9999.0, return_outlet_id=False, remove_disconnected=False, adjacency_method='D8')[source]

Finds the node adjacent to a boundary node with the smallest value. This node is set as the outlet. The outlet node must have a data value. Can return the outlet id as a one element numpy array if return_outlet_id is set to True.

All nodes with nodata_value are set to CLOSED_BOUNDARY (grid.status_at_node == 4). All nodes with data values are set to CORE_NODES (grid.status_at_node == 0), with the exception that the outlet node is set to a FIXED_VALUE_BOUNDARY (grid.status_at_node == 1).

Note that the outer ring (perimeter) of the raster is set to CLOSED_BOUNDARY, even if there are nodes that have values. The only exception to this would be if the outlet node is on the perimeter, which is acceptable.

This routine assumes that all of the nodata_values are on the outside of the data values. In other words, there are no islands of nodata_values surrounded by nodes with data.

This also assumes that the grid has a single watershed (that is a single outlet node).

If you are considering running flow routing algorithms on this model grid, it is recommended that you verify the absence of non-closed nodes surrounded only by closed nodes. The presence of these isolated non- closed nodes may result from clipping a raster to a polygon and will prevent the flow router from functioning as intended.

This can be acomplished by setting the parameter: remove_disconnected to True (default is False).

This will run the function: set_open_nodes_disconnected_from_watershed_to_closed which will find any isolated open nodes that have no neigbors in the main watershed and set them to closed. The adjacency method used to assess connectivity can be set to either ‘D8’(default) or ‘D4’ using the flag adjacency_method.

Finally, the developer has seen cases in which DEM data that has been filled results in a different outlet from DEM data which has not been filled. Be aware that if you identify an outlet on a filled DEM, make sure that the filled DEM is what is being used for your modeling. Otherwise, this may find a different outlet. To force the outlet location, use either set_watershed_boundary_condition_outlet_coords or set_watershed_boundary_condition_outlet_id.

Parameters:

node_data : ndarray

Data values.

nodata_value : float, optional

Value that indicates an invalid value.

return_outlet_id : boolean, optional

Indicates whether or not to return the id of the found outlet

remove_disconnected : boolean, optional

Indicates whether to search for and remove disconnected nodes.

adjacency_method : string, optional. Default is ‘D8’.

Sets the connection method for use if remove_disconnected==True

Examples

The first example will use a 4,4 grid with node data values as illustrated:

-9999. -9999. -9999. -9999. -9999. 67. 0. -9999. -9999. 67. 67. -9999. -9999. -9999. -9999. -9999.

The second example will use a 4,4 grid with node data values as illustrated:

-9999. -9999. -9999. -9999. -9999. 67. 0. -9999. -9999. 67. 67. -2. -9999. -9999. -9999. -9999. ——— >>> import numpy as np >>> from landlab import RasterModelGrid >>> rmg = RasterModelGrid((4,4),1.) >>> node_data = np.array([-9999., -9999., -9999., -9999., ... -9999., 67., 67., -9999., ... -9999., 67., 0., -9999., ... -9999., -9999., -9999., -9999.]) >>> out_id = rmg.set_watershed_boundary_condition(node_data, -9999., ... True) >>> out_id array([10]) >>> rmg.status_at_node array([4, 4, 4, 4, 4, 0, 0, 4, 4, 0, 1, 4, 4, 4, 4, 4], dtype=int8) >>> rmg2 = RasterModelGrid((4,4),1.) >>> node_data2 = np.array([-9999., -9999., -9999., -9999., ... -9999., 67., 67., -2., ... -9999., 67., 0., -9999., ... -9999., -9999., -9999., -9999.]) >>> rmg2.set_watershed_boundary_condition(node_data2, -9999.) >>> rmg2.status_at_node array([4, 4, 4, 4, 4, 0, 0, 1, 4, 0, 0, 4, 4, 4, 4, 4], dtype=int8)

LLCATS: BC

set_watershed_boundary_condition_outlet_coords(outlet_coords, node_data, nodata_value=-9999.0)[source]

Set the boundary conditions for a watershed. All nodes with nodata_value are set to CLOSED_BOUNDARY (grid.status_at_node == 4). All nodes with data values are set to CORE_NODES (grid.status_at_node == 0), with the exception that the outlet node is set to a FIXED_VALUE_BOUNDARY (grid.status_at_node == 1).

Note that the outer ring of the raster is set to CLOSED_BOUNDARY, even if there are nodes that have values. The only exception to this would be if the outlet node is on the boundary, which is acceptable.

Assumes that outlet is already known.

This assumes that the grid has a single watershed. If this is not the case this will not work.

This must be passed the values of the outlet_row and outlet_column. Also takes node_data and optionally, nodata_value.

Parameters:

outlet_coords : list - two integer values

row, column of outlet, NOT THE ABSOLUTE X AND Y LOCATIONS

node_data : ndarray

Data values.

nodata_value : float, optional

Value that indicates an invalid value.

Examples

The example will use a 4,4 grid with node data values as illustrated:

-9999. -9999. -9999. -9999. -9999. 67. 0. -9999. -9999. 67. 67. -9999. -9999. -9999. -9999. -9999.

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4,4),1.)
>>> rmg.status_at_node
array([1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8)
>>> node_data = np.array([-9999., -9999., -9999., -9999.,
...                      -9999.,    67.,    67., -9999.,
...                      -9999.,    67.,     0., -9999.,
...                      -9999., -9999., -9999., -9999.])
>>> rmg.set_watershed_boundary_condition_outlet_coords(
...     (2, 2), node_data, -9999.)
>>> rmg.status_at_node
array([4, 4, 4, 4, 4, 0, 0, 4, 4, 0, 1, 4, 4, 4, 4, 4], dtype=int8)

LLCATS: BC

set_watershed_boundary_condition_outlet_id(outlet_id, node_data, nodata_value=-9999.0)[source]

Set the boundary conditions for a watershed. All nodes with nodata_value are set to CLOSED_BOUNDARY (4). All nodes with data values are set to CORE_NODES (0), with the exception that the outlet node is set to a FIXED_VALUE_BOUNDARY (1).

Note that the outer ring of the raster is set to CLOSED_BOUNDARY, even if there are nodes that have values. The only exception to this would be if the outlet node is on the boundary, which is acceptable.

Assumes that the id of the outlet is already known.

This assumes that the grid has a single watershed. If this is not the case this will not work.

Parameters:

outlet_id : integer

id of the outlet node

node_data : ndarray

Data values.

nodata_value : float, optional

Value that indicates an invalid value.

Returns:

outlet_loc : int

id of outlet location

Examples

The example will use a 4,4 grid with node data values as illustrated:

-9999. -9999. -9999. -9999. -9999. 67. 0. -9999. -9999. 67. 67. -9999. -9999. -9999. -9999. -9999.

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4,4),1.)
>>> rmg.status_at_node
array([1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int8)
>>> node_data = np.array([-9999., -9999., -9999., -9999.,
...                      -9999.,    67.,    67., -9999.,
...                      -9999.,    67.,     0., -9999.,
...                      -9999., -9999., -9999., -9999.])
>>> outlet = rmg.set_watershed_boundary_condition_outlet_id(
...     10, node_data, -9999.)
>>> rmg.status_at_node
array([4, 4, 4, 4, 4, 0, 0, 4, 4, 0, 1, 4, 4, 4, 4, 4], dtype=int8)

LLCATS: BC

shape

Get the shape of the grid.

Returns:

shape : tuple of ints

The shape of the grid as number of node rows and node columns.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 4))
>>> grid.shape
(3, 4)

LLCATS: GINF NINF

snap_coords_to_grid(*args, **kwargs)[source]

Snap coordinates to the nearest node.

Note

This method is deprecated as of Landlab version 0.2.

Use find_nearest_node() instead.

This method takes existing coordinates, inside the grid, and returns the ID of the closest grid node. That node can be a boundary node.

LLCATS: DEPR NINF SUBSET

update_boundary_nodes(*args, **kwargs)[source]

Update the boundary nodes.

Note

This method is deprecated as of Landlab version 1.0.

Use _update_links_nodes_cells_to_new_BCs() instead.

This method updates all the boundary nodes in the grid field on which they are set (i.e., it updates the field rmg.at_node[rmg.fixed_gradient_node_properties[‘fixed_gradient_of’]]). It currently works only with fixed value (type 1) and fixed gradient (type 2) conditions. Looping must be handled internally to a component, and is not dealt with here.

LLCATS: DEPR NINF BC

update_noflux_boundaries(*args, **kwargs)[source]

Deprecated.

Note

This method is deprecated as of Landlab version 0.1.

Use set_closed_boundaries_at_grid_edges() instead.

Sets the value of u at all noflux boundary cells equal to the value of their interior neighbors, as recorded in the “boundary_nbrs” array.

LLCATS: DEPR BC

LLCATS: LINF

class RasterModelGridPlotter[source]

Bases: object

MixIn that provides plotting functionality.

Inhert from this class to provide a ModelDataFields object with the method function, imshow, that plots a data field.

imshow(group, var_name, **kwds)[source]

Plot a data field.

This is a wrapper for plot.imshow_grid, and can take the same keywords. See that function for full documentation.

Parameters:

group : str

Name of group.

var_name : str

Name of field

See also

landlab.plot.imshow_grid

LLCATS
GINF
from_dict(param_dict)[source]

Create a RasterModelGrid from a dict-like object.

Create a RasterModelGrid from the dictionary-like object, param_dict. Required keys of the dictionary are NUM_ROWS, NUM_COLS. Raises a KeyError if either of these are missing is given, use it as the HexModelGrid dx parameter, otherwise default to unit spacing.

grid_edge_is_closed_from_dict(boundary_conditions)[source]

Get a list of closed-boundary status at grid edges.

Get a list that indicates grid edges that are closed boundaries. The returned list provides a boolean that gives the boundary condition status for edges order as [bottom, left, top, right].

boundary_conditions is a dict whose keys indicate edge location (as “bottom”, “left”, “top”, “right”) and values must be one of “open”, or “closed”. If an edge location key is missing, that edge is assumed to be open.

Parameters:

boundary_conditions : dict

Boundary condition for grid edges.

Returns:

list

List of booleans indicating if an edge is a closed boundary.

Examples

>>> from landlab.grid.raster import grid_edge_is_closed_from_dict
>>> grid_edge_is_closed_from_dict(dict(bottom='closed', top='open'))
[False, False, False, True]
>>> grid_edge_is_closed_from_dict({})
[False, False, False, False]

Mapping data between different grid elements

Grid element mappers that are specific to raster grids.

Mapping functions unique to raster grids

map_sum_of_inlinks_to_node(grid, var_name[, out]) Map the sum of links entering a node to the node.
map_mean_of_inlinks_to_node(grid, var_name) Map the mean of links entering a node to the node.
map_max_of_inlinks_to_node(grid, var_name[, out]) Map the maximum of links entering a node to the node.
map_min_of_inlinks_to_node(grid, var_name[, out]) Map the minimum of links entering a node to the node.
map_sum_of_outlinks_to_node(grid, var_name) Map the sum of links leaving a node to the node.
map_mean_of_outlinks_to_node(grid, var_name) Map the mean of links leaving a node to the node.
map_max_of_outlinks_to_node(grid, var_name) Map the max of links leaving a node to the node.
map_min_of_outlinks_to_node(grid, var_name) Map the min of links leaving a node to the node.
map_mean_of_links_to_node(grid, var_name[, out]) Map the mean of links touching a node to the node.
map_mean_of_horizontal_links_to_node(grid, ...) Map the mean of links in the x direction touching a node to the node.
map_mean_of_horizontal_active_links_to_node(...) Map the mean of active links in the x direction touching node to the node.
map_mean_of_vertical_links_to_node(grid, ...) Map the mean of links in the y direction touching a node to the node.
map_mean_of_vertical_active_links_to_node(...) Map the mean of active links in the y direction touching node to the node.

Map the maximum of links entering a node to the node.

map_max_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. it finds the maximum value at the the inlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_max_of_inlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_max_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_max_of_inlinks_to_node(rmg, 'z')
array([  0.,   0.,   1.,   2.,
         3.,   7.,   8.,   9.,
        10.,  14.,  15.,  16.])

LLCATS: NINF LINF MAP

Map the max of links leaving a node to the node.

map_max_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. it finds the maximum value at the the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_max_of_outlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_max_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_max_of_outlinks_to_node(rmg, 'z')
array([  3.,   4.,   5.,   6.,  10.,  11.,  12.,  13.,  14.,  15.,  16.,
         0.])

LLCATS: NINF LINF MAP

Map the mean of active links in the x direction touching node to the node.

map_mean_of_horizontal_active_links_to_node takes an array at the links and finds the average of all horizontal (x-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. If a node has no active links, it receives 0. Note that here a positive returned value means flux to the east, and a negative to the west.

Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_horizontal_active_links_to_node
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', -np.arange(17, dtype=float))
>>> rmg.status_at_node[rmg.nodes_at_left_edge] = CLOSED_BOUNDARY
>>> map_mean_of_horizontal_active_links_to_node(rmg, 'z')
array([ 0. ,  0. ,  0. ,  0. ,  0. , -8. , -8.5, -9. ,  0. ,  0. ,  0. ,
        0. ])

LLCATS: NINF LINF MAP

Map the mean of links in the x direction touching a node to the node.

map_mean_of_horizontal_links_to_node takes an array at the links and finds the average of all horizontal (x-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. Note that here a positive returned value means flux to the east, and a negative to the west.

Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_horizontal_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_horizontal_links_to_node(rmg, 'z')
array([  0. ,   0.5,   1.5,   2. ,   7. ,   7.5,   8.5,   9. ,  14. ,
        14.5,  15.5,  16. ])

LLCATS: NINF LINF MAP

Map the mean of links entering a node to the node.

map_mean_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. It finds the average of the inlinks and returns values at the nodes.

This considers all inactive links to have a value of 0.

Construction:

map_mean_of_inlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_inlinks_to_node(rmg, 'z')
array([  0. ,   0. ,   0.5,   1. ,   1.5,   5.5,   6.5,   7.5,   5. ,
        12.5,  13.5,  14.5])

LLCATS: NINF LINF MAP

Map the mean of links touching a node to the node.

map_mean_all_links_to_node takes an array at the links and finds the average of all ~existing~ link neighbor values for each node in the grid. it returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_mean_of_links_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_links_to_node(rmg, 'z')
array([  1.5       ,   1.66666667,   2.66666667,   4.        ,
         6.66666667,   7.5       ,   8.5       ,   9.33333333,
        12.        ,  13.33333333,  14.33333333,  14.5       ])

LLCATS: NINF LINF MAP

Map the mean of links leaving a node to the node.

map_mean_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. it finds the average of the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_mean_of_outlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_outlinks_to_node(rmg, 'z')
array([  1.5,   2.5,   3.5,   3. ,   8.5,   9.5,  10.5,   6.5,   7. ,
         7.5,   8. ,   0. ])

LLCATS: NINF LINF MAP

Map the mean of active links in the y direction touching node to the node.

map_mean_of_vertical_active_links_to_node takes an array at the links and finds the average of all vertical (y-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. If a node has no active links, it receives 0. Note that here a positive returned value means flux to the north, and a negative to the south.

Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_vertical_active_links_to_node
>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', -np.arange(17, dtype=float))
>>> rmg.status_at_node[rmg.nodes_at_bottom_edge] = CLOSED_BOUNDARY
>>> map_mean_of_vertical_active_links_to_node(rmg, 'z')
array([  0.,   0.,   0.,   0.,   0., -11., -12.,   0.,   0., -11., -12.,
         0.])

LLCATS: NINF LINF MAP

Map the mean of links in the y direction touching a node to the node.

map_mean_of_vertical_links_to_node takes an array at the links and finds the average of all vertical (y-direction) link neighbor values for each node in the grid. It returns an array at the nodes of the mean of these values. If a link is absent, it is ignored. Note that here a positive returned value means flux to the north, and a negative to the south.

Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_mean_of_vertical_links_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_mean_of_vertical_links_to_node(rmg, 'z')
array([  3. ,   4. ,   5. ,   6. ,   6.5,   7.5,   8.5,   9.5,  10. ,
        11. ,  12. ,  13. ])

LLCATS: NINF LINF MAP

Map the minimum of links entering a node to the node.

map_min_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. it finds the minimum value at the the inlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_min_of_inlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_min_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_min_of_inlinks_to_node(rmg, 'z')
array([  0.,   0.,   0.,   0.,   0.,   4.,   5.,   6.,   0.,  11.,  12.,
        13.])

LLCATS: NINF LINF MAP

Map the min of links leaving a node to the node.

map_min_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. It finds the minimum value at the the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_min_of_outlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_min_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_min_of_outlinks_to_node(rmg, 'z')
array([ 0.,  1.,  2.,  0.,  7.,  8.,  9.,  0.,  0.,  0.,  0.,  0.])

LLCATS: NINF LINF MAP

Map the sum of links entering a node to the node.

map_sum_of_inlinks_to_node takes an array at the links and finds the inlink values for each node in the grid. it sums the inlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_sum_of_inlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_sum_of_inlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_sum_of_inlinks_to_node(rmg, 'z')
array([  0.,   0.,   1.,   2.,   3.,  11.,  13.,  15.,  10.,  25.,  27.,
        29.])

LLCATS: NINF LINF MAP

Map the sum of links leaving a node to the node.

map_sum_of_outlinks_to_node takes an array at the links and finds the outlink values for each node in the grid. it sums the outlinks and returns values at the nodes.

Note

This considers all inactive links to have a value of 0.

Construction:

map_sum_of_outlinks_to_node(grid, var_name, out=None)
Parameters:

grid : ModelGrid

A landlab ModelGrid.

var_name : array or field name

Values defined at links.

out : ndarray, optional

Buffer to place mapped values into or None to create a new array.

Returns:

ndarray

Mapped values at nodes.

Examples

>>> import numpy as np
>>> from landlab.grid.raster_mappers import map_sum_of_outlinks_to_node
>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((3, 4))
>>> _ = rmg.add_field('link', 'z', np.arange(17.))
>>> map_sum_of_outlinks_to_node(rmg, 'z')
array([  3.,  5.,  7.,   6.,  17.,  19.,  21.,  13.,  14.,  15.,  16.,
         0.])

LLCATS: NINF LINF MAP

Gradient calculation functions

Calculate gradients on a raster grid.

Gradient calculators for raster grids

calc_grad_at_link(grid, vals, \*args, \*\*kwds) Calculate gradients in node_values at links.
calc_grad_at_active_link(grid, vals, \*args, ...) Calculate gradients over active links.
calc_grad_across_cell_faces(grid, vals, ...) Get gradients across the faces of a cell.
calc_grad_across_cell_corners(grid, vals, ...) Get gradients to diagonally opposite nodes.
landlab.grid.raster_gradients.alculate_gradient_along_node_links
calc_aspect_at_cell_subtriangles(grid, elevs='topographic__elevation', subtriangle_unit_normals=None, unit='degrees')[source]

Get tuple of arrays of aspect of each of the eight cell subtriangles.

Aspect is returned as radians clockwise of north, unless input parameter units is set to ‘degrees’.

If subtriangle_unit_normals is provided the aspect will be calculated from these data.

If it is not, it will be derived from elevation data at the nodes, which can either be a string referring to a grid field (default: ‘topographic__elevation’), or an nnodes-long numpy array of the values themselves.

Parameters:

grid : ModelGrid

A ModelGrid.

elevs : str or array (optional)

Node field name or node array of elevations. If subtriangle_unit_normals is not provided, must be set, but unused otherwise.

subtriangle_unit_normals : tuple of 8 (ncels, 3) arrays (optional)

The unit normal vectors for the eight subtriangles of each cell, if already known. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

unit : {‘degrees’, ‘radians’}

Controls the unit that the aspect is returned as.

Returns:

(a_ENE, a_NNE, a_NNW, a_WNW, a_WSW, a_SSW, a_SSE, a_ESE) :

each a length num-cells array

Len-8 tuple of the aspect of each of the eight cell subtriangles. Aspect is returned as angle clockwise of north. Units are given as radians unless input parameter units is set to ‘degrees’. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> z = np.array([1., 0., 1., 0., 0., 0., 1., 0., 1.])
>>> eight_tris = mg.calc_unit_normals_at_cell_subtriangles(z)
>>> A = mg.calc_aspect_at_cell_subtriangles(z, eight_tris)
>>> A0 = mg.calc_aspect_at_cell_subtriangles(z)
>>> np.allclose(A, A0)
True
>>> type(A) is tuple
True
>>> len(A)
8
>>> len(A[0]) == mg.number_of_cells
True
>>> A0  
(array([ 180.]), array([ 270.]), array([ 90.]), array([ 180.]),
 array([ 0.]), array([ 90.]), array([ 270.]), array([ 0.]))

LLCATS: CINF SURF

calc_grad_across_cell_corners(grid, vals, *args, **kwds)[source]

Get gradients to diagonally opposite nodes.

Calculate gradient of the value field provided by node_values to the values at diagonally opposite nodes. The returned gradients are ordered as upper-right, upper-left, lower-left and lower-right.

Construction:

grid.calc_grad_across_cell_corners(node_values, [cell_ids],
                                            out=None)
Parameters:

node_values : array_like or field name

Quantity to take the gradient of defined at each node.

cell_ids : array_like, optional

If provided, cell ids to measure gradients. Otherwise, find gradients for all cells.

out : array_like, optional

Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.

Returns:

(N, 4) ndarray

Gradients to each diagonal node.

Examples

Create a grid with two cells.

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(3, 4)
>>> x = np.array([1., 0., 0., 1.,
...               0., 0., 1., 1.,
...               3., 3., 3., 3.])

A decrease in quantity to a diagonal node is a negative gradient.

>>> from math import sqrt
>>> grid.calc_grad_across_cell_corners(x) * sqrt(2.)
array([[ 3.,  3.,  1.,  0.],
       [ 2.,  2., -1.,  0.]])
>>> grid = RasterModelGrid((3, 4), spacing=(3, 4))
>>> grid.calc_grad_across_cell_corners(x)
array([[ 0.6,  0.6,  0.2,  0. ],
       [ 0.4,  0.4, -0.2,  0. ]])

LLCATS: CNINF GRAD

calc_grad_across_cell_faces(grid, vals, *args, **kwds)[source]

Get gradients across the faces of a cell.

Calculate gradient of the value field provided by node_values across each of the faces of the cells of a grid. The returned gradients are ordered as right, top, left, and bottom.

Note that the returned gradients are masked to exclude neighbor nodes which are closed. Beneath the mask is the value -1.

Construction:

grid.calc_grad_across_cell_faces(node_values, [cell_ids],
                                          out=None)
Parameters:

node_values : array_like or field name

Quantity to take the gradient of defined at each node.

cell_ids : array_like, optional

If provided, cell ids to measure gradients. Otherwise, find gradients for all cells.

out : array_like, optional

Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.

Returns:

(N, 4) Masked ndarray

Gradients for each face of the cell.

Examples

Create a grid with two cells.

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(3, 4)
>>> x = np.array([0., 0., 0., 0.,
...               0., 0., 1., 1.,
...               3., 3., 3., 3.])

A decrease in quantity across a face is a negative gradient.

>>> grid.calc_grad_across_cell_faces(x) 
masked_array(data =
 [[ 1.  3.  0.  0.]
 [ 0.  2. -1. -1.]],
             mask =
 False,
       fill_value = 1e+20)
>>> grid = RasterModelGrid((3, 4), spacing=(2, 1))
>>> grid.calc_grad_across_cell_faces(x) 
masked_array(data =
 [[ 1.   1.5  0.   0. ]
 [ 0.   1.  -1.  -0.5]],
              mask =
 False,
       fill_value = 1e+20)

LLCATS: FINF GRAD

Get gradients along links touching a node.

Calculate gradient of the value field provided by node_values across each of the faces of the nodes of a grid. The returned gradients are ordered as right, top, left, and bottom. All returned values follow our standard sign convention, where a link pointing N or E and increasing in value is positive, a link pointing S or W and increasing in value is negative.

Note that the returned gradients are masked to exclude neighbor nodes which are closed. Beneath the mask is the value -1.

Construction:

grid.calc_grad_along_node_links(node_values, [cell_ids],
                                         out=None)
Parameters:

node_values : array_like or field name

Quantity to take the gradient of defined at each node.

node_ids : array_like, optional

If provided, node ids to measure gradients. Otherwise, find gradients for all nodes.

out : array_like, optional

Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.

Returns:

(N, 4) Masked ndarray

Gradients for each link of the node. Ordering is E,N,W,S.

Examples

Create a grid with nine nodes.

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(3, 3)
>>> x = np.array([0., 0., 0.,
...               0., 1., 2.,
...               2., 2., 2.])

A decrease in quantity across a face is a negative gradient.

>>> grid.calc_grad_along_node_links(x) 
masked_array(data =
 [[-- -- -- --]
 [-- 1.0 -- --]
 [-- -- -- --]
 [1.0 -- -- --]
 [1.0 1.0 1.0 1.0]
 [-- -- 1.0 --]
 [-- -- -- --]
 [-- -- -- 1.0]
 [-- -- -- --]],
             mask =
 [[ True  True  True  True]
 [ True False  True  True]
 [ True  True  True  True]
 [False  True  True  True]
 [False False False False]
 [ True  True False  True]
 [ True  True  True  True]
 [ True  True  True False]
 [ True  True  True  True]],
       fill_value = 1e+20)
>>> grid = RasterModelGrid((3, 3), spacing=(2, 4))
>>> grid.calc_grad_along_node_links(x) 
masked_array(data =
 [[-- -- -- --]
 [-- 0.5 -- --]
 [-- -- -- --]
 [0.25 -- -- --]
 [0.25 0.5 0.25 0.5]
 [-- -- 0.25 --]
 [-- -- -- --]
 [-- -- -- 0.5]
 [-- -- -- --]],
             mask =
 [[ True  True  True  True]
 [ True False  True  True]
 [ True  True  True  True]
 [False  True  True  True]
 [False False False False]
 [ True  True False  True]
 [ True  True  True  True]
 [ True  True  True False]
 [ True  True  True  True]],
       fill_value = 1e+20)

LLCATS: NINF LINF GRAD

Calculate gradients over active links.

Deprecated since version 0.1: Use calc_grad_across_cell_faces() or calc_grad_across_cell_corners() instead

Calculates the gradient in quantity s at each active link in the grid. This is nearly identical to the method of the same name in ModelGrid, except that it uses a constant node spacing for link length to improve efficiency.

Note that a negative gradient corresponds to a lower node in the direction of the link.

Returns:

ndarray

Gradients of the nodes values for each link.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid(4, 5, 1.0)
>>> u = [0., 1., 2., 3., 0.,
...      1., 2., 3., 2., 3.,
...      0., 1., 2., 1., 2.,
...      0., 0., 2., 2., 0.]
>>> grad = grid.calc_grad_at_active_link(u)
>>> grad 
array([ 1.,  1., -1.,
        1.,  1., -1.,  1.,
       -1., -1., -1.,
        1.,  1., -1.,  1.,
       -1.,  0.,  1.])

For greater speed, sending a pre-created numpy array as an argument avoids having to create a new one with each call:

>>> grad = np.empty(grid.number_of_active_links)
>>> rtn = grid.calc_grad_at_active_link(u, out=grad)
>>> grad 
array([ 1.,  1., -1.,
        1.,  1., -1.,  1.,
       -1., -1., -1.,
        1.,  1., -1.,  1.,
       -1.,  0.,  1.])
>>> rtn is grad
True
>>> grid = RasterModelGrid((3, 3), spacing=(1, 2))
>>> node_values = [0., 0., 0.,
...                1., 3., 1.,
...                2., 2., 2.]
>>> grid.calc_grad_at_active_link(node_values)
array([ 3.,  1., -1., -1.])

This function is deprecated. Instead, use calc_grad_at_link.

>>> grid = RasterModelGrid((3, 3), spacing=(1, 2))
>>> node_values = [0., 0., 0.,
...                1., 3., 1.,
...                2., 2., 2.]
>>> grid.calc_grad_at_link(node_values)[grid.active_links]
array([ 3.,  1., -1., -1.])

LLCATS: LINF GRAD

Calculate gradients in node_values at links.

Construction:

calc_grad_at_link(grid, node_values, out=None)
Parameters:

grid : RasterModelGrid

A grid.

node_values : array_like or field name

Values at nodes.

out : ndarray, optional

Buffer to hold result. If None, create a new array.

Returns:

ndarray

Gradients of the nodes values for each link.

Examples

>>> from landlab import RasterModelGrid
>>> grid = RasterModelGrid((3, 3))
>>> node_values = [0., 0., 0.,
...                1., 3., 1.,
...                2., 2., 2.]
>>> grid.calc_grad_at_link(node_values)
array([ 0.,  0.,  1.,  3.,  1.,  2., -2.,  1., -1.,  1.,  0.,  0.])
>>> out = np.empty(grid.number_of_links, dtype=float)
>>> rtn = grid.calc_grad_at_link(node_values, out=out)
>>> rtn is out
True
>>> out
array([ 0.,  0.,  1.,  3.,  1.,  2., -2.,  1., -1.,  1.,  0.,  0.])
>>> grid = RasterModelGrid((3, 3), spacing=(1, 2))
>>> grid.calc_grad_at_link(node_values)
array([ 0.,  0.,  1.,  3.,  1.,  1., -1.,  1., -1.,  1.,  0.,  0.])
>>> _ = grid.add_field('node', 'elevation', node_values)
>>> grid.calc_grad_at_link('elevation')
array([ 0.,  0.,  1.,  3.,  1.,  1., -1.,  1., -1.,  1.,  0.,  0.])

LLCATS: LINF GRAD

calc_grad_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, subtriangle_unit_normals=None, slope_magnitude=None)[source]

Calculate the components of the gradient of each raster patch.

Returns the mean gradient of the four possible patch subtriangles, in radians.

If ignore_closed_nodes is True, closed nodes do not affect gradient calculations. If more than one closed node is present in a patch, the patch gradients in both x and y directions are set to zero.

Parameters:

grid : RasterModelGrid

A grid.

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

subtriangle_unit_normals : tuple of 4 (npatches, 3) arrays (optional)

The unit normal vectors for the four subtriangles of each patch, if already known. Order is TR, TL, BL, BR.

slope_magnitude : array with size num_patches (optional)

The mean slope of each patch, if already known. Units must be the same as provided here!

Returns:

gradient_tuple : (x_component_at_patch, y_component_at_patch)

Len-2 tuple of arrays giving components of gradient in the x and y directions, in the units of radians.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_y
>>> (x_grad, y_grad) = mg.calc_grad_at_patch(elevs=z)
>>> np.allclose(y_grad, np.pi/4.)
True
>>> np.allclose(x_grad, 0.)
True
>>> from landlab import CLOSED_BOUNDARY, FIXED_VALUE_BOUNDARY
>>> z = mg.node_x.copy()
>>> mg.set_closed_boundaries_at_grid_edges(True, True, True, True)
>>> mg.status_at_node[11] = CLOSED_BOUNDARY
>>> mg.status_at_node[[9, 2]] = FIXED_VALUE_BOUNDARY
>>> z[11] = 100.  # this should get ignored now
>>> z[9] = 2.  # this should be felt by patch 7 only
>>> z[2] = 1.  # should be felt by patches 1 and 2
>>> xgrad, ygrad = mg.calc_grad_at_patch(
...     elevs=z, ignore_closed_nodes=True)
>>> (xgrad.reshape((3, 4)) * 4./np.pi)[1, 1:]
array([ 1.,  1., -1.])
>>> np.allclose(ygrad[1:3], xgrad[1:3])
True

LLCATS: PINF GRAD

calc_slope_at_cell_subtriangles(grid, elevs='topographic__elevation', subtriangle_unit_normals=None)[source]

Calculate the slope (positive magnitude of gradient) at each of the eight cell subtriangles.

Parameters:

grid : RasterModelGrid

A grid.

elevs : str or ndarray, optional

Field name or array of node values.

subtriangle_unit_normals : tuple of 8 (ncells, 3) arrays (optional)

The unit normal vectors for the eight subtriangles of each cell, if already known. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Returns:

(s_ENE, s_NNE, s_NNW, s_WNW, s_WSW, s_SSW, s_SSE, s_ESE) :

each a length num-cells array Len-8 tuple of the slopes (positive gradient magnitude) of each of the eight cell subtriangles, in radians. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> z = np.array([np.sqrt(3.), 0., 4./3.,
...               0., 0., 0.,
...               1., 0., 1./np.sqrt(3.)])
>>> eight_tris = mg.calc_unit_normals_at_cell_subtriangles(z)
>>> S = mg.calc_slope_at_cell_subtriangles(z, eight_tris)
>>> S0 = mg.calc_slope_at_cell_subtriangles(z)
>>> np.allclose(S, S0)
True
>>> type(S) is tuple
True
>>> len(S)
8
>>> len(S[0]) == mg.number_of_cells
True
>>> np.allclose(S[0], S[1])
True
>>> np.allclose(S[2], S[3])
True
>>> np.allclose(S[4], S[5])
True
>>> np.allclose(S[6], S[7])
True
>>> np.allclose(np.rad2deg(S[0])[0], 30.)
True
>>> np.allclose(np.rad2deg(S[2])[0], 45.)
True
>>> np.allclose(np.rad2deg(S[4])[0], 60.)
True
>>> np.allclose(np.cos(S[6])[0], 3./5.)
True

LLCATS: CINF GRAD

calc_slope_at_node(grid, elevs='topographic__elevation', method='patch_mean', ignore_closed_nodes=True, return_components=False)[source]

Array of slopes at nodes, averaged over neighboring patches.

Produces a value for node slope (i.e., mean gradient magnitude) at each node in a manner analogous to a GIS-style slope map. If method==’patch_mean’, it averages the gradient on each of the patches surrounding the node; if method==’Horn’, it returns the resolved slope direction. Directional information can still be returned through use of the return_components keyword. All values are returned in radians, including the components; take the tan to recover the rise/run.

Note that under these definitions, it is not always true that:

mag, cmp = mg.calc_slope_at_node(z)
mag**2 == cmp[0]**2 + cmp[1]**2  # only if method=='Horn'

If ignore_closed_nodes is False, all proximal elevation values will be used in the calculation. If True, only unclosed nodes are used.

This is a verion of this code specialized for a raster. It subdivides the four square patches around each node into subtriangles, in order to ensure more correct solutions that incorporate equally weighted information from all surrounding nodes on rough surfaces.

Parameters:

elevs : str or ndarray, optional

Field name or array of node values.

method : {‘patch_mean’, ‘Horn’}

Controls the slope algorithm. Current options are ‘patch_mean’, which takes the mean slope of each pf the four neighboring square patches, and ‘Horn’, which is the standard ArcGIS slope algorithm. These produce very similar solutions; the Horn method gives a vector mean and the patch_mean gives a scalar mean.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

return_components : bool

If True, return a tuple, (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If false, return an array of floats of the slope magnitude.

Returns:

float array or length-2 tuple of float arrays

If return_components, returns (array_of_magnitude, (array_of_slope_x_radians, array_of_slope_y_radians)). If not return_components, returns an array of slope magnitudes.

Examples

>>> import numpy as np
>>> from landlab import RadialModelGrid, RasterModelGrid
>>> mg = RasterModelGrid((5, 5), 1.)
>>> z = mg.node_x
>>> slopes = mg.calc_slope_at_node(elevs=z)
>>> np.allclose(slopes, np.pi / 4.)
True
>>> mg = RasterModelGrid((4, 5), 2.)
>>> z = - mg.node_y
>>> slope_mag, cmp = mg.calc_slope_at_node(elevs=z,
...                                        return_components=True)
>>> np.allclose(slope_mag, np.pi / 4.)
True
>>> np.allclose(cmp[0], 0.)
True
>>> np.allclose(cmp[1], - np.pi / 4.)
True
>>> mg = RasterModelGrid((4, 4))
>>> z = mg.node_x ** 2 + mg.node_y ** 2
>>> slopes, cmp = mg.calc_slope_at_node(z, return_components=True)
>>> slopes
array([ 0.95531662,  1.10991779,  1.32082849,  1.37713803,  1.10991779,
        1.20591837,  1.3454815 ,  1.38904403,  1.32082849,  1.3454815 ,
        1.39288142,  1.41562833,  1.37713803,  1.38904403,  1.41562833,
        1.43030663])
>>> np.allclose(cmp[0].reshape((4, 4))[:, 0],
...             cmp[1].reshape((4, 4))[0, :])  # test radial symmetry
True

LLCATS: NINF GRAD SURF

calc_slope_at_patch(grid, elevs='topographic__elevation', ignore_closed_nodes=True, subtriangle_unit_normals=None)[source]

Calculate the slope (positive magnitude of gradient) at raster patches.

Returns the mean of the slopes of the four possible patch subtriangles.

If ignore_closed_nodes is True, closed nodes do not affect slope calculations. If more than one closed node is present in a patch, the patch slope is set to zero.

Parameters:

grid : RasterModelGrid

A grid.

elevs : str or ndarray, optional

Field name or array of node values.

ignore_closed_nodes : bool

If True, do not incorporate values at closed nodes into the calc.

subtriangle_unit_normals : tuple of 4 (npatches, 3) arrays (optional)

The unit normal vectors for the four subtriangles of each patch, if already known. Order is TR, TL, BL, BR.

Returns:

slopes_at_patch : n_patches-long array

The slope (positive gradient magnitude) of each patch, in radians.

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_x
>>> S = mg.calc_slope_at_patch(elevs=z)
>>> S.size == mg.number_of_patches
True
>>> np.allclose(S, np.pi/4.)
True
>>> z = mg.node_y**2
>>> mg.calc_slope_at_patch(elevs=z).reshape((3, 4))
array([[ 0.78539816,  0.78539816,  0.78539816,  0.78539816],
       [ 1.24904577,  1.24904577,  1.24904577,  1.24904577],
       [ 1.37340077,  1.37340077,  1.37340077,  1.37340077]])
>>> from landlab import CLOSED_BOUNDARY, FIXED_VALUE_BOUNDARY
>>> z = mg.node_x.copy()
>>> mg.set_closed_boundaries_at_grid_edges(True, True, True, True)
>>> mg.status_at_node[11] = CLOSED_BOUNDARY
>>> mg.status_at_node[9] = FIXED_VALUE_BOUNDARY
>>> z[11] = 100.  # this should get ignored now
>>> z[9] = 2.  # this should be felt by patch 7 only
>>> mg.calc_slope_at_patch(elevs=z, ignore_closed_nodes=True).reshape(
...     (3, 4)) * 4./np.pi
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.]])

LLCATS: PINF GRAD

calc_unit_normals_at_cell_subtriangles(grid, elevs='topographic__elevation')[source]

Calculate unit normals on a cell.

Calculate the eight unit normal vectors <a, b, c> to the eight subtriangles of a four-cornered (raster) cell.

Parameters:

grid : RasterModelGrid

A grid.

elevs : str or ndarray, optional

Field name or array of node values.

Returns:

(n_ENE, n_NNE, n_NNW, n_WNW, n_WSW, n_SSW, n_SSE, n_ESE) :

each a num-cells x length-3 array Len-8 tuple of the eight unit normal vectors <a, b, c> for the eight subtriangles in the cell. Order is from north of east, counter clockwise to south of east (East North East, North North East, North North West, West North West, West South West, South South West, South South East, East South East).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((3, 3))
>>> z = mg.node_x ** 2
>>> eight_tris = mg.calc_unit_normals_at_cell_subtriangles(z)
>>> type(eight_tris) is tuple
True
>>> len(eight_tris)
8
>>> eight_tris[0].shape == (mg.number_of_cells, 3)
True
>>> eight_tris
(array([[-0.9486833 ,  0.        ,  0.31622777]]),
 array([[-0.9486833 ,  0.        ,  0.31622777]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.70710678,  0.        ,  0.70710678]]),
 array([[-0.9486833 ,  0.        ,  0.31622777]]),
 array([[-0.9486833 ,  0.        ,  0.31622777]]))

LLCATS: CINF GRAD

calc_unit_normals_at_patch_subtriangles(grid, elevs='topographic__elevation')[source]

Calculate unit normals on a patch.

Calculate the four unit normal vectors <a, b, c> to the four possible subtriangles of a four-cornered (raster) patch.

Parameters:

grid : RasterModelGrid

A grid.

elevs : str or ndarray, optional

Field name or array of node values.

Returns:

(n_TR, n_TL, n_BL, n_BR) : each a num-patches x length-3 array

Len-4 tuple of the four unit normal vectors <a, b, c> for the four possible subtriangles in the patch. Order is (topright, topleft, bottomleft, bottomright).

Examples

>>> import numpy as np
>>> from landlab import RasterModelGrid
>>> mg = RasterModelGrid((4, 5))
>>> z = mg.node_x ** 2
>>> four_tris = mg.calc_unit_normals_at_patch_subtriangles(z)
>>> type(four_tris) is tuple
True
>>> len(four_tris)
4
>>> np.allclose(four_tris[0], four_tris[1])
True
>>> np.allclose(four_tris[2], four_tris[3])
True
>>> np.allclose(four_tris[0], four_tris[2])
True
>>> np.allclose(np.square(four_tris[0]).sum(axis=1), 1.)
True
>>> four_tris[0]
array([[-0.70710678,  0.        ,  0.70710678],
       [-0.9486833 ,  0.        ,  0.31622777],
       [-0.98058068,  0.        ,  0.19611614],
       [-0.98994949,  0.        ,  0.14142136],
       [-0.70710678,  0.        ,  0.70710678],
       [-0.9486833 ,  0.        ,  0.31622777],
       [-0.98058068,  0.        ,  0.19611614],
       [-0.98994949,  0.        ,  0.14142136],
       [-0.70710678,  0.        ,  0.70710678],
       [-0.9486833 ,  0.        ,  0.31622777],
       [-0.98058068,  0.        ,  0.19611614],
       [-0.98994949,  0.        ,  0.14142136]])

LLCATS: PINF GRAD

Slope-aspect calculation functions

Calculate slope aspects on a RasterModelGrid.

calc_slope_aspect_of_nodes_horn(*args, **kwargs)[source]

Calculate slope and aspect.

Note

This method is deprecated as of Landlab version 1.0.

Use grid.calc_slope_at_node() instead.

Note

THIS CODE HAS ISSUES (SN 25-Sept-14): This code didn’t perform well on a NS facing elevation profile. Please check slope_aspect_routines_comparison.py under landlabexamples before using this. Suggested alternative: calculate_slope_aspect_at_nodes_burrough

Calculates the local topographic slope (i.e., the down-dip slope, and presented as positive), and the aspect (dip direction in radians clockwise from north), at the given nodes, ids. All ids must be of core nodes.

This method uses the Horn 1981 algorithm, the one employed by many GIS packages. It should be significantly faster than alternative slope methods.

If ids is not provided, the slope will be returned for all core nodes.

vals is either the name of an existing grid field from which to draw topographic data, or an array of values to use. If an array of values is passed, it must be nnodes long. If vals is not provided, this method will default to trying to use the field “topographic__elevation”.

Parameters:

grid : RasterModelGrid

Grid on which to calculate slopes and aspects.

ids : array_like of int, optional

Nodes on which to calculate slope and aspect.

vals : str or ndarray, optional

Node values used to measure slope and aspect.

Returns:

(slope, aspect) : tuple of float

slope: a len(ids) array of slopes at each node provided. aspect: a len(ids) array of aspects at each node provided.

Examples

>>> from landlab import RasterModelGrid
>>> import numpy as np
>>> grid = RasterModelGrid((4, 5))

Create a south-facing slope.

>>> elevation = np.array([
...     0., 0., 0., 0., 0,
...     1., 1., 1., 1., 1,
...     2., 2., 2., 2., 2,
...     3., 3., 3., 3., 3])
>>> (slope, aspect) = calc_slope_aspect_of_nodes_horn(grid,
...     vals=elevation)
>>> len(slope) == grid.number_of_core_nodes
True
>>> len(aspect) == grid.number_of_core_nodes
True
>>> slope
array([ 1.,  1.,  1.,  1.,  1.,  1.])
>>> aspect * 180. / np.pi
array([ 180.,  180.,  180.,  180.,  180.,  180.])

Make the slope north-facing by multiplying elevations by -1. The slopes will still be positive but the aspects will change.

>>> elevation *= -1
>>> (slope, aspect) = calc_slope_aspect_of_nodes_horn(grid,
...     vals=elevation)
>>> slope
array([ 1.,  1.,  1.,  1.,  1.,  1.])
>>> aspect * 180. / np.pi
array([ 0.,  0.,  0.,  0.,  0.,  0.])

Double the slope and make it west-facing.

>>> elevation = np.array([
...     0., 1., 2., 3., 4.,
...     0., 1., 2., 3., 4.,
...     0., 1., 2., 3., 4.,
...     0., 1., 2., 3., 4.])
>>> elevation *= 2.
>>> (slope, aspect) = calc_slope_aspect_of_nodes_horn(grid,
...     vals=elevation)
>>> slope
array([ 2.,  2.,  2.,  2.,  2.,  2.])
>>> aspect * 180. / np.pi
array([ 270.,  270.,  270.,  270.,  270.,  270.])

Make the slope east-facing by multiplying elevations by -1. The slopes will still be positive but the aspects will change.

>>> elevation *= -1.
>>> (slope, aspect) = calc_slope_aspect_of_nodes_horn(grid,
...     vals=elevation)
>>> slope
array([ 2.,  2.,  2.,  2.,  2.,  2.])
>>> aspect * 180. / np.pi
array([ 90.,  90.,  90.,  90.,  90.,  90.])

LLCATS: DEPR NINF SURF

Steepest-descent functions

Calculate steepest descent on a raster grid.

Steepest descent functions for raster grids

_calc_steepest_descent_across_adjacent_cells(...) Get steepest gradient to neighbor and diagonal cells.
_calc_steepest_descent_across_cell_corners(...) Get steepest gradient to the diagonals of a cell.
_calc_steepest_descent_across_cell_faces(...) Get steepest gradient across the faces of a cell.

Boundary handling for grid edges

set_status_at_node_on_edges(grid, right=None, top=None, left=None, bottom=None)[source]

Set node status on grid edges.

Parameters:

grid : RasterModelGrid

A grid.

right : int, optional

Node status along right edge.

top : int, optional

Node status along top edge.

left : int, optional

Node status along left edge.

bottom : int, optional

Node status along bottom edge.

Examples

>>> from landlab import RasterModelGrid, CLOSED_BOUNDARY
>>> grid = RasterModelGrid((3, 4))
>>> grid.status_at_node 
array([1, 1, 1, 1,
       1, 0, 0, 1,
       1, 1, 1, 1], dtype=int8)
>>> grid.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)
>>> grid.status_at_node 
array([1, 1, 1, 4,
       1, 0, 0, 4,
       1, 1, 1, 4], dtype=int8)
>>> from landlab import FIXED_GRADIENT_BOUNDARY
>>> grid = RasterModelGrid((3, 4))

The status of a corner is set along with its clockwise edge. That is, if setting the status for the top and right edges, the upper-right corner has the status of the right edge.

>>> grid.set_status_at_node_on_edges(top=CLOSED_BOUNDARY,
...     right=FIXED_GRADIENT_BOUNDARY)
>>> grid.status_at_node 
array([1, 1, 1, 2,
       1, 0, 0, 2,
       4, 4, 4, 2], dtype=int8)

In the above example, if you wanted the corner to have the status of the top edge, you need to make two calls to set_status_at_node_on_edges,

>>> grid = RasterModelGrid((3, 4))
>>> grid.set_status_at_node_on_edges(right=FIXED_GRADIENT_BOUNDARY)
>>> grid.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)
>>> grid.status_at_node 
array([1, 1, 1, 2,
       1, 0, 0, 2,
       4, 4, 4, 4], dtype=int8)

An example that sets all of the edges shows how corners are set.

>>> grid.set_status_at_node_on_edges(right=1, top=2, left=3, bottom=4)
>>> grid.status_at_node 
array([3, 4, 4, 4,
       3, 0, 0, 1,
       2, 2, 2, 1], dtype=int8)

LLCATS: BC

Miscellaneous raster-grid functions

calculate_flux_divergence_at_nodes(grid, active_link_flux, out=None)[source]

Net flux into or out of nodes.

Same as calculate_flux_divergence_at_core_cells, but works with and returns a list of net unit fluxes that corresponds to all nodes, rather than just core nodes.

Parameters:

grid : RasterModelGrid

Input grid.

active_link_flux : array_like

Flux values at links.

out : ndarray, optional

Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output.

See also

calculate_flux_divergence_at_active_cells

Notes

Note that we DO compute net unit fluxes at boundary nodes (even though these don’t have active cells associated with them, and often don’t have cells of any kind, because they are on the perimeter). It’s up to the user to decide what to do with these boundary values.

Examples

Calculate the gradient of values at a grid’s nodes.

>>> from landlab import RasterModelGrid
>>> rmg = RasterModelGrid((4, 5), spacing=1.0)
>>> u = np.array([0., 1., 2., 3., 0.,
...               1., 2., 3., 2., 3.,
...               0., 1., 2., 1., 2.,
...               0., 0., 2., 2., 0.])
>>> grad = rmg.calc_grad_at_link(u)[rmg.active_links]
>>> grad 
array([ 1.,  1., -1.,
        1.,  1., -1.,  1.,
       -1., -1., -1.,
        1.,  1., -1.,  1.,
       -1.,  0.,  1.])

Calculate the divergence of the gradients at each node.

>>> flux = - grad    # downhill flux proportional to gradient
>>> rmg.calculate_flux_divergence_at_nodes(flux)
...     
array([ 0., -1., -1.,  1.,  0.,
       -1.,  2.,  4., -2.,  1.,
       -1.,  0.,  1., -4.,  1.,
        0., -1.,  0.,  1.,  0.])

If calculate_gradients_at_nodes is called inside a loop, you can improve speed by creating an array outside the loop. For example, do this once, before the loop:

>>> df = rmg.zeros(centering='node') # outside loop
>>> rmg.number_of_nodes
20

Then do this inside the loop so that the function will not have to create the df array but instead puts values into the df array.

>>> df = rmg.calculate_flux_divergence_at_nodes(flux, out=df)
>>> grid = RasterModelGrid((4, 5), spacing=(1, 2))
>>> u = np.array([0., 1., 2., 3., 0.,
...               1., 2., 3., 2., 3.,
...               0., 1., 2., 1., 2.,
...               0., 0., 2., 2., 0.])
>>> grad = grid.calc_grad_at_link(2 * u)[grid.active_links]
>>> grad 
array([ 2.,  2., -2.,
        1.,  1., -1.,  1.,
       -2., -2., -2.,
        1.,  1., -1., 1.,
       -2.,  0.,  2.])
>>> grid.calculate_flux_divergence_at_nodes(- grad)
...     
array([ 0., -1., -1.,  1.,  0.,
       -1.,  2.,  4., -2.,  1.,
       -1.,  0.,  1., -4.,  1.,
        0., -1.,  0.,  1.,  0.])
calculate_slope_aspect_bfp(xs, ys, zs)[source]

Calculate slope and aspect.

Code author: Katy Barnhart <katherine.barnhart@colorado.edu>

Fits a plane to the given N points with given xs, ys, and zs values using single value decomposition.

Returns a tuple of (slope, aspect) based on the normal vector to the best fit plane.

Note

This function does not check if the points fall on a line, rather than a plane.

corner_node_at_cell(grid, corner_ids[, cell_ids])[source]

Return an array of the node ids for diagonal neighbors of cell_id cells. corner_ids is an index into the corners of a cell as measured clockwise starting from the southeast.

If cell_ids is not given, return neighbors for all cells in the grid.

Parameters:

grid : RasterModelGrid

Input grid.

corner_ids : array_like

IDs of the corner nodes.

cell_ids : array_like, optional

IDs of cell about which to get corners

Examples

>>> from landlab import RasterModelGrid
>>> from landlab.grid.raster_funcs import corner_node_at_cell
>>> grid = RasterModelGrid(4, 5, 1.0)
>>> corner_node_at_cell(grid, 0, 0)
array([2])

Get the lower-right and the the upper-left corners for all the cells.

>>> corner_node_at_cell(grid, 0)
array([2, 3, 4, 7, 8, 9])
>>> corner_node_at_cell(grid, 2)
array([10, 11, 12, 15, 16, 17])

As an alternative to the above, use fancy-indexing to get both sets of corners with one call.

>>> corner_node_at_cell(grid, np.array([0, 2]), [1, 4])
array([[ 3, 11],
       [ 8, 16]])
find_nearest_node(rmg, coords, mode='raise')[source]

Find the node nearest a point.

Find the index to the node nearest the given x, y coordinates. Coordinates are provided as numpy arrays in the coords tuple. coords is tuple of coordinates, one for each dimension.

The mode keyword to indicate what to do if a point is outside of the grid. Valid choices are the same as that used with the numpy function ravel_multi_index.

A point is considered to be outside of the grid if it is outside the perimeter of the grid by one half of the grid spacing.

Parameters:

rmg : RasterModelGrid

The source grid.

coords : tuple

Coordinates of point as (x, y)

mode : {‘raise’, ‘wrap’, ‘clip’}, optional

Action to take if a point is outside of the grid.

Returns:

array_like :

Indices of the nodes nearest the given coordinates.

Examples

Create a grid of 4 by 5 nodes with unit spacing.

>>> import landlab
>>> from landlab.grid.raster_funcs import find_nearest_node
>>> rmg = landlab.RasterModelGrid(4, 5)

The points can be either a tuple of scalars or of arrays.

>>> find_nearest_node(rmg, (0.2, 0.6))
5
>>> find_nearest_node(rmg, (np.array([1.6, 3.6]), np.array([2.3, .7])))
array([12,  9])

The mode keyword indicates what to do if a point is outside of the grid.

>>> find_nearest_node(rmg, (-0.6, 0.6), mode='raise')
Traceback (most recent call last):
    ...
ValueError: invalid entry in coordinates array
>>> find_nearest_node(rmg, (-0.6, 0.6), mode='clip')
5
>>> find_nearest_node(rmg, (-0.6, 0.6), mode='wrap')
9
is_coord_on_grid(rmg, coords, axes=(0, 1))[source]

Check if coordinates are contained on a grid.

Parameters:

rmg : RasterModelGrid

Source grid.

coords : tuple

Coordinates of point as (x, y)

axes : tuple, optional

Check bounds only on a particular axis

Examples

Create a grid that ranges from x=0 to x=4, and y=0 to y=3.

>>> from landlab import RasterModelGrid
>>> from landlab.grid.raster_funcs import is_coord_on_grid
>>> grid = RasterModelGrid(4, 5)
>>> is_coord_on_grid(grid, (3.999, 2.999))
True

Check two points with one call. Numpy broadcasting rules apply for the point coordinates.

>>> is_coord_on_grid(grid, ([3.9, 4.1], 2.9))
array([ True, False], dtype=bool)
>>> is_coord_on_grid(grid, ([3.9, 4.1], 2.9), axes=(0, ))
array([ True,  True], dtype=bool)

Return an array of the active link ids for neighbors of cell_id cells. link_ids is an index into the links of a cell as measured clockwise starting from the south.

If cell_ids is not given, return neighbors for all cells in the grid.

Parameters:

grid : RasterModelGrid

Source grid.

link_inds : array_like

IDs of links

cell_ids : array_like, optional

IDs of cells for which to get links

neighbor_node_at_cell(grid, neighbor_ids[, cell_ids])[source]

Return an array of the node ids for neighbors of cell_id cells. neighbor_ids is an index into the neighbors of a cell as measured clockwise starting from the south.

If cell_ids is not given, return neighbors for all cells in the grid.

Parameters:

grid : RasterModelGrid

Input grid.

neighbor_ids : array_like

IDs of the neighbor nodes.

cell_ids : array_like, optional

IDs of cell about which to get neighbors.

Returns:

ndarray

Node IDs for given neighbors of cells.

Examples

>>> from landlab import RasterModelGrid
>>> from landlab.grid.raster_funcs import neighbor_node_at_cell
>>> grid = RasterModelGrid(4, 5, 1.0)
>>> neighbor_node_at_cell(grid, 0, 0)
array([1])

Get the lower and the the upper neighbors for all the cells.

>>> neighbor_node_at_cell(grid, 0)
array([1, 2, 3, 6, 7, 8])
>>> neighbor_node_at_cell(grid, 2)
array([11, 12, 13, 16, 17, 18])

As an alternative to the above, use fancy-indexing to get both sets of neighbors with one call.

>>> neighbor_node_at_cell(grid, np.array([0, 2]), [1, 4])
array([[ 2, 12],
       [ 7, 17]])

Voronoi-DeLaunay Grids (VoronoiDelaunayGrid)

Inherits from ModelGrid and adds:

Python implementation of VoronoiDelaunayGrid, a class used to create and manage unstructured, irregular grids for 2D numerical models.

Do NOT add new documentation here. Grid documentation is now built in a semi- automated fashion. To modify the text seen on the web, edit the files docs/text_for_[gridfile].py.txt.

class VoronoiDelaunayGrid(x=None, y=None, reorient_links=True, **kwds)[source]

Bases: landlab.grid.base.ModelGrid

This inherited class implements an unstructured grid in which cells are Voronoi polygons and nodes are connected by a Delaunay triangulation. Uses scipy.spatial module to build the triangulation.

Create an unstructured grid from points whose coordinates are given by the arrays x, y.

Parameters:

x : array_like

x-coordinate of points

y : array_like

y-coordinate of points

reorient_links (optional) : bool

whether to point all links to the upper-right quadrant

Returns:

VoronoiDelaunayGrid

A newly-created grid.

Examples

>>> from numpy.random import rand
>>> from landlab.grid import VoronoiDelaunayGrid
>>> x, y = rand(25), rand(25)
>>> vmg = VoronoiDelaunayGrid(x, y)  # node_x_coords, node_y_coords
>>> vmg.number_of_nodes
25
>>> import numpy as np
>>> x = [0, 0.1, 0.2, 0.3,
...      1, 1.1, 1.2, 1.3,
...      2, 2.1, 2.2, 2.3,]
>>> y = [0, 1, 2, 3,
...      0, 1, 2, 3,
...      0, 1, 2, 3]
>>> vmg = VoronoiDelaunayGrid(x, y)
>>> vmg.node_x 
array([ 0. ,  1. ,  2. ,
        0.1,  1.1,  2.1,
        0.2,  1.2,  2.2,
        0.3,  1.3,  2.3])
>>> vmg.node_y 
array([ 0.,  0.,  0.,
        1.,  1.,  1.,
        2.,  2.,  2.,
        3.,  3.,  3.])

Returns the links forming each patch.

Examples

>>> from landlab import HexModelGrid
>>> mg = HexModelGrid(3, 2)
>>> mg.links_at_patch
array([[ 3,  2,  0],
       [ 5,  1,  2],
       [ 6,  3,  4],
       [ 8,  7,  5],
       [10,  9,  6],
       [11,  8,  9]])

LLCATS: LINF PINF CONN

nodes_at_patch

Get the four nodes at the corners of each patch in a regular grid.

LLCATS: PINF NINF CONN

number_of_patches

Number of patches.

Returns the number of patches over the grid.

LLCATS: PINF

Returns the patches adjoined to each link.

Examples

>>> from landlab import HexModelGrid
>>> mg = HexModelGrid(3, 2)
>>> mg.patches_at_link
array([[ 0, -1],
       [ 1, -1],
       [ 0,  1],
       [ 0,  2],
       [ 2, -1],
       [ 1,  3],
       [ 2,  4],
       [ 3, -1],
       [ 3,  5],
       [ 4,  5],
       [ 4, -1],
       [ 5, -1]])

LLCATS: PINF LINF CONN

patches_at_node

Return a (nnodes, max_voronoi_polygon_sides) array of patches at nodes.

The patches are returned in LL standard order (ccw from E), with any nonexistent patches recorded after the ids of existing faces. Nonexistent patches are ID’ed as -1.

Examples

>>> from landlab import HexModelGrid
>>> mg = HexModelGrid(3, 3)
>>> mg.patches_at_node 
array([[ 0,  2, -1, -1, -1, -1],
       [ 1,  3,  0, -1, -1, -1],
       [ 4,  1, -1, -1, -1, -1],
       [ 5,  2, -1, -1, -1, -1],
       [ 6,  8,  5,  2,  0,  3],
       [ 7,  9,  6,  3,  1,  4],
       [ 7,  4, -1, -1, -1, -1],
       [ 5,  8, -1, -1, -1, -1],
       [ 8,  6,  9, -1, -1, -1],
       [ 9,  7, -1, -1, -1, -1]])

LLCATS: NINF PINF CONN

save(path, clobber=False)[source]

Save a grid and fields.

This method uses cPickle to save a Voronoi grid as a cPickle file. At the time of coding, this is the only convenient output format for Voronoi grids, but support for netCDF is likely coming.

All fields will be saved, along with the grid.

The recommended suffix for the save file is ‘.grid’. This will be added to your save if you don’t include it.

This method is equivalent to save_grid(), and load_grid() can be used to load these files.

Caution: Pickling can be slow, and can produce very large files. Caution 2: Future updates to Landlab could potentially render old saves unloadable.

Parameters:

path : str

Path to output file.

clobber : bool (defaults to false)

Set to true to allow overwriting

Examples

>>> from landlab import VoronoiDelaunayGrid
>>> import numpy as np
>>> import os
>>> x = np.random.rand(20)
>>> y = np.random.rand(20)
>>> vmg = VoronoiDelaunayGrid(x,y)
>>> vmg.save('./mytestsave.grid')
>>> os.remove('mytestsave.grid') #to remove traces of this test

LLCATS: GINF

Calculates and returns length of links between nodes.

Parameters:

pts : Nx2 numpy array containing (x,y) values

link_from : 1D numpy array containing index numbers of nodes at starting

point (“from”) of links

link_to : 1D numpy array containing index numbers of nodes at ending point

(“to”) of links

Returns:

out : ndarray

1D numpy array containing horizontal length of each link

Examples

>>> import numpy as np
>>> from landlab.grid.voronoi import calculate_link_lengths
>>> pts = np.array([[0.,0.],[3.,0.],[3.,4.]]) # 3:4:5 triangle
>>> lfrom = np.array([0,1,2])
>>> lto = np.array([1,2,0])
>>> calculate_link_lengths(pts, lfrom, lto)
array([ 3.,  4.,  5.])
simple_poly_area(x, y)[source]

Calculates and returns the area of a 2-D simple polygon.

Input vertices must be in sequence (clockwise or counterclockwise). x and y are arrays that give the x- and y-axis coordinates of the polygon’s vertices.

Parameters:

x : ndarray

x-coordinates of of polygon vertices.

y : ndarray

y-coordinates of of polygon vertices.

Returns:

out : float

Area of the polygon

Examples

>>> import numpy as np
>>> from landlab.grid.voronoi import simple_poly_area
>>> x = np.array([3., 1., 1., 3.])
>>> y = np.array([1.5, 1.5, 0.5, 0.5])
>>> simple_poly_area(x, y)
2.0

If the input coordinate arrays are 2D, calculate the area of each polygon. Note that when used in this mode, all polygons must have the same number of vertices, and polygon vertices are listed column-by-column.

>>> x = np.array([[ 3.,  1.,  1.,  3.],
...               [-2., -2., -1., -1.]]).T
>>> y = np.array([[1.5, 1.5, 0.5, 0.5],
...               [ 0.,  1.,  2.,  0.]]).T
>>> simple_poly_area(x, y)
array([ 2. ,  1.5])

Hex Grids (HexModelGrid)

Inherits from VoronoiDelauneyGrid and adds:

Python implementation of HexModelGrid, a grid class used to create and manage structured Voronoi-Delaunay grids for 2D numerical models.

Do NOT add new documentation here. Grid documentation is now built in a semi- automated fashion. To modify the text seen on the web, edit the files docs/text_for_[gridfile].py.txt.

class HexModelGrid(base_num_rows=0, base_num_cols=0, dx=1.0, orientation='horizontal', shape='hex', reorient_links=True, **kwds)[source]

Bases: landlab.grid.voronoi.VoronoiDelaunayGrid

A grid of hexagonal cells.

This inherited class implements a regular 2D grid with hexagonal cells and triangular patches. It is a special type of VoronoiDelaunay grid in which the initial set of points is arranged in a triangular/hexagonal lattice.

Parameters:

base_num_rows : int

Number of rows of nodes in the left column.

base_num_cols : int

Number of nodes on the first row.

dx : float, optional

Node spacing.

orientation : string, optional

One of the 3 cardinal directions in the grid, either ‘horizontal’ (default) or ‘vertical’

shape : string, optional

Controls the shape of the bounding hull, i.e., are the nodes arranged in a hexagon, or a rectangle? Either ‘hex’ (default) or ‘rect’.

Returns:

HexModelGrid

A newly-created grid.

Examples

Create a hex grid with 2 rows of nodes. The first and third rows will have 2 nodes, and the second nodes.

>>> from landlab import HexModelGrid
>>> hmg = HexModelGrid(3, 2, 1.0)
>>> hmg.number_of_nodes
7
classmethod from_dict(params)[source]

LLCATS: GINF

hexplot(data, data_label=None, color_map=None)[source]

Create a plot of the grid elements.

Creates a plot of the grid and one node-data field, showing hexagonal cells colored by values in the field.

Parameters:

data : str or node array (1d numpy array with number_of_nodes entries)

Data field to be colored.

data_label : str, optional

Label for colorbar.

color_map : matplotlib colormap object, None

Color map to apply (defaults to “jet”)

See also

plot.imshow_grid
Another Landlab function capable of producing hexplots, with a fuller-featured set of options.
LLCATS
GINF
nodes_at_bottom_edge

Get nodes along the bottom edge of a grid, if grid is rectangular.

Examples

>>> import numpy as np
>>> from landlab import HexModelGrid
>>> grid = HexModelGrid(3, 4, shape='rect')
>>> grid.nodes_at_bottom_edge
array([0, 1, 2, 3])

LLCATS: NINF BC SUBSET

nodes_at_left_edge

Get nodes along the left edge of a grid, if grid is rectangular.

Examples

>>> import numpy as np
>>> from landlab import HexModelGrid
>>> grid = HexModelGrid(3, 4, shape='rect')
>>> grid.nodes_at_left_edge
array([0, 4, 8])

LLCATS: NINF BC SUBSET

nodes_at_right_edge

Get nodes along the right edge of a grid, if grid is rectangular.

Examples

>>> import numpy as np
>>> from landlab import HexModelGrid
>>> grid = HexModelGrid(3, 4, shape='rect')
>>> grid.nodes_at_right_edge
array([ 3,  7, 11])

LLCATS: NINF BC SUBSET

nodes_at_top_edge

Get nodes along the top edge of a grid, if grid is rectangular.

Examples

>>> import numpy as np
>>> from landlab import HexModelGrid
>>> grid = HexModelGrid(3, 4, shape='rect')
>>> grid.nodes_at_top_edge
array([ 8,  9, 10, 11])

LLCATS: NINF BC SUBSET

number_of_node_columns

Number of node columns hex grid.

Number of node columns in a rectangular-shaped and/or vertically oriented hex grid.

Returns the number of columns, including boundaries.

Notes

Will generate an error if called with a hex-shaped, horizontally aligned grid.

Examples

>>> from landlab import HexModelGrid
>>> grid = HexModelGrid(5, 5, shape='rect')
>>> grid.number_of_node_columns
5

LLCATS: GINF NINF

number_of_node_rows

Number of node rows in a rectangular-shaped and/or horizontally oriented hex grid.

Returns the number of rows, including boundaries.

Notes

Will generate an error if called with a hex-shaped, vertically aligned grid.

Examples

>>> from landlab import HexModelGrid
>>> grid = HexModelGrid(5, 5, shape='rect')
>>> grid.number_of_node_rows
5

LLCATS: GINF NINF

from_dict(param_dict)[source]

Create a HexModelGrid from the dictionary-like object, param_dict. Required keys of the dictionary are NUM_ROWS, NUM_COLS. Raises a KeyError if either of these are missing. If GRID_SPACING is given, use it as the HexModelGrid dx parameter, otherwise default to unit spacing.

Radial Grids (HexModelGrid)

Inherits from VoronoiDelauneyGrid and adds:

Python implementation of RadialModelGrid, a grid class used to create and manage structured Voronoi-Delaunay grids for 2D numerical models.

Do NOT add new documentation here. Grid documentation is now built in a semi- automated fashion. To modify the text seen on the web, edit the files docs/text_for_[gridfile].py.txt.

class RadialModelGrid(num_shells=0, dr=1.0, origin_x=0.0, origin_y=0.0, **kwds)[source]

Bases: landlab.grid.voronoi.VoronoiDelaunayGrid

Grid of concentric circles.

This inherited class implements a circular grid in which grid nodes are placed at regular radial and semi-regular arc-wise intervals. That is, if the radial spacing between shells is dr, the nodes are placed around the circular shell at regular intervals that get as close as possible to dr. The points are then arranged in a Delaunay triangulation with Voronoi cells. Within each ring, nodes are numbered according to Landlab convention, from the first node counterclockwise of east. Numbering begins at the centermost node and works outwards through the rings.

Parameters:

num_shells : int

Number of rings in the grid.

dr : float, optional

Radial interval for rings.

origin_x : float, optional

x-coordinate of origin node.

origin_y : float, optional

y-coordinate of origin node.

Returns:

RadialModelGrid

A newly-created grid.

Examples

A grid with just one ring will have a node at the origin surrounded by six other nodes.

>>> from landlab import RadialModelGrid
>>> omg = RadialModelGrid(num_shells=1, dr=1., origin_x=0., origin_y=0.)
>>> omg.number_of_nodes
7
>>> omg.number_of_cells
1

A second rings will have 13 nodes.

>>> omg = RadialModelGrid(2)
>>> omg.number_of_nodes
20
classmethod from_dict(params)[source]

LLCATS: GINF

number_of_nodes_in_shell

Number of nodes in each shell.

Returns:

int

Number of nodes in each shell, excluding the center node.

LLCATS: GINF NINF

number_of_shells

Number of node shells in grid.

Returns:

int

The number of node shells in the radial grid (not counting the center node).

LLCATS: GINF

radius_at_node

Distance for center node to each node.

Returns:

ndarray of float

The distance from the center node of each node.

>>> mg = RadialModelGrid(num_shells=2)
>>> mg.radius_at_node

array([ 2., 2., 2., 2., 2., 1., 1., 2., 0., 1., 1., 2., 2.,

1., 1., 2., 2., 2., 2., 2.])

LLCATS: NINF MEAS

shell_spacing

Fixed distance between shells.

Note

This method is deprecated as of Landlab version 1.0.

Use spacing_of_shells() instead.

LLCATS: DEPR GINF MEAS

spacing_of_shells

Fixed distance between shells.

LLCATS: GINF MEAS