natcap.invest package

Subpackages

Submodules

natcap.invest.carbon module

natcap.invest.cli module

Single entry point for all InVEST applications.

class natcap.invest.cli.SelectModelAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Bases: argparse.Action

Given a possibly-ambiguous model string, identify the model to run.

This is a subclass of argparse.Action and is executed when the argparse interface detects that the user has attempted to select a model by name.

natcap.invest.cli.build_model_list_json()

Build a json object of relevant information for the CLI.

The json object returned uses the human-readable model names for keys and the values are another dict containing the internal python name of the model and the aliases recognized by the CLI.

Returns:A string representation of the JSON object.
natcap.invest.cli.build_model_list_table()

Build a table of model names, aliases and other details.

This table is a table only in the sense that its contents are aligned into columns, but are not separated by a delimited. This table is intended to be printed to stdout.

Returns:A string representation of the formatted table.
natcap.invest.cli.main(user_args=None)

CLI entry point for launching InVEST runs.

This command-line interface supports two methods of launching InVEST models from the command-line:

  • through its GUI
  • in headless mode, without its GUI.

Running in headless mode allows us to bypass all GUI functionality, so models may be run in this way without having GUI packages installed.

natcap.invest.coastal_vulnerability module

natcap.invest.crop_production_percentile module

natcap.invest.crop_production_regression module

natcap.invest.datastack module

Functions for reading and writing InVEST model parameters.

A datastack for InVEST is a compressed archive that includes the arguments for a model, all of the data files referenced by the arguments, and a logfile with some extra information about how the archive was created. The resulting archive can then be extracted on a different computer and should have all of the information it needs to run an InVEST model in its entirity.

A parameter set for InVEST is a JSON-formatted text file that contains all of the parameters needed to run the current model, where the parameters are located on the local hard disk. Paths to files may be either relative or absolute. If paths are relative, they are interpreted as relative to the location of the parameter set file.

A logfile for InVEST is a text file that is written to disk for each model run.

class natcap.invest.datastack.ParameterSet(args, model_name, invest_version)

Bases: tuple

args

Alias for field number 0

invest_version

Alias for field number 2

model_name

Alias for field number 1

natcap.invest.datastack.build_datastack_archive(args, model_name, datastack_path)

Build an InVEST datastack from an arguments dict.

Parameters:
  • args (dict) – The arguments dictionary to include in the datastack.
  • model_name (string) – The python-importable module string of the model these args are for.
  • datastack_path (string) – The path to where the datastack archive should be written.
Returns:

None

natcap.invest.datastack.build_parameter_set(args, model_name, paramset_path, relative=False)

Record a parameter set to a file on disk.

Parameters:
  • args (dict) – The args dictionary to record to the parameter set.
  • model_name (string) – An identifier string for the callable or InVEST model that would accept the arguments given.
  • paramset_path (string) – The path to the file on disk where the parameters should be recorded.
  • relative (bool) – Whether to save the paths as relative. If True, The datastack assumes that paths are relative to the parent directory of paramset_path.
Returns:

None

natcap.invest.datastack.extract_datastack_archive(datastack_path, dest_dir_path)

Extract a datastack to a given folder.

Parameters:
  • datastack_path (string) – The path to a datastack archive on disk.
  • dest_dir_path (string) – The path to a directory. The contents of the demonstration datastack archive will be extracted into this directory. If the directory does not exist, it will be created.
Returns:

A dictionary of arguments from the extracted

archive. Paths to files are absolute paths.

Return type:

args (dict)

natcap.invest.datastack.extract_parameter_set(paramset_path)

Extract and return attributes from a parameter set.

Any string values found will have environment variables expanded. See :py:ref:os.path.expandvars and :py:ref:os.path.expanduser for details.

Parameters:paramset_path (string) – The file containing a parameter set.
Returns:A ParameterSet namedtuple with these attributes:
args (dict): The arguments dict for the callable
invest_version (string): The version of InVEST used to record the
    parameter set.
model_name (string): The name of the callable or model that these
    arguments are intended for.
natcap.invest.datastack.extract_parameters_from_logfile(logfile_path)

