landlab

landlab.core package

Submodules

landlab.core.model_component module

Defines the base component class from which Landlab components inherit.

Base component class methods

from_path(grid, path) Create a component from an input file.
landlab.core.model_component.Component.name
units
landlab.core.model_component.Component.definitions
input_var_names
output_var_names
optional_var_names
var_type(name) Returns the dtype of a field (float, int, bool, str...), if declared.
var_units(name) Get the units of a particular field.
var_definition(name) Get a description of a particular field.
landlab.core.model_component.Component.var_mapping
var_loc(name) Location where a particular variable is defined.
var_help(name) Print a help message for a particular field.
initialize_output_fields() Create fields for a component based on its input and output var names.
initialize_optional_output_fields() Create fields for a component based on its optional field outputs, if declared in _optional_var_names.
shape Return the grid shape attached to the component, if defined.
grid Return the grid attached to the component.
coords Return the coordinates of nodes on grid attached to the component.
imshow(name, \*\*kwds) Plot data on the grid attached to the component.
class Component(grid, map_vars=None, **kwds)[source]

Bases: object

Defines the base component class from which Landlab components inherit.

from_path(grid, path) Create a component from an input file.
landlab.core.model_component.Component.name
units
landlab.core.model_component.Component.definitions
input_var_names
output_var_names
optional_var_names
var_type(name) Returns the dtype of a field (float, int, bool, str...), if declared.
var_units(name) Get the units of a particular field.
var_definition(name) Get a description of a particular field.
landlab.core.model_component.Component.var_mapping
var_loc(name) Location where a particular variable is defined.
var_help(name) Print a help message for a particular field.
initialize_output_fields() Create fields for a component based on its input and output var names.
initialize_optional_output_fields() Create fields for a component based on its optional field outputs, if declared in _optional_var_names.
shape Return the grid shape attached to the component, if defined.
grid Return the grid attached to the component.
coords Return the coordinates of nodes on grid attached to the component.
imshow(name, \*\*kwds) Plot data on the grid attached to the component.
coords

Return the coordinates of nodes on grid attached to the component.

definitions

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:

@classmethod def f(cls, arg1, arg2, ...):

...

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

classmethod from_path(grid, path)[source]

Create a component from an input file.

Parameters:

grid : ModelGrid

A landlab grid.

path : str or file_like

Path to a parameter file, contents of a parameter file, or a file-like object.

Returns:

Component

A newly-created component.

grid

Return the grid attached to the component.

imshow(name, **kwds)[source]

