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.

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.

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.datastack module¶

Functions for reading and writing InVEST model parameters.

A datastack for InVEST is a compressed archive that includes the arguments for a model, all of the data files referenced by the arguments, and a logfile with some extra information about how the archive was created. The resulting archive can then be extracted on a different computer and should have all of the information it needs to run an InVEST model in its entirity.

A parameter set for InVEST is a JSON-formatted text file that contains all of the parameters needed to run the current model, where the parameters are located on the local hard disk. Paths to files may be either relative or absolute. If paths are relative, they are interpreted as relative to the location of the parameter set file.

A logfile for InVEST is a text file that is written to disk for each model run.

class natcap.invest.datastack.ParameterSet(args, model_name, invest_version)

Bases: tuple

args

Alias for field number 0

invest_version

Alias for field number 2

model_name

Alias for field number 1

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

Build an InVEST datastack from an arguments dict.

Parameters: args (dict) – The arguments dictionary to include in the datastack. model_name (string) – The python-importable module string of the model these args are for. datastack_path (string) – The path to where the datastack archive should be written. None
natcap.invest.datastack.build_parameter_set(args, model_name, paramset_path, relative=False)

Record a parameter set to a file on disk.

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

Extract a datastack to a given folder.

Parameters: datastack_path (string) – The path to a datastack archive on disk. dest_dir_path (string) – The path to a directory. The contents of the demonstration datastack archive will be extracted into this directory. If the directory does not exist, it will be created. A dictionary of arguments from the extracted archive. Paths to files are absolute paths. args (dict)
natcap.invest.datastack.extract_parameter_set(paramset_path)

Extract and return attributes from a parameter set.

Any string values found will have environment variables expanded. See :py:ref:os.path.expandvars and :py:ref:os.path.expanduser for details.

Parameters: paramset_path (string) – The file containing a parameter set. A ParameterSet namedtuple with these attributes:args (dict): The arguments dict for the callable invest_version (string): The version of InVEST used to record the parameter set. model_name (string): The name of the callable or model that these arguments are intended for. 
natcap.invest.datastack.extract_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 starting with "Arguments", and ending with a blank line. If no such section exists within the logfile, ValueError will be raised.

If possible, the model name and InVEST version will be parsed from the same line as "Arguments", but IUI-formatted logfiles (without model name and InVEST version information) are also supported.

Parameters: logfile_path (string) – The path to an InVEST logfile on disk. An instance of the ParameterSet namedtuple. If a model name and InVEST version cannot be parsed from the Arguments section of the logfile, ParameterSet.model_name and ParameterSet.invest_version will be set to datastack.UNKNOWN. ValueError - when no arguments could be parsed from the logfile.
natcap.invest.datastack.format_args_dict(args_dict, model_name)

Nicely format an arguments dictionary for writing to a stream.

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

Parameters: args_dict (dict) – The args dictionary to format. model_name (string) – The model name (in python package import format) A formatted, unicode string.
natcap.invest.datastack.get_datastack_info(filepath)

Parameters: filepath (string) – The path to a file on disk that can be extracted as a datastack, parameter set, or logfile. "archive" when the file is a datastack archive. "json" when the file is a json parameter set. "logfile" when the file is a text logfile. The second item of the tuple is a ParameterSet namedtuple with the raw parsed args, modelname and invest version that the file was built with. A 2-tuple. The first item of the tuple is one of

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.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.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 key_field – (string): 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. to_lower (string) – if True, converts all unicode in the CSV, including headers and values to lowercase, otherwise uses raw string values. 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. 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. lookup_dict (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)