natcap.invest.spec

class natcap.invest.spec.BooleanInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False)

Bases: Input

A boolean input, or parameter, of an invest model.

describe_rst()

Generate RST documentation for this input.

Returns:

list of strings, where each string is a line of RST-formatted text.

property display_name
static format_column(col, *args)

Format a column of a pandas dataframe that contains BooleanInput values.

Values are cast to boolean.

Parameters:

col – Column of a pandas dataframe to format

Returns:

Transformed dataframe column

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

preprocess(value)

Normalize a value to a boolean.

Parameters:

value – value to preprocess

Returns:

bool or None

rst_section: ClassVar[str] = 'truefalse'
type: ClassVar[str] = 'boolean'
validate(value)

Validate a value against the requirements for this input.

Parameters:

value – The value to validate.

Returns:

A string error message if an error was found. None otherwise.

class natcap.invest.spec.CSVInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: Annotated[str, AfterValidator(func=validate_permissions_string)] = 'r', columns: list[Input] | None = None, orientation: Literal['column', 'row'] = 'column', index_col: str | None = None, na_allowed: list[str] = [])

Bases: FileInput

A CSV table input, or parameter, of an invest model.

For CSVs with a simple layout, columns may be specified. For more complex table structures that cannot be described by columns, you may omit the attribute. Note that more complex table structures are often more difficult to use; consider dividing them into multiple, simpler tabular inputs.

check_column_types()
check_index_col_in_columns()
columns: list[Input] | None

An iterable of Input`s representing the columns that this CSV is expected to have. The `id of each input must match the corresponding column header.

describe_rst()

Generate RST documentation for this input.

Returns:

list of strings, where each string is a line of RST-formatted text.

property display_name
get_column(key: str) Input
get_validated_dataframe(csv_path: str, read_csv_kwargs={}, args=None)

Read a CSV into a dataframe that is guaranteed to match the spec.

This is only supported when columns is provided. Each column will be read in to a dataframe and values will be pre-processed according to that column input type. Column/row headers are matched case-insensitively. Values are cast to the appropriate type and relative paths are expanded.

Parameters:
  • csv_path – Path to the CSV to process

  • read_csv_kwargs – Additional kwargs to pass to pandas.read_csv

  • args – Optional. Dictionary of arg values used to evaluate the required condition of self.columns.

Returns:

pandas dataframe

Raises:
  • ValueError if the CSV cannot be parsed to fulfill the requirements

  • for this input - if a required column or row is missing, or if the

  • values in a column cannot be interpreted as the expected type.

  • AssertionError from utils.evaluate_expression if any conditonal

  • requirement string can't be evaluated given the values in args.

index_col: str | None

The header name of the column to use as the index. When processing a CSV file to a dataframe, the dataframe index will be set to this column.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

na_allowed: list[str]

List of header names of columns in which NA values are allowed.

orientation: Literal['column', 'row']

Orientation of the table. Defaults to ‘column’, meaning that the column headers go horizontally. This is the recommended orientation for most tables. If the table must be oriented row-wise, meaning that the headers go vertically, set this to ‘row’.

preprocess(value)

Preprocess a CSV path.

Parameters:

value (string) – path to process

Returns:

path string or None

rst_section: ClassVar[str] = 'csv'
type: ClassVar[str] = 'csv'
validate(**kwargs)
class natcap.invest.spec.CSVOutput(*, id: str, about: str | None = None, created_if: bool | str = True, path: str, columns: list[Output] | None = None, orientation: Literal['column', 'row'] = 'column', index_col: str | None = None)

Bases: FileOutput

A CSV table output, or result, of an invest model.

For CSVs with a simple layout, columns may be specified. For more complex table structures that cannot be described by columns, you may omit the attribute. Note that more complex table structures are often more difficult to use; consider dividing them into multiple, simpler tabular outputs.

check_column_types()
columns: list[Output] | None

An iterable of Output`s representing the table’s columns. The `key of each input must match the corresponding column header.

get_column(key: str) Output
index_col: str | None

The header name of the column that is the index of the table.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

orientation: Literal['column', 'row']

Orientation of the table. Defaults to ‘column’, meaning that the column headers go horizontally. This is the recommended orientation for most tables. If the table must be oriented row-wise, meaning that the headers go vertically, set this to ‘row’.