Plot data on 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()[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, if specified by _optional_var_names. New fields are created as arrays of floats, unless the component also contains the specifying property _var_type.

input_var_names = ()
name

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:

@classmethod def f(cls, arg1, arg2, ...):

...

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

optional_var_names = ()
output_var_names = ()
shape

Return the grid shape attached to the component, if defined.

units = ()
classmethod var_definition(name)[source]

Get a description of a particular field.

Parameters:

name : str

A field name.

Returns:

tuple of (name, description)

A description of each field.

classmethod var_help(name)[source]

Print a help message for a particular field.

Parameters:

name : str

A field name.

classmethod var_loc(name)[source]

Location where a particular variable is defined.

Parameters:

name : str

A field name.

Returns:

str

The location (‘node’, ‘link’, etc.) where a variable is defined.

var_mapping

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:

@classmethod def f(cls, arg1, arg2, ...):

...

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

classmethod var_type(name)[source]

Returns the dtype of a field (float, int, bool, str...), if declared. Default is float.

Parameters:

name : str

A field name.

Returns:

dtype

The dtype of the field.

classmethod var_units(name)[source]

Get the units of a particular field.

Parameters:

name : str

A field name.

Returns:

str

Units for the given field.

class classproperty[source]

Bases: property

landlab.core.model_parameter_dictionary module

Read input variables for landlab components.

The Model Parameter Dictionary is a tool for numerical modelers to easily read and access model parameters from a simple formatted input (text) file. Each parameter has a KEY, which identifies the parameter, and a VALUE, which can be a number or a string. A ModelParameterDictionary object reads model parameters from an input file to a Dictionary, and provides functions for the user to look up particular parameters by key name.

The format of the input file looks like:

>>> from six import StringIO
>>> param_file = StringIO('''
... PI: the text "PI" is an example of a KEY
... 3.1416
... AVOGADROS_NUMBER: this is another
... 6.022e23
... FAVORITE_FRUIT: yet another
... mangoes
... NUMBER_OF_MANGO_WALKS: this one is an integer
... 4
... ALSO_LIKES_APPLES: this is a boolean
... true
... ''')

Example code that reads these parameters from a file called myinputs.txt:

>>> from landlab import ModelParameterDictionary
>>> my_param_dict = ModelParameterDictionary()
>>> my_param_dict.read_from_file(param_file)
>>> pi = my_param_dict.read_float('PI')
>>> avogado = my_param_dict.read_float('AVOGADROS_NUMBER')
>>> fruit = my_param_dict.read_string('FAVORITE_FRUIT')
>>> nmang = my_param_dict.read_int('NUMBER_OF_MANGO_WALKS')
>>> apples_ok = my_param_dict.read_bool('ALSO_LIKES_APPLES')

As in Python, hash marks (#) denote comments. The rules are that each key must have one and only one parameter value, and each value must appear on a separate line immediately below the key line.

Also available are functions to read input parameters from the command line (e.g., read_float_cmdline( ‘PI’ ) )

exception Error[source]

Bases: exceptions.Exception

Base class for exceptions raised from this module.

exception MissingKeyError(key)[source]

Bases: landlab.core.model_parameter_dictionary.Error

Error to indicate a missing parameter key.

Raise this error if the parameter dictionary file does not contain a requested key.

class ModelParameterDictionary(from_file=None, auto_type=False)[source]

Bases: dict

Model parameter file as specified as key/value pairs.

Reads model parameters from an input file to a dictionary and provides functions for the user to look up particular parameters by key name.

If the keyword auto_type is True, then guess at the type for each value. Use from_file to read in a parameter file from a file-like object or a file with the given file name.

Parameters:

from_file : str or file_like, optional

File from which to read parameters.

auto_type : boolean, optional

Try to guess parameter data types.

Examples

Create a file-like object that contains a model parameter dictionary.

>>> from six import StringIO
>>> test_file = StringIO('''
... INT_VAL:
... 1
... DBL_VAL:
... 1.2
... BOOL_VAL:
... true
... INT_ARRAY:
... 1,2,3
... DBL_ARRAY:
... 1.,2.,3.
... STR_VAL:
... landlab is awesome!
... ''')

Create a ModelParameterDictionary, fill it with values from the parameter dictionary, and try to convert each value string to its intended type.

>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(auto_type=True, from_file=test_file)

The returned ModelParameterDictionary can now be used just like a regular Python dictionary to get items, keys, etc.

>>> sorted(params.keys())
['BOOL_VAL', 'DBL_ARRAY', 'DBL_VAL', 'INT_ARRAY', 'INT_VAL', 'STR_VAL']
>>> params['INT_VAL']
1
>>> params['DBL_VAL']
1.2
>>> params['BOOL_VAL']
True
>>> params['STR_VAL']
'landlab is awesome!'

Lines containing commas are converted to numpy arrays. The type of the array is determined by the values.

>>> isinstance(params['DBL_ARRAY'], np.ndarray)
True
>>> params['INT_ARRAY']
array([1, 2, 3])
>>> params['DBL_ARRAY']
array([ 1.,  2.,  3.])
get(key, [default, ]ptype=str)[source]

Get a value by key name.

Get a value from a model parameter dictionary. Use the ptype keyword to convert the value to a given type. ptype is a function that converts the retreived value to the desired value. If a second argument after key is provided, use it as a default in case key is not contained in the ModelParameterDictionary.

Parameters:

key : str

A parameter name.

default : str or number, optional

A default value if the key is missing.

ptype : str, optional

The data type of the paramter.

Examples

>>> from six import StringIO
>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_INT:
... 1
... '''))
>>> params.get('MY_INT')
'1'
>>> params.get('MY_INT', ptype=int)
1
>>> params.get('MY_MISSING_INT', 2, ptype=int)
2

Be careful when dealing with booleans. If you want to be returned a boolean value, DO NOT set the ptype keyword to the builtin bool. This will not work as the Python bool function does not convert strings to booleans as you might expect. For example:

>>> bool('True')
True
>>> bool('False')
True

If you would like to get a boolean, use ptype='bool'.

Note

Use ptype='bool' not ptype=bool.

If you use bool to convert a string the returned boolean will be True for any non-empty string. This is just how the Python built-in bool works:

>>> bool('0')
True
>>> bool('1')
True
>>> bool('')
False
>>> from six import StringIO
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_BOOL:
... false
... '''))
>>> params.get('MY_BOOL')
'false'
>>> params.get('MY_BOOL', ptype='bool')
False
params()[source]

