natcap.invest package

Subpackages

Submodules

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.
  • args['n_workers'] (int) – (optional) The number of worker processes to use for processing this model. If omitted, computation will take place in the current process.
Returns:

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.aggregate_to_polygons(base_aggregate_vector_path, target_aggregate_vector_path, landcover_raster_projection, crop_to_landcover_table, nutrient_table, yield_percentile_headers, output_dir, file_suffix, target_aggregate_table_path)

Write table with aggregate results of yield and nutrient values.

Use zonal statistics to summarize total observed and interpolated production and nutrient information for each polygon in base_aggregate_vector_path.

Parameters:
  • base_aggregate_vector_path (string) – path to polygon vector
  • target_aggregate_vector_path (string) – path to re-projected copy of polygon vector
  • landcover_raster_projection (string) – a WKT projection string
  • crop_to_landcover_table (dict) – landcover codes keyed by crop names
  • nutrient_table (dict) – a lookup of nutrient values by crop in the form of nutrient_table[<crop>][<nutrient>].
  • yield_percentile_headers (list) – list of strings indicating percentiles at which yield was calculated.
  • output_dir (string) – the file path to the output workspace.
  • file_suffix (string) – string to appened to any output filenames.
  • target_aggregate_table_path (string) – path to ‘aggregate_results.csv’ in the output workspace
Returns:

None

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

  • args['n_workers'] (int) – (optional) The number of worker processes to use for processing this model. If omitted, computation will take place in the current process.
Returns:

None.

natcap.invest.crop_production_percentile.tabulate_results(nutrient_table, yield_percentile_headers, crop_to_landcover_table, pixel_area_ha, landcover_raster_path, landcover_nodata, output_dir, file_suffix, target_table_path)

Write table with total yield and nutrient results by crop.

This function includes all the operations that write to results_table.csv.

Parameters:
  • nutrient_table (dict) – a lookup of nutrient values by crop in the form of nutrient_table[<crop>][<nutrient>].
  • yield_percentile_headers (list) – list of strings indicating percentiles at which yield was calculated.
  • crop_to_landcover_table (dict) – landcover codes keyed by crop names
  • pixel_area_ha (float) – area of lulc raster cells (hectares)
  • landcover_raster_path (string) – path to landcover raster
  • landcover_nodata (float) – landcover raster nodata value
  • output_dir (string) – the file path to the output workspace.
  • file_suffix (string) – string to appened to any output filenames.
  • target_table_path (string) – path to ‘result_table.csv’ in the output workspace
Returns:

None

natcap.invest.crop_production_regression module

InVEST Crop Production Percentile Model.

natcap.invest.crop_production_regression.aggregate_regression_results_to_polygons(base_aggregate_vector_path, target_aggregate_vector_path, landcover_raster_projection, crop_to_landcover_table, nutrient_table, output_dir, file_suffix, target_aggregate_table_path)

Write table with aggregate results of yield and nutrient values.

Use zonal statistics to summarize total observed and interpolated production and nutrient information for each polygon in base_aggregate_vector_path.

Parameters:
  • base_aggregate_vector_path (string) – path to polygon vector
  • target_aggregate_vector_path (string) – path to re-projected copy of polygon vector
  • landcover_raster_projection (string) – a WKT projection string
  • crop_to_landcover_table (dict) – landcover codes keyed by crop names
  • nutrient_table (dict) – a lookup of nutrient values by crop in the form of nutrient_table[<crop>][<nutrient>].
  • output_dir (string) – the file path to the output workspace.
  • file_suffix (string) – string to appened to any output filenames.
  • target_aggregate_table_path (string) – path to ‘aggregate_results.csv’ in the output workspace
Returns:

None

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

Returns:

None.

natcap.invest.crop_production_regression.tabulate_regression_results(nutrient_table, crop_to_landcover_table, pixel_area_ha, landcover_raster_path, landcover_nodata, output_dir, file_suffix, target_table_path)

Write table with total yield and nutrient results by crop.

This function includes all the operations that write to results_table.csv.