validate_index_col_in_columns()
class natcap.invest.spec.DirectoryInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, contents: list[Input], permissions: Annotated[str, AfterValidator(func=validate_permissions_string)] = '', must_exist: bool = True)

Bases: Input

A directory input, or parameter, of an invest model.

Use this type when you need to specify a group of many file-based inputs, or an unknown number of file-based inputs, by grouping them together in a directory. This may also be used to describe an empty directory where model outputs will be written to.

check_contents_types()
contents: list[Input]

An iterable of Input`s representing the contents of this directory. The `key of each input must be the file name or pattern.

property display_name
get_contents(key: str) Input
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

must_exist: bool

Defaults to True, indicating the directory must already exist before running the model. Set to False if the directory will be created.

permissions: Annotated[str, AfterValidator(func=validate_permissions_string)]

A string that includes the lowercase characters r, w and/or x, indicating read, write, and execute permissions (respectively) required for this directory.

rst_section: ClassVar[str] = 'directory'
type: ClassVar[str] = 'directory'
validate(**kwargs)
class natcap.invest.spec.FileInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: Annotated[str, AfterValidator(func=validate_permissions_string)] = 'r')

Bases: Input

A generic file input, or parameter, of an invest model.

This represents a not-otherwise-specified file input type. Use this only if a more specific type, such as CSVInput or VectorInput, does not apply.

property display_name
static format_column(col: Series, base_path: str) Series

Format a column of a pandas dataframe that contains FileInput values.

File path values are cast to pandas.StringDtype. Relative paths are expanded to absolute paths relative to base_path. NA values remain NA.

Parameters:
  • col – Column of a pandas dataframe to format

  • base_path – Base path of the source CSV. Relative file path values will be expanded relative to this base path.

Returns:

Transformed dataframe column

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

permissions: Annotated[str, AfterValidator(func=validate_permissions_string)]

A string that includes the lowercase characters r, w and/or x, indicating read, write, and execute permissions (respectively) required for this file.

rst_section: ClassVar[str] = 'file'
type: ClassVar[str] = 'file'
validate(**kwargs)
class natcap.invest.spec.FileOutput(*, id: str, about: str | None = None, created_if: bool | str = True, path: str)

Bases: Output

A generic file output, or result, of an invest model.

This represents a not-otherwise-specified file output type. Use this only if a more specific type, such as CSVOutput or VectorOutput, does not apply.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

path: str

Path to the output file within the workspace directory

class natcap.invest.spec.IOModel

Bases: ImmutableBaseModel

Base class for both Input and Output.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

class natcap.invest.spec.ImmutableBaseModel

Bases: BaseModel

BaseModel with frozen attributes.

model_config = {'frozen': True}

Make models immutable so that they must be copied before modifying.

class natcap.invest.spec.Input(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False)

Bases: IOModel

A data input, or parameter, of an invest model.

This represents an abstract input or parameter, which is rendered as an input field in the InVEST workbench. This does not store the value of the parameter for a specific run of the model.

about: str | None

User-facing description of the input

allowed: bool | str

Defaults to True. If the input is not allowed to be provided under a certain condition (such as when running the model in a mode where the input is not used), provide a string expression that evaluates to a boolean to describe this condition.

capitalize_name() str

Capitalize a self.name into title case.

Returns:

capitalized string (each word capitalized except linking words)

describe_rst()

Generate RST documentation for this input.

Note that conditional requirements (where required is a string expression) are not documented because it may be too complicated to auto-format into human readable text. For any conditionally-required input, the conditions upon which it is required should also be described in the about attribute.

Returns:

list of strings, where each string is a line of RST-formatted text.

format_required_string() str

Represent this input’s required status as a user-friendly string.

hidden: bool

Whether to hide the input from the model input form in the workbench. Use this if the value should not be configurable from the input form, such as if it’s pulled in from another source. Defaults to False.

id: str

Input identifier that should be unique within a model

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

name: str | None

The user-facing name of the input. The workbench UI displays this property as a label for each input. The name should be as short as possible. Any extra description should go in about. The name should be all lower-case, except for things that are always capitalized (acronyms, proper names).

Good examples: precipitation, Kc factor, valuation table

