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 |
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
auto_type : boolean, optional
|
---|
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
default : str or number, optional
ptype : str, optional
|
---|
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
|
---|
read_bool
(key)[source]¶Locate key in the input file and return it as a boolean.
Parameters: | key : str
default : bool
|
---|---|
Returns: | bool
|
Raises: | MissingKeyError
ParameterValueError
|
Examples
>>> from six import StringIO
>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_BOOL:
... true
... '''))
>>> params.read_bool('MY_BOOL')
True
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
|
---|---|
Returns: | bool
|
read_float
(key[, default])[source]¶Locate key in the input file and return it as a float.
Parameters: | key : str
default : float
|
---|---|
Returns: | float
|
Raises: | MissingKeyError
ParameterValueError
|
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
|
---|---|
Returns: | float
|
Raises: | ParameterValueError
|
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:
Parameters: | param_file : str or file_like
|
---|
read_int
(key[, default])[source]¶Locate key in the input file and return it as an integer.
Parameters: | key : str
default : int
|
---|---|
Returns: | int
|
Raises: | MissingKeyError
ParameterValueError
|
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
|
---|---|
Returns: | int
|
Raises: | ParameterValueError
|
read_string
(key)[source]¶Locate key in the input file and return it as a string.
Parameters: | key : str
default : str
|
---|---|
Returns: | str
|
Raises: | MissingKeyError
|
Examples
>>> from six import StringIO
>>> from landlab import ModelParameterDictionary
>>> params = ModelParameterDictionary(StringIO(
... '''
... MY_STRING:
... landlab
... '''))
>>> params.read_string('MY_STRING')
'landlab'
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.
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.
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.
from_path
(grid, path)[source]¶Create a component from an input file.
Parameters: | grid : ModelGrid
path : str or file_like
|
---|---|
Returns: | Component
|
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
()[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
= ()¶var_definition
(name)[source]¶Get a description of a particular field.
Parameters: | name : str
|
---|---|
Returns: | tuple of (name, description)
|
var_help
(name)[source]¶Print a help message for a particular field.
Parameters: | name : str
|
---|
var_loc
(name)[source]¶Location where a particular variable is defined.
Parameters: | name : str
|
---|---|
Returns: | str
|
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.
Palette
(*args, **kwds)[source]¶Bases: landlab.framework.collections.Collection
A collection of component classes that have yet to be instantiated.
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.
NoProvidersError
(var_name)[source]¶Bases: landlab.framework.collections.Error
Raise this exception if no components provide the a variable
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.
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.
Framework
[source]¶Bases: object
A framework for connecting and running component from The Landlab.
FieldError
(field)[source]¶Bases: landlab.field.scalar_data_fields.Error
, exceptions.KeyError
Raise this error for a missing field name.
LandlabTester
(package=None, raise_warnings='develop')[source]¶Bases: numpy.testing.nosetester.NoseTester
excludes
= ['examples']¶load_params
(file_like)[source]¶Load parameters from a file.
Parameters: | file_like : file_like or str
|
---|---|
Returns: | dict
|
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)