# InVEST Model Entry Points¶

All InVEST models share a consistent python API:

1. The model has a function called execute that takes a single python dict ("args") as its argument.
2. This arguments dict contains an entry, 'workspace_dir', which points to the folder on disk where all files created by the model should be saved.

Calling a model requires importing the model’s execute function and then calling the model with the correct parameters. For example, if you were to call the Carbon Storage and Sequestration model, your script might include

import natcap.invest.carbon.carbon_combined
args = {
'workspace_dir': 'path/to/workspace'
# Other arguments, as needed for Carbon.
}

natcap.invest.carbon.carbon_combined.execute(args)


For examples of scripts that could be created around a model run, or multiple successive model runs, see Creating Sample Python Scripts.

## Annual Water Yield: Reservoir Hydropower Production¶

natcap.invest.hydropower.hydropower_water_yield.execute(args)

Annual Water Yield: Reservoir Hydropower Production.

Executes the hydropower/water_yield model

Parameters: args['workspace_dir'] (string) – a uri to the directory that will write output and other temporary files during calculation. (required) args['lulc_uri'] (string) – a uri to a land use/land cover raster whose LULC indexes correspond to indexes in the biophysical table input. Used for determining soil retention and other biophysical properties of the landscape. (required) args['depth_to_root_rest_layer_uri'] (string) – a uri to an input raster describing the depth of “good” soil before reaching this restrictive layer (required) args['precipitation_uri'] (string) – a uri to an input raster describing the average annual precipitation value for each cell (mm) (required) args['pawc_uri'] (string) – a uri to an input raster describing the plant available water content value for each cell. Plant Available Water Content fraction (PAWC) is the fraction of water that can be stored in the soil profile that is available for plants’ use. PAWC is a fraction from 0 to 1 (required) args['eto_uri'] (string) – a uri to an input raster describing the annual average evapotranspiration value for each cell. Potential evapotranspiration is the potential loss of water from soil by both evaporation from the soil and transpiration by healthy Alfalfa (or grass) if sufficient water is available (mm) (required) args['watersheds_uri'] (string) – a uri to an input shapefile of the watersheds of interest as polygons. (required) args['sub_watersheds_uri'] (string) – a uri to an input shapefile of the subwatersheds of interest that are contained in the args['watersheds_uri'] shape provided as input. (optional) args['biophysical_table_uri'] (string) – a uri to an input CSV table of land use/land cover classes, containing data on biophysical coefficients such as root_depth (mm) and Kc, which are required. A column with header LULC_veg is also required which should have values of 1 or 0, 1 indicating a land cover type of vegetation, a 0 indicating non vegetation or wetland, water. NOTE: these data are attributes of each LULC class rather than attributes of individual cells in the raster map (required) args['seasonality_constant'] (float) – floating point value between 1 and 10 corresponding to the seasonal distribution of precipitation (required) args['results_suffix'] (string) – a string that will be concatenated onto the end of file names (optional) args['demand_table_uri'] (string) – a uri to an input CSV table of LULC classes, showing consumptive water use for each landuse / land-cover type (cubic meters per year) (required for water scarcity) args['valuation_table_uri'] (string) – a uri to an input CSV table of hydropower stations with the following fields (required for valuation): (‘ws_id’, ‘time_span’, ‘discount’, ‘efficiency’, ‘fraction’, ‘cost’, ‘height’, ‘kw_price’) None

## Coastal Blue Carbon¶

natcap.invest.coastal_blue_carbon.coastal_blue_carbon.execute(args)

Coastal Blue Carbon.

Parameters: workspace_dir (str) – location into which all intermediate and output files should be placed. results_suffix (str) – a string to append to output filenames. lulc_lookup_uri (str) – filepath to a CSV table used to convert the lulc code to a name. Also used to determine if a given lulc type is a coastal blue carbon habitat. lulc_transition_matrix_uri (str) – generated by the preprocessor. This file must be edited before it can be used by the main model. The left-most column represents the source lulc class, and the top row represents the destination lulc class. carbon_pool_initial_uri (str) – the provided CSV table contains information related to the initial conditions of the carbon stock within each of the three pools of a habitat. Biomass includes carbon stored above and below ground. All non-coastal blue carbon habitat lulc classes are assumed to contain no carbon. The values for ‘biomass’, ‘soil’, and ‘litter’ should be given in terms of Megatonnes CO2 e/ ha. carbon_pool_transient_uri (str) – the provided CSV table contains information related to the transition of carbon into and out of coastal blue carbon pools. All non-coastal blue carbon habitat lulc classes are assumed to neither sequester nor emit carbon as a result of change. The ‘yearly_accumulation’ values should be given in terms of Megatonnes of CO2 e/ha-yr. The ‘half-life’ values must be given in terms of years. The ‘disturbance’ values must be given as a decimal (e.g. 0.5 for 50%) of stock distrubed given a transition occurs away from a lulc-class. lulc_baseline_map_uri (str) – a GDAL-supported raster representing the baseline landscape/seascape. lulc_baseline_year (int) – The year of the baseline snapshot. lulc_transition_maps_list (list) – a list of GDAL-supported rasters representing the landscape/seascape at particular points in time. Provided in chronological order. lulc_transition_years_list (list) – a list of years that respectively correspond to transition years of the rasters. Provided in chronological order. analysis_year (int) – optional. Indicates how many timesteps to run the transient analysis beyond the last transition year. Must come chronologically after the last transition year if provided. Otherwise, the final timestep of the model will be set to the last transition year. do_economic_analysis (bool) – boolean value indicating whether model should run economic analysis. do_price_table (bool) – boolean value indicating whether a price table is included in the arguments and to be used or a price and interest rate is provided and to be used instead. price (float) – the price per Megatonne CO2 e at the base year. inflation_rate (float) – the interest rate on the price per Megatonne CO2e, compounded yearly. Provided as a percentage (e.g. 3.0 for 3%). price_table_uri (bool) – if args[‘do_price_table’] is set to True the provided CSV table is used in place of the initial price and interest rate inputs. The table contains the price per Megatonne CO2e sequestered for a given year, for all years from the original snapshot to the analysis year, if provided. discount_rate (float) – the discount rate on future valuations of sequestered carbon, compounded yearly. Provided as a percentage (e.g. 3.0 for 3%).

Example Args:

args = {
'workspace_dir': 'path/to/workspace/',
'results_suffix': '',
'lulc_lookup_uri': 'path/to/lulc_lookup_uri',
'lulc_transition_matrix_uri': 'path/to/lulc_transition_uri',
'carbon_pool_initial_uri': 'path/to/carbon_pool_initial_uri',
'carbon_pool_transient_uri': 'path/to/carbon_pool_transient_uri',
'lulc_baseline_map_uri': 'path/to/baseline_map.tif',
'lulc_baseline_year': <int>,
'lulc_transition_maps_list': [raster1_uri, raster2_uri, ...],
'lulc_transition_years_list': [2000, 2005, ...],
'analysis_year': 2100,
'do_economic_analysis': '<boolean>',
'do_price_table': '<boolean>',
'price': '<float>',
'inflation_rate': '<float>',
'price_table_uri': 'path/to/price_table',
'discount_rate': '<float>'
}


## Coastal Blue Carbon Preprocessor¶

natcap.invest.coastal_blue_carbon.preprocessor.execute(args)

Coastal Blue Carbon Preprocessor.

The preprocessor accepts a list of rasters and checks for cell-transitions across the rasters. The preprocessor outputs a CSV file representing a matrix of land cover transitions, each cell prefilled with a string indicating whether carbon accumulates or is disturbed as a result of the transition, if a transition occurs.

Parameters: workspace_dir (string) – directory path to workspace results_suffix (string) – append to outputs directory name if provided lulc_lookup_uri (string) – filepath of lulc lookup table lulc_snapshot_list (list) – a list of filepaths to lulc rasters

Example Args:

args = {
'workspace_dir': 'path/to/workspace_dir/',
'results_suffix': '',
'lulc_lookup_uri': 'path/to/lookup.csv',
'lulc_snapshot_list': ['path/to/raster1', 'path/to/raster2', ...]
}


## Coastal Vulnerability¶

natcap.invest.coastal_vulnerability.coastal_vulnerability.execute(args)

Coastal Vulnerability.

Parameters: workspace_dir (string) – The path to the workspace directory on disk (required) aoi_uri (string) – Path to an OGR vector on disk representing the area of interest. (required) landmass_uri (string) – Path to an OGR vector on disk representing the global landmass. (required) bathymetry_uri (string) – Path to a GDAL raster on disk representing the bathymetry. Must overlap with the Area of Interest if if provided. (optional) bathymetry_constant (int) – An int between 1 and 5 (inclusive). (optional) relief_uri (string) – Path to a GDAL raster on disk representing the elevation within the land polygon provided. (optional) relief_constant (int) – An int between 1 and 5 (inclusive). (optional) elevation_averaging_radius (int) – a positive int. The radius around which to compute the average elevation for relief. Must be in meters. (required) mean_sea_level_datum (int) – a positive int. This input is the elevation of Mean Sea Level (MSL) datum relative to the datum of the bathymetry layer that they provide. The model transforms all depths to MSL datum by subtracting the value provided by the user to the bathymetry. This input can be used to run the model for a future sea-level rise scenario. Must be in meters. (required) cell_size (int) – Cell size in meters. The higher the value, the faster the computation, but the coarser the output rasters produced by the model. (required) depth_threshold (int) – Depth in meters (integer) cutoff to determine if fetch rays project over deep areas. (optional) exposure_proportion (float) – Minimum proportion of rays that project over exposed and/or deep areas need to classify a shore segment as exposed. (required) geomorphology_uri (string) – A OGR-supported polygon vector file that has a field called “RANK” with values between 1 and 5 in the attribute table. (optional) geomorphology_constant (int) – Integer value between 1 and 5. If layer associated to this field is omitted, replace all shore points for this layer with a constant rank value in the computation of the coastal vulnerability index. If both the file and value for the layer are omitted, the layer is skipped altogether. habitats_directory_uri (string) – Directory containing OGR-supported polygon vectors associated with natural habitats. The name of these shapefiles should be suffixed with the ID that is specified in the natural habitats CSV file provided along with the habitats (optional) habitats_csv_uri (string) – A CSV file listing the attributes for each habitat. For more information, see ‘Habitat Data Layer’ section in the model’s documentation. (required if args['habitat_directory_uri'] is provided) habitat_constant (int) – Integer value between 1 and 5. If layer associated to this field is omitted, replace all shore points for this layer with a constant rank value in the computation of the coastal vulnerability index. If both the file and value for the layer are omitted, the layer is skipped altogether. (optional) area_computed (string) – Determine if the output data is about all the coast about sheltered segments only. Either 'sheltered' or 'both' (required) suffix (string) – A string that will be added to the end of the output file. (optional) climatic_forcing_uri (string) – An OGR-supported vector containing both wind wave information across the region of interest. (optional) climatic_forcing_constant (int) – Integer value between 1 and 5. If layer to this field is omitted, replace all shore points for this layer with a constant rank value in the computation of the coastal vulnerability index. If both the file and value for the layer are omitted, the layer is skipped altogether. (optional) continental_shelf_uri (string) – An OGR-supported polygon vector delineating edges of the continental shelf. Default is global continental shelf shapefile. If omitted, the user can specify depth contour. See entry below. (optional) depth_contour (int) – Used to delineate shallow and deep areas. Continental limit is at about 150 meters. (optional) sea_level_rise_uri (string) – An OGR-supported point or polygon vector file features with “Trend” fields in the attributes table. (optional) sea_level_rise_constant (int) – Integer value between 1 and 5. If layer to this field is omitted, replace all shore points for this layer with a constant rank value in the computation of the coastal vulnerability index. If both the file and value for the layer are omitted, the layer is skipped altogether. (optional) structures_uri (string) – An OGR-supported vector file containing rigid structures to identify the portions of the coast that is armored. (optional) structures_constant (int) – Integer value between 1 and 5. If layer associated this field is omitted, replace all shore points for this layer with a constant rank value in the computation of the coastal vulnerability index. If both the file and value for the layer are omitted, the layer is skipped altogether. (optional) population_uri (string) – A GDAL-supported raster file representing the population. (required) urban_center_threshold (int) – Minimum population required to consider shore segment a population center. (required) additional_layer_uri (string) – An OGR-supported vector file representing level rise, and will be used in the computation of coastal vulnerability and coastal vulnerability without habitat. (optional) additional_layer_constant (int) – Integer value between 1 and 5. If layer to this field is omitted, replace all shore points for this layer with a constant rank value in the computation of the coastal vulnerability index. If both the file and value for the layer are omitted, the layer is skipped altogether. (optional) rays_per_sector (int) – Number of rays used to subsample the fetch distance each of the 16 sectors. (required) max_fetch (int) – Maximum fetch distance computed by the model (>=60,000m). (optional) spread_radius (int) – Integer multiple of ‘cell size’. The coast from geomorphology layer could be of a better resolution than the global landmass, so the shores do not necessarily overlap. To make them coincide, the shore from the geomorphology layer is widened by 1 or more pixels. The value should be a multiple of ‘cell size’ that indicates how many pixels the coast from the geomorphology layer is widened. The widening happens on each side of the coast (n pixels landward, and n pixels seaward). (required) population_radius (int) – Radius length in meters used to count the number people leaving close to the coast. (optional)