Parse an InVEST logfile for the parameters (args) dictionary.

Argument key-value pairs are parsed, one pair per line, starting the line after the line starting with "Arguments", and ending with a blank line. If no such section exists within the logfile, ValueError will be raised.

If possible, the model name and InVEST version will be parsed from the same line as "Arguments", but IUI-formatted logfiles (without model name and InVEST version information) are also supported.

Parameters:logfile_path (string) – The path to an InVEST logfile on disk.
Returns:An instance of the ParameterSet namedtuple. If a model name and InVEST version cannot be parsed from the Arguments section of the logfile, ParameterSet.model_name and ParameterSet.invest_version will be set to datastack.UNKNOWN.
Raises:ValueError - when no arguments could be parsed from the logfile.
natcap.invest.datastack.format_args_dict(args_dict, model_name)

Nicely format an arguments dictionary for writing to a stream.

If printed to a console, the returned string will be aligned in two columns representing each key and value in the arg dict. Keys are in ascending, sorted order. Both columns are left-aligned.

Parameters:
  • args_dict (dict) – The args dictionary to format.
  • model_name (string) – The model name (in python package import format)
Returns:

A formatted, unicode string.

natcap.invest.datastack.get_datastack_info(filepath)

Get information about a datastack.

Parameters:filepath (string) – The path to a file on disk that can be extracted as a datastack, parameter set, or logfile.
Returns:
  • "archive" when the file is a datastack archive.
    • "json" when the file is a json parameter set.
    • "logfile" when the file is a text logfile.

The second item of the tuple is a ParameterSet namedtuple with the raw parsed args, modelname and invest version that the file was built with.

Return type:A 2-tuple. The first item of the tuple is one of

natcap.invest.delineateit module

natcap.invest.forest_carbon_edge_effect module

natcap.invest.globio module

natcap.invest.habitat_quality module

natcap.invest.hra module

natcap.invest.pollination module

natcap.invest.routedem module

natcap.invest.scenario_gen_proximity module

natcap.invest.urban_cooling_model module

natcap.invest.urban_flood_risk_mitigation module

natcap.invest.utils module

InVEST specific code utils.

class natcap.invest.utils.ThreadFilter(thread_name)

Bases: logging.Filter

Filters out log messages issued by the given thread.

Any log messages generated by a thread with the name matching the threadname provided to the constructor will be excluded.

filter(record)

Filter the given log record.

Parameters:record (log record) – The log record to filter.
Returns:True if the record should be included, false if not.
natcap.invest.utils.build_file_registry(base_file_path_list, file_suffix)

Combine file suffixes with key names, base filenames, and directories.

Parameters:
  • base_file_tuple_list (list) – a list of (dict, path) tuples where the dictionaries have a ‘file_key’: ‘basefilename’ pair, or ‘file_key’: list of ‘basefilename’s. ‘path’ indicates the file directory path to prepend to the basefile name.
  • file_suffix (string) – a string to append to every filename, can be empty string
Returns:

dictionary of ‘file_keys’ from the dictionaries in base_file_tuple_list mapping to full file paths with suffixes or lists of file paths with suffixes depending on the original type of the ‘basefilename’ pair.

Raises:
  • ValueError if there are duplicate file keys or duplicate file paths.
  • ValueError if a path is not a string or a list of strings.
natcap.invest.utils.build_lookup_from_csv(table_path, key_field, to_lower=True, warn_if_missing=True)

Read a CSV table into a dictionary indexed by key_field.

Creates a dictionary from a CSV whose keys are unique entries in the CSV table under the column named by key_field and values are dictionaries indexed by the other columns in table_path including key_field whose values are the values on that row of the CSV table.

Parameters:
  • table_path (string) – path to a CSV file containing at least the header key_field
  • key_field – (string): a column in the CSV file at table_path that can uniquely identify each row in the table.
  • to_lower (bool) – if True, converts all unicode in the CSV, including headers and values to lowercase, otherwise uses raw string values.
  • warn_if_missing (bool) – If True, warnings are logged if there are empty headers or value rows.
Returns:

a dictionary of the form {

key_field_0: {csv_header_0: value0, csv_header_1: value1…}, key_field_1: {csv_header_0: valuea, csv_header_1: valueb…}

}

if to_lower all strings including key_fields and values are converted to lowercase unicode.

Return type:

lookup_dict (dict)

natcap.invest.utils.capture_gdal_logging(*args, **kwds)

Context manager for logging GDAL errors with python logging.

GDAL error messages are logged via python’s logging system, at a severity that corresponds to a log level in logging. Error messages are logged with the osgeo.gdal logger.

Parameters:None
Returns:None
natcap.invest.utils.exponential_decay_kernel_raster(expected_distance, kernel_filepath)

Create a raster-based exponential decay kernel.

The raster created will be a tiled GeoTiff, with 256x256 memory blocks.

Parameters:
  • expected_distance (int or float) – The distance (in pixels) of the kernel’s radius, the distance at which the value of the decay function is equal to 1/e.
  • kernel_filepath (string) – The path to the file on disk where this kernel should be stored. If this file exists, it will be overwritten.
Returns:

None

natcap.invest.utils.log_to_file(*args, **kwds)

Log all messages within this context to a file.

Parameters:
  • logfile (string) – The path to where the logfile will be written. If there is already a file at this location, it will be overwritten.
  • exclude_threads=None (list) – If None, logging from all threads will be included in the log. If a list, it must be a list of string thread names that should be excluded from logging in this file.
  • logging_level=logging.NOTSET (int) – The logging threshold. Log messages with a level less than this will be automatically excluded from the logfile. The default value (logging.NOTSET) will cause all logging to be captured.
  • log_fmt=LOG_FMT (string) – The logging format string to use. If not provided, utils.LOG_FMT will be used.
  • date_fmt (string) – The logging date format string to use. If not provided, ISO8601 format will be used.
Yields:

handler

An instance of logging.FileHandler that

represents the file that is being written to.

Returns:

None

natcap.invest.utils.make_directories(directory_list)

Create directories in directory_list if they do not already exist.

natcap.invest.utils.make_suffix_string(args, suffix_key)

Make an InVEST appropriate suffix string.

Creates an InVEST appropriate suffix string given the args dictionary and suffix key. In general, prepends an ‘_’ when necessary and generates an empty string when necessary.

Parameters:
  • args (dict) – the classic InVEST model parameter dictionary that is passed to execute.
  • suffix_key (string) – the key used to index the base suffix.
Returns:

If suffix_key is not in args, or args[‘suffix_key’] is “”

return “”,

If args[‘suffix_key’] starts with ‘_’ return args[‘suffix_key’]

else return ‘_’+`args[‘suffix_key’]`

natcap.invest.utils.mean_pixel_size_and_area(pixel_size_tuple)

Convert to mean and raise Exception if they are not close.

Parameter:
pixel_size_tuple (tuple): a 2 tuple indicating the x/y size of a
pixel.
Returns:tuple of (mean absolute average of pixel_size, area of pixel size)
Raises:ValueError if the dimensions of pixel_size_tuple are not almost – square.
natcap.invest.utils.prepare_workspace(*args, **kwds)
natcap.invest.utils.sandbox_tempdir(*args, **kwds)

Create a temporary directory for this context and clean it up on exit.

Parameters are identical to those for tempfile.mkdtemp().

When the context manager exits, the created temporary directory is recursively removed.

Parameters:
  • suffix='' (string) – a suffix for the name of the directory.
  • prefix='tmp' (string) – the prefix to use for the directory name.
  • dir=None (string or None) – If a string, a directory that should be the parent directory of the new temporary directory. If None, tempfile will determine the appropriate tempdir to use as the parent folder.
Yields:

sandbox (string) – The path to the new folder on disk.

Returns:

None

natcap.invest.validation module

natcap.invest.wave_energy module

natcap.invest.wind_energy module

Module contents

init module for natcap.invest.

natcap.invest.local_dir(source_file)

Return the path to where source_file would be on disk.

If this is frozen (as with PyInstaller), this will be the folder with the executable in it. If not, it’ll just be the foldername of the source_file being passed in.