natcap.invest.spec

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

Bases: Input

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

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

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 = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: str = 'r', columns: Iterable[Input] | None = None, rows: Iterable[Input] | None = None, index_col: str | None = None)

Bases: FileInput

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

For CSVs with a simple layout, columns or rows (but not both) may be specified. For more complex table structures that cannot be described by columns or rows, you may omit both attributes. Note that more complex table structures are often more difficult to use; consider dividing them into multiple, simpler tabular inputs.

columns: Iterable[Input] | None = None

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

get_validated_dataframe(csv_path: str, read_csv_kwargs={})

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

This is only supported when columns or rows 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

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.

index_col: str | None = 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.

rows: Iterable[Input] | None = None

An iterable of Input`s representing the rows that this CSV is expected to have. The `key of each input must match the corresponding row header.

type: ClassVar[str] = 'csv'
validate(**kwargs)
class natcap.invest.spec.CSVOutput(id: str = '', about: str = '', created_if: bool | str = True, columns: Iterable[Output] | None = None, rows: Iterable[Output] | None = None, index_col: str | None = None)

Bases: Output

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

For CSVs with a simple layout, columns or rows (but not both) may be specified. For more complex table structures that cannot be described by columns or rows, you may omit both attributes. Note that more complex table structures are often more difficult to use; consider dividing them into multiple, simpler tabular outputs.

columns: Iterable[Output] | None = None

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

index_col: str | None = None

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

rows: Iterable[Output] | None = None

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

class natcap.invest.spec.DirectoryInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, contents: Iterable[Input] | None = None, permissions: str = '', 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.

contents: Iterable[Input] | None = None

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

must_exist: bool = True

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

permissions: str = ''

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

type: ClassVar[str] = 'directory'
validate(**kwargs)
class natcap.invest.spec.DirectoryOutput(id: str = '', about: str = '', created_if: bool | str = True, contents: Iterable[Output] | None = None)

Bases: Output

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

Use this type when you need to specify a group of many file-based outputs, or an unknown number of file-based outputs, by grouping them together in a directory.

contents: Iterable[Output] | None = None

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

class natcap.invest.spec.FileInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: str = '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.

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

permissions: str = 'r'

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

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

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.

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

Bases: object

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 = ''

User-facing description of the input

allowed: bool | str = True

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.

hidden: bool = False

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

name: str = ''

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

required: bool | str = True

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 = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False)

Bases: Input

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

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

type: ClassVar[str] = 'integer'
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 = '', created_if: bool | str = True)

Bases: Output

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

class natcap.invest.spec.IterableWithDotAccess(*args)

Bases: object

Iterable that supports dot notation access by id attribute.

get(key)

Get an item by its id.

Parameters:

key – the item id

Returns:

the corresponding item

to_json()

Return a JSON serializable representation of self.

Returns:

dict mapping item IDs to items

class natcap.invest.spec.ModelSpec(model_id: str, model_title: str, userguide: str, input_field_order: list[list[str]], inputs: ~typing.Iterable[~natcap.invest.spec.Input], outputs: ~typing.Iterable[~natcap.invest.spec.Output], validate_spatial_overlap: bool = True, different_projections_ok: bool = True, aliases: set = <factory>)

Bases: object

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

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.

different_projections_ok: bool = True

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.

get_input(key)

Get an Input 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: Iterable[Input]

An iterable of the data inputs, or parameters, to the model.

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

outputs: Iterable[Output]

An iterable of the data outputs, or results, of the model.

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 = True

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.NumberInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, units: Unit | None = 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.

expression: str | None = 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

type: ClassVar[str] = 'number'
units: Unit | None = 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 = '', 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.

units: Unit | None = None

The units of measurement for this numeric value

class natcap.invest.spec.OptionStringInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, options: list | None = None, 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.

dropdown_function: Callable | None = 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

options: list | None = None

A list of the values that this input may take. Use this if the set of options is predetermined.

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 = '', created_if: bool | str = True, options: list | None = None)

Bases: Output

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

options: list | None = None

A list of the values that this input may take

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

Bases: object

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 = ''

User-facing description of the output

created_if: bool | str = True

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

class natcap.invest.spec.PercentInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, units: Unit | None = None, 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). Values are restricted to the range [0, 100].

type: ClassVar[str] = 'percent'
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 = '', 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).

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

Bases: object

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.

band_id: int | str = 1

band index used to access the raster band

data_type

float or int

alias of float

units: Unit | None = None

units of measurement of the raster band values

class natcap.invest.spec.RasterInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: str = 'r', bands: ~typing.Iterable[~natcap.invest.spec.RasterBand] = <factory>, projected: bool | None = None, projection_units: ~pint.registry.Unit | None = None)

Bases: FileInput

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: Iterable[RasterBand]

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

projected: bool | None = 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 = None

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

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

Bases: FileInput

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

data_type

Data type for the raster values (float or int)

alias of float

fields: Iterable[Input] | None = None

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

projected: bool | None = 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 = None

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

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

Units of measurement of the raster values