Note

If neither args['bathymetry_uri'] nor args['bathymetry_constant'] is provided, bathymetry is ignored altogether.

If neither args['relief_uri'] nor args['relief_constant'] is provided, relief is ignored altogether.

If neither args['geomorphology_uri'] nor args['geomorphology_constant'] is provided, geomorphology is ignored altogether.

If neither args['climatic_forcing_uri'] nor args['climatic_forcing_constant'] is provided, climatic_forcing is ignored altogether.

If neither args['sea_level_rise_uri'] nor args['sea_level_rise_constant'] is provided, sea level rise is ignored altogether.

If neither args['structures_uri'] nor args['structures_constant'] is provided, structures is ignored altogether.

If neither args['additional_layer_uri'] nor args['additional_layer_constant'] is provided, the additional layer option is ignored altogether.

Example args:

args = {
u'aoi_uri': u'CoastalProtection/Input/AOI_BarkClay.shp',
u'area_computed': u'both',
u'cell_size': 1000,
u'climatic_forcing_uri': u'CoastalProtection/Input/WaveWatchIII.shp',
u'continental_shelf_uri': u'CoastalProtection/Input/continentalShelf.shp',
u'depth_contour': 150,
u'depth_threshold': 0,
u'exposure_proportion': 0.8,
u'geomorphology_uri': u'CoastalProtection/Input/Geomorphology_BarkClay.shp',
u'habitats_csv_uri': u'CoastalProtection/Input/NaturalHabitat_WCVI.csv',
u'habitats_directory_uri': u'CoastalProtection/Input/NaturalHabitat',
u'landmass_uri': u'Base_Data/Marine/Land/global_polygon.shp',
u'max_fetch': 12000,
u'mean_sea_level_datum': 0,
u'rays_per_sector': 1,
u'sea_level_rise_uri': u'CoastalProtection/Input/SeaLevRise_WCVI.shp',
u'structures_uri': u'CoastalProtection/Input/Structures_BarkClay.shp',
u'urban_center_threshold': 5000,
u'workspace_dir': u'coastal_vulnerability_workspace'
}

Returns: None

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

## Crop Production Regression 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.

## Delineateit: Watershed Delineation¶

natcap.invest.routing.delineateit.execute(args)

Delineateit: Watershed Delineation.

This ‘model’ provides an InVEST-based wrapper around the natcap.invest.pygeoprocessing_0_3_3 routing API for watershed delineation.

Upon successful completion, the following files are written to the output workspace:

• snapped_outlets.shp - an ESRI shapefile with the points snapped to a nearby stream.
• watersheds.shp - an ESRI shapefile of watersheds determined by the d-infinity routing algorithm.
• stream.tif - a GeoTiff representing detected streams based on the provided flow_threshold parameter. Values of 1 are streams, values of 0 are not.
Parameters: workspace_dir (string) – The selected folder is used as the workspace all intermediate and output files will be written.If the selected folder does not exist, it will be created. If datasets already exist in the selected folder, they will be overwritten. (required) suffix (string) – This text will be appended to the end of output files to help separate multiple runs. (optional) dem_uri (string) – A GDAL-supported raster file with an elevation for each cell. Make sure the DEM is corrected by filling in sinks, and if necessary burning hydrographic features into the elevation model (recommended when unusual streams are observed.) See the ‘Working with the DEM’ section of the InVEST User’s Guide for more information. (required) outlet_shapefile_uri (string) – This is a vector of points representing points that the watersheds should be built around. (required) flow_threshold (int) – The number of upstream cells that must into a cell before it’s considered part of a stream such that retention stops and the remaining export is exported to the stream. Used to define streams from the DEM. (required) snap_distance (int) – Pixel Distance to Snap Outlet Points (required) None

## Finfish Aquaculture¶

natcap.invest.finfish_aquaculture.finfish_aquaculture.execute(args)

Finfish Aquaculture.

This function will take care of preparing files passed into the finfish aquaculture model. It will handle all files/inputs associated with biophysical and valuation calculations and manipulations. It will create objects to be passed to the aquaculture_core.py module. It may write log, warning, or error messages to stdout.

Parameters: workspace_dir (string) – The directory in which to place all result files. ff_farm_loc (string) – URI that points to a shape file of fishery locations farm_ID (string) – column heading used to describe individual farms. Used to link GIS location data to later inputs. g_param_a (float) – Growth parameter alpha, used in modeling fish growth, should be an int or float. g_param_b (float) – Growth parameter beta, used in modeling fish growth, should be an int or float. g_param_tau (float) – Growth parameter tau, used in modeling fish growth, should be an int or float use_uncertainty (boolean) – g_param_a_sd (float) – (description) g_param_b_sd (float) – (description) num_monte_carlo_runs (int) – water_temp_tbl (string) – URI to a CSV table where daily water temperature values are stored from one year farm_op_tbl (string) – URI to CSV table of static variables for calculations outplant_buffer (int) – This value will allow the outplanting start day to be flexible plus or minus the number of days specified here. do_valuation (boolean) – Boolean that indicates whether or not valuation should be performed on the aquaculture model p_per_kg (float) – Market price per kilogram of processed fish frac_p (float) – Fraction of market price that accounts for costs rather than profit discount (float) – Daily market discount rate

Example Args Dictionary:

{
'workspace_dir': 'path/to/workspace_dir',
'ff_farm_loc': 'path/to/shapefile',
'farm_ID': 'FarmID'
'g_param_a': 0.038,
'g_param_b': 0.6667,
'g_param_tau': 0.08,
'use_uncertainty': True,
'g_param_a_sd': 0.005,
'g_param_b_sd': 0.05,
'num_monte_carlo_runs': 1000,
'water_temp_tbl': 'path/to/water_temp_tbl',
'farm_op_tbl': 'path/to/farm_op_tbl',
'outplant_buffer': 3,
'do_valuation': True,
'p_per_kg': 2.25,
'frac_p': 0.3,
'discount': 0.000192,
}


## Fisheries¶

natcap.invest.fisheries.fisheries.execute(args, create_outputs=True)

Fisheries.