Bad examples: PRECIPITATION, kc_factor, table of valuation parameters

preprocess(value)

Base preprocessing function.

Override this when specific preprocessing is needed.

Parameters:

value (object) – value to preprocess

Returns:

unchanged value (object)

required: bool | str

Whether the input is required to be provided. Defaults to True. Set to False if the input is always optional. If the input is conditionally required depending on the state of other inputs, provide a string expression that evaluates to a boolean to describe this condition.

class natcap.invest.spec.IntegerInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, units: Unit | None = None, expression: str | None = None)

Bases: NumberInput

An integer input, or parameter, of an invest model.

property display_name
static format_column(col, *args)

Format a column of a pandas dataframe that contains IntegerInput values.

Values are cast to pandas.Int64Dtype.

Parameters:

col – Column of a pandas dataframe to format

Returns:

Transformed dataframe column

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

preprocess(value)

Normalize a value to an integer.

Parameters:

value – value to preprocess

Returns:

int or None

rst_section: ClassVar[str] = 'integer'
type: ClassVar[str] = 'integer'
units: Unit | None

The units of measurement for this numeric value

validate(value)

Validate a value against the requirements for this input.

Parameters:

value – The value to validate.

Returns:

A string error message if an error was found. None otherwise.

class natcap.invest.spec.IntegerOutput(*, id: str, about: str | None = None, created_if: bool | str = True)

Bases: Output

An integer output, or result, of an invest model.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

class natcap.invest.spec.ModelSpec(*, model_id: str, model_title: str, userguide: str, input_field_order: list[list[str]], inputs: list[Input], outputs: list[Output], validate_spatial_overlap: bool | list[str] = True, different_projections_ok: bool = True, aliases: set = {}, module_name: str, reporter: str = '', about: str = '')

Bases: ImmutableBaseModel

Specification of an invest model describing metadata, inputs, and outputs.

about: str

A brief description of the model.

aliases: set

Optional. A set of alternative names by which the model can be called from the invest command line interface, in addition to the model_id.

check_inputs_in_field_order()

Check that all inputs either appear in input_field_order, or are marked as hidden.

classmethod check_reporter(value: str) str
create_output_directories(args)

Create the necessary output directories given a set of args.

Parameters:

args (dict) – maps input keys to values

Returns:

None

different_projections_ok: bool

Whether spatial inputs are allowed to have different projections. If False, validation will check that all top-level spatial inputs have the same projection. This is only considered if validate_spatial_overlap is True.

execute(args, create_logfile=False, log_level=0, generate_metadata=False, save_file_registry=False, check_outputs=False, generate_report=False)

Invest model execute function wrapper.

Performs additonal work before and after the execute function runs:
  • GDAL exceptions are enabled

  • Optionally,

