natcap.invest package



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.


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.

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.

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


Alias for field number 0


Alias for field number 2


Alias for field number 1

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

Build an InVEST datastack from an arguments dict.

  • 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.


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

Record a parameter set to a file on disk.

  • 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.


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

Extract a datastack to a given folder.

  • 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.

A dictionary of arguments from the extracted

archive. Paths to files are absolute paths.

Return type:

args (dict)


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.

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.

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

A formatted, unicode string.


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.
  • "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 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.

  • 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

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.

  • 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, column_list=None, to_lower=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.

If an entire row is NA/NaN (including key_field) then it is dropped from the table and a warning is given of the dropped rows.

  • 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 and sets the row index.
  • column_list (list) – a list of column names to subset from the CSV file, default=None
  • to_lower (bool) – if True, converts all unicode in the CSV, including headers and values to lowercase, otherwise uses raw string values. default=True.

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)

If ValueError occurs during conversion to dictionary.
If key_field is not present during set_index call.

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.

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.

  • 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.


natcap.invest.utils.log_to_file(logfile, exclude_threads=None, logging_level=0, log_fmt='%(asctime)s %(module)s.%(funcName)s(%(lineno)d) %(levelname)s %(message)s', date_fmt=None)

Log all messages within this context to a file.

  • 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.


An instance of logging.FileHandler that

represents the file that is being written to.




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.

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

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’]`


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

pixel_size_tuple (tuple): a 2 tuple indicating the x/y size of a
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(workspace, name, logging_level=0, exclude_threads=None)
natcap.invest.utils.sandbox_tempdir(suffix='', prefix='tmp', dir=None)

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.

  • 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.

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



natcap.invest.validation module

natcap.invest.wave_energy module

natcap.invest.wind_energy module

Module contents

init module for natcap.invest.


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.