Parameters: args['workspace_dir'] (str) – location into which all intermediate and output files should be placed. args['results_suffix'] (str) – a string to append to output filenames args['aoi_uri'] (str) – location of shapefile which will be used as subregions for calculation. Each region must conatin a ‘Name’ attribute (case-sensitive) matching the given name in the population parameters csv file. args['timesteps'] (int) – represents the number of time steps that the user desires the model to run. args['population_type'] (str) – specifies whether the model is age-specific or stage-specific. Options will be either “Age Specific” or “Stage Specific” and will change which equation is used in modeling growth. args['sexsp'] (str) – specifies whether or not the age and stage classes are distinguished by sex. args['harvest_units'] (str) – specifies how the user wants to get the harvest data. Options are either “Individuals” or “Weight”, and will change the harvest equation used in core. (Required if args[‘val_cont’] is True) args['do_batch'] (bool) – specifies whether program will perform a single model run or a batch (set) of model runs. args['population_csv_uri'] (str) – location of the population parameters csv. This will contain all age and stage specific parameters. (Required if args[‘do_batch’] is False) args['population_csv_dir'] (str) – location of the directory that contains the Population Parameters CSV files for batch processing (Required if args[‘do_batch’] is True) args['spawn_units'] (str) – (description) args['total_init_recruits'] (float) – represents the initial number of recruits that will be used in calculation of population on a per area basis. args['recruitment_type'] (str) – Name corresponding to one of the built-in recruitment functions {‘Beverton-Holt’, ‘Ricker’, ‘Fecundity’, Fixed}, or ‘Other’, meaning that the user is passing in their own recruitment function as an anonymous python function via the optional dictionary argument ‘recruitment_func’. args['recruitment_func'] (function) – Required if args[‘recruitment_type’] is set to ‘Other’. See below for instructions on how to create a user-defined recruitment function. args['alpha'] (float) – must exist within args for BH or Ricker Recruitment. Parameter that will be used in calculation of recruitment. args['beta'] (float) – must exist within args for BH or Ricker Recruitment. Parameter that will be used in calculation of recruitment. args['total_recur_recruits'] (float) – must exist within args for Fixed Recruitment. Parameter that will be used in calculation of recruitment. args['migr_cont'] (bool) – if True, model uses migration args['migration_dir'] (str) – if this parameter exists, it means migration is desired. This is the location of the parameters folder containing files for migration. There should be one file for every age class which migrates. (Required if args[‘migr_cont’] is True) args['val_cont'] (bool) – if True, model computes valuation args['frac_post_process'] (float) – represents the fraction of the species remaining after processing of the whole carcass is complete. This will exist only if valuation is desired for the particular species. (Required if args[‘val_cont’] is True) args['unit_price'] (float) – represents the price for a single unit of harvest. Exists only if valuation is desired. (Required if args[‘val_cont’] is True)

Example Args:

args = {
'workspace_dir': 'path/to/workspace_dir/',
'results_suffix': 'scenario_name',
'aoi_uri': 'path/to/aoi_uri',
'total_timesteps': 100,
'population_type': 'Stage-Based',
'sexsp': 'Yes',
'harvest_units': 'Individuals',
'do_batch': False,
'population_csv_uri': 'path/to/csv_uri',
'population_csv_dir': '',
'spawn_units': 'Weight',
'total_init_recruits': 100000.0,
'recruitment_type': 'Ricker',
'alpha': 32.4,
'beta': 54.2,
'total_recur_recruits': 92.1,
'migr_cont': True,
'migration_dir': 'path/to/mig_dir/',
'val_cont': True,
'frac_post_process': 0.5,
'unit_price': 5.0,
}


Creating a User-Defined Recruitment Function

An optional argument has been created in the Fisheries Model to allow users proficient in Python to pass their own recruitment function into the program via the args dictionary.

Using the Beverton-Holt recruitment function as an example, here’s how a user might create and pass in their own recruitment function:

import natcap.invest
import numpy as np

# define input data
Matu = np.array([...])  # the Maturity vector in the Population Parameters File
Weight = np.array([...])  # the Weight vector in the Population Parameters File
LarvDisp = np.array([...])  # the LarvalDispersal vector in the Population Parameters File
alpha = 2.0  # scalar value
beta = 10.0  # scalar value
sexsp = 2   # 1 = not sex-specific, 2 = sex-specific

# create recruitment function
def spawners(N_prev):
return (N_prev * Matu * Weight).sum()

def rec_func_BH(N_prev):
N_0 = (LarvDisp * ((alpha * spawners(
N_prev) / (beta + spawners(N_prev)))) / sexsp)
return (N_0, spawners(N_prev))

# fill out args dictionary
args = {}
# ... define other arguments ...
args['recruitment_type'] = 'Other'  # lets program know to use user-defined function
args['recruitment_func'] = rec_func_BH  # pass recruitment function as 'anonymous' Python function

# run model
natcap.invest.fisheries.fisheries.execute(args)


Conditions that a new recruitment function must meet to run properly:

• The function must accept as an argument: a single numpy three-dimensional array (N_prev) representing the state of the population at the previous time step. N_prev has three dimensions: the indices of the first dimension correspond to the region (must be in same order as provided in the Population Parameters File), the indices of the second dimension represent the sex if it is specific (i.e. two indices representing female, then male if the model is ‘sex-specific’, else just a single zero index representing the female and male populations aggregated together), and the indicies of the third dimension represent age/stage in ascending order.
• The function must return: a tuple of two values. The first value (N_0) being a single numpy one-dimensional array representing the youngest age of the population for the next time step. The indices of the array correspond to the regions of the population (outputted in same order as provided). If the model is sex-specific, it is currently assumed that males and females are produced in equal number and that the returned array has been already been divided by 2 in the recruitment function. The second value (spawners) is the number or weight of the spawners created by the population from the previous time step, provided as a scalar float value (non-negative).

Example of How Recruitment Function Operates within Fisheries Model:

# input data
N_prev_xsa = [[[region0-female-age0, region0-female-age1],
[region0-male-age0, region1-male-age1]],
[[region1-female-age0, region1-female-age1],
[region1-male-age0], [region1-male-age1]]]

# execute function
N_0_x, spawners = rec_func(N_prev_xsa)

# output data - where N_0 contains information about the youngest
#     age/stage of the population for the next time step:
N_0_x = [region0-age0, region1-age0] # if sex-specific, rec_func should divide by two before returning
type(spawners) is float


## Fisheries: Habitat Scenario Tool¶

natcap.invest.fisheries.fisheries_hst.execute(args)

Fisheries: Habitat Scenario Tool.

The Fisheries Habitat Scenario Tool generates a new Population Parameters CSV File with modified survival attributes across classes and regions based on habitat area changes and class-level dependencies on those habitats.