Parameters:
  • args (dict) – the raw user input args dictionary

  • generate_metadata (bool) – Defaults to False. If True, use geometamaker to create metadata files in the workspace after execution completes.

  • save_file_registry (bool) – Defaults to False. If True, the file registry dictionary will be saved to the workspace as a JSON file after execution completes.

  • create_logfile (bool) – Defaults to False. If True, all logging from the execute function as well as all other pre- and post-processing will be written to a logfile in the workspace.

  • log_level (int) – The logging threshold for the log file (only applies if create_logfile is true. Log messages with a level less than this will be excluded from the logfile. The default value (logging.NOTSET) will cause all logging to be captured.

  • check_outputs (bool) – Defaults to False. If True, will check that the expected outputs and no others were created based on the given args and the created_if attribute of each output. An error will be raised if a discrepancy is found.

  • generate_report (bool) – Defaults to False. If True, create an html report that summarizes model results. Requires self.reporter to be a Python module with a report function. If True, generate_metadata will be overridden.

Returns:

file registry dictionary

Raises:
  • RuntimeError if check_outputs is True and a discrepancy is

  • detected between actual and expected outputs

generate_metadata_for_outputs(file_registry, args_dict)

Create metadata for all items in an invest model output workspace.

Parameters:
  • file_registry (dict) – of FileRegistry.registry

  • args_dict (dict) – model’s execute function.

Returns:

None

get_input(key: str) Input

Get an Input of this model by its key.

get_output(key: str) Output

Get an Output of this model by its key.

input_field_order: list[list[str]]

A list that specifies the order and grouping of model inputs. Inputs will be displayed in the input form from top to bottom in the order listed here. Sub-lists represent groups of inputs that will be visually separated by a horizontal line. This improves UX by breaking up long lists and visually grouping related inputs. If you do not wish to use groups, all inputs may go in the same sub-list. It is a convention to begin with a group of workspace_dir and results_suffix. Each item in the sub-lists must match the key of an Input in inputs. The key of each Input must be included exactly once, unless it is hidden.

Example: [['workspace_dir', 'results_suffix'], ['foo'], ['bar', baz']]

inputs: list[Input]

A list of the data inputs, or parameters, to the model.

model_config = {'frozen': True}

Make models immutable so that they must be copied before modifying.

model_id: str

The unique identifier for the plugin model, used internally by invest. This identifier should be concise, meaningful, and unique - a good choice is often a short version of the model_title, or the name of the github repo. Using snake-case is recommended for consistancy. Including the word “model” is redundant and not recommended.

Good example: 'carbon_storage' Bad examples: 'Carbon storage', carbon_storage_model

model_title: str

The user-facing title for the plugin. This is displayed in the workbench. Title-case is recommended. Including the word “model” is redundant and not recommended.

Good example: 'Carbon Storage' Bad examples: 'Carbon storage', The Carbon Storage Model, carbon_storage

module_name: str

The importable module name of the model e.g. natcap.invest.foo.

outputs: list[Output]

A list of the data outputs, or results, of the model.

preprocess_inputs(input_values)

Preprocess a dictionary of input values.

The resulting dict will contain exactly the input keys in the model spec. Inputs which were not provided will have a value of None. Each provided input value is passed through the corresponding Input.preprocess method.

Parameters:

input_values (dict) – Dict mapping input keys to input values

Returns:

dictionary mapping input keys to preprocessed input values

reporter: str

The importable name of a report-generating module with a report function. e.g. 'natcap.invest.ndr.reporter'

setup(args, taskgraph_key='taskgraph_cache')

Perform boilerplate setup needed in an invest execute function.

Parameters:
  • args (dict) – maps input keys to values

  • taskgraph_key (str) – Input key that identifies the taskgraph cache. Defaults to ‘taskgraph_cache’.

Returns:

Tuple of (args, file_registry, graph) where args is the result of passing the input args through self.preprocess_inputs, file_registry is a FileRegistry, and graph is a TaskGraph, all instantiated appropriately for the given args and model specification.

to_json()

Serialize an MODEL_SPEC dict to a JSON string.

Parameters:

spec (dict) – An invest model’s MODEL_SPEC.

Raises:
  • TypeError if any object type within the spec is not handled by

  • json.dumps or by the fallback serializer.

Returns:

JSON String

userguide: str

Optional. For core invest models, this is the name of the models’ documentation file in the core invest user guide. For plugins, this field is currently unused. It may be set to a URL pointing to the plugin documentation. A future invest release will display it as a link.

Example: "https://github.com/natcap/invest-demo-plugin/blob/main/README.md"

validate_spatial_overlap: bool | list[str]

If True, validation will check that the bounding boxes of all top-level spatial inputs overlap (after reprojecting all to the same coordinate reference system).

class natcap.invest.spec.NWorkersInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, units: Unit | None = None, expression: str | None = None)

Bases: IntegerInput

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

preprocess(value)

Normalize a value to an integer.

Parameters:

value – value to preprocess

Returns:

int or None

class natcap.invest.spec.NumberInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, units: Unit | None, expression: str | None = None)

Bases: Input

A floating-point number input, or parameter, of an invest model.

Use a more specific type (such as IntegerInput, RatioInput, or PercentInput) where applicable.

describe_rst()

Generate RST documentation for this input.

Note that the expression attribute is not documented here because it may be too complicated to to auto-format into human readable text. The requirements enforced by the expression should also be described in the about attribute.

Returns:

list of strings, where each string is a line of RST-formatted text.

property display_name
expression: str | None

A string expression that can be evaluated to a boolean indicating whether the value meets a required condition. The expression must contain the string value, which will represent the user-provided value (after it has been cast to a float). Example: "(value >= 0) & (value <= 1)".

static format_column(col, *args)

Format a column of a pandas dataframe that contains NumberInput values.

Values are cast to float.

Parameters:

col – Column of a pandas dataframe to format

Returns:

Transformed dataframe column

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

preprocess(value)

Normalize a value to a float.

Parameters:

value – value to preprocess

Returns:

float or None

rst_section: ClassVar[str] = 'number'
type: ClassVar[str] = 'number'
units: Unit | None

The units of measurement for this numeric value

validate(value)

Validate a numeric value against the requirements for this input.

Parameters:

value – The value to validate.

Returns:

A string error message if an error was found. None otherwise.

class natcap.invest.spec.NumberOutput(*, id: str, about: str | None = None, created_if: bool | str = True, units: Unit | None = None)

Bases: Output

A floating-point number output, or result, of an invest model.

Use a more specific type (such as IntegerOutput, RatioOutput, or PercentOutput) where applicable.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

units: Unit | None

The units of measurement for this numeric value

class natcap.invest.spec.Option(*, key: str, display_name: str | None = None, about: str | None = None)

Bases: ImmutableBaseModel

An option in an OptionStringInput or OptionStringOutput.

about: str | None

Optional description of this option. Only needed for keys that are not self-explanatory.

display_name: str | None

For OptionStringInputs that are represented by a dropdown menu, this optional attribute will be displayed in the menu instead of the key.

key: str

The unique key that identifies this option. If the OptionStringInput is represented by a dropdown menu, and display_name is None, this key will be displayed in the menu. For options in CSV columns etc, this is the value that should be entered in the column.

model_config = {'frozen': True}

Make models immutable so that they must be copied before modifying.

class natcap.invest.spec.OptionStringInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, options: list[Option], include_placeholder: bool = False, dropdown_function: Callable | None = None)

