landlab.core.utils

Some utilities for the landlab package.

Landlab utilities

radians_to_degrees(rads)

Convert radians to compass-style degrees.

as_id_array(array)

Convert an array to an array of ids.

make_optional_arg_into_id_array(...)

Transform an optional argument into an array of element ids.

get_functions_from_module(mod[, pattern, ...])

Get all the function in a module.

add_functions_to_class(cls, funcs)

Add functions as methods of a class.

add_module_functions_to_class(cls, module[, ...])

Add functions from a module to a class as methods.

strip_grid_from_method_docstring(funcs)

Remove 'grid' from the parameters of a dict of functions' docstrings.

argsort_points_by_x_then_y(points)

Sort points by coordinates, first x then y, returning sorted indices.

sort_points_by_x_then_y(pts)

Sort points by coordinates, first x then y.

anticlockwise_argsort_points(pts[, midpt])

Argort points into anticlockwise order around a supplied center.

get_categories_from_grid_methods(grid_type)

Create a dict of category:[method_names] for a LL grid type.

class ExampleData[source]

Bases: object

__init__(example, case='')[source]
__new__(**kwargs)
property base
fetch()[source]

Fetch landlab example data files.

Examples

>>> data = ExampleData("io/shapefile")
>>> sorted(data)
['methow', 'redb', 'soque']
>>> import os
>>> data.fetch()  
>>> sorted(os.listdir())  
['methow', 'redb', 'soque']
add_functions_to_class(cls, funcs)[source]

Add functions as methods of a class.

Parameters:
  • cls (class) – A class.

  • funcs (dict) – Dictionary of function names and instances.

add_module_functions_to_class(cls, module, pattern=None, exclude=None)[source]

Add functions from a module to a class as methods.

Parameters:
  • cls (class) – A class.

  • module (module) – An instance of a module.

  • pattern (str, optional) – Only get functions whose name match a regular expression.

  • exclude (str, optional) – Only get functions whose name exclude the regular expression.

  • met. (*Note* if both pattern and exclude are provided both conditions must be)

anticlockwise_argsort_points(pts, midpt=None)[source]

Argort points into anticlockwise order around a supplied center.

Sorts CCW from east. Assumes a convex hull.

Parameters:
  • pts (Nx2 NumPy array of float)

  • (x

  • sorted (y) points to be)

  • midpt (len-2 NumPy array of float (optional))

  • (x

  • provided (y) of point about which to sort. If not)

  • is (mean of pts)

  • used.

Returns:

pts – sorted (x,y) points

Return type:

N NumPy array of int

Examples

>>> import numpy as np
>>> from landlab.core.utils import anticlockwise_argsort_points
>>> pts = np.zeros((4, 2))
>>> pts[:, 0] = np.array([-3.0, -1.0, -1.0, -3.0])
>>> pts[:, 1] = np.array([-1.0, -3.0, -1.0, -3.0])
>>> sortorder = anticlockwise_argsort_points(pts)
>>> np.all(sortorder == np.array([2, 0, 3, 1]))
True
anticlockwise_argsort_points_multiline(pts_x, pts_y, out=None)[source]

Argort multi lines of points into CCW order around the geometric center.

This version sorts columns of data in a 2d array. Sorts CCW from east around the geometric center of the points in the row. Assumes a convex hull.

Parameters:
  • pts_x (rows x n_elements array of float) – rows x points_to_sort x x_coord of points

  • pts_y (rows x n_elements array of float) – rows x points_to_sort x y_coord of points

  • out (rows x n_elements (optional)) – If provided, the ID array to be sorted

Returns:

sortorder – sorted (x,y) points

Return type:

rows x n_elements NumPy array of int

Examples

>>> import numpy as np
>>> from landlab.core.utils import anticlockwise_argsort_points_multiline
>>> pts = np.array([[1, 3, 0, 2], [2, 0, 3, 1]])
>>> pts_x = np.array([[-3.0, -1.0, -1.0, -3.0], [-3.0, -1.0, -1.0, -3.0]])
>>> pts_y = np.array([[-1.0, -3.0, -1.0, -3.0], [-3.0, -1.0, -3.0, -1.0]])
>>> sortorder = anticlockwise_argsort_points_multiline(pts_x, pts_y, out=pts)
>>> np.all(sortorder == np.array([[2, 0, 3, 1], [1, 3, 0, 2]]))
True
>>> np.all(pts == np.array([[0, 1, 2, 3], [0, 1, 2, 3]]))
True
argsort_points_by_x_then_y(points)[source]

Sort points by coordinates, first x then y, returning sorted indices.

Parameters:

points (tuple of ndarray or ndarray of float, shape (*, 2)) – Coordinates of points to be sorted. Sort by first coordinate, then second.

Returns:

