landlab

landlab package

Subpackages

Module contents

The Landlab

Package name:TheLandlab
Release date:2013-03-24
Authors:Greg Tucker, Nicole Gasparini, Erkan Istanbulluoglu, Daniel Hobley, Sai Nudurupati, Jordan Adams, Eric Hutton
URL:http://csdms.colorado.edu/trac/landlab
License:MIT
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 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.

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.

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 Palette(*args, **kwds)[source]

Bases: landlab.framework.collections.Collection

A collection of component classes that have yet to be instantiated.

class Arena[source]

Bases: landlab.framework.collections.Collection

A collection of component instances.

connect(user_name, provider_name, var_name)[source]

Connect two components through a variable. user_name is the name of the component that uses var_name and provider_name is the name of the component that provides var_name.

If the arena doesn’t contain either user_name or provider_name, UnknownComponentError() is raised.

instantiate(cls, name)[source]

Instantiate a component and call it name. The component, cls, is either an instance of a BMI-like object or a class that implements the BMI. If cls is a class, it is instantiated by calling it’s __init__ method without any arguments.

walk(root, tree=None)[source]

Walk a connected set of components.

Walk a connected set of components with the component named root. If the tree keyword is given, treat it as a list of components already in the tree and add to that list. If a component is already in the tree, do not iterate through that component. This function returns a list of component names in the order they are visited by the walk.

exception NoProvidersError(var_name)[source]

Bases: landlab.framework.collections.Error

Raise this exception if no components provide the a variable

class Implements(*interfaces)[source]

Bases: object

Decorator to indicate if a class implements interfaces. Similar to the ImplementsOrRaise decorator except that this decorator silently ignores implemention errors. If the class does implement the interface, decorate it with a __implements__ data mamber that is a tuple of the interfaces it implements. Otherwise, don’t do anything.

class ImplementsOrRaise(*interfaces)[source]

Bases: object

Decorator to indicate if a class implements interfaces. If the class does not implement the interface, raise an InterfaceImplementationError. If the class does implement the interface, decorate it with a __implements__ data mamber that is a tuple of the interfaces it implements.

class Framework[source]

Bases: object

A framework for connecting and running component from The Landlab.

arena_provides()[source]

Get a list of variable names that components in the arena provide.

arena_uses()[source]

Get a list of variable names that components in the arena use.

instantiate(name)[source]

Instantiate a component called name from the palette and move it to the arena.

list_arena()[source]

Get a list of names of the components in the arena.

list_palette()[source]

Get a list of names of the components in the palette.

palette_provides()[source]

Get a list of variable names that components in the palette provide.

palette_uses()[source]

Get a list of variable names that components in the palette use.

remove(name)[source]

Remove a component called name from the arena.

exception FieldError(field)[source]

Bases: landlab.field.scalar_data_fields.Error, exceptions.KeyError

Raise this error for a missing field name.

class LandlabTester(package=None, raise_warnings='develop')[source]

Bases: numpy.testing.nosetester.NoseTester

excludes = ['examples']
test(**kwds)[source]
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)