Bases: Input

A string input, or parameter, which is limited to a set of options.

This corresponds to a dropdown menu in the workbench, where the user is limited to a set of pre-defined options.

check_options()
describe_rst()

Generate RST documentation for this input.

Returns:

list of strings, where each string is a line of RST-formatted text.

property display_name
dropdown_function: Callable | None

A function that returns a list of the values that this input may take. Use this if the set of options must be dynamically generated.

static format_column(col, *args)

Format a pandas dataframe column that contains OptionStringInput values.

Values are cast to pandas.StringDtype, lowercased, and leading and trailing whitespace is stripped. NA values remain NA.

Parameters:

col – Column of a pandas dataframe to format

Returns:

Transformed dataframe column

format_rst()

Represent self.options as a RST-formatted bulleted list.

Parameters:

options – list of Options to format

Returns:

list of RST-formatted strings, where each is a line in a bullet list

include_placeholder: bool

If True, a placeholder ‘Select an option’ will be included in the dropdown options list as the default (selected but invalid) option.

list_options()

Return a sorted list of the option keys.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

options: list[Option]

A list of the values that this input may take. Use this if the set of options is predetermined. If using dropdown_function instead, this should be an empty list.

preprocess(value)

Normalize an option string value to a lower cased string.

Parameters:

value – value to preprocess

Returns:

string

rst_section: ClassVar[str] = 'option'
type: ClassVar[str] = 'option_string'
validate(value)

Validate a value against the requirements for this input.

Parameters:

value – The value to validate.

Returns:

A string error message if an error was found. None otherwise.

class natcap.invest.spec.OptionStringOutput(*, id: str, about: str | None = None, created_if: bool | str = True, options: list[Option])

Bases: Output

A string output, or result, which is limited to a set of options.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

options: list[Option]

A list of the values that this input may take

class natcap.invest.spec.Output(*, id: str, about: str | None = None, created_if: bool | str = True)

Bases: IOModel

A data output, or result, of an invest model.

This represents an abstract output which is produced as a result of running an invest model. This does not store the value of the output for a specific run of the model.

about: str | None

User-facing description of the output

created_if: bool | str

Defaults to True. If the input is only created under a certain condition (such as when running the model in a specific mode), provide a string expression that evaluates to a boolean to describe this condition.

id: str

Output identifier that should be unique within a model

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

class natcap.invest.spec.PercentInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, expression: str | None = None)

Bases: NumberInput