Parameters: args['workspace_dir'] (str) – location into which the resultant modified Population Parameters CSV file should be placed. args['sexsp'] (str) – specifies whether or not the age and stage classes are distinguished by sex. Options: ‘Yes’ or ‘No’ args['population_csv_uri'] (str) – location of the population parameters csv file. This file contains all age and stage specific parameters. args['habitat_chg_csv_uri'] (str) – location of the habitat change parameters csv file. This file contains habitat area change information. args['habitat_dep_csv_uri'] (str) – location of the habitat dependency parameters csv file. This file contains habitat-class dependency information. args['gamma'] (float) – describes the relationship between a change in habitat area and a change in survival of life stages dependent on that habitat None

Example Args:

args = {
'workspace_dir': 'path/to/workspace_dir/',
'sexsp': 'Yes',
'population_csv_uri': 'path/to/csv',
'habitat_chg_csv_uri': 'path/to/csv',
'habitat_dep_csv_uri': 'path/to/csv',
'gamma': 0.5,
}


Note

• Modified Population Parameters CSV File saved to ‘workspace_dir/output/’

## Forest Carbon Edge Effect¶

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

## GLOBIO¶

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

## Habitat Quality¶

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

## Habitat Risk Assessment¶

natcap.invest.habitat_risk_assessment.hra.execute(args)

Habitat Risk Assessment.

This function will prepare files passed from the UI to be sent on to the hra_core module.

All inputs are required.

Parameters: workspace_dir (string) – The location of the directory into which intermediate and output files should be placed. csv_uri (string) – The location of the directory containing the CSV files of habitat, stressor, and overlap ratings. Will also contain a .txt JSON file that has directory locations (potentially) for habitats, species, stressors, and criteria. grid_size (int) – Represents the desired pixel dimensions of both intermediate and ouput rasters. risk_eq (string) – A string identifying the equation that should be used in calculating risk scores for each H-S overlap cell. This will be either ‘Euclidean’ or ‘Multiplicative’. decay_eq (string) – A string identifying the equation that should be used in calculating the decay of stressor buffer influence. This can be ‘None’, ‘Linear’, or ‘Exponential’. max_rating (int) – An int representing the highest potential value that should be represented in rating, data quality, or weight in the CSV table. max_stress (int) – This is the highest score that is used to rate a criteria within this model run. These values would be placed within the Rating column of the habitat, species, and stressor CSVs. aoi_tables (string) – A shapefile containing one or more planning regions for a given model. This will be used to get the average risk value over a larger area. Each potential region MUST contain the attribute “name” as a way of identifying each individual shape.

Example Args Dictionary:

{
'workspace_dir': 'path/to/workspace_dir',
'csv_uri': 'path/to/csv',
'grid_size': 200,
'risk_eq': 'Euclidean',
'decay_eq': 'None',
'max_rating': 3,
'max_stress': 4,
'aoi_tables': 'path/to/shapefile',
}

Returns: None

## Habitat Risk Assessment Preprocessor¶

natcap.invest.habitat_risk_assessment.hra_preprocessor.execute(args)

Habitat Risk Assessment Preprocessor.

Want to read in multiple hab/stressors directories, in addition to named criteria, and make an appropriate csv file.

Parameters: args['workspace_dir'] (string) – The directory to dump the output CSV files to. (required) args['habitats_dir'] (string) – A directory of shapefiles that are habitats. This is not required, and may not exist if there is a species layer directory. (optional) args['species_dir'] (string) – Directory which holds all species shapefiles, but may or may not exist if there is a habitats layer directory. (optional) args['stressors_dir'] (string) – A directory of ArcGIS shapefiles that are stressors. (required) args['exposure_crits'] (list) – list containing string names of exposure criteria (hab-stress) which should be applied to the exposure score. (optional) args['sensitivity-crits'] (list) – List containing string names of sensitivity (habitat-stressor overlap specific) criteria which should be applied to the consequence score. (optional) args['resilience_crits'] (list) – List containing string names of resilience (habitat or species-specific) criteria which should be applied to the consequence score. (optional) args['criteria_dir'] (string) – Directory which holds the criteria shapefiles. May not exist if the user does not desire criteria shapefiles. This needs to be in a VERY specific format, which shall be described in the user’s guide. (optional) None

This function creates a series of CSVs within args['workspace_dir']. There will be one CSV for every habitat/species. These files will contain information relevant to each habitat or species, including all criteria. The criteria will be broken up into those which apply to only the habitat, and those which apply to the overlap of that habitat, and each stressor.

JSON file containing vars that need to be passed on to hra non-core when that gets run. Should live inside the preprocessor folder which will be created in args['workspace_dir']. It will contain habitats_dir, species_dir, stressors_dir, and criteria_dir.

## Habitat Suitability¶

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

## InVEST Carbon Model¶

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.

## Nutrient Delivery Ratio¶

natcap.invest.ndr.ndr.execute(args)

Nutrient Delivery Ratio.

Parameters: args['workspace_dir'] (string) – path to current workspace args['dem_path'] (string) – path to digital elevation map raster args['lulc_path'] (string) – a path to landcover map raster args['runoff_proxy_path'] (string) – a path to a runoff proxy raster args['watersheds_path'] (string) – path to the watershed shapefile args['biophysical_table_path'] (string) – path to csv table on disk containing nutrient retention values. For each nutrient type [t] in args[‘calc_[t]’] that is true, must contain the following headers: ’load_[t]’, ‘eff_[t]’, ‘crit_len_[t]’ If args[‘calc_n’] is True, must also contain the header ‘proportion_subsurface_n’ field. args['calc_p'] (boolean) – if True, phosphorous is modeled, additionally if True then biophysical table must have p fields in them args['calc_n'] (boolean) – if True nitrogen will be modeled, additionally biophysical table must have n fields in them. args['results_suffix'] (string) – (optional) a text field to append to all output files args['threshold_flow_accumulation'] – a number representing the flow accumulation in terms of upstream pixels. args['_prepare'] – (optional) The preprocessed set of data created by the ndr._prepare call. This argument could be used in cases where the call to this function is scripted and can save a significant amount DEM processing runtime. None

## Overlap Analysis¶

natcap.invest.overlap_analysis.overlap_analysis.execute(args)

Overlap Analysis.

This function will take care of preparing files passed into the overlap analysis model. It will handle all files/inputs associated with calculations and manipulations. It may write log, warning, or error messages to stdout.