Indices of sorted points.

Return type:

ndarray of int, shape (n_points, )

Examples

>>> import numpy as np
>>> from landlab.core.utils import argsort_points_by_x_then_y
>>> points = np.zeros((10, 2))
>>> points[:, 0] = np.array([0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0])
>>> points[:, 1] = np.array([0.0, 1.0, 2.0, -0.5, 0.5, 1.5, 2.5, 0.0, 1.0, 2.0])
>>> argsort_points_by_x_then_y(points)
array([3, 0, 7, 4, 1, 8, 5, 2, 9, 6])
>>> x = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
>>> y = [0.0, 1.0, 2.0, -0.5, 0.5, 1.5, 2.5, 0.0, 1.0, 2.0]
>>> indices = argsort_points_by_x_then_y((x, y))
>>> indices
array([3, 0, 7, 4, 1, 8, 5, 2, 9, 6])
>>> argsort_points_by_x_then_y(np.array((x, y)))
array([3, 0, 7, 4, 1, 8, 5, 2, 9, 6])
as_id_array(array)[source]

Convert an array to an array of ids.

Parameters:

array (ndarray) – Array of IDs.

Returns:

A, possibly new, array of IDs.

Return type:

ndarray

Examples

>>> import numpy as np
>>> from landlab.core.utils import as_id_array
>>> x = np.arange(5)
>>> y = as_id_array(x)
>>> y
array([0, 1, 2, 3, 4])
>>> x = np.arange(5, dtype=int)
>>> y = as_id_array(x)
>>> y
array([0, 1, 2, 3, 4])
>>> x = np.arange(5, dtype=np.int32)
>>> y = as_id_array(x)
>>> y
array([0, 1, 2, 3, 4])
>>> y.dtype == int
True
>>> x = np.arange(5, dtype=np.int64)
>>> y = as_id_array(x)
>>> y
array([0, 1, 2, 3, 4])
>>> y.dtype == int
True
>>> x = np.arange(5, dtype=np.intp)
>>> y = as_id_array(x)
>>> y
array([0, 1, 2, 3, 4])
>>> y.dtype == int
True
>>> x = np.arange(5, dtype=np.intp)
>>> y = np.where(x < 3)[0]
>>> y.dtype == np.intp
True
>>> as_id_array(y).dtype == int
True
degrees_to_radians(degrees)[source]

Convert compass-style degrees to radians.

Convert angles in degrees measured clockwise starting from north to angles measured counter-clockwise from the positive x-axis in radians

Parameters:

degrees (float or ndarray) – Converted angles in degrees.

Returns:

rads – Angles in radians.

Return type:

float or ndarray

Examples

>>> import numpy as np
>>> from landlab.core.utils import degrees_to_radians
>>> degrees_to_radians(90.0)
0.0
>>> degrees_to_radians(0.0) == np.pi / 2.0
True
>>> degrees_to_radians(-180.0) == 3.0 * np.pi / 2.0
True
>>> np.testing.assert_array_almost_equal(
...     [np.pi, np.pi], degrees_to_radians([-90.0, 270.0])
... )
get_categories_from_grid_methods(grid_type)[source]

Create a dict of category:[method_names] for a LL grid type.

Looks in the final line of the docstrings of class methods and properties for a catgory declaration, “LLCATS: “. It then creates and returns a dict with keys found as categories and values that are lists of the names of methods that have that category.

Currently defined LLCATS are:

  • DEPR : deprecated

  • GINF : information about the grid as a whole

  • NINF : information about nodes

  • LINF : information about links

  • PINF : information about patches

  • CINF : information about cells

  • FINF : information about faces

  • CNINF : information about corners

  • FIELDIO : methods to access and change fields

  • FIELDADD : methods to create new fields/delete old fields

  • FIELDINF : information about fields (keys, names, etc)

  • GRAD : methods for gradients, fluxes, divergences and slopes

  • MAP : methods to map from one element type to another

  • BC : methods to interact with BCs

  • SURF : methods for surface analysis (slope, aspect, hillshade)

  • SUBSET : methods to indentify part of the grid based on conditions

  • CONN : method describing the connectivity of one element to another (i.e., ‘links_at_node’)

  • MEAS : method describing a quantity defined on an element (i.e., ‘length_of_link’)

  • OTHER : anything else

Parameters:

grid_type (str) – String of grid to inspect. Options are ‘ModelGrid’, ‘RasterModelGrid’, ‘HexModelGrid’, ‘RadialModelGrid’, ‘VoronoiDelaunayGrid’, or ‘NetworkModelGrid’.

Returns:

  • cat_dict (dict) – Dictionary with cats as keys and lists of method name strings as values.

  • grid_dict (dict) – Dictionary with method name strings as keys and lists of cats as values.

  • FAILS (dict of dicts) – contains any problematic LLCAT entries. Keys: ‘MISSING’ - list of names of any public method or property without an LLCAT declared.