Parameters:
  • nutrient_table (dict) – a lookup of nutrient values by crop in the form of nutrient_table[<crop>][<nutrient>].
  • crop_to_landcover_table (dict) – landcover codes keyed by crop names
  • pixel_area_ha (float) – area of lulc raster cells (hectares)
  • landcover_raster_path (string) – path to landcover raster
  • landcover_nodata (float) – landcover raster nodata value
  • output_dir (string) – the file path to the output workspace.
  • file_suffix (string) – string to appened to any output filenames.
  • target_table_path (string) – path to ‘result_table.csv’ in the output workspace
Returns:

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

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

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

A dictionary of arguments from the extracted

archive. Paths to files are absolute paths.

Return type:

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.
Returns: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.
Returns: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.
Raises: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)
Returns:

A formatted, unicode string.

natcap.invest.datastack.get_datastack_info(filepath)

Get information about a datastack.

Parameters:filepath (string) – The path to a file on disk that can be extracted as a datastack, parameter set, or logfile.
Returns:
  • "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.

Return type: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 (2015).

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 path 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_vector_path'] (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_path'] (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_raster_path']
    • 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_raster_path'] (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_vector_path'] (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.
Returns:

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_path'] (string) – used in “mode (a)” path to a base landcover map with integer codes
  • args['lulc_to_globio_table_path'] (string) –

    used in “mode (a)” path to table that translates the land-cover args[‘lulc_path’] 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_path'] (string) – used in “mode (a)” path to pasture raster
  • args['potential_vegetation_path'] (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_path'] (string) – path to MSA classification parameters
  • args['aoi_path'] (string) – (optional) if it exists then final MSA raster is summarized by AOI
  • args['globio_lulc_path'] (string) – used in “mode (b)” path to predefined globio raster.
  • args['n_workers'] (int) – (optional) The number of worker processes to use for processing this model. If omitted, computation will take place in the current process.
Returns:

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_path(sigma, kernel_path)

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 path to the directory that will write output and other temporary files (required)
  • lulc_cur_path (string) – a path to an input land use/land cover raster (required)
  • lulc_fut_path (string) – a path to an input land use/land cover raster (optional)
  • lulc_bas_path (string) – a path to an input land use/land cover raster (optional, but required for rarity calculations)
  • threat_folder (string) – a path to the directory that will contain all threat rasters (required)
  • threats_table_path (string) – a path 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_vector_path (string) – a path to an input polygon shapefile containing data on the relative protection against threats (optional)
  • sensitivity_table_path (string) – a path 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 path paths just before the file extension.

Example Args Dictionary:

{
    'workspace_dir': 'path/to/workspace_dir',
    'lulc_cur_path': 'path/to/lulc_cur_raster',
    'lulc_fut_path': 'path/to/lulc_fut_raster',
    'lulc_bas_path': 'path/to/lulc_bas_raster',
    'threat_raster_folder': 'path/to/threat_rasters/',
    'threats_table_path': 'path/to/threats_csv',
    'access_vector_path': 'path/to/access_shapefile',
    'sensitivity_table_path': 'path/to/sensitivity_csv',
    'half_saturation_constant': 0.5,
    'suffix': '_results',
}
Returns:None
natcap.invest.habitat_quality.make_linear_decay_kernel_path(max_distance, kernel_path)

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_path (string) – path to output raster whose values are in (0,1) representing distance to edge. Size is (max_distance * 2 + 1)^2
Returns:

None

natcap.invest.habitat_quality.map_raster_to_dict_values(key_raster_path, out_path, attr_dict, field, out_nodata, values_required)

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_path - a GDAL raster path dataset whose pixel values relate to
the keys in ‘attr_dict’

out_path - 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
Returns: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.
Returns:

the full path, plus extension, to the valid raster.

natcap.invest.pollination module

Pollinator service model for InVEST.

natcap.invest.pollination.execute(args)

InVEST Pollination Model.

Parameters:
  • args['workspace_dir'] (string) – a path to the output workspace folder. Will overwrite any files that exist if the path already exists.
  • args['results_suffix'] (string) – string appended to each output file path.
  • args['landcover_raster_path'] (string) – file path to a landcover raster.
  • args['guild_table_path'] (string) –

    file path to a table indicating the bee species to analyze in this model run. Table headers must include:

    • ’species’: a bee species whose column string names will
      be referred to in other tables and the model will output analyses per species.
    • one or more columns matching _NESTING_SUITABILITY_PATTERN
      with values in the range [0.0, 1.0] indicating the suitability of the given species to nest in a particular substrate.
    • one or more columns matching _FORAGING_ACTIVITY_RE_PATTERN
      with values in the range [0.0, 1.0] indicating the relative level of foraging activity for that species during a particular season.
    • _ALPHA_HEADER the sigma average flight distance of that bee
      species in meters.
    • ’relative_abundance’: a weight indicating the relative
      abundance of the particular species with respect to the sum of all relative abundance weights in the table.
  • args['landcover_biophysical_table_path'] (string) –

    path to a table mapping landcover codes in args[‘landcover_path’] to indexes of nesting availability for each nesting substrate referenced in guilds table as well as indexes of abundance of floral resources on that landcover type per season in the bee activity columns of the guild table.

    All indexes are in the range [0.0, 1.0].

    Columns in the table must be at least
    • ’lucode’: representing all the unique landcover codes in
      the raster ast args[‘landcover_path’]
    • For every nesting matching _NESTING_SUITABILITY_PATTERN in the guild stable, a column matching the pattern in _LANDCOVER_NESTING_INDEX_HEADER.
    • For every season matching _FORAGING_ACTIVITY_RE_PATTERN in the guilds table, a column matching the pattern in _LANDCOVER_FLORAL_RESOURCES_INDEX_HEADER.
  • args['farm_vector_path'] (string) –

    (optional) path to a single layer polygon shapefile representing farms. If present will trigger the farm yield component of the model.

    The layer must have at least the following fields:

    • season (string): season in which the farm needs pollination
    • crop_type (string): a text field to identify the crop type for
      summary statistics.
    • half_sat (float): a real in the range [0.0, 1.0] representing
      the proportion of wild pollinators to achieve a 50% yield of that crop.
    • p_dep (float): a number in the range [0.0, 1.0]
      representing the proportion of yield dependent on pollinators.
    • p_managed (float): proportion of pollinators that come from
      non-native/managed hives.
    • fr_[season] (float): one or more fields that match this pattern
      such that season also matches the season headers in the biophysical and guild table. Any areas that overlap the landcover map will replace seasonal floral resources with this value. Ranges from 0..1.
    • n_[substrate] (float): One or more fields that match this
      pattern such that substrate also matches the nesting substrate headers in the biophysical and guild table. Any areas that overlap the landcover map will replace nesting substrate suitability with this value. Ranges from 0..1.
  • args['n_workers'] (int) – (optional) The number of worker processes to use for processing this model. If omitted, computation will take place in the current process.
Returns:

None

natcap.invest.routedem module

RouteDEM for exposing the natcap.invest’s routing package to UI.

natcap.invest.routedem.execute(args)

RouteDEM: Hydrological routing.

This model exposes the pygeoprocessing D8 and Multiple Flow Direction routing functionality as an InVEST model.

This tool will always fill pits on the input DEM.

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['dem_band_index'] (int) – Optional. The band index to operate on. If not provided, band index 1 is assumed.
  • args['algorithm'] (string) – The routing algorithm to use. Must be one of ‘D8’ or ‘MFD’ (case-insensitive). Required when calculating flow direction, flow accumulation, stream threshold, and downstream distance.
  • args['calculate_flow_direction'] (bool) – If True, model will calculate flow direction for the filled DEM.
  • args['calculate_flow_accumulation'] (bool) – If True, model will calculate a flow accumulation raster. Only applies when args[‘calculate_flow_direction’] is True.
  • 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']. Only applies when args[‘calculate_flow_accumulation’] and args[‘calculate_flow_direction’] are True.
  • 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. Only applies when args[‘calculate_flow_accumulation’], args[‘calculate_flow_direction’], and args[‘calculate_stream_threshold’] are all True.
  • args['calculate_slope'] (bool) – If True, model will calculate a slope raster from the DEM.
  • args['n_workers'] (int) – The n_workers parameter to pass to the task graph. The default is -1 if not provided.
Returns:

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}.
  • args['n_workers'] (int) – (optional) The number of worker processes to use for processing this model. If omitted, computation will take place in the current process.
Returns:

None.

natcap.invest.sdr module

natcap.invest.utils module

InVEST specific code utils.

class natcap.invest.utils.ThreadFilter(thread_name)

Bases: logging.Filter

Filters out log messages issued by the given thread.

Any log messages generated by a thread with the name matching the threadname provided to the constructor will be excluded.

filter(record)

Filter the given log record.

Parameters:record (log record) – The log record to filter.
Returns:True if the record should be included, false if not.
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
Returns:

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.

Raises:
  • 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, 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.
  • to_lower (bool) – if True, converts all unicode in the CSV, including headers and values to lowercase, otherwise uses raw string values.
  • warn_if_missing (bool) – If True, warnings are logged if there are empty headers or value rows.
Returns:

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

Return type:

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

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.
  • exclude_threads=None (list) – If None, logging from all threads will be included in the log. If a list, it must be a list of string thread names that should be excluded from logging in this file.
  • 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.
Yields:

handler

An instance of logging.FileHandler that

represents the file that is being written to.

Returns:

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

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.mean_pixel_size_and_area(pixel_size_tuple)

Convert to mean and raise Exception if they are not close.

Parameter:
pixel_size_tuple (tuple): a 2 tuple indicating the x/y size of a
pixel.
Returns:tuple of (mean absolute average of pixel_size, area of pixel size)
Raises:ValueError if the dimensions of pixel_size_tuple are not almost – square.
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.
Yields:

sandbox (string) – The path to the new folder on disk.

Returns:

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

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.

In addition, this validates the n_workers argument if it’s included.

Raises:AssertionError when an invalid format is found.

Example

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

# do your validation here

natcap.invest.wave_energy module

InVEST Wave Energy Model Core Code

exception natcap.invest.wave_energy.IntersectionError

Bases: exceptions.Exception

A custom error message for when the AOI does not intersect any wave data points.

natcap.invest.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 (str) – Where the intermediate and output folder/files will be saved. (required)
  • wave_base_data_path (str) – Directory location of wave base data including WAVEWATCH III (WW3) data and analysis area shapefile. (required)
  • analysis_area_path (str) – 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_path (str) – 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_path (str) – The path of a CSV file that holds the machine performance table. (required)
  • machine_param_path (str) – The path of a CSV file that holds the machine parameter table. (required)
  • dem_path (str) – The path of the Global Digital Elevation Model (DEM). (required)
  • suffix (str) – A python string of characters to append to each output filename (optional)
  • valuation_container (boolean) – Indicates whether the model includes valuation
  • land_gridPts_path (str) – A CSV file path containing the Landing and Power Grid Connection Points table. (required for Valuation)
  • machine_econ_path (str) – 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_path': 'path/to/base_data_dir',
    'analysis_area_path': 'West Coast of North America and Hawaii',
    'aoi_path': 'path/to/shapefile',
    'machine_perf_path': 'path/to/csv',
    'machine_param_path': 'path/to/csv',
    'dem_path': 'path/to/raster',
    'suffix': '_results',
    'valuation_container': True,
    'land_gridPts_path': 'path/to/csv',
    'machine_econ_path': 'path/to/csv',
    'number_of_machines': 28,
}

natcap.invest.wind_energy module

InVEST Wind Energy model.

natcap.invest.wind_energy.execute(args)

Wind Energy.

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

Parameters:
  • workspace_dir (str) – a path to the output workspace folder (required)
  • wind_data_path (str) – 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_vector_path (str) – a path to an OGR polygon vector that is 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_path (str) – a path to a GDAL raster that has the depth values of the area of interest (required)
  • land_polygon_vector_path (str) – a path to an OGR polygon vector 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_path (str) – 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 (str) – a str to append to the end of the output files (optional)
  • turbine_parameters_path (str) – a path 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_path (str) – a path 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 (str) – a path 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_path': 'path/to/file',
    'aoi_vector_path': 'path/to/shapefile',
    'bathymetry_path': 'path/to/raster',
    'land_polygon_vector_path': 'path/to/shapefile',
    'global_wind_parameters_path': 'path/to/csv',
    'suffix': '_results',
    'turbine_parameters_path': '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_path': '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

Module contents

init module for natcap.invest.

natcap.invest.local_dir(source_file)

Return the path to where source_file would be on disk.

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