Parameters: args – A python dictionary created by the UI and passed to this method. It will contain the following data. args['workspace_dir'] (string) – The directory in which to place all resulting files, will come in as a string. (required) args['zone_layer_uri'] (string) – A URI pointing to a shapefile with the analysis zones on it. (required) args['grid_size'] (int) – This is an int specifying how large the gridded squares over the shapefile should be. (required) args['overlap_data_dir_uri'] (string) – URI pointing to a directory where multiple shapefiles are located. Each shapefile represents an activity of interest for the model. (required) args['do-inter'] (bool) – Boolean that indicates whether or not inter-activity weighting is desired. This will decide if the overlap table will be created. (required) args['do_intra'] (bool) – Boolean which indicates whether or not intra-activity weighting is desired. This will will pull attributes from shapefiles passed in in ‘zone_layer_uri’. (required) args['do_hubs'] (bool) – Boolean which indicates if human use hubs are desired. (required) args['overlap_layer_tbl'] (string) – URI to a CSV file that holds relational data and identifier data for all layers being passed in within the overlap analysis directory. (optional) args['intra_name'] (string) – string which corresponds to a field within the layers being passed in within overlap analysis directory. This is the intra-activity importance for each activity. (optional) args['hubs_uri'] (string) – The location of the shapefile containing points for human use hub calculations. (optional) args['decay_amt'] (float) – A double representing the decay rate of value from the human use hubs. (optional) None

## Overlap Analysis: Management Zones¶

natcap.invest.overlap_analysis.overlap_analysis_mz.execute(args)

Overlap Analysis: Management Zones.

Parameters: args – A python dictionary created by the UI and passed to this method. It will contain the following data. args['workspace_dir'] (string) – The directory in which to place all resulting files, will come in as a string. (required) args['zone_layer_loc'] (string) – A URI pointing to a shapefile with the analysis zones on it. (required) args['overlap_data_dir_loc'] (string) – URI pointing to a directory where multiple shapefiles are located. Each shapefile represents an activity of interest for the model. (required) None

## Recreation¶

natcap.invest.recreation.recmodel_client.execute(args)

Recreation.

Execute recreation client model on remote server.

Parameters: args['workspace_dir'] (string) – path to workspace directory args['aoi_path'] (string) – path to AOI vector args['hostname'] (string) – FQDN to recreation server args['port'] (string or int) – port on hostname for recreation server args['start_year'] (string) – start year in form YYYY. This year is the inclusive lower bound to consider points in the PUD and regression. args['end_year'] (string) – end year in form YYYY. This year is the inclusive upper bound to consider points in the PUD and regression. args['grid_aoi'] (boolean) – if true the polygon vector in args[‘aoi_path’] should be gridded into a new vector and the recreation model should be executed on that args['grid_type'] (string) – optional, but must exist if args[‘grid_aoi’] is True. Is one of ‘hexagon’ or ‘square’ and indicates the style of gridding. args['cell_size'] (string/float) – optional, but must exist if args[‘grid_aoi’] is True. Indicates the cell size of square pixels and the width of the horizontal axis for the hexagonal cells. args['compute_regression'] (boolean) – if True, then process the predictor table and scenario table (if present). args['predictor_table_path'] (string) – required if args[‘compute_regression’] is True. Path to a table that describes the regression predictors, their IDs and types. Must contain the fields ‘id’, ‘path’, and ‘type’ where: ’id’: is a <=10 character length ID that is used to uniquely describe the predictor. It will be added to the output result shapefile attribute table which is an ESRI Shapefile, thus limited to 10 characters. ’path’: an absolute or relative (to this table) path to the predictor dataset, either a vector or raster type. ’type’: one of the following, ’raster_mean’: mean of values in the raster under the response polygon ’raster_sum’: sum of values in the raster under the response polygon ’point_count’: count of the points contained in the response polygon ’point_nearest_distance’: distance to the nearest point from the response polygon ’line_intersect_length’: length of lines that intersect with the response polygon in projected units of AOI ’polygon_area’: area of the polygon contained within response polygon in projected units of AOI args['scenario_predictor_table_path'] (string) – (optional) if present runs the scenario mode of the recreation model with the datasets described in the table on this path. Field headers are identical to args[‘predictor_table_path’] and ids in the table are required to be identical to the predictor list. args['results_suffix'] (string) – optional, if exists is appended to any output file paths. None

## RouteDEM: D-Infinity Routing¶

natcap.invest.routing.routedem.execute(args)

RouteDEM: D-Infinity Routing.

This model exposes the pygeoprocessing_0_3_3 d-infinity routing functionality as an InVEST 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 file names args['dem_path'] (string) – path to a digital elevation raster args['calculate_flow_accumulation'] (bool) – If True, model will calculate a flow accumulation raster. args['calculate_stream_threshold'] (bool) – if True, model will calculate a stream classification layer by thresholding flow accumulation to the provided value in args[‘threshold_flow_accumulation’]. args['threshold_flow_accumulation'] (int) – The number of upstream cells that must flow into a cell before it’s classified as a stream. args['calculate_downstream_distance'] (bool) – If True, and a stream threshold is calculated, model will calculate a downstream distance raster in units of pixels. args['calculate_slope'] (bool) – If True, model will calculate a slope raster. None

## Scenario Generator: 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.

## Scenario Generator: Rule-Based¶

natcap.invest.scenario_generator.scenario_generator.execute(args)

Scenario Generator: Rule-Based.

Model entry-point.

Parameters: workspace_dir (str) – path to workspace directory suffix (str) – string to append to output files landcover (str) – path to land-cover raster transition (str) – path to land-cover attributes table calculate_priorities (bool) – whether to calculate priorities priorities_csv_uri (str) – path to priority csv table calculate_proximity (bool) – whether to calculate proximity proximity_weight (float) – weight given to proximity calculate_transition (bool) – whether to specifiy transitions calculate_factors (bool) – whether to use suitability factors suitability_folder (str) – path to suitability folder suitability (str) – path to suitability factors table weight (float) – suitability factor weight factor_inclusion (int) – the rasterization method – all touched or center points factors_field_container (bool) – whether to use suitability factor inputs calculate_constraints (bool) – whether to use constraint inputs constraints (str) – filepath to constraints shapefile layer constraints_field (str) – shapefile field containing constraints field override_layer (bool) – whether to use override layer override (str) – path to override shapefile override_field (str) – shapefile field containing override value override_inclusion (int) – the rasterization method seed (int or None) – a number to use as the randomization seed. If not provided, None is assumed.

Example Args:

args = {
'workspace_dir': 'path/to/dir',
'suffix': '',
'landcover': 'path/to/raster',
'transition': 'path/to/csv',
'calculate_priorities': True,
'priorities_csv_uri': 'path/to/csv',
'calculate_proximity': True,
'calculate_transition': True,
'calculate_factors': True,
'suitability_folder': 'path/to/dir',
'suitability': 'path/to/csv',
'weight': 0.5,
'factor_inclusion': 0,
'factors_field_container': True,
'calculate_constraints': True,
'constraints': 'path/to/shapefile',
'constraints_field': '',
'override_layer': True,
'override': 'path/to/shapefile',
'override_field': '',
'override_inclusion': 0
}


