Core Landlab Classes#
landlab.core.messages module#
Print user messages formatted landlab-style.
This module provides functions for printing nicely-formatted messages to the user. Messages are formatted in a particular style so that all of landlab messages will have a similar look. Anytime landlab prints something for an end-user to see, this module should be used.
This module also provides convenience functions for print particular types of messages. Warning and error messages, for instance.
Oftentimes when writing code we may need to print a lengthy message for the user. This may result in code that looks like the following.
>>> message = ('Lorem ipsum dolor sit amet, consectetur '
... 'adipiscing elit, sed do eiusmod tempor '
... 'incididunt ut labore et dolore magna aliqua. '
... 'Ut enim ad minim veniam, quis nostrud exercitation '
... 'ullamco laboris nisi ut aliquip ex ea commodo '
... 'consequat.')
Printing this message string would result in one long line that would, most likely, extend beyond the user’s terminal and be difficult to read. One solution would be to join the lines by line separators but then that would result in a bunch of really short lines.
To help with this, landlab provides a set of functions with the most basic being format_message.
>>> from landlab.core.messages import format_message
>>> print(format_message(message))
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
landlab also provides functions for printing warning and error messages.
>>> from landlab.core.messages import warning_message
>>> message = ('Lorem ipsum dolor sit amet, consectetur\n'
... 'adipiscing elit, sed do eiusmod tempor\n'
... 'incididunt ut labore et dolore magna aliqua.')
>>> print(warning_message(message))
.. warning::
<BLANKLINE> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
>>> from landlab.core.messages import error_message >>> print(error_message(message))
Error
<BLANKLINE> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Another common design pattern used in landlab is to allow the user, usually through a keyword, to control what happens if a particular assertion fails. For instance, the user may want the code to raise an error, or print a warning message, or do nothing at all. The assert_or_print function should be used in these cases.
>>> from landlab.core.messages import assert_or_print
>>> dt = 1e6
>>> assert_or_print(dt < 1, 'Unstable time step!', onerror='pass')
>>> assert_or_print(dt < 1, 'Unstable time step!', onerror='warn')
...
Warning
Unstable time step!
>>> assert_or_print(dt < 1, 'Unstable time step!', onerror='raise')
...
Traceback (most recent call last):
...
AssertionError
- assert_or_print(cond, msg=None, onerror='raise', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]#
Make an assertion printing a message if it fails.
Specify an action to take if an assertion fails, depending on the values of onerror. onerror must be one of:
“pass”: do nothing if the assertion passes or fails.
“warn”: print a warning message if the assertion fails.
“error”: print an error message and raise an AssertionError on failure.
- Parameters:
cond (expression) – An expression to test.
msg (str, optional) – Message to print if the condition is not met.
onerror ({'pass', 'warn', 'raise'}, optional) – What to do if the condition evaluates to False.
file (file_like, optional) – File-like object where the message is printed.
Examples
>>> from landlab.core.messages import assert_or_print
>>> assert_or_print(True, 'Lorem ipsum', onerror='pass') >>> assert_or_print(False, 'Lorem ipsum', onerror='pass')
>>> assert_or_print(True, 'Lorem ipsum', onerror='warn') >>> assert_or_print(False, 'Lorem ipsum', onerror='warn')
>>> assert_or_print(True, 'Lorem ipsum', onerror='raise') >>> assert_or_print(False, 'Lorem ipsum', onerror='raise') ... Traceback (most recent call last): ... AssertionError
- deprecation_message(msg=None, **kwds)[source]#
Create a deprecation message, landlab-style.
- Parameters:
msg (str, optional) – Warning message.
- Returns:
The formatted warning message.
- Return type:
Examples
>>> from landlab.core.messages import deprecation_message >>> print(deprecation_message("Dictumst vestibulum rhoncus est pellentesque.")) DEPRECATION WARNING =================== Dictumst vestibulum rhoncus est pellentesque.
>>> print( ... deprecation_message( ... "Dictumst vestibulum rhoncus est pellentesque.", ... use="Lorem ipsum dolor sit amet", ... ) ... ) DEPRECATION WARNING =================== Dictumst vestibulum rhoncus est pellentesque.
Example
Lorem ipsum dolor sit amet
- error_message(msg=None, **kwds)[source]#
Create an error message, landlab-style.
- Parameters:
msg (str, optional) – Warning message.
- Returns:
The formatted warning message.
- Return type:
Examples
>>> from landlab.core.messages import error_message >>> print(error_message('Dictumst vestibulum rhoncus est pellentesque.'))
Error
<BLANKLINE> Dictumst vestibulum rhoncus est pellentesque.
- format_message(msg, header=None, footer=None, linesep='\n')[source]#
Format a message, landlab-style.
Create a nicely formatted message that splits paragraphs, dedents paragraphs, and wraps text at 70 characters. Optionally, add a header and footer to the resulting message.
- Parameters:
- Returns:
The formatted message.
- Return type:
Examples
>>> from landlab.core.messages import format_message >>> text = ''' ... Lorem ipsum dolor sit amet, consectetur ... adipiscing elit, sed do eiusmod tempor ... incididunt ut labore et dolore magna aliqua. ... ... Pharetra pharetra massa massa ultricies mi ... quis hendrerit. ... ... Dictumst vestibulum rhoncus est pellentesque. ... Sed viverra tellus in hac habitasse platea ... dictumst vestibulum rhoncus.''' >>> print(format_message(text)) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pharetra pharetra massa massa ultricies mi quis hendrerit. Dictumst vestibulum rhoncus est pellentesque. Sed viverra tellus in hac habitasse platea dictumst vestibulum rhoncus.
- indent_and_wrap(content, indent='')[source]#
Indent and wrap some text.
Lines are first dedented to remove common leading whitespace, then indented according to the value of indent, and then wrapped at 70 characters (indenting if necessary with subsequent indent being twice indent).
Note that when looking for common whitespace, the first line is ignored.
- Parameters:
content (str) – The content to wrap.
- Returns:
The content properly wrapped and indented.
- Return type:
Examples
>>> from landlab.core.messages import indent_and_wrap >>> content = '''@book{knuth1998art, ... title={The art of computer programming: sorting and searching}, ... author={Knuth, Donald Ervin}, ... volume={3}, ... year={1998}, ... publisher={Pearson Education} ... }''' >>> print(indent_and_wrap(content)) @book{knuth1998art, title={The art of computer programming: sorting and searching}, author={Knuth, Donald Ervin}, volume={3}, year={1998}, publisher={Pearson Education} }
- split_paragraphs(msg, linesep='\n')[source]#
Split text into paragraphs.
Split a block of text into paragraphs. A paragraph is defined as adjacent new-line characters (possibly separated by some whitespace).
- Parameters:
- Returns:
List of paragraphs.
- Return type:
Examples
>>> from landlab.core.messages import split_paragraphs >>> text = ''' ... Pharetra pharetra massa massa ultricies mi quis hendrerit. ... ... Dictumst vestibulum rhoncus est pellentesque. ... ''' >>> split_paragraphs(text, linesep='\n') ['Pharetra pharetra massa massa ultricies mi quis hendrerit.', 'Dictumst vestibulum rhoncus est pellentesque.']
>>> text = ''' ... Pharetra pharetra massa massa ultricies mi quis hendrerit. ... Dictumst vestibulum rhoncus est pellentesque. ... ''' >>> len(split_paragraphs(text, linesep='\n')) 1
- warning_message(msg=None, **kwds)[source]#
Create a warning message, landlab-style.
- Parameters:
msg (str, optional) – Warning message.
- Returns:
The formatted warning message.
- Return type:
Examples
>>> from landlab.core.messages import warning_message >>> print(warning_message('Dictumst vestibulum rhoncus est pellentesque.'))
Warning
<BLANKLINE> Dictumst vestibulum rhoncus est pellentesque.
landlab.core.model_component module#
Defines the base component class from which Landlab components inherit.
Base component class methods#
|
Create a component from an input file. |
|
Returns the dtype of a field (float, int, bool, str...). |
|
Get the units of a particular field. |
|
Get a description of a particular field. |
|
Location where a particular variable is defined. |
|
Print a help message for a particular field. |
|
Create fields for a component based on its input and output var names. |
Create fields for a component based on its optional field outputs, if declared in _optional_var_names. |
|
Return the grid shape attached to the component, if defined. |
|
Return the grid attached to the component. |
|
Return the coordinates of nodes on grid attached to the component. |
- class Component(*args, **kwds)[source]#
Bases:
object
Base component class from which Landlab components inherit.
- cite_as = ''#
- property coords#
Return the coordinates of nodes on grid attached to the component.
- property current_time#
Current time.
Some components may keep track of the current time. In this case, the
current_time
attribute is incremented. Otherwise it is set to None.- Return type:
current_time
- definitions = ()#
- property grid#
Return the grid attached to the component.
- initialize_optional_output_fields()[source]#
Create fields for a component based on its optional field outputs, if declared in _optional_var_names.
This method will create new fields (without overwrite) for any fields output by the component as optional. New fields are initialized to zero. New fields are created as arrays of floats, unless the component also contains the specifying property _var_type.
- initialize_output_fields(values_per_element=None)[source]#
Create fields for a component based on its input and output var names.
This method will create new fields (without overwrite) for any fields output by, but not supplied to, the component. New fields are initialized to zero. Ignores optional fields. New fields are created as arrays of floats, unless the component specifies the variable type.
- Parameters:
values_per_element (int (optional)) – On occasion, it is necessary to create a field that is of size (n_grid_elements, values_per_element) instead of the default size (n_grid_elements,). Use this keyword argument to acomplish this task.
- input_var_names = ()#
- name = None#
- optional_var_names = ()#
- output_var_names = ()#
- property shape#
Return the grid shape attached to the component, if defined.
- unit_agnostic = None#
- units = ()#
- classmethod var_definition(name)[source]#
Get a description of a particular field.
- Parameters:
name (str) – A field name.
- Returns:
A description of each field.
- Return type:
tuple of (name, *description*)
- classmethod var_help(name)[source]#
Print a help message for a particular field.
- Parameters:
name (str) – A field name.
- var_mapping = ()#
landlab.core.model_parameter_loader module#
- load_params(file_like)[source]#
Load parameters from a YAML style file.
- Parameters:
file_like (file_like or str) – Contents of a parameter file, a file-like object, or the path to a parameter file.
- Returns:
Parameters as key-value pairs.
- Return type:
Examples
>>> from landlab.core import load_params >>> contents = """ ... start: 0. ... stop: 10. ... step: 2. ... """ >>> params = load_params(contents) >>> isinstance(params, dict) True >>> params['start'], params['stop'], params['step'] (0.0, 10.0, 2.0)
landlab.core.utils module#
Some utilities for the landlab package.
Landlab utilities#
|
Convert radians to compass-style degrees. |
|
Convert an array to an array of ids. |
Transform an optional argument into an array of element ids. |
|
|
Get all the function in a module. |
|
Add functions as methods of a class. |
|
Add functions from a module to a class as methods. |
Remove 'grid' from the parameters of a dict of functions' docstrings. |
|
|
Sort points by coordinates, first x then y, returning sorted indices. |
Sort points by coordinates, first x then y. |
|
|
Argort points into anticlockwise order around a supplied center. |
|
Create a dict of category:[method_names] for a LL grid type. |
- 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:
- 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., -1., -1., -3.]) >>> pts[:,1] = np.array([-1., -3., -1., -3.]) >>> 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:
- 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., -1., -1., -3.], [-3., -1., -1., -3.]]) >>> pts_y = np.array([[-1., -3., -1., -3.], [-3., -1., -3., -1.]]) >>> 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., 1., 1., 1., 1., 2., 2., 2.]) >>> points[:, 1] = np.array([0., 1., 2., -0.5, 0.5, 1.5, 2.5, 0., 1., 2.]) >>> argsort_points_by_x_then_y(points) array([3, 0, 7, 4, 1, 8, 5, 2, 9, 6])
>>> x = [0., 0., 0., ... 1., 1., 1., 1., ... 2., 2., 2.] >>> y = [ 0. , 1. , 2. , ... -0.5, 0.5, 1.5, 2.5, ... 0. , 1. , 2.] >>> 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. True >>> degrees_to_radians(-180.0) == 3. * np.pi / 2. True >>> np.testing.assert_array_almost_equal([ np.pi, np.pi], ... degrees_to_radians([ -90., 270.]))
- 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:
- Returns:
Dictionary of functions contained in the module. Keys are the function names, values are the functions themselves.
- Return type:
- 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.) 90.0 >>> radians_to_degrees(np.pi / 2.) 0.0 >>> radians_to_degrees(- 3 * np.pi / 2.) 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., 1., 1., 1., 1., 2., 2., 2.]) >>> pts[:,1] = np.array([0., 1., 2., -0.5, 0.5, 1.5, 2.5, 0., 1., 2.]) >>> 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> –
Module contents#
- load_params(file_like)[source]#
Load parameters from a YAML style file.
- Parameters:
file_like (file_like or str) – Contents of a parameter file, a file-like object, or the path to a parameter file.
- Returns:
Parameters as key-value pairs.
- Return type:
Examples
>>> from landlab.core import load_params >>> contents = """ ... start: 0. ... stop: 10. ... step: 2. ... """ >>> params = load_params(contents) >>> isinstance(params, dict) True >>> params['start'], params['stop'], params['step'] (0.0, 10.0, 2.0)