A percent input, or parameter, of an invest model.

A percent is a proportion expressed as a value from 0% to 100% (in contrast to a ratio, which ranges from 0 to 1). By default there is no restriction on the range a percent value can take, so values may be less than 0 or greater than 100. Use the expression parameter to enforce a value range.

property display_name
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

rst_section: ClassVar[str] = 'percent'
type: ClassVar[str] = 'percent'
units: ClassVar[None] = None

The units of measurement for this numeric value

validate(value)

Validate a value against the requirements for this input.

Parameters:

value – The value to validate.

Returns:

A string error message if an error was found. None otherwise.

class natcap.invest.spec.PercentOutput(*, id: str, about: str | None = None, created_if: bool | str = True)

Bases: Output

A percent output, or result, of an invest model.

A percent is a proportion expressed as a value from 0 to 100 (in contrast to a ratio, which ranges from 0 to 1).

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

class natcap.invest.spec.RasterBand(*, band_id: int | str = 1, data_type: Type = <class 'float'>, units: Unit | None)

Bases: IOModel

A representation of a single raster band.

band_id: int | str

band index used to access the raster band

data_type: Type

float or int

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

units: Unit | None

units of measurement of the raster band values

class natcap.invest.spec.RasterInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: Annotated[str, AfterValidator(func=validate_permissions_string)] = 'r', projected: bool | None = None, projection_units: Unit | None = None, bands: list[RasterBand])

Bases: SpatialFileInput

A raster input, or parameter, of an invest model.

This represents a raster file input (all GDAL-supported raster file types are allowed), which may have multiple bands.

bands: list[RasterBand]

An iterable of RasterBand representing the bands expected to be in the raster.

property display_name
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

rst_section: ClassVar[str] = 'raster'
type: ClassVar[str] = 'raster'
validate(**kwargs)
class natcap.invest.spec.RasterOrVectorInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: ~typing.Annotated[str, ~pydantic.functional_validators.AfterValidator(func=~natcap.invest.spec.validate_permissions_string)] = 'r', projected: bool | None = None, projection_units: ~pint.registry.Unit | None = None, data_type: ~typing.Type = <class 'float'>, units: ~pint.registry.Unit | None, geometry_types: set, fields: list[~natcap.invest.spec.Input])

Bases: SpatialFileInput

An invest model input that can be either a single-band raster or a vector.

data_type: Type

Data type for the raster values (float or int)

property display_name
fields: list[Input]

An iterable of Input`s representing the fields that this vector is expected to have. The `key of each input must match the corresponding field name.

geometry_types: set

A set of geometry type(s) that are allowed for this vector

get_field(key: str) Input
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

rst_section: ClassVar[str] = 'raster'
type: ClassVar[str] = 'raster_or_vector'
units: Unit | None

Units of measurement of the raster values

validate(**kwargs)
class natcap.invest.spec.RasterOutput(*, id: str, about: str | None = None, created_if: bool | str = True, path: str, bands: list[RasterBand])

Bases: FileOutput

A raster output, or result, of an invest model.

This represents a raster file output (all GDAL-supported raster file types are allowed), which may have multiple bands.

bands: list[RasterBand]

An iterable of RasterBand representing the bands expected to be in the raster.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

class natcap.invest.spec.RatioInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, expression: str | None = None)

Bases: NumberInput

A ratio input, or parameter, of an invest model.

A ratio is a proportion expressed as a value from 0 to 1 (in contrast to a percent, which ranges from 0 to 100). Values are restricted to the range [0, 1].

property display_name
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

rst_section: ClassVar[str] = 'ratio'
type: ClassVar[str] = 'ratio'
units: ClassVar[None] = None

The units of measurement for this numeric value

validate(value)

Validate a value against the requirements for this input.

Parameters:

value – The value to validate.

Returns:

A string error message if an error was found. None otherwise.

class natcap.invest.spec.RatioOutput(*, id: str, about: str | None = None, created_if: bool | str = True)

Bases: Output

A ratio output, or result, of an invest model.

A ratio is a proportion expressed as a value from 0 to 1 (in contrast to a percent, which ranges from 0 to 100).

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

class natcap.invest.spec.ResultsSuffixInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, regexp: str | None = None)

Bases: StringInput

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