d = {
'proximity_weight': 0.3,
'distance_field': '',
'transition_id': 'ID',
'percent_field': 'Percent Change',
'area_field': 'Area Change',
'priority_field': 'Priority',
'proximity_field': 'Proximity',
'suitability_id': '',
'suitability_layer': '',
'suitability_field': '',
}


## Scenic Quality¶

natcap.invest.scenic_quality.scenic_quality.execute(args)

Scenic Quality.

Warning

The Scenic Quality model is under active development and is currently unstable.

Parameters: workspace_dir (string) – The selected folder is used as the workspace where all intermediate and output files will be written. If the selected folder does not exist, it will be created. If datasets already exist in the selected folder, they will be overwritten. (required) aoi_uri (string) – An OGR-supported vector file. This AOI instructs the model where to clip the input data and the extent of analysis. Users will create a polygon feature layer that defines their area of interest. The AOI must intersect the Digital Elevation Model (DEM). (required) cell_size (float) – Length (in meters) of each side of the (square) cell. (optional) structure_uri (string) – An OGR-supported vector file. The user must specify a point feature layer that indicates locations of objects that contribute to negative scenic quality, such as aquaculture netpens or wave energy facilities. In order for the viewshed analysis to run correctly, the projection of this input must be consistent with the project of the DEM input. (required) dem_uri (string) – A GDAL-supported raster file. An elevation raster layer is required to conduct viewshed analysis. Elevation data allows the model to determine areas within the AOI’s land-seascape where point features contributing to negative scenic quality are visible. (required) refraction (float) – The earth curvature correction option corrects for the curvature of the earth and refraction of visible light in air. Changes in air density curve the light downward causing an observer to see further and the earth to appear less curved. While the magnitude of this effect varies with atmospheric conditions, a standard rule of thumb is that refraction of visible light reduces the apparent curvature of the earth by one-seventh. By default, this model corrects for the curvature of the earth and sets the refractivity coefficient to 0.13. (required) pop_uri (string) – A GDAL-supported raster file. A population raster layer is required to determine population within the AOI’s land-seascape where point features contributing to negative scenic quality are visible and not visible. (optional) overlap_uri (string) – An OGR-supported vector file. The user has the option of providing a polygon feature layer where they would like to determine the impact of objects on visual quality. This input must be a polygon and projected in meters. The model will use this layer to determine what percent of the total area of each polygon feature can see at least one of the point features impacting scenic quality.optional valuation_function (string) – Either ‘polynomial’ or ‘logarithmic’. This field indicates the functional form f(x) the model will use to value the visual impact for each viewpoint. For distances less than 1 km (x<1), the model uses a linear form g(x) where the line passes through f(1) (i.e. g(1) == f(1)) and extends to zero with the same slope as f(1) (i.e. g’(x) == f’(1)). (optional) a_coefficient (float) – First coefficient used either by the polynomial or by the logarithmic valuation function. (required) b_coefficient (float) – Second coefficient used either by the polynomial or by the logarithmic valuation function. (required) c_coefficient (float) – Third coefficient for the polynomial’s quadratic term. (required) d_coefficient (float) – Fourth coefficient for the polynomial’s cubic exponent. (required) max_valuation_radius (float) – Radius beyond which the valuation is set to zero. The valuation function ‘f’ cannot be negative at the radius ‘r’ (f(r)>=0). (required) None

## Seasonal Water Yield¶

natcap.invest.seasonal_water_yield.seasonal_water_yield.execute(args)

Seasonal Water Yield.

This function invokes the InVEST seasonal water yield model described in “Spatial attribution of baseflow generation at the parcel level for ecosystem-service valuation”, Guswa, et. al (under review in “Water Resources Research”)

Parameters: args['workspace_dir'] (string) – output directory for intermediate, and final files (temporary,) – args['results_suffix'] (string) – (optional) string to append to any output files args['threshold_flow_accumulation'] (number) – used when classifying stream pixels from the DEM by thresholding the number of upstream cells that must flow into a cell before it’s considered part of a stream. args['et0_dir'] (string) – required if args[‘user_defined_local_recharge’] is False. Path to a directory that contains rasters of monthly reference evapotranspiration; units in mm. args['precip_dir'] (string) – required if args[‘user_defined_local_recharge’] is False. A path to a directory that contains rasters of monthly precipitation; units in mm. args['dem_raster_path'] (string) – a path to a digital elevation raster args['lulc_raster_path'] (string) – a path to a land cover raster used to classify biophysical properties of pixels. args['soil_group_path'] (string) – required if args[‘user_defined_local_recharge’] is False. A path to a raster indicating SCS soil groups where integer values are mapped to soil types: 1: A 2: B 3: C 4: D  args['aoi_path'] (string) – path to a vector that indicates the area over which the model should be run, as well as the area in which to aggregate over when calculating the output Qb. args['biophysical_table_path'] (string) – path to a CSV table that maps landcover codes paired with soil group types to curve numbers as well as Kc values. Headers must include ‘lucode’, ‘CN_A’, ‘CN_B’, ‘CN_C’, ‘CN_D’, ‘Kc_1’, ‘Kc_2’, ‘Kc_3’, ‘Kc_4’, ‘Kc_5’, ‘Kc_6’, ‘Kc_7’, ‘Kc_8’, ‘Kc_9’, ‘Kc_10’, ‘Kc_11’, ‘Kc_12’. args['rain_events_table_path'] (string) – Not required if args[‘user_defined_local_recharge’] is True or args[‘user_defined_climate_zones’] is True. Path to a CSV table that has headers ‘month’ (1-12) and ‘events’ (int >= 0) that indicates the number of rain events per month args['alpha_m'] (float or string) – required if args[‘monthly_alpha’] is false. Is the proportion of upslope annual available local recharge that is available in month m. args['beta_i'] (float or string) – is the fraction of the upgradient subsidy that is available for downgradient evapotranspiration. args['gamma'] (float or string) – is the fraction of pixel local recharge that is available to downgradient pixels. args['user_defined_local_recharge'] (boolean) – if True, indicates user will provide pre-defined local recharge raster layer args['l_path'] (string) – required if args[‘user_defined_local_recharge’] is True. If provided pixels indicate the amount of local recharge; units in mm. args['user_defined_climate_zones'] (boolean) – if True, user provides a climate zone rain events table and a climate zone raster map in lieu of a global rain events table. args['climate_zone_table_path'] (string) – required if args[‘user_defined_climate_zones’] is True. Contains monthly precipitation events per climate zone. Fields must be: “cz_id”, “jan”, “feb”, “mar”, “apr”, “may”, “jun”, “jul”, “aug”, “sep”, “oct”, “nov”, “dec”. args['climate_zone_raster_path'] (string) – required if args[‘user_defined_climate_zones’] is True, pixel values correspond to the “cz_id” values defined in args[‘climate_zone_table_path’] args['monthly_alpha'] (boolean) – if True, use the alpha args['monthly_alpha_path'] (string) – required if args[‘monthly_alpha’] is True. None

## Sediment Delivery Ratio¶

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.

## Wave Energy¶

natcap.invest.wave_energy.wave_energy.execute(args)

Wave Energy.

Executes both the biophysical and valuation parts of the wave energy model (WEM). Files will be written on disk to the intermediate and output directories. The outputs computed for biophysical and valuation include: wave energy capacity raster, wave power raster, net present value raster, percentile rasters for the previous three, and a point shapefile of the wave points with attributes.

Parameters: workspace_dir (string) – Where the intermediate and output folder/files will be saved. (required) wave_base_data_uri (string) – Directory location of wave base data including WW3 data and analysis area shapefile. (required) analysis_area_uri (string) – A string identifying the analysis area of interest. Used to determine wave data shapefile, wave data text file, and analysis area boundary shape. (required) aoi_uri (string) – A polygon shapefile outlining a more detailed area within the analysis area. This shapefile should be projected with linear units being in meters. (required to run Valuation model) machine_perf_uri (string) – The path of a CSV file that holds the machine performance table. (required) machine_param_uri (string) – The path of a CSV file that holds the machine parameter table. (required) dem_uri (string) – The path of the Global Digital Elevation Model (DEM). (required) suffix (string) – A python string of characters to append to each output filename (optional) valuation_container (boolean) – Indicates whether the model includes valuation land_gridPts_uri (string) – A CSV file path containing the Landing and Power Grid Connection Points table. (required for Valuation) machine_econ_uri (string) – A CSV file path for the machine economic parameters table. (required for Valuation) number_of_machines (int) – An integer specifying the number of machines for a wave farm site. (required for Valuation)

Example Args Dictionary:

{
'workspace_dir': 'path/to/workspace_dir',
'wave_base_data_uri': 'path/to/base_data_dir',
'analysis_area_uri': 'West Coast of North America and Hawaii',
'aoi_uri': 'path/to/shapefile',
'machine_perf_uri': 'path/to/csv',
'machine_param_uri': 'path/to/csv',
'dem_uri': 'path/to/raster',
'suffix': '_results',
'valuation_container': True,
'land_gridPts_uri': 'path/to/csv',
'machine_econ_uri': 'path/to/csv',
'number_of_machines': 28,
}


## Wind Energy¶

natcap.invest.wind_energy.wind_energy.execute(args)

Wind Energy.

This module handles the execution of the wind energy model given the following dictionary:

Parameters: workspace_dir (string) – a python string which is the uri path to where the outputs will be saved (required) wind_data_uri (string) – path to a CSV file with the following header: [‘LONG’,’LATI’,’LAM’, ‘K’, ‘REF’]. Each following row is a location with at least the Longitude, Latitude, Scale (‘LAM’), Shape (‘K’), and reference height (‘REF’) at which the data was collected (required) aoi_uri (string) – a uri to an OGR datasource that is of type polygon and projected in linear units of meters. The polygon specifies the area of interest for the wind data points. If limiting the wind farm bins by distance, then the aoi should also cover a portion of the land polygon that is of interest (optional for biophysical and no distance masking, required for biophysical and distance masking, required for valuation) bathymetry_uri (string) – a uri to a GDAL dataset that has the depth values of the area of interest (required) land_polygon_uri (string) – a uri to an OGR datasource of type polygon that provides a coastline for determining distances from wind farm bins. Enabled by AOI and required if wanting to mask by distances or run valuation global_wind_parameters_uri (string) – a float for the average distance in kilometers from a grid connection point to a land connection point (required for valuation if grid connection points are not provided) suffix (string) – a String to append to the end of the output files (optional) turbine_parameters_uri (string) – a uri to a CSV file that holds the turbines biophysical parameters as well as valuation parameters (required) number_of_turbines (int) – an integer value for the number of machines for the wind farm (required for valuation) min_depth (float) – a float value for the minimum depth for offshore wind farm installation (meters) (required) max_depth (float) – a float value for the maximum depth for offshore wind farm installation (meters) (required) min_distance (float) – a float value for the minimum distance from shore for offshore wind farm installation (meters) The land polygon must be selected for this input to be active (optional, required for valuation) max_distance (float) – a float value for the maximum distance from shore for offshore wind farm installation (meters) The land polygon must be selected for this input to be active (optional, required for valuation) valuation_container (boolean) – Indicates whether model includes valuation foundation_cost (float) – a float representing how much the foundation will cost for the specific type of turbine (required for valuation) discount_rate (float) – a float value for the discount rate (required for valuation) grid_points_uri (string) – a uri to a CSV file that specifies the landing and grid point locations (optional) avg_grid_distance (float) – a float for the average distance in kilometers from a grid connection point to a land connection point (required for valuation if grid connection points are not provided) price_table (boolean) – a bool indicating whether to use the wind energy price table or not (required) wind_schedule (string) – a URI to a CSV file for the yearly prices of wind energy for the lifespan of the farm (required if ‘price_table’ is true) wind_price (float) – a float for the wind energy price at year 0 (required if price_table is false) rate_change (float) – a float as a percent for the annual rate of change in the price of wind energy. (required if price_table is false)

Example Args Dictionary:

{
'workspace_dir': 'path/to/workspace_dir',
'wind_data_uri': 'path/to/file',
'aoi_uri': 'path/to/shapefile',
'bathymetry_uri': 'path/to/raster',
'land_polygon_uri': 'path/to/shapefile',
'global_wind_parameters_uri': 'path/to/csv',
'suffix': '_results',
'turbine_parameters_uri': 'path/to/csv',
'number_of_turbines': 10,
'min_depth': 3,
'max_depth': 60,
'min_distance': 0,
'max_distance': 200000,
'valuation_container': True,
'foundation_cost': 3.4,
'discount_rate': 7.0,
'grid_points_uri': 'path/to/csv',
'avg_grid_distance': 4,
'price_table': True,
'wind_schedule': 'path/to/csv',
'wind_price': 0.4,
'rate_change': 0.0,

}

Returns: None