get_functions_from_module(mod, pattern=None, exclude=None)[source]

Get all the function in a module.

Parameters:
  • mod (module) – An instance of a module.

  • pattern (str, optional) – Only get functions whose name match a regular expression.

  • exclude (str, optional) – Only get functions whose name exclude the regular expression.

  • met. (*Note* if both pattern and exclude are provided both conditions must be)

Returns:

Dictionary of functions contained in the module. Keys are the function names, values are the functions themselves.

Return type:

dict

make_optional_arg_into_id_array(number_of_elements, *args)[source]

Transform an optional argument into an array of element ids.

Many landlab functions an optional argument of element ids that tells the function to operate only on the elements provided. However, if the argument is absent, all of the elements are to be operated on. This is a convenience function that converts such an arguments list into an array of elements ids.

Parameters:
  • number_of_elements (int) – Number of elements in the grid.

  • array (array_like) – Iterable to convert to an array.

Returns:

Input array converted to a numpy array, or a newly-created numpy array.

Return type:

ndarray

Examples

>>> import numpy as np
>>> from landlab.core.utils import make_optional_arg_into_id_array
>>> make_optional_arg_into_id_array(4)
array([0, 1, 2, 3])
>>> make_optional_arg_into_id_array(4, [0, 0, 0, 0])
array([0, 0, 0, 0])
>>> make_optional_arg_into_id_array(4, (1, 1, 1, 1))
array([1, 1, 1, 1])
>>> make_optional_arg_into_id_array(4, np.ones(4))
array([1, 1, 1, 1])
>>> make_optional_arg_into_id_array(4, 0)
array([0])
>>> make_optional_arg_into_id_array(4, np.array([[1, 2], [3, 4]]))
array([1, 2, 3, 4])
radians_to_degrees(rads)[source]

Convert radians to compass-style degrees.

Convert angles (measured counter-clockwise from the positive x-axis) in radians to angles in degrees measured clockwise starting from north.

Parameters:

rads (float or ndarray) – Angles in radians.

Returns:

degrees – Converted angles in degrees.

Return type:

float or ndarray

Examples

>>> import numpy as np
>>> from landlab.core.utils import radians_to_degrees
>>> radians_to_degrees(0.0)
90.0
>>> radians_to_degrees(np.pi / 2.0)
0.0
>>> radians_to_degrees(-3 * np.pi / 2.0)
0.0
>>> radians_to_degrees(np.array([-np.pi, np.pi]))
array([270., 270.])
sort_points_by_x_then_y(pts)[source]

Sort points by coordinates, first x then y.

Parameters:

pts (Nx2 NumPy array of float) – (x,y) points to be sorted

Returns:

pts – sorted (x,y) points

Return type:

Nx2 NumPy array of float

Examples

>>> import numpy as np
>>> from landlab.core.utils import sort_points_by_x_then_y
>>> pts = np.zeros((10, 2))
>>> pts[:, 0] = np.array([0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0])
>>> pts[:, 1] = np.array([0.0, 1.0, 2.0, -0.5, 0.5, 1.5, 2.5, 0.0, 1.0, 2.0])
>>> pts = sort_points_by_x_then_y(pts)
>>> pts
array([[ 1. , -0.5],
       [ 0. ,  0. ],
       [ 2. ,  0. ],
       [ 1. ,  0.5],
       [ 0. ,  1. ],
       [ 2. ,  1. ],
       [ 1. ,  1.5],
       [ 0. ,  2. ],
       [ 2. ,  2. ],
       [ 1. ,  2.5]])
strip_grid_from_method_docstring(funcs)[source]

Remove ‘grid’ from the parameters of a dict of functions’ docstrings.

Note that the docstring must be close to numpydoc standards for this to work.

Parameters:

funcs (dict) – Dictionary of functions to modify. Keys are the function names, values are the functions themselves.

Examples

>>> def dummy_func(grid, some_arg):
...     '''A dummy function.
...
...     Parameters
...     ----------
...     grid : ModelGrid
...         A landlab grid.
...     some_arg:
...         An argument.
...     '''
...     pass
...
>>> funcs = {"dummy_func_to_demonstrate_docstring_modification": dummy_func}
>>> print(dummy_func.__doc__)
A dummy function.
Parameters:
  • grid (ModelGrid) – A landlab grid.

  • some_arg – An argument.

  • <BLANKLINE>

  • strip_grid_from_method_docstring(funcs) (>>>)

  • print(dummy_func.__doc__) (>>>)

  • function. (A dummy)

  • <BLANKLINE>

  • some_arg – An argument.

  • <BLANKLINE>