preprocess(value)

Normalize a value to a string.

Parameters:

value – value to preprocess

Returns:

string or None

class natcap.invest.spec.SingleBandRasterInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: Annotated[str, ~pydantic.functional_validators.AfterValidator(func=~natcap.invest.spec.validate_permissions_string)] = 'r', projected: bool | None = None, projection_units: Unit | None = None, data_type: Type = <class 'float'>, units: Unit | None)

Bases: SpatialFileInput

A single-band raster input, or parameter, of an invest model.

This represents a raster file input (all GDAL-supported raster file types are allowed), where only the first band is needed. While the same thing can be achieved using a RasterInput, this class exists to simplify access to the band properties when there is only one band.

data_type: Type

float or int

describe_rst()

Generate RST documentation for this input.

Returns:

list of strings, where each string is a line of RST-formatted text.

property display_name
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

rst_section: ClassVar[str] = 'raster'
type: ClassVar[str] = 'raster'
units: Unit | None

units of measurement of the raster values

validate(**kwargs)
class natcap.invest.spec.SingleBandRasterOutput(*, id: str, about: str | None = None, created_if: bool | str = True, path: str, data_type: Type = <class 'float'>, units: Unit | None = None)

Bases: FileOutput

A single-band raster output, or result, of an invest model.

This represents a raster file output (all GDAL-supported raster file types are allowed), where only the first band is used.

data_type: Type

float or int

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

units: Unit | None

units of measurement of the raster values

class natcap.invest.spec.SpatialFileInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: Annotated[str, AfterValidator(func=validate_permissions_string)] = 'r', projected: bool | None = None, projection_units: Unit | None = None)

Bases: FileInput

Base class for raster and vector spatial inputs.

check_projected_projection_units()
static format_column(col: Series, base_path: str) Series

Format a dataframe column that contains spatial file paths.

File path values are cast to pandas.StringDtype. Relative paths are expanded to absolute paths relative to base_path. NA values remain NA.

Parameters:
  • col – Column of a pandas dataframe to format

  • base_path – Base path of the source CSV. Relative file path values will be expanded relative to this base path.

Returns:

Transformed dataframe column

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

preprocess(value)

Normalize a path to a GDAL-compatible local or remote path.

Parameters:

value (string) – path to normalize

Returns:

normalized path string or None

projected: bool | None

Defaults to None, indicating a projected (as opposed to geographic) coordinate system is not required. Set to True if a projected coordinate system is required.

projection_units: Unit | None

Defaults to None. If projected is True, and a specific unit of projection (such as meters) is required, indicate it here.

class natcap.invest.spec.StringInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, regexp: str | None = None)

Bases: Input

A string input, or parameter, of an invest model.

This represents a textual input. Do not use this to represent numeric or file-based inputs which can be better represented by another type.

classmethod check_regexp(regexp: str | None) str | None
property display_name
static format_column(col, *args)

Format a column of a pandas dataframe that contains StringInput values.

Values are cast to pandas.StringDtype, lowercased, and leading and trailing whitespace is stripped. NA values remain NA.

Parameters:

col – Column of a pandas dataframe to format

Returns:

Transformed dataframe column

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

preprocess(value)

Normalize a value to a string.

Parameters:

value – value to preprocess

Returns:

string or None

regexp: str | None

An optional regex pattern which the text value must match

rst_section: ClassVar[str] = 'text'
type: ClassVar[str] = 'string'
validate(value)

Validate a value against the requirements for this input.

Parameters:

value – The value to validate.

Returns:

A string error message if an error was found. None otherwise.

class natcap.invest.spec.StringOutput(*, id: str, about: str | None = None, created_if: bool | str = True)

Bases: Output

A string output, or result, of an invest model.

This represents a textual output. Do not use this to represent numeric or file-based inputs which can be better represented by another type.

model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

class natcap.invest.spec.VectorInput(*, id: str, name: str | None = None, about: str | None = None, required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: Annotated[str, AfterValidator(func=validate_permissions_string)] = 'r', projected: bool | None = None, projection_units: Unit | None = None, geometry_types: set, fields: list[Input])

Bases: SpatialFileInput

A vector input, or parameter, of an invest model.