validate(**kwargs)
class natcap.invest.spec.RasterOutput(id: str = '', about: str = '', created_if: bool | str = True, bands: ~typing.Iterable[~natcap.invest.spec.RasterBand] = <factory>)

Bases: Output

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: Iterable[RasterBand]

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

class natcap.invest.spec.RatioInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, units: Unit | None = None, 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].

type: ClassVar[str] = 'ratio'
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 = '', 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).

class natcap.invest.spec.SingleBandRasterInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: str = 'r', data_type: ~typing.Type = <class 'float'>, units: ~pint.registry.Unit | None = None, projected: bool | None = None, projection_units: ~pint.registry.Unit | None = None)

Bases: FileInput

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

float or int

alias of float

projected: bool | None = 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 = None

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

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

units of measurement of the raster values

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

Bases: Output

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

float or int

alias of float

units: Unit | None = None

units of measurement of the raster values

class natcap.invest.spec.StringInput(id: str = '', name: str = '', about: str = '', 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.

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

regexp: str | None = None

An optional regex pattern which the text value must match

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 = '', 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.

class natcap.invest.spec.VectorInput(id: str = '', name: str = '', about: str = '', required: bool | str = True, allowed: bool | str = True, hidden: bool = False, permissions: str = 'r', geometry_types: set = <factory>, fields: ~typing.Iterable[~natcap.invest.spec.Input] | None = None, projected: bool | None = None, projection_units: ~pint.registry.Unit | None = None)

Bases: FileInput

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.

fields: Iterable[Input] | None = None

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

projected: bool | None = 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 = None

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

type: ClassVar[str] = 'vector'
validate(**kwargs)
class natcap.invest.spec.VectorOutput(id: str = '', about: str = '', created_if: bool | str = True, geometry_types: set = <factory>, fields: ~typing.Iterable[~natcap.invest.spec.Output] | None = None)

Bases: Output

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.

fields: Iterable[Output] | None = None

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

natcap.invest.spec.build_input_spec(argkey, arg)

Convert an old-style input spec dictionary to the new class-based style.

natcap.invest.spec.build_model_spec(model_spec)

Convert an old-style MODEL_SPEC dictionary to the new class-based style.

natcap.invest.spec.build_output_spec(key, spec)

Convert an old-style output spec dictionary to the new class-based style.

natcap.invest.spec.capitalize(title)

Capitalize a string into title case.

Parameters:

title (str) – string to capitalize

Returns:

capitalized string (each word capitalized except linking words)

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.describe_arg_from_name(module_name, *arg_keys)

Generate RST documentation for an arg, given its model and name.

Parameters:
  • module_name (str) – invest model module containing the arg.

  • *arg_keys – one or more strings that are nested arg keys.

Returns:

String describing the arg in RST format. Contains an anchor named <arg_keys[0]>-<arg_keys[1]>…-<arg_keys[n]> where underscores in arg keys are replaced with hyphens.

natcap.invest.spec.describe_arg_from_spec(name, spec)

Generate RST documentation for an arg, given an arg spec.

This is used for documenting:
  • a single top-level arg

  • a row or column in a CSV

  • a field in a vector

  • an item in a directory

Parameters:
  • name (str) – Name to give the section. For top-level args this is arg[‘name’]. For nested args it’s typically their key in the dictionary one level up.

  • spec (dict) – A arg spec dictionary that conforms to the InVEST args spec specification. It must at least have the key ‘type’, and whatever other keys are expected for that type.

Returns:

list of strings, where each string is a line of RST-formatted text. The first line has the arg name, type, required state, description, and units if applicable. Depending on the type, there may be additional lines that are indented, that describe details of the arg such as vector fields and geometry types, option_string options, etc.

natcap.invest.spec.format_geometry_types_string(geometry_types)

Represent a set of allowed vector geometry types as user-friendly text.

Parameters:

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

Returns:

string

natcap.invest.spec.format_options_string_from_dict(options)

Represent a dictionary of option: description pairs as a bulleted list.

Parameters:

options (dict) – the dictionary of options to document, where keys are options and values are dictionaries describing the options. They may have either or both ‘display_name’ and ‘description’ keys, for example: {‘option1’: {‘display_name’: ‘Option 1’, ‘description’: ‘the first option’}}

Returns:

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

natcap.invest.spec.format_options_string_from_list(options)

Represent options as a comma-separated list.

Parameters:

options (list[str]) – the set of options to document

Returns:

string of comma-separated options

natcap.invest.spec.format_permissions_string(permissions)

Represent a rwx-style permissions string as user-friendly text.

Parameters:

permissions (str) – rwx-style permissions string

Returns:

string

natcap.invest.spec.format_required_string(required)

Represent an arg’s required status as a user-friendly string.

Parameters:

required (bool | str | None) – required property of an arg. May be True, False, None, or a conditional string.

Returns:

string

natcap.invest.spec.format_type_string(arg_type)

Represent an arg type as a user-friendly string.

Parameters:

arg_type (str|set(str)) – the type to format. May be a single type or a set of types.

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.generate_metadata_for_outputs(model_module, args_dict)

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

Parameters:
  • model_module (object) – the MODEL_SPEC attribute

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

Returns:

None

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