# natcap.invest package¶

## natcap.invest.carbon module¶

Carbon Storage and Sequestration.

natcap.invest.carbon.execute(args)

InVEST Carbon Model.

Calculate the amount of carbon stocks given a landscape, or the difference due to a future change, and/or the tradeoffs between that and a REDD scenario, and calculate economic valuation on those scenarios.

The model can operate on a single scenario, a combined present and future scenario, as well as an additional REDD scenario.

Parameters: args['workspace_dir'] (string) – a path to the directory that will write output and other temporary files during calculation. args['results_suffix'] (string) – appended to any output file name. args['lulc_cur_path'] (string) – a path to a raster representing the current carbon stocks. args['calc_sequestration'] (bool) – if true, sequestration should be calculated and ‘lulc_fut_path’ and ‘do_redd’ should be defined. args['lulc_fut_path'] (string) – a path to a raster representing future landcover scenario. Optional, but if present and well defined will trigger a sequestration calculation. args['do_redd'] (bool) – if true, REDD analysis should be calculated and ‘lulc_redd_path’ should be defined args['lulc_redd_path'] (string) – a path to a raster representing the alternative REDD scenario which is only possible if the args[‘lulc_fut_path’] is present and well defined. args['carbon_pools_path'] (string) – path to CSV or that indexes carbon storage density to lulc codes. (required if ‘do_uncertainty’ is false) args['lulc_cur_year'] (int/string) – an integer representing the year of args[‘lulc_cur_path’] used if args[‘calc_sequestration’] is True. args['lulc_fut_year'] (int/string) – an integer representing the year of args[‘lulc_fut_path’] used in valuation if it exists. Required if args[‘do_valuation’] is True and args[‘lulc_fut_path’] is present and well defined. args['do_valuation'] (bool) – if true then run the valuation model on available outputs. At a minimum will run on carbon stocks, if sequestration with a future scenario is done and/or a REDD scenario calculate NPV for either and report in final HTML document. args['price_per_metric_ton_of_c'] (float) – Is the present value of carbon per metric ton. Used if args[‘do_valuation’] is present and True. args['discount_rate'] (float) – Discount rate used if NPV calculations are required. Used if args[‘do_valuation’] is present and True. args['rate_change'] (float) – Annual rate of change in price of carbon as a percentage. Used if args[‘do_valuation’] is present and True. None.

## natcap.invest.cli module¶

Single entry point for all InVEST applications.

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

Bases: argparse.Action

An argparse action to list the available models.

__call__(parser, namespace, values, option_string=None)

Print the available models and quit the argparse parser.

See https://docs.python.org/2.7/library/argparse.html#action-classes for the full documentation for argparse classes.

Overridden from argparse.Action.__call__

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

__call__(parser, namespace, values, option_string=None)

Given the user’s input, determine which model they’re referring to.

When the user didn’t provide a model name, we print the help and exit with a nonzero exit code.

Identifiable model names are:

• the model name (verbatim) as identified in the keys of _MODEL_UIS
• a uniquely identifiable prefix for the model name (e.g. “d” matches “delineateit”, but “fi” matches both “fisheries” and “finfish”
• a known model alias, as registered in _MODEL_UIS

If no single model can be identified based on these rules, an error message is printed and the parser exits with a nonzero exit code.

See https://docs.python.org/2.7/library/argparse.html#action-classes for the full documentation for argparse classes and this __call__ method.

Overridden from argparse.Action.__call__

natcap.invest.cli.build_model_list_table()

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

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

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

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 wthout having GUI packages installed.

## natcap.invest.crop_production_percentile module¶

InVEST Crop Production Percentile Model.

natcap.invest.crop_production_percentile.execute(args)

Crop Production Percentile Model.

This model will take a landcover (crop cover?) map and produce yields, production, and observed crop yields, a nutrient table, and a clipped observed map.

Parameters: args['workspace_dir'] (string) – output directory for intermediate, temporary, and final files args['results_suffix'] (string) – (optional) string to append to any output file names args['landcover_raster_path'] (string) – path to landcover raster args['landcover_to_crop_table_path'] (string) – path to a table that converts landcover types to crop names that has two headers: * lucode: integer value corresponding to a landcover code in args[‘landcover_raster_path’]. crop_name: a string that must match one of the crops in args[‘model_data_path’]/climate_bin_maps/[cropname]_* A ValueError is raised if strings don’t match. args['aggregate_polygon_path'] (string) – path to polygon shapefile that will be used to aggregate crop yields and total nutrient value. (optional, if value is None, then skipped) args['aggregate_polygon_id'] (string) – This is the id field in args[‘aggregate_polygon_path’] to be used to index the final aggregate results. If args[‘aggregate_polygon_path’] is not provided, this value is ignored. args['model_data_path'] (string) – path to the InVEST Crop Production global data directory. This model expects that the following directories are subdirectories of this path * climate_bin_maps (contains [cropname]_climate_bin.tif files) * climate_percentile_yield (contains [cropname]_percentile_yield_table.csv files) Please see the InVEST user’s guide chapter on crop production for details about how to download these data. None.

## natcap.invest.crop_production_regression module¶

InVEST Crop Production Percentile Model.

natcap.invest.crop_production_regression.execute(args)

Crop Production Regression Model.

This model will take a landcover (crop cover?), N, P, and K map and produce modeled yields, and a nutrient table.

Parameters: args['workspace_dir'] (string) – output directory for intermediate, temporary, and final files args['results_suffix'] (string) – (optional) string to append to any output file names args['landcover_raster_path'] (string) – path to landcover raster args['landcover_to_crop_table_path'] (string) – path to a table that converts landcover types to crop names that has two headers: * lucode: integer value corresponding to a landcover code in args[‘landcover_raster_path’]. crop_name: a string that must match one of the crops in args[‘model_data_path’]/climate_regression_yield_tables/[cropname]_* A ValueError is raised if strings don’t match. args['fertilization_rate_table_path'] (string) – path to CSV table that contains fertilization rates for the crops in the simulation, though it can contain additional crops not used in the simulation. The headers must be ‘crop_name’, ‘nitrogen_rate’, ‘phosphorous_rate’, and ‘potassium_rate’, where ‘crop_name’ is the name string used to identify crops in the ‘landcover_to_crop_table_path’, and rates are in units kg/Ha. args['aggregate_polygon_path'] (string) – path to polygon shapefile that will be used to aggregate crop yields and total nutrient value. (optional, if value is None, then skipped) args['aggregate_polygon_id'] (string) – This is the id field in args[‘aggregate_polygon_path’] to be used to index the final aggregate results. If args[‘aggregate_polygon_path’] is not provided, this value is ignored. args['model_data_path'] (string) – path to the InVEST Crop Production global data directory. This model expects that the following directories are subdirectories of this path * climate_bin_maps (contains [cropname]_climate_bin.tif files) * climate_percentile_yield (contains [cropname]_percentile_yield_table.csv files) Please see the InVEST user’s guide chapter on crop production for details about how to download these data. None.

## natcap.invest.fileio module¶

class natcap.invest.fileio.CSVDriver(uri, fieldnames=None)

The CSVDriver class is a subclass of TableDriverTemplate.

get_fieldnames()
get_file_object(uri=None)
read_table()
write_table(table_list, uri=None, fieldnames=None)
exception natcap.invest.fileio.ColumnMissingFromTable

Bases: exceptions.KeyError

A custom exception for when a key is missing from a table. More descriptive than just throwing a KeyError. This class inherits the KeyError exception, so any existing exception handling should still work properly.

class natcap.invest.fileio.DBFDriver(uri, fieldnames=None)

The DBFDriver class is a subclass of TableDriverTemplate.

get_fieldnames()

Return a list of strings containing the fieldnames.

get_file_object(uri=None, read_only=True)

Return the library-specific file object by using the input uri. If uri is None, return use self.uri.

read_table()

Return the table object with data built from the table using the file-specific package as necessary. Should return a list of dictionaries.

write_table(table_list, uri=None, fieldnames=None)

Take the table_list input and write its contents to the appropriate URI. If uri == None, write the file to self.uri. Otherwise, write the table to uri (which may be a new file). If fieldnames == None, assume that the default fieldnames order will be used.

class natcap.invest.fileio.TableDriverTemplate(uri, fieldnames=None)

Bases: object

The TableDriverTemplate classes provide a uniform, simple way to interact with specific tabular libraries. This allows us to interact with multiple filetypes in exactly the same way and in a uniform syntax. By extension, this also allows us to read and write to and from any desired table format as long as the appropriate TableDriver class has been implemented.

These driver classes exist for convenience, and though they can be accessed directly by the user, these classes provide only the most basic functionality. Other classes, such as the TableHandler class, use these drivers to provide a convenient layer of functionality to the end-user.

This class is merely a template to be subclassed for use with appropriate table filetype drivers. Instantiating this object will yield a functional object, but it won’t actually get you any relevant results.

get_fieldnames()

Return a list of strings containing the fieldnames.

get_file_object(uri=None)

Return the library-specific file object by using the input uri. If uri is None, return use self.uri.

read_table()

Return the table object with data built from the table using the file-specific package as necessary. Should return a list of dictionaries.

write_table(table_list, uri=None, fieldnames=None)

Take the table_list input and write its contents to the appropriate URI. If uri == None, write the file to self.uri. Otherwise, write the table to uri (which may be a new file). If fieldnames == None, assume that the default fieldnames order will be used.

class natcap.invest.fileio.TableHandler(uri, fieldnames=None)

Bases: object

__iter__()

Allow this handler object’s table to be iterated through. Returns an iterable version of self.table.

create_column(column_name, position=None, default_value=0)

Create a new column in the internal table object with the name column_name. If position == None, it will be appended to the end of the fieldnames. Otherwise, the column will be inserted at index position. This function will also loop through the entire table object and create an entry with the default value of default_value.

Note that it’s up to the driver to actually add the field to the file on disk.

Returns nothing

find_driver(uri, fieldnames=None)

Locate the driver needed for uri. Returns a driver object as documented by self.driver_types.

get_fieldnames(case='lower')

Returns a python list of the original fieldnames, true to their original case.

case=’lower’ - a python string representing the desired status of the
fieldnames. ‘lower’ for lower case, ‘orig’ for original case.

returns a python list of strings.

get_map(key_field, value_field)

Returns a python dictionary mapping values contained in key_field to values contained in value_field. If duplicate keys are found, they are overwritten in the output dictionary.

This is implemented as a dictionary comprehension on top of self.get_table_list(), so there shouldn’t be a need to reimplement this for each subclass of AbstractTableHandler.

If the table list has not been retrieved, it is retrieved before generating the map.

key_field - a python string. value_field - a python string.

returns a python dictionary mapping key_fields to value_fields.

get_table()

Return the table list object.

get_table_dictionary(key_field, include_key=True)

Returns a python dictionary mapping a key value to all values in that particular row dictionary (including the key field). If duplicate keys are found, the are overwritten in the output dictionary.

key_field - a python string of the desired field value to be used as
the key for the returned dictionary.
include_key=True - a python boolean indicating whether the
key_field provided should be included in each row_dictionary.

returns a python dictionary of dictionaries.

get_table_row(key_field, key_value)

Return the first full row where the value of key_field is equivalent to key_value. Raises a KeyError if key_field does not exist.

key_field - a python string. key_value - a value of appropriate type for this field.

returns a python dictionary of the row, or None if the row does not exist.

set_field_mask(regexp=None, trim=0, trim_place='front')

Set a mask for the table’s self.fieldnames. Any fieldnames that match regexp will have trim number of characters stripped off the front.

regexp=None - a python string or None. If a python string, this
will be a regular expression. If None, this represents no regular expression.

trim - a python int. trim_place - a string, either ‘front’ or ‘back’. Indicates where

the trim should take place.

Returns nothing.

write_table(table=None, uri=None)

Invoke the driver to save the table to disk. If table == None, self.table will be written, otherwise, the list of dictionaries passed in to table will be written. If uri is None, the table will be written to the table’s original uri, otherwise, the table object will be written to uri.

natcap.invest.fileio.get_free_space(folder='/', unit='auto')

Get the free space on the drive/folder marked by folder. Returns a float of unit unit.

folder - (optional) a string uri to a folder or drive on disk. Defaults
to ‘/’ (‘C:’ on Windows’)
unit - (optional) a string, one of [‘B’, ‘MB’, ‘GB’, ‘TB’, ‘auto’]. If
‘auto’, the unit returned will be automatically calculated based on available space. Defaults to ‘auto’.

returns a string marking the space free and the selected unit. Number is rounded to two decimal places.’

## natcap.invest.forest_carbon_edge_effect module¶

InVEST Carbon Edge Effect Model.

An implementation of the model described in ‘Degradation in carbon stocks near tropical forest edges’, by Chaplin-Kramer et. al (in review).

natcap.invest.forest_carbon_edge_effect.execute(args)

Forest Carbon Edge Effect.

InVEST Carbon Edge Model calculates the carbon due to edge effects in tropical forest pixels.

Parameters: args['workspace_dir'] (string) – a uri to the directory that will write output and other temporary files during calculation. (required) args['results_suffix'] (string) – a string to append to any output file name (optional) args['n_nearest_model_points'] (int) – number of nearest neighbor model points to search for args['aoi_uri'] (string) – (optional) if present, a path to a shapefile that will be used to aggregate carbon stock results at the end of the run. args['biophysical_table_uri'] (string) – a path to a CSV table that has at least the fields ‘lucode’ and ‘c_above’. If args['compute_forest_edge_effects'] == True, table must also contain an ‘is_tropical_forest’ field. If args['pools_to_calculate'] == 'all', this table must contain the fields ‘c_below’, ‘c_dead’, and ‘c_soil’. lucode: an integer that corresponds to landcover codes in the raster args['lulc_uri'] is_tropical_forest: either 0 or 1 indicating whether the landcover type is forest (1) or not (0). If 1, the value in c_above is ignored and instead calculated from the edge regression model. c_above: floating point number indicating tons of above ground carbon per hectare for that landcover type {'c_below', 'c_dead', 'c_soil'}: three other optional carbon pools that will statically map landcover types to the carbon densities in the table. Example: lucode,is_tropical_forest,c_above,c_soil,c_dead,c_below 0,0,32.8,5,5.2,2.1 1,1,n/a,2.5,0.0,0.0 2,1,n/a,1.8,1.0,0.0 16,0,28.1,4.3,0.0,2.0  Note the “n/a” in c_above are optional since that field is ignored when is_tropical_forest==1. args['lulc_uri'] (string) – path to a integer landcover code raster args['pools_to_calculate'] (string) – if “all” then all carbon pools will be calculted. If any other value only above ground carbon pools will be calculated and expect only a ‘c_above’ header in the biophysical table. If “all” model expects ‘c_above’, ‘c_below’, ‘c_dead’, ‘c_soil’ in header of biophysical_table and will make a translated carbon map for each based off the landcover map. args['compute_forest_edge_effects'] (boolean) – if True, requires biophysical table to have ‘is_tropical_forest’ forest field, and any landcover codes that have a 1 in this column calculate carbon stocks using the Chaplin-Kramer et. al method and ignore ‘c_above’. args['tropical_forest_edge_carbon_model_shape_uri'] (string) – path to a shapefile that defines the regions for the local carbon edge models. Has at least the fields ‘method’, ‘theta1’, ‘theta2’, ‘theta3’. Where ‘method’ is an int between 1..3 describing the biomass regression model, and the thetas are floating point numbers that have different meanings depending on the ‘method’ parameter. Specifically, method 1 (asymptotic model):biomass = theta1 - theta2 * exp(-theta3 * edge_dist_km)  method 2 (logarithmic model):# NOTE: theta3 is ignored for this method biomass = theta1 + theta2 * numpy.log(edge_dist_km)  method 3 (linear regression):biomass = theta1 + theta2 * edge_dist_km  args['biomass_to_carbon_conversion_factor'] (string/float) – Number by which to multiply forest biomass to convert to carbon in the edge effect calculation. None

## natcap.invest.globio module¶

GLOBIO InVEST Model.

natcap.invest.globio.execute(args)

GLOBIO.

The model operates in two modes. Mode (a) generates a landcover map based on a base landcover map and information about crop yields, infrastructure, and more. Mode (b) assumes the globio landcover map is generated. These modes are used below to describe input parameters.

Parameters: args['workspace_dir'] (string) – output directory for intermediate, temporary, and final files args['predefined_globio'] (boolean) – if True then “mode (b)” else “mode (a)” args['results_suffix'] (string) – (optional) string to append to any output files args['lulc_uri'] (string) – used in “mode (a)” path to a base landcover map with integer codes args['lulc_to_globio_table_uri'] (string) – used in “mode (a)” path to table that translates the land-cover args[‘lulc_uri’] to intermediate GLOBIO classes, from which they will be further differentiated using the additional data in the model. Contains at least the following fields: ‘lucode’: Land use and land cover class code of the dataset used. LULC codes match the ‘values’ column in the LULC raster of mode (b) and must be numeric and unique. ‘globio_lucode’: The LULC code corresponding to the GLOBIO class to which it should be converted, using intermediate codes described in the example below. args['infrastructure_dir'] (string) – used in “mode (a) and (b)” a path to a folder containing maps of either gdal compatible rasters or OGR compatible shapefiles. These data will be used in the infrastructure to calculation of MSA. args['pasture_uri'] (string) – used in “mode (a)” path to pasture raster args['potential_vegetation_uri'] (string) – used in “mode (a)” path to potential vegetation raster args['pasture_threshold'] (float) – used in “mode (a)” args['intensification_fraction'] (float) – used in “mode (a)”; a value between 0 and 1 denoting proportion of total agriculture that should be classified as ‘high input’ args['primary_threshold'] (float) – used in “mode (a)” args['msa_parameters_uri'] (string) – path to MSA classification parameters args['aoi_uri'] (string) – (optional) if it exists then final MSA raster is summarized by AOI args['globio_lulc_uri'] (string) – used in “mode (b)” path to predefined globio raster. None
natcap.invest.globio.load_msa_parameter_table(msa_parameter_table_filename, intensification_fraction)

Load parameter table to a dict that to define the MSA ranges.

Parameters: msa_parameter_table_filename (string) – path to msa csv table intensification_fraction (float) – a number between 0 and 1 indicating what level between msa_lu 8 and 9 to define the general GLOBIO code “12” to. a dictionary of the form (returns) – { ‘msa_f’: { valuea: msa_f_value, ... valueb: ... ‘<’: (bound, msa_f_value), ‘>’: (bound, msa_f_value)} ‘msa_i_other_table’: { valuea: msa_i_value, ... valueb: ... ‘<’: (bound, msa_i_other_value), ‘>’: (bound, msa_i_other_value)} ‘msa_i_primary’: { valuea: msa_i_primary_value, ... valueb: ... ‘<’: (bound, msa_i_primary_value), ‘>’: (bound, msa_i_primary_value)} ‘msa_lu’: { valuea: msa_lu_value, ... valueb: ... ‘<’: (bound, msa_lu_value), ‘>’: (bound, msa_lu_value) 12: (msa_lu_8 * (1.0 - intensification_fraction) + msa_lu_9 * intensification_fraction} }
natcap.invest.globio.make_gaussian_kernel_uri(sigma, kernel_uri)

Create a gaussian kernel raster.

## natcap.invest.habitat_quality module¶

InVEST Habitat Quality model.

natcap.invest.habitat_quality.execute(args)

Habitat Quality.

Open files necessary for the portion of the habitat_quality model.

Parameters: workspace_dir (string) – a uri to the directory that will write output and other temporary files during calculation (required) landuse_cur_uri (string) – a uri to an input land use/land cover raster (required) landuse_fut_uri (string) – a uri to an input land use/land cover raster (optional) landuse_bas_uri (string) – a uri to an input land use/land cover raster (optional, but required for rarity calculations) threat_folder (string) – a uri to the directory that will contain all threat rasters (required) threats_uri (string) – a uri to an input CSV containing data of all the considered threats. Each row is a degradation source and each column a different attribute of the source with the following names: ‘THREAT’,’MAX_DIST’,’WEIGHT’ (required). access_uri (string) – a uri to an input polygon shapefile containing data on the relative protection against threats (optional) sensitivity_uri (string) – a uri to an input CSV file of LULC types, whether they are considered habitat, and their sensitivity to each threat (required) half_saturation_constant (float) – a python float that determines the spread and central tendency of habitat quality scores (required) suffix (string) – a python string that will be inserted into all raster uri paths just before the file extension.

Example Args Dictionary:

{
'workspace_dir': 'path/to/workspace_dir',
'landuse_cur_uri': 'path/to/landuse_cur_raster',
'landuse_fut_uri': 'path/to/landuse_fut_raster',
'landuse_bas_uri': 'path/to/landuse_bas_raster',
'threat_raster_folder': 'path/to/threat_rasters/',
'threats_uri': 'path/to/threats_csv',
'access_uri': 'path/to/access_shapefile',
'sensitivity_uri': 'path/to/sensitivity_csv',
'half_saturation_constant': 0.5,
'suffix': '_results',
}

Returns: None
natcap.invest.habitat_quality.make_linear_decay_kernel_uri(max_distance, kernel_uri)

Create a linear decay kernel as a raster.

Pixels in raster are equal to d / max_distance where d is the distance to the center of the raster in number of pixels.

Parameters: max_distance (int) – number of pixels out until the decay is 0. kernel_uri (string) – path to output raster whose values are in (0,1) representing distance to edge. Size is (max_distance * 2 + 1)^2 None
natcap.invest.habitat_quality.map_raster_to_dict_values(key_raster_uri, out_uri, attr_dict, field, out_nodata, raise_error)

Creates a new raster from ‘key_raster’ where the pixel values from ‘key_raster’ are the keys to a dictionary ‘attr_dict’. The values corresponding to those keys is what is written to the new raster. If a value from ‘key_raster’ does not appear as a key in ‘attr_dict’ then raise an Exception if ‘raise_error’ is True, otherwise return a ‘out_nodata’

key_raster_uri - a GDAL raster uri dataset whose pixel values relate to
the keys in ‘attr_dict’

out_uri - a string for the output path of the created raster attr_dict - a dictionary representing a table of values we are interested

in making into a raster
field - a string of which field in the table or key in the dictionary
to use as the new raster pixel values

out_nodata - a floating point value that is the nodata value. raise_error - a string that decides how to handle the case where the

value from ‘key_raster’ is not found in ‘attr_dict’. If ‘raise_error’ is ‘values_required’, raise Exception, if ‘none’, return ‘out_nodata’
returns - a GDAL raster, or raises an Exception and fail if:
1. raise_error is True and
2. the value from ‘key_raster’ is not a key in ‘attr_dict’
natcap.invest.habitat_quality.raster_pixel_count(raster_path)

Count unique pixel values in raster.

Parameters: raster_path (string) – path to a raster dict of pixel values to frequency.
natcap.invest.habitat_quality.resolve_ambiguous_raster_path(path, raise_error=True)

Determine real path when we don’t know true path extension.

Parameters: path (string) – file path that includes the name of the file but not its extension raise_error (boolean) – if True then function will raise an ValueError if a valid raster file could not be found. the full path, plus extension, to the valid raster.

## natcap.invest.habitat_suitability module¶

Habitat suitability model.

natcap.invest.habitat_suitability.execute(args)

Habitat Suitability.

Calculate habitat suitability indexes given biophysical parameters.

The objective of a habitat suitability index (HSI) is to help users identify areas within their AOI that would be most suitable for habitat restoration. The output is a gridded map of the user’s AOI in which each grid cell is assigned a suitability rank between 0 (not suitable) and 1 (most suitable). The suitability rank is generally calculated as the weighted geometric mean of several individual input criteria, which have also been ranked by suitability from 0-1. Habitat types (e.g. marsh, mangrove, coral, etc.) are treated separately, and each habitat type will have a unique set of relevant input criteria and a resultant habitat suitability map.

Parameters: args['workspace_dir'] (string) – directory path to workspace directory for output files. args['results_suffix'] (string) – (optional) string to append to any output file names. args['aoi_path'] (string) – file path to an area of interest shapefile. args['exclusion_path_list'] (list) – (optional) a list of file paths to shapefiles which define areas which the HSI should be masked out in a final output. args['output_cell_size'] (float) – (optional) size of output cells. If not present, the output size will snap to the smallest cell size in the HSI range rasters. args['habitat_threshold'] (float) – a value to threshold the habitat score values to 0 and 1. args['hsi_ranges'] (dict) – a dictionary that describes the habitat biophysical base rasters as well as the ranges for optimal and tolerable values. Each biophysical value has a unique key in the dictionary that is used to name the mapping of biophysical to local HSI value. Each value is dictionary with keys: ‘raster_path’: path to disk for biophysical raster. ‘range’: a 4-tuple in non-decreasing order describing the “tolerable” to “optimal” ranges for those biophysical values. The endpoints non-inclusively define where the suitability score is 0.0, the two midpoints inclusively define the range where the suitability is 1.0, and the ranges above and below are linearly interpolated between 0.0 and 1.0. Example: { 'depth': { 'raster_path': r'C:/path/to/depth.tif', 'range': (-50, -30, -10, -10), }, 'temperature': { 'temperature_path': ( r'C:/path/to/temperature.tif'), 'range': (5, 7, 12.5, 16), } }  args['categorical_geometry'] (dict) – a dictionary that describes categorical vector geometry that directly defines the HSI values. The dictionary specifies paths to the vectors and the fieldname that provides the raw HSI values with keys: ‘vector_path’: a path to disk for the vector coverage polygon ‘fieldname’: a string matching a field in the vector polygon with HSI values. Example { ‘categorical_geometry’: { ‘substrate’: { ‘vector_path’: r’C:/path/to/Substrate.shp’, ‘fieldname’: ‘Suitabilit’, } } } None

## natcap.invest.pollination module¶

Pollinator service model for InVEST.

natcap.invest.pollination.execute(args)

InVEST Pollination Model.

Parameters: args['workspace_dir'] (string) – a path to the output workspace folder. Will overwrite any files that exist if the path already exists. args['results_suffix'] (string) – string appended to each output file path. args['landcover_raster_path'] (string) – file path to a landcover raster. args['guild_table_path'] (string) – file path to a table indicating the bee species to analyze in this model run. Table headers must include: ‘species’: a bee species whose column string names will be referred to in other tables and the model will output analyses per species. one or more columns matching _NESTING_SUITABILITY_PATTERN with values in the range [0.0, 1.0] indicating the suitability of the given species to nest in a particular substrate. one or more columns matching _FORAGING_ACTIVITY_RE_PATTERN with values in the range [0.0, 1.0] indicating the relative level of foraging activity for that species during a particular season. _ALPHA_HEADER the sigma average flight distance of that bee species in meters. ‘relative_abundance’: a weight indicating the relative abundance of the particular species with respect to the sum of all relative abundance weights in the table. args['landcover_biophysical_table_path'] (string) – path to a table mapping landcover codes in args[‘landcover_path’] to indexes of nesting availability for each nesting substrate referenced in guilds table as well as indexes of abundance of floral resources on that landcover type per season in the bee activity columns of the guild table. All indexes are in the range [0.0, 1.0]. Columns in the table must be at least ‘lucode’: representing all the unique landcover codes in the raster ast args[‘landcover_path’] For every nesting matching _NESTING_SUITABILITY_PATTERN in the guild stable, a column matching the pattern in _LANDCOVER_NESTING_INDEX_HEADER. For every season matching _FORAGING_ACTIVITY_RE_PATTERN in the guilds table, a column matching the pattern in _LANDCOVER_FLORAL_RESOURCES_INDEX_HEADER. args['farm_vector_path'] (string) – (optional) path to a single layer polygon shapefile representing farms. If present will trigger the farm yield component of the model. The layer must have at least the following fields: season (string): season in which the farm needs pollination crop_type (string): a text field to identify the crop type for summary statistics. half_sat (float): a real in the range [0.0, 1.0] representing the proportion of wild pollinators to achieve a 50% yield of that crop. p_dep (float): a number in the range [0.0, 1.0] representing the proportion of yield dependent on pollinators. p_managed (float): proportion of pollinators that come from non-native/managed hives. fr_[season] (float): one or more fields that match this pattern such that season also matches the season headers in the biophysical and guild table. Any areas that overlap the landcover map will replace seasonal floral resources with this value. Ranges from 0..1. n_[substrate] (float): One or more fields that match this pattern such that substrate also matches the nesting substrate headers in the biophysical and guild table. Any areas that overlap the landcover map will replace nesting substrate suitability with this value. Ranges from 0..1. None

## natcap.invest.scenario_gen_proximity module¶

Scenario Generation: Proximity Based.

natcap.invest.scenario_gen_proximity.execute(args)

Scenario Generator: Proximity-Based.

Main entry point for proximity based scenario generator model.

Parameters: args['workspace_dir'] (string) – output directory for intermediate, temporary, and final files args['results_suffix'] (string) – (optional) string to append to any output files args['base_lulc_path'] (string) – path to the base landcover map args['replacment_lucode'] (string or int) – code to replace when converting pixels args['area_to_convert'] (string or float) – max area (Ha) to convert args['focal_landcover_codes'] (string) – a space separated string of landcover codes that are used to determine the proximity when refering to “towards” or “away” from the base landcover codes args['convertible_landcover_codes'] (string) – a space separated string of landcover codes that can be converted in the generation phase found in args[‘base_lulc_path’]. args['n_fragmentation_steps'] (string) – an int as a string indicating the number of steps to take for the fragmentation conversion args['aoi_path'] (string) – (optional) path to a shapefile that indicates area of interest. If present, the expansion scenario operates only under that AOI and the output raster is clipped to that shape. args['convert_farthest_from_edge'] (boolean) – if True will run the conversion simulation starting from the furthest pixel from the edge and work inwards. Workspace will contain output files named ‘toward_base{suffix}.{tif,csv}. args['convert_nearest_to_edge'] (boolean) – if True will run the conversion simulation starting from the nearest pixel on the edge and work inwards. Workspace will contain output files named ‘toward_base{suffix}.{tif,csv}. None.

## natcap.invest.scenarios module¶

Functions for creating and extracting InVEST demonstration scenarios.

A demonstration scenario 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.

class natcap.invest.scenarios.ParameterSet(args, invest_version, name)

Bases: tuple

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__getstate__()

Exclude the OrderedDict from pickling

__repr__()

Return a nicely formatted representation string

args

Alias for field number 0

invest_version

Alias for field number 1

name

Alias for field number 2

natcap.invest.scenarios.build_scenario_archive(args, name, scenario_path)

Build an InVEST demonstration scenario from an arguments dict.

Parameters: args (dict) – The arguments dictionary to include in the demonstration scenario. scenario_path (string) – The path to where the scenario archive should be written. None
natcap.invest.scenarios.extract_scenario_archive(scenario_path, dest_dir_path)

Extract a demonstration scenario to a given folder.

Parameters: scenario_path (string) – The path to a demonstration scenario archive on disk. dest_dir_path (string) – The path to a directory. The contents of the demonstration scenario archive will be extracted into this directory. If the directory does not exist, it will be created. args – A dictionary of arguments from the extracted archive dict
natcap.invest.scenarios.format_args_dict(args_dict)

Nicely format an arguments dictionary for writing to a stream.

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

Parameters: args_dict (dict) – The args dictionary to format. A formatted, unicode string.
natcap.invest.scenarios.read_parameter_set(filepath)

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: filepath (string) – The file containing a parameter set. :args (dict): The arguments dict for the callable invest_version (string): The version of InVEST used to record the parameter set. name (string): The name of the callable or model that these arguments are intended for. A ParameterSet namedtuple with these attributes
natcap.invest.scenarios.read_parameters_from_logfile(logfile_path)

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

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

Parameters: logfile_path (string) – The path to an InVEST logfile on disk. args – A dictionary of key-value pairs parsed from the logfile. dict ValueError - when no arguments could be parsed from the logfile. –
natcap.invest.scenarios.write_parameter_set(filepath, args, name, relative=False)

Record a parameter set to a file on disk.

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

## natcap.invest.sdr module¶

InVEST Sediment Delivery Ratio (SDR) module.

The SDR method in this model is based on:
Winchell, M. F., et al. “Extension and validation of a geographic information system-based method for calculating the Revised Universal Soil Loss Equation length-slope factor for erosion risk assessments in large watersheds.” Journal of Soil and Water Conservation 63.3 (2008): 105-111.
natcap.invest.sdr.execute(args)

Sediment Delivery Ratio.

This function calculates the sediment export and retention of a landscape using the sediment delivery ratio model described in the InVEST user’s guide.

Parameters: args['workspace_dir'] (string) – output directory for intermediate, temporary, and final files args['results_suffix'] (string) – (optional) string to append to any output file names args['dem_path'] (string) – path to a digital elevation raster args['erosivity_path'] (string) – path to rainfall erosivity index raster args['erodibility_path'] (string) – a path to soil erodibility raster args['lulc_path'] (string) – path to land use/land cover raster args['watersheds_path'] (string) – path to vector of the watersheds args['biophysical_table_path'] (string) – path to CSV file with biophysical information of each land use classes. contain the fields ‘usle_c’ and ‘usle_p’ args['threshold_flow_accumulation'] (number) – number of upstream pixels on the dem to threshold to a stream. args['k_param'] (number) – k calibration parameter args['sdr_max'] (number) – max value the SDR args['ic_0_param'] (number) – ic_0 calibration parameter args['drainage_path'] (string) – (optional) path to drainage raster that is used to add additional drainage areas to the internally calculated stream layer None.

## natcap.invest.utils module¶

InVEST specific code utils.

class natcap.invest.utils.ThreadFilter(thread_name)

Bases: logging.Filter

When used, this filters out log messages that were recorded from other threads. This is especially useful if we have logging coming from several concurrent threads. Arguments passed to the constructor:

thread_name - the name of the thread to identify. If the record was
reported from this thread name, it will be passed on.
filter(record)
natcap.invest.utils.build_file_registry(base_file_path_list, file_suffix)

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

Parameters: base_file_tuple_list (list) – a list of (dict, path) tuples where the dictionaries have a ‘file_key’: ‘basefilename’ pair, or ‘file_key’: list of ‘basefilename’s. ‘path’ indicates the file directory path to prepend to the basefile name. file_suffix (string) – a string to append to every filename, can be empty string 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, to_lower=True, numerical_cast=True, warn_if_missing=True)

Read a CSV table into a dictionary indexed by key_field.

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

Parameters: table_path (string) – path to a CSV file containing at least the header key_field
:param key_field:: a column in the CSV file at table_path that
can uniquely identify each row in the table. If numerical_cast is true the values will be cast to floats/ints/unicode if possible.

:type key_field:: string :param to_lower: if True, converts all unicode in the CSV,

including headers and values to lowercase, otherwise uses raw string values.
Parameters: numerical_cast (bool) – If true, all values in the CSV table will attempt to be cast to a floating point type; if it fails will be left as unicode. If false, all values will be considered raw unicode. warn_if_missing (bool) – If True, warnings are logged if there are empty headers or value rows. lookup_dict – 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 unicde. if numerical_cast all values that can be represented as floats are, otherwise unicode. dict
natcap.invest.utils.capture_gdal_logging(*args, **kwds)

Context manager for logging GDAL errors with python logging.

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

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

Create a raster-based exponential decay kernel.

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

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

Log all messages within this context to a file.

Parameters: logfile (string) – The path to where the logfile will be written. If there is already a file at this location, it will be overwritten. threadname=None (string) – If None, logging from all threads will be included in the log. If a string, only logging from the thread with the same name will be included in the logfile. 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=DATE_FMT (string) – The logging date format string to use. If not provided, utils.DATE_FMT will be used. handler – An instance of logging.FileHandler that represents the file that is being written to. None
natcap.invest.utils.make_directories(directory_list)

Create directories in directory_list if they do not already exist.

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

Make an InVEST appropriate suffix string.

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

Parameters: args (dict) – the classic InVEST model parameter dictionary that is passed to execute. suffix_key (string) – the key used to index the base suffix. If suffix_key is not in args, or args[‘suffix_key’] is “” return “”, If args[‘suffix_key’] starts with ‘_’ return args[‘suffix_key’] else return ‘_’+args[‘suffix_key’]
natcap.invest.utils.prepare_workspace(*args, **kwds)
natcap.invest.utils.sandbox_tempdir(*args, **kwds)

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

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

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

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

## natcap.invest.validation module¶

Common validation utilities for InVEST models.

natcap.invest.validation.CHECK_ALL_KEYS = None

A flag to pass to the validation context manager indicating that all keys should be checked.

class natcap.invest.validation.ValidationContext(args, limit_to)

Bases: object

An object to represent a validation context.

A validation context reduces the amount of boilerplate code needed within an InVEST validation function to produce validation warnings that are consistent with the InVEST Validation API.

is_arg_complete(key, require=False)

Test if a given argument is complete and should be validated.

An argument is complete if:

• The value associated with key is neither '' or None
• The key-value pair is in self.args
• The key should be validated (the key matches the value of self.limit_to or self.limit_to == None)

If the argument is incomplete and require == True, a warning is recorded in the ValidationContext’s warnings list.

Parameters: key (string) – The key to test. require=False (bool) – Whether the parameter is required. A bool, indicating whether the argument is complete.
warn(message, keys)

Record a warning in the internal warnings list.

Parameters: message (string) – The message of the warning to log. keys (iterable) – An iterable of string keys that the message refers to.
natcap.invest.validation.invest_validator(validate_func)

Decorator to enforce characteristics of validation inputs and outputs.

Attributes of inputs and outputs that are enforced are:

• args parameter to validate must be a dict

• limit_to parameter to validate must be either None or a string (str or unicode) that exists in the args dict.

• All keys in args must be strings

• Decorated validate func must return a list of 2-tuples, where each 2-tuple conforms to these rules:

• The first element of the 2-tuple is an iterable of strings. It is an error for the first element to be a string.
• The second element of the 2-tuple is a string error message.
Raises: AssertionError when an invalid format is found. –

Example

from natcap.invest import validation @validation.invest_validator def validate(args, limit_to=None):

natcap.invest.local_dir(source_file)