This represents a vector file input (all GDAL-supported vector file types are allowed). It is assumed that only the first layer is used.

check_field_types()
describe_rst()

Generate RST documentation for this input.

Returns:

list of strings, where each string is a line of RST-formatted text.

property display_name
fields: list[Input]

An iterable of Input`s representing the fields that this vector is expected to have. The `key of each input must match the corresponding field name.

format_geometry_types_rst()

Represent self.geometry_types in RST text.

Parameters:

geometry_types (set(str)) – set of geometry names

Returns:

string

geometry_types: set

A set of geometry type(s) that are allowed for this vector

get_field(key: str) Input
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

rst_section: ClassVar[str] = 'vector'
type: ClassVar[str] = 'vector'
validate(**kwargs)
class natcap.invest.spec.VectorOutput(*, id: str, about: str | None = None, created_if: bool | str = True, path: str, geometry_types: set = {}, fields: list[Output])

Bases: FileOutput

A vector output, or result, of an invest model.

This represents a vector file output (all GDAL-supported vector file types are allowed). It is assumed that only the first layer is used.

check_field_types()
fields: list[Output]

An iterable of Output`s representing the fields created in this vector. The `key of each input must match the corresponding field name.

geometry_types: set

A set of geometry type(s) that are produced in this vector

get_field(key: str) Output
model_config = {'arbitrary_types_allowed': True, 'frozen': True}

Allow fields to have arbitrary types that don’t inherit from BaseModel (needed for pint.Unit).

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

natcap.invest.spec.check_headers(expected_headers, actual_headers, header_type='header')

Validate that expected headers are in a list of actual headers.

  • Each expected header should be found exactly once.

  • Actual headers may contain extra headers that are not expected.

  • Headers are converted to lowercase before matching.

Parameters:
  • expected_headers (list[str]) – A list of headers that are expected to exist in actual_headers.

  • actual_headers (list[str]) – A list of actual headers to validate against expected_headers.

  • header_type (str) – A string to use in the error message to refer to the header (typically one of ‘column’, ‘row’, ‘field’)

Returns:

None, if validation passes; or a string describing the problem, if a validation rule is broken.

natcap.invest.spec.format_type_string(_input)

Represent an arg type as a user-friendly string.

Parameters:

_input (Input) – the input to format.

Returns:

formatted string that links to a description of the input type(s)

natcap.invest.spec.format_unit(unit)

Represent a pint Unit as user-friendly unicode text.

This attempts to follow the style guidelines from the NIST Guide to the SI (https://www.nist.gov/pml/special-publication-811): - Use standard symbols rather than spelling out - Use ‘/’ to represent division - Use the center dot ‘ · ‘ to represent multiplication - Combine denominators into one, surrounded by parentheses

Parameters:

unit (pint.Unit) – the unit to format

Raises:

TypeError if unit is not an instance of pint.Unit.

Returns:

String describing the unit.

natcap.invest.spec.timeout(func, timeout=5)

Stop a function after a given amount of time.

Parameters:
  • func (function) – function to apply the timeout to

  • args – arguments to pass to the function

  • timeout (number) – how many seconds to allow the function to run. Defaults to 5.

Returns:

A string warning message if the thread completed in time and returned warnings, None otherwise.

Raises:

RuntimeWarning` if the thread does not complete in time

natcap.invest.spec.validate_permissions_string(permissions)

Validate an rwx-style permissions string.

Parameters:

permissions (str) – a string to validate as permissions

Returns:

None

Raises:
  • AssertionError if permissions isn't a string, if it's

  • an empty string, if it has any letters besides 'r', 'w', 'x',

  • or if it has any of those letters more than once

natcap.invest.spec.write_metadata_file(datasource_path, spec, keywords_list, lineage_statement='', out_workspace=None)

Write a metadata sidecar file for an invest dataset.

Create metadata for invest model inputs or outputs, taking care to preserve existing human-modified attributes.

Note: We do not want to overwrite any existing metadata so if there is invalid metadata for the datasource (i.e., doesn’t pass geometamaker validation in describe), this function will NOT create new metadata.

Parameters:
  • datasource_path (str)

  • spec (dict)

  • keywords_list (list)

  • lineage_statement (str, optional) – the dataset

  • out_workspace (str, optional) – from data location

Returns:

None