List of all the parameters names in the parameter dictionary.

Returns:

list of str

The names of parameters in the file.

read_bool(key)[source]

Locate key in the input file and return it as a boolean.

Parameters:

key : str

The name of a parameter.

default : bool

The default value if the key is missing.

Returns:

bool

The value type cast to a bool.

Raises:

MissingKeyError

If key isn’t in the dictionary or if its value is not an integer.

ParameterValueError

If the value is not a boolean.

Examples

>>> from six import StringIO
>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_BOOL:
... true
... '''))
>>> params.read_bool('MY_BOOL')
True
static read_bool_cmdline(key)[source]

Read a boolean from the command line.

Read a boolean from the command line and use it as a value for key in the dictonary.

Parameters:

key : str

The name of a parameter.

Returns:

bool

The parameter value.

read_float(key[, default])[source]

Locate key in the input file and return it as a float.

Parameters:

key : str

The name of a parameter.

default : float

The default value if the key is missing.

Returns:

float

The value type cast to a float.

Raises:

MissingKeyError

If key isn’t in the dictionary or if its value is not an integer.

ParameterValueError

If the value is not a float.

Examples

>>> from __future__ import print_function
>>> from six import StringIO
>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_FLOAT:
... 3.14
... '''))
>>> print('%.2f' % params.read_float('MY_FLOAT'))
3.14
read_float_cmdline(key)[source]

Read a float from the command line.

Read a float from the command line and use it as a value for key in the dictonary.

Parameters:

key : str

The name of a parameter.

Returns:

float

The parameter value.

Raises:

ParameterValueError

If the value is not an float.

read_from_file(param_file)[source]

Read parameters for a file.

Read and parse parameter dictionary information from a file or file-like object in param_file.

The format of the parameter file should be like:

# A comment line
SOME_KEY: this the key for some parameter
1.234

In other words, the rules are:

  • Comments are preceded by hash characters
  • Each parameter has two consecutive lines, one for the key and one for the value
  • The key must be followed by a space, colon, or eol
  • The parameter can be numeric or text
Parameters:

param_file : str or file_like

Name of parameter file (or file_like)

read_int(key[, default])[source]

Locate key in the input file and return it as an integer.

Parameters:

key : str

The name of a parameter.

default : int

The default value if the key is missing.

Returns:

int

The value type cast to an int.

Raises:

MissingKeyError

If key isn’t in the dictionary or if its value is not an integer.

ParameterValueError

If the value is not an integer.

Examples

>>> from six import StringIO
>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_INT:
... 1
... '''))
>>> params.read_int('MY_INT')
1
read_int_cmdline(key)[source]

Read an integer from the command line.

Read an integer from the command line and use it as a value for key in the dictonary.

Parameters:

key : str

The name of a parameter.

Returns:

int

The parameter value.

Raises:

ParameterValueError

If the value is not an int.

read_string(key)[source]

Locate key in the input file and return it as a string.

Parameters:

key : str

The name of a parameter.

default : str

The default value if the key is missing.

Returns:

str

The value type cast to a str.

Raises:

MissingKeyError

If key isn’t in the dictionary or if its value is not an integer.

Examples

>>> from six import StringIO
>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_STRING:
... landlab
... '''))
>>> params.read_string('MY_STRING')
'landlab'
read_string_cmdline(key)[source]

Read a string from the command line.

Read a string from the command line and use it as a value for key in the dictonary.

Parameters:

key : str

The name of a parameter.

Returns:

str

The parameter value.

exception ParameterValueError(key, val, expected_type)[source]

Bases: landlab.core.model_parameter_dictionary.Error

Error to indicate a bad parameter values.

Raise this error if a parameter value given by key is not of the expected type.

landlab.core.model_parameter_loader module

load_file_contents(file_like)[source]

Load the contents of a file or file-like object.

Parameters:

file_like : file_like or str

File to load either as a file-like object, path to an existing file, or the contents of a file.

Returns:

str

The contents of the file.

load_params(file_like)[source]

Load parameters from a 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:

dict

Parameters as key-value pairs.

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)
>>> contents = """
... start: Start time
... 0.
... stop: Stop time
... 10.
... step: Step time
... 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

radians_to_degrees(rads) Convert radians to compass-style degrees.
extend_array(x[, fill]) Extend an array by one element.
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.
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)[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.

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,y) points to be sorted

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

(x, y) of point about which to sort. If not provided, mean of pts is

used.

Returns:

pts : N NumPy array of int

sorted (x,y) points

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:

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 : rows x n_elements NumPy array of int

sorted (x,y) points

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:

ndarray of int, shape (n_points, )

Indices of sorted 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:

ndarray

A, possibly new, array of IDs.

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=np.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 == np.int
True
>>> x = np.arange(5, dtype=np.int64)
>>> y = as_id_array(x)
>>> y
array([0, 1, 2, 3, 4])
>>> y.dtype == np.int
True
>>> x = np.arange(5, dtype=np.intp)
>>> y = as_id_array(x)
>>> y
array([0, 1, 2, 3, 4])
>>> y.dtype == np.int
True
extend_array(x, fill=0)[source]

Extend an array by one element.

The new array will appear as a view of the input array. However, its data now points to a newly-allocated buffer that’s one element longer and contains a copy of the contents of x. The last element of the buffer is filled with fill. To access the extended array, use the x attribute of the returned array.

Parameters:

x : ndarray

The array to extend.

fill : number, optional

The value to fill the extra element with.

Returns:

ndarray

A view of the original array with the data buffer extended by one element.

Examples

>>> from landlab.core.utils import extend_array
>>> import numpy as np
>>> arr = extend_array(np.arange(4).reshape((2, 2)))
>>> arr
array([[0, 1],
       [2, 3]])
>>> arr.ext
array([0, 1, 2, 3, 0])

If the array is already extended, don’t extend it more. However, possibly change its fill value.

>>> rtn = extend_array(arr, fill=999)
>>> rtn is arr
True
>>> rtn.ext
array([  0,   1,   2,   3, 999])
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 : {‘ModelGrid’, ‘RasterModelGrid’, ‘HexModelGrid’,

‘RadialModelGrid’, ‘VoronoiDelaunayGrid’}

String of raster to inspect.

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)[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.

Returns:

dict

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

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:

ndarray

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

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 : float or ndarray

Converted angles in degrees.

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 : Nx2 NumPy array of float

sorted (x,y) points

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

>>> from landlab.grid.mappers import dummy_func_to_demonstrate_docstring_modification as dummy_func
>>> funcs = {'dummy_func_to_demonstrate_docstring_modification':
...          dummy_func}
>>> help(dummy_func)
Help on function dummy_func_to_demonstrate_docstring_modification in module landlab.grid.mappers:

dummy_func_to_demonstrate_docstring_modification(grid, some_arg)
    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
    --------
    ...

>>> strip_grid_from_method_docstring(funcs)
>>> help(dummy_func)
Help on function dummy_func_to_demonstrate_docstring_modification in module landlab.grid.mappers:

dummy_func_to_demonstrate_docstring_modification(grid, some_arg)
    A dummy function to demonstrate automated docstring changes.

    Construction::

        grid.dummy_func_to_demonstrate_docstring_modification(some_arg)

    Parameters
    ----------
    some_arg : whatever
        A dummy argument.

    Examples
    --------
    ...

Module contents

load_params(file_like)[source]

Load parameters from a 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:

dict

Parameters as key-value pairs.

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)
>>> contents = """
... start: Start time
... 0.
... stop: Stop time
... 10.
... step: Step time
... 2.
... """
>>> params = load_params(contents)
>>> isinstance(params, dict)
True
>>> params['start'], params['stop'], params['step']
(0.0, 10.0, 2.0)