natcap.invest package



natcap.invest.fileio module

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

Bases: natcap.invest.fileio.TableDriverTemplate

The CSVDriver class is a subclass of TableDriverTemplate.

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)

Bases: natcap.invest.fileio.TableDriverTemplate

The DBFDriver class is a subclass of TableDriverTemplate.


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.


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.


Return a list of strings containing the fieldnames.


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


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


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.


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.


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.

System Message: WARNING/2 (/home/docs/checkouts/ of natcap.invest.fileio.TableHandler.set_field_mask, line 8)

Definition list ends without a blank line; unexpected unindent.

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

System Message: ERROR/3 (/home/docs/checkouts/ of natcap.invest.fileio.TableHandler.set_field_mask, line 10)

Unexpected indentation.
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)


Forest Carbon Edge Effect.

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

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



    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) – one of “all” or “above_ground”. 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. If “above_ground”, this is only done with ‘c_above’.
  • 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.


natcap.invest.globio module




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.

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


natcap.invest.globio.load_msa_parameter_table(msa_parameter_table_filename, intensification_fraction)

Loads a specifically formatted parameter table into a dictionary that can be used to dynamically define the MSA ranges.

  • 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) +

    System Message: ERROR/3 (/home/docs/checkouts/ of natcap.invest.globio.load_msa_parameter_table, line 35)

    Unexpected indentation.
    msa_lu_9 * intensification_fraction}

    System Message: WARNING/2 (/home/docs/checkouts/ of natcap.invest.globio.load_msa_parameter_table, line 36)

    Definition list ends without a blank line; unexpected unindent.


natcap.invest.globio.make_gaussian_kernel_uri(sigma, kernel_uri)

create a gaussian kernel raster

natcap.invest.habitat_suitability module

Habitat suitability model.


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.

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


                'raster_path': r'C:/path/to/depth.tif',
                'range': (-50, -30, -10, -10),
                'temperature_path': (
                'range': (5, 7, 12.5, 16),


natcap.invest.postprocessing module

This is a collection of postprocessing functions that are useful for some of the InVEST models.

natcap.invest.postprocessing.plot_flow_direction(flow_dataset_uri, output_uri)

Generates a quiver plot (arrows on a grid) of a flow matrix

flow_dataset_uri - a uri to a GDAL compatable raster whose values are
radians indicating the direction of outward flow.

System Message: WARNING/2 (/home/docs/checkouts/ of natcap.invest.postprocessing.plot_flow_direction, line 5)

Definition list ends without a blank line; unexpected unindent.

output_uri - the location to disk to save the resulting plot png file

returns nothing

natcap.invest.scenario_gen_proximity module

Scenario Generation: Proximity Based


Scenario Generator: Proximity-Based.

Main entry point for proximity based scenario generator model.

  • 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_uri'] (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_uri’].
  • args['n_fragmentation_steps'] (string) – an int as a string indicating the number of steps to take for the fragmentation conversion
  • args['aoi_uri'] (string) – (optional) path to a shapefile that indicates an 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}.


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.

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.

  • 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


natcap.invest.utils module

InVEST specific code utils.

natcap.invest.utils.build_file_registry(base_file_path_list, file_suffix)

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

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

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


ValueError if there are duplicate file keys or duplicate file paths.

natcap.invest.utils.exponential_decay_kernel_raster(expected_distance, kernel_filepath)

Create a raster-based exponential decay kernel.

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

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


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

Make an InVEST appropriate suffix string.

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

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

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

return “”,

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

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

Module contents

init module for natcap.invest.


Return the path to where source_file would be on disk.

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