InVEST: Integrated Valuation of Ecosystem Services and Tradeoffs

Release: 3.8.7.post0+gd523e39d.d20200717

InVEST (Integrated Valuation of Ecosystem Services and Tradeoffs) is a family of tools for quantifying the values of natural capital in clear, credible, and practical ways. In promising a return (of societal benefits) on investments in nature, the scientific community needs to deliver knowledge and tools to quantify and forecast this return. InVEST enables decision-makers to quantify the importance of natural capital, to assess the tradeoffs associated with alternative choices, and to integrate conservation and human development.

Older versions of InVEST ran as script tools in the ArcGIS ArcToolBox environment, but have almost all been ported over to a purely open-source python environment.

InVEST is licensed under a permissive, modified BSD license.

For more information, see:

Getting Started

Installing InVEST

Binary Dependencies

InVEST itself depends only on python packages, but many of these package dependencies depend on low-level libraries or have complex build processes. In recent history, some of these packages (notably, numpy and scipy) have started to release precompiled binary packages of their own, removing the need to install these packages through a system package manager. Others, however, remain easiest to install through a package manager.

Linux

Linux users have it easy, as almost every package required to use natcap.invest is available in the package repositories. The provided commands will install only the libraries and binaries that are needed, allowing pip to install the rest.

Ubuntu & Debian

Attention

The package versions in the debian:stable repositories often lag far behind the latest releases. It may be necessary to install a later version of a library from a different package repository, or else build the library from source.

$ sudo apt-get install python3-dev python3-setuptools python3-gdal python3-rtree python3-shapely
Fedora
$ sudo yum install python3-devel python3-setuptools python3-gdal python3-rtree python3-shapely
Mac OS X

The easiest way to install binary packages on Mac OS X is through a package manager such as Homebrew:

$ brew install gdal spatialindex pyqt

The GDAL and PyQt packages include their respective python packages. The others will allow their corresponding python packages to be compiled against these binaries via pip.

Windows

While many packages are available for Windows on the Python Package Index, some may need to be fetched from a different source. Many are available from Christogh Gohlke’s unofficial build page: http://www.lfd.uci.edu/~gohlke/pythonlibs/

PyQt4 installers can also be downloaded from the Riverbank Computing website.

Python Dependencies

Dependencies for natcap.invest are listed in requirements.txt:

#
# Any lines with "# pip-only" at the end will be processed by
# scripts/convert-requirements-to-conda-yml.py as though it can only be found
# on pip.

GDAL>=2.0,<3.0
Pyro4==4.77  # pip-only
pandas>=1.0
numpy>=1.11.0,!=1.16.0
Rtree>=0.8.2,!=0.9.1
scipy>=0.16.1,<1.5.0
Shapely>=1.6.4,<1.7.0
pygeoprocessing>=1.9.2,<2.0  # pip-only
taskgraph[niced_processes]>=0.9.1
psutil>=5.6.6
chardet>=3.0.4
xlrd>=1.2.0
xlwt

Optional Qt User Interface

InVEST’s user interface is built with PyQt. Because of the hefty binary requirement of Qt and the relative difficulty of installing PyQt, these dependencies will not be installed with the standard pip install natcap.invest. Several of these dependencies are available as extras, however, and can be installed via pip:

$ pip install natcap.invest[ui]

These extras do not include a distribution of PyQt, so you will need to install PyQt in an appropriate way on your system. PyQt4 is not currently available from the Python Package Index, but other sources and package managers allow for straightforward installation on Windows, Mac OS X, and Linux.

The InVEST user interface uses a wrapper layer to support both PyQt4 and PyQt5, one of which must be installed on your system for the UI to be able to run. If both are installed, PyQt5 is preferred, but you can force the UI to use PyQt4 by defining an environment variable before launching the UI:

$ QT_API=pyqt4 invest pollination

We have had the best luck running the UI under PyQt4 and PySide2.

Installing from Source

Note

Python 3.6 users will need to install Microsoft Visual Studio 2017, or at least the Build Tools for Visual Studio 2017. See the python wiki page on compilation under Windows for more information.

Assuming you have a C/C++ compiler installed and configured for your system, and dependencies installed, the easiest way to install InVEST as a python package is:

$ pip install natcap.invest

Installing the latest development version

Pre-built binaries for Windows

Pre-built installers and wheels of development versions of natcap.invest for 32-bit Windows python installations are available from http://releases.naturalcapitalproject.org/?prefix=invest/, along with other distributions of InVEST. Once downloaded, wheels can be installed locally via pip:

> pip install .\natcap.invest-3.3.0.post89+nfc4a8d4de776-cp27-none-win32.whl
Installing from our source tree

The latest development version of InVEST can be installed from our git source tree if you have a compiler installed:

$ pip install "git+https://github.com/natcap/invest@master#egg=natcap.invest"

The InVEST CLI

Installing

The invest cli application is installed with the natcap.invest python package. See Installing InVEST

It is also available to Windows users who installed InVEST with the downloadable installer. Just replace invest in the commands below with the full path to invest.exe (e.g. C:\InVEST_3.8.0_x86\invest-3-x86\invest.exe)

Usage

To run an InVEST model from the command-line, use the invest cli single entry point:

$ invest --help
usage: invest [-h] [--version] [-v | --debug]
          {list,launch,run,quickrun,validate,getspec} ...

Integrated Valuation of Ecosystem Services and Tradeoffs. InVEST (Integrated
Valuation of Ecosystem Services and Tradeoffs) is a family of tools for
quantifying the values of natural capital in clear, credible, and practical
ways. In promising a return (of societal benefits) on investments in nature,
the scientific community needs to deliver knowledge and tools to quantify and
forecast this return. InVEST enables decision-makers to quantify the
importance of natural capital, to assess the tradeoffs associated with
alternative choices, and to integrate conservation and human development.
Older versions of InVEST ran as script tools in the ArcGIS ArcToolBox
environment, but have almost all been ported over to a purely open-source
python environment.

positional arguments:
  {list,launch,run,quickrun,validate,getspec}
    list                List the available InVEST models
    launch              Start the InVEST launcher window
    run                 Run an InVEST model
    quickrun            Run through a model with a specific datastack, exiting
                        immediately upon completion. This subcommand is only
                        intended to be used by automated testing scripts.
    validate            Validate the parameters of a datastack
    getspec             Get the specification of a model.

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v, --verbose         Increase verbosity. Affects how much logging is
                        printed to the console and (if running in headless
                        mode) how much is written to the logfile.
  --debug               Enable debug logging. Alias for -vvvvv

To list the available models:

$ invest list

To launch a model’s user-interface:

$ invest run carbon

To run a model directly from the command-line:

$ invest -vvv run <modelname> --headless -d <datastack json file> -w <output_workspace>

For more detailed instructions, get the help for each command:

$ invest run --help

Changelog

3.8.7 (2020-07-17)

  • General
    • Fixed an issue where some users would be unable to launch InVEST binaries on Windows. This crash was due to a configuration issue in PySide2==5.15.0 that will be fixed in a future release of PySide2.
  • GLOBIO
    • Fix a bug that mishandled combining infrastructure data when only one infrastructure data was present.
  • Urban Flood Risk
    • The output vector flood_risk_service.shp now includes a field, flood_vol that is the sum of the modeled flood volume (from Q_m3.tif) within the AOI.
    • Fieldnames in flood_risk_service.shp have been updated to more closely match the variables they match as documented in the User’s Guide chapter. Specifically, serv_bld is now serv.blt and aff_bld is now aff.bld.
    • Q_mm.tif has been moved from the intermediate directory into the workspace.
    • Fixed a bug in the flood volume (Q_m3.tif) calculations that was producing incorrect values in all cases.

3.8.6 (2020-07-03)

  • Crop Production
    • Fixed critical bug in crop regression that caused incorrect yields in all cases.

3.8.5 (2020-06-26)

  • General
    • Fix bug in utils.build_lookup_from_csv that was allowing key_field to be non unique and overwriting values.
    • Fix bug in utils.build_lookup_from_csv where trailing commas caused returned values to be malformed.
    • Add optional argument column_list to utils.build_lookup_from_csv that takes a list of column names and only returns those in the dictionary.
    • Remove warn_if_missing argument from utils.build_lookup_from_csv and warning by default.
  • Scenic Quality
    • Fixing an issue in Scenic Quality where the creation of the weighted sum of visibility rasters could cause “Too Many Open Files” errors and/or MemoryError when the model is run with many viewpoints.
    • Progress logging has been added to several loops that may take a longer time when the model is run with thousands of points at a time.
    • A major part of the model’s execution was optimized for speed, particularly when the model is run with many, many points.
  • SDR:
    • Removed the unused parameter args['target_pixel_size'] from the SDR execute docstring.
  • Urban Flood Risk Mitigation
    • Fixed an issue where the output vector flood_risk_service.shp would only be created when the built infrastructure vector was provided. Now, the flood_risk_service.shp vector is always created, but the fields created differ depending on whether the built infrastructure input is present during the model run.
    • Fixed an issue where the model would crash if an infrastructure geometry were invalid or absent. Such features are now skipped.

3.8.4 (2020-06-05)

  • General:
    • Advanced the Taskgraph version requirement to fix a bug where workspace directories created by InVEST versions <=3.8.0 could not be re-used by more recent InVEST versions.
  • NDR:
    • The Start Menu shortcut on Windows and launcher label on Mac now have consistent labels for NDR: “NDR: Nutrient Delivery Ratio”.
  • SDR:
    • The Start Menu shortcut on Windows and launcher label on Mac now have consistent labels for SDR: “SDR: Sediment Delivery Ratio”.

3.8.3 (2020-05-29)

  • SDR’s compiled core now defines its own SQRT2 instead of relying on an available standard C library definition. This new definition helps to avoid some compiler issues on Windows.

3.8.2 (2020-05-15)

  • InVEST’s CSV encoding requirements are now described in the validation error message displayed when a CSV cannot be opened.

3.8.1 (2020-05-08)

  • Fixed a compilation issue on Mac OS X Catalina.
  • Fixed an issue with NDR’s raster normalization function so that Float64 nodata values are now correctly cast to Float32. This issue was affecting the summary vector, where the surf_n, sub_n and n_export_tot columns would contain values of -inf.
  • Fixed minor bug in Coastal Vulnerability shore point creation. Also added a check to fail fast when zero shore points are found within the AOI.
  • The Finfish Aquaculture model no longer generates histograms for uncertainty analysis due to issues with matplotlib that make InVEST unstable. See https://github.com/natcap/invest/issues/87 for more.
  • Corrected the Urban Cooling Model’s help text for the “Cooling Capacity Calculation Method” in the User Interface.
  • Fixing an issue with SDR’s LS calculations. The x term is now the weighted mean of proportional flow from the current pixel into its neighbors. Note that for ease of debugging, this has been implemented as a separate raster and is now included in RKLS calculations instead of in the LS calculations.
  • Fixed a bug in validation where checking for spatial overlap would be skipped entirely in cases where optional model arguments were not used.
  • Bumping the psutil dependency requirement to psutil>=5.6.6 to address a double-free vulnerability documented in CVE-2019-18874.
  • Adding a GitHub Actions workflow for building python wheels for Mac and Windows as well as a source distribution.
  • Updating links in setup.py, README.rst and README_PYTHON.rst to refer to the repository’s new home on github.
  • Binary builds for Windows and Mac OS X have been moved to GitHub Actions from AppVeyor. All AppVeyor-specific configuration has been removed.
  • Fixing an issue with the InVEST Makefile where make deploy was attempting to synchronize nonexistent sample data zipfiles with a storage bucket on GCP. Sample data zipfiles are only built on Windows, and so make deploy will only attempt to upload them when running on Windows.
  • Fixed a bug in CLI logging where logfiles created by the CLI were incompatible with the natcap.invest.datastack operation that allows the UI to load model arguments from logfiles.
  • Added error-handling in Urban Flood Risk Mitigation to tell users to “Check that the Soil Group raster does not contain values other than (1, 2, 3, 4)” when a ValueError is raised from _lu_to_cn_op.
  • Updated the Makefile to use the new git location of the InVEST User’s Guide repository at https://github.com/natcap/invest.users-guide
  • Automated tests are now configured to use Github Actions for 32- and 64-bit build targets for Python 3.6 and 3.7 on Windows. We are still using AppVeyor for our binary builds for the time being.
  • Makefile has been updated to fetch the version string from git rather than hg. A mercurial client is still needed in order to clone the InVEST User’s Guide.
  • Removing Python 2 compatibility code such as future, pyqt4, basestring, unicode, six, unicode casting, etc…
  • Update api-docs conf file to mock sdr.sdr_core and to use updated unittest mock

3.8.0 (2020-02-07)

  • Created a sub-directory for the sample data in the installation directory.
  • Fixed minor bug in HRA that was duplicating the results_suffix in some output filenames.
  • Updated the DelineateIt UI to improve the language around what the model should do when it encounters invalid geometry. The default is now that it should skip invalid geometry.
  • Updating how threat rasters are handled in Habitat Quality to address a few related and common usability issues for the model. First, threat rasters are now aligned to the LULC instead of the intersection of the whole stack. This means that the model now handles threat inputs that do not all completely overlap the LULC (they must all still be in the same projection). Second, nodata values in threat rasters are converted to a threat value of 0. Any threat pixel values other than 0 or nodata are interpreted as a threat value of 1.
  • Updating the psutil requirement to avoid a possible import issue when building binaries under WINE. Any version of psutil should work except for 5.6.0.
  • InVEST sample data was re-organized to simply have one folder per model. New datastacks were added for SDR, NDR, Seasonal Water Yield, Annual Water Yield, DelineateIt, and Coastal Vulnerability.
  • Fixed an issue with NDR where the model was not properly checking for the bounds of the raster, which could in some cases lead to exceptions being printed to the command-line. The model now correctly checks for these raster boundaries.
  • Habitat Risk Assessment model supports points and lines – in addition to previously supported polygons and rasters – for habitats or stressors.
  • Updated raster percentile algorithms in Scenic Quality and Wave Energy models to use a more efficient and reliable raster percentile function from pygeoprocessing.
  • InVEST is now compatible with pygeoprocessing 1.9.1.
  • All InVEST models now have an ARGS_SPEC object that contains metadata about the model and describes the model’s arguments. Validation has been reimplemented across all models to use these ARGS_SPEC objects.
  • The results suffix key for the Wave Energy and Wind Energy models has been renamed results_suffix (was previously suffix). This is for consistency across InVEST models.
  • Speed and memory optimization of raster processing in the Recreation model.
  • Removed a constraint in Coastal Vulnerability so the AOI polygon no longer needs to intersect the continental shelf contour line. So the AOI can now be used exclusively to delineate the coastal area of interest.
  • Improved how Coastal Vulnerability calculates local wind-driven waves. This requires a new bathymetry raster input and implements equation 10 of the User Guide. Also minor updates to fields in intermediate outputs, notably a ‘shore_id’ field is now the unique ID for joining tables and FIDs are no longer used.
  • Added a status message to the UI if a datastack file fails to load, instead of staying silent.
  • Correcting an issue with repository fetching in the InVEST Makefile. Managed repositories will now be fetched and updated to the expected revision even if the repository already exists.
  • Fixed the duplicate results_suffix input in Wave Energy UI.
  • Added a human-friendly message on NDR model KeyError.
  • Adding a check to Annual Water Yield to ensure that the LULC_veg column has correct values.
  • Improved how Seasonal Water Yield handles nodata values when processing floating-point precipitation and quickflow rasters.
  • Add SDR feature to model sediment deposition across the landscape.
  • Fixed an issue that would cause an exception if SDR landcover map was masked out if the original landcover map had no-nodata value defined.
  • Fixed an issue in the SDR model that could cause reported result vector values to not correspond with known input vectors if the input watershed vector was not an ESRI Shapefile.
  • Fixed issue in Seasonal Water Yield model that would cause an unhandled exception when input rasters had areas of a valid DEM but nodata in other input layers that overlap that dem.
  • Fixed an issue in the NDR model that would cause an exception if the critical length of a landcover field was set to 0.
  • Implemented PEP518-compatible build system definition in the file pyproject.toml. This should make it easier to install natcap.invest from a source distribution.
  • Fixed a TypeError issue in Seasonal Water Yield that would occur when the Land-Use/Land-Cover raster did not have a defined nodata value. This case is now handled correctly.
  • The binary build process for InVEST on Windows (which includes binaries based on PyInstaller and an NSIS Installer package) has been migrated to 32-bit Python 3.7. The build itself is taking place on AppVeyor, and the configuration for this is contained within appveyor.yml. Various python scripts involved in the distribution and release processes have been updated for compatibility with python 3.7 as a part of this migration.
  • Fixed an IndexError issue in Wave Energy encountered in runs using the global wave energy dataset. This error was the result of an incorrect spatial query of points and resulted in some wave energy points being double-counted.
  • Fixed taskgraph-related issues with Habitat Risk Assessment where 1) asynchronous mode was failing due to missing task dependencies and 2) avoided recomputation was confounded by two tasks modifying the same files.
  • Fixed an issue with Habitat Quality where the model was incorrectly expecting the sensitivity table to have a landcover code of 0.
  • The InVEST CLI has been completely rebuilt to divide functionality into various topic-specific subcommands. The various internal consumers of this API have been updated accordingly. invest --help will contain details of the new interface.
  • Updated the InVEST Launcher to list the human-readable model names rather than the internal model identifiers.
  • Updated Coastal Vulnerability Model with significant speedups including ~40x speedup for geomorphology process and ~3x speedup for wind exposure process. Also saving an intermediate vector with wave energy values and a geomorphology vector with points that were assigned the geomorphology_fill_value.
  • Updated trove classifiers to indicate support for python versions 2.7, 3.6 and 3.7.
  • Updated all InVEST models to be compatible with a Python 2.7 or a Python 3.6 environment. Also tested all models against GDAL versions 2.2.4 and 2.4.1.
  • Fixed an issue with Habitat Quality where convolutions over threat rasters were not excluding nodata values, leading to incorrect outputs. Nodata values are now handled correctly and excluded from the convolution entirely.
  • Updated the subpackage natcap.invest.ui to work with python 3.6 and later and also to support the PySide2 bindings to Qt5.
  • InVEST Coastal Blue Carbon model now writes out a net present value raster for the year of the current landcover, each transition year, and the final analysis year (if provided).
  • Correcting an issue with InVEST Coastal Blue Carbon where incorrect configuration of a nodata value would result in -inf values in output rasters. Now, any values without a defined reclassification rule that make it past validation will be written out as nodata.
  • DelineateIt has been reimplemented using the latest version of pygeoprocessing (and the watershed delineation routine it provides) and now uses taskgraph for avoiding unnecessary recomputation.
  • Fixed a bug in Recreation Model that was causing server-side code to execute twice for every client-side call.
  • Fixed a bug in Recreation model that did not apply results_suffix to the monthly_table.csv output.
  • Various fixes in Coastal Vulnerability Model. CSV output files now have FID column for joining to vector outputs. results_suffix can be used without triggering task re-execution. Raster processing maintains original resolution of the input raster so long as it is projected. Otherwise resamples to model_resolution.
  • Fixed a bug in Coastal Vulnerability model’s task graph that sometimes caused an early task to re-execute when it should be deemed pre-calculated.
  • Fixed a bug in the pollination model that would cause outputs to be all 0 rasters if all the relative_abundance fields in the guild table were integers.
  • Fixed a file cache flushing issue observed on Debian in utils.exponential_decay_kernel_raster that would cause an exponential kernel raster to contain random values rather than expected value.
  • Added a new InVEST model: Urban Flood Risk Mitigation.
  • Fixed an issue in the SDR model that would cause an unhandled exception if either the erosivity or erodibility raster had an undefined nodata value.
  • Added a new InVEST model: Urban Cooling Model.

3.7.0 (2019-05-09)

  • Refactoring Coastal Vulnerability (CV) model. CV now uses TaskGraph and Pygeoprocessing >=1.6.1. The model is now largely vector-based instead of raster-based. Fewer input datasets are required for the same functionality. Runtime in sycnhronous mode is similar to previous versions, but runtime can be reduced with multiprocessing. CV also supports avoided recomputation for successive runs in the same workspace, even if a different file suffix is used. Output vector files are in CSV and geopackage formats.
  • Model User Interface ‘Report an Issue’ link points to our new community.naturalcapitalproject.org
  • Correcting an issue with the Coastal Blue Carbon preprocessor where using misaligned landcover rasters would cause an exception to be raised.
  • Correcting an issue with RouteDEM where runs of the tool with Flow Direction enabled would cause the tool to crash if n_workers > 0.
  • Correcting an issue with Habitat Quality’s error checking where nodata values in landcover rasters were not being taken into account.
  • Valuation is now an optional component of the InVEST Scenic Quality model.
  • Fixing a bug in the percentiles algorithm used by Scenic Quality that would result in incorrect visual quality outputs.
  • Carbon Model and Crop Production models no longer crash if user-input rasters do not have a nodata value defined. In this case these models treat all pixel values as valid data.
  • Adding bitbucket pipelines and AppVeyor build configurations.
  • Refactoring Recreation Model client to use taskgraph and the latest pygeoprocessing. Avoided re-computation from taskgraph means that successive model runs with the same AOI and gridding option can re-use PUD results and avoid server communication entirely. Successive runs with the same predictor data will re-use intermediate geoprocessing results. Multiprocessing offered by taskgraph means server-side PUD calculations and client-side predictor data processing can happen in parallel. Some output filenames have changed.
  • Upgrading to SDR to use new PyGeoprocessing multiflow routing, DEM pit filling, contiguous stream extraction, and TaskGraph integration. This also includes a new TaskGraph feature that avoids recomputation by copying results from previous runs so long as the expected result would be identical. To use this feature, users must execute successive runs of SDR in the same workspace but use a different file suffix. This is useful when users need to do a parameter study or run scenarios with otherwise minor changes to inputs.
  • Refactoring Habitat Risk Assessment (HRA) Model to use TaskGraph >= 0.8.2 and Pygeoprocessing >= 1.6.1. The HRA Proprocessor is removed and its previous functionality was simplified and merged into the HRA model itself. The model will no longer generate HTML plots and tables.
  • Adding a software update notification button, dialog, and a link to the download page on the User Interface when a new InVEST version is available.
  • Migrating the subversion sample and test data repositories to Git LFS repositories on BitBucket. Update the repository URL and fetch commands on Makefile accordingly.
  • Fixing a bug in Habitat Quality UI where the absence of the required half_saturation_constant variable did not raise an exception.
  • Adding encoding=’utf-8-sig’ to pandas.read_csv() to support utils.build_lookup_from_csv() to read CSV files encoded with UTF-8 BOM (byte-order mark) properly.

3.6.0 (2019-01-30)

  • Correcting an issue with the InVEST Carbon Storage and Sequestration model where filepaths containing non-ASCII characters would cause the model’s report generation to crash. The output report is now a UTF-8 document.
  • Refactoring RouteDEM to use taskgraph and the latest pygeoprocessing (>=1.5.0). RouteDEM now fills hydrological sinks and users have the option to use either of the D8 or Multiple Flow Direction (MFD) routing algorithms.
  • Adding a new input to the InVEST Settings window to allow users to customize the value that should be used for the n_workers parameter in taskgraph-enabled models. This change involves removing the “Number of Parallel Workers” input from the model inputs pane for some models in favor of this new location. The default value for this setting is -1, indicating synchronous (non-threaded, non-multiprocessing) execution of tasks.
  • Removing Scenario Generator: Rule-based model.
  • Fixing a bug in Hydropower model where watershed aggregations would be incorrect if a watershed is partially covering nodata raster values. Nodata values are now ignored in zonal statistics. Numerical results change very slightly in the case where a watershed only includes a few nodata pixels.
  • Adding TaskGraph functionality to GLOBIO model.
  • Adding some TaskGraph functionality to Scenario Generator: Proximity.
  • Fixing an issue with the InVEST Fisheries model that would prevent the model from batch-processing a directory of population tables. The model will now process these files as expected.
  • Reimplementing Crop Production models using taskgraph.
  • Fixing an issue with Crop Production Regression’s result_table.csv where the ‘production_modeled’ and ‘<nutrient>_modeled’ values calculated for each crop were done so using the same crop raster (e.g. wheat, soybean, and barley values were all based on soybean data).
  • Hydropower subwatershed results now include all the same metrics as the watershed results, with the exception of economic valuation metrics.
  • Reimplementing the Hydropower model using taskgraph.
  • Reimplementing the Carbon model using taskgraph.
  • Fixing an issue with Coastal Blue Carbon validation to allow column names to ignore case.
  • Updating core carbon forest edge regression data coefficient to drop impossible negative coefficients.
  • Fixing an issue with the Scenario Generator: Proximity model that would raise an exception if no AOI were passed in even though the AOI is optional.
  • Removing Overlap Analysis and Overlap Analysis: Management Zones.
  • Removing Habitat Suitability.
  • Added comprehensive error checking to hydropower model to test for the VERY common errors of missing biophysical, demand, and valuation coefficients in their respective tables.
  • Fixing an issue with Hydropower Water Yield (“Annual Water Yield”) where valuation would never be triggered when running the model through the User Interface. And a related issue where the model would crash if a valuation table was provided but a demand table was not. The UI no longer validates that config.
  • Fixing an issue with how logging is captured when a model is run through the InVEST User Interface. Now, logging from any thread started by the executor thread will be written to the log file, which we expect to aid in debugging.
  • Fixing an issue with Scenic Quality where viewpoints outside of the AOI were not being properly excluded. Viewpoints are now excluded correctly.
  • The crop production model has been refactored to drop the “aggregate ID” concept when summarizing results across an aggregate polygon. The model now uses the polygon FIDs internally and externally when producing the result summary table.
  • Correcting the rating instructions in the criteria rating instructions on how the data quality (DQ) and weight should be rated in the HRA Preprocessor. A DQ score of 1 should represent better data quality whereas the score of 3 is worse data quality. A weight score of 1 is more important, whereas that of 3 is less important.
  • Fixing a case where a zero discount rate and rate of change in the carbon model would cause a divide by zero error.

3.5.0 (2018-08-14)

  • Bumped pygeoprocessing requirement to pygeoprocessing>=1.2.3.
  • Bumped taskgraph requirement to taskgraph>=0.6.1.
  • Reimplemented the InVEST Scenic Quality model. This new version removes the ‘population’ and ‘overlap’ postprocessing steps, updates the available valuation functions and greatly improves the runtime and memory-efficiency of the model. See the InVEST User’s Guide chapter for more information.
  • Updated Recreation server’s database to include metadata from photos taken from 2005-2017 (previous range was 2005-2014). The new range is reflected in the UI.
  • Fixed an issue with the InVEST binary build where binaries on Windows would crash with an error saying Python27.dll could not be loaded.
  • Fixed an issue in the Rule-Based Scenario Generator UI where vector column names from override and constraint layers were not being loaded. This bug caused the field ‘UNKNOWN’ to be passed to the model, causing an error.
  • Fixed an issue with the InVEST UI (all models), where attempting to drag-and-drop a directory onto a model input would cause the application to crash.
  • Coastal Vulnerability UI now specifies a number of reasonable defaults for some numeric inputs.
  • Fixed an issue with the Fisheries UI where alpha and beta parameter inputs were incorrectly disabled for the Ricker recruitment function.
  • InVEST now uses a Makefile to automate the build processes. GNU Make is required to use the Makefile. See README.rst for instructions on building InVEST. This replaces the old pavement.py build entrypoint, which has been removed.
  • Fixed an issue with the InVEST UI (all models), where attempting to drag-and-drop a directory onto a model input would cause the application to crash.
  • Fixed an issue with Forest Carbon Edge Effect where the UI layer was always causing the model to run with only the aboveground carbon pool
  • Added functionality to the InVEST UI so that Dropdown inputs can now map dropdown values to different output values.
  • Fixed an issue in the Crop Production Percentile model that would treat the optional AOI vector field as a filename and crash on a run if it were empty.
  • Fixing an issue in the Pollination Model that would cause occasional crashes due to a missing dependent task; it had previously been patched by setting taskgraph to operate in single thread mode. This restores multithreading in the pollination model.
  • Fixed an issue in the water yield / hydropower model that would skip calculation of water demand tables when “water scarcity” was enabled.
  • Fixed an issue in the model data of the crop production model where some crops were using incorrect climate bin rasters. Since the error was in the data and not the code, users will need to download the most recent version of InVEST’s crop model data during the installation step to get the fix.

3.4.4 (2018-03-26)

  • InVEST now requires GDAL 2.0.0 and has been tested up to GDAL 2.2.3. Any API users of InVEST will need to use GDAL version >= 2.0. When upgrading GDAL we noticed slight numerical differences in our test suite in both numerical raster differences, geometry transforms, and occasionally a single pixel difference when using gdal.RasterizeLayer. Each of these differences in the InVEST test suite is within a reasonable numerical tolerance and we have updated our regression test suite appropriately. Users comparing runs between previous versions of InVEST may also notice reasonable numerical differences between runs.
  • Added a UI keyboard shortcut for showing documentation. On Mac OSX, this will be Command-?. On Windows, GNOME and KDE, this will be F1.
  • Patching an issue in NDR that was using the nitrogen subsurface retention efficiency for both nitrogen and phosphorous.
  • Fixed an issue with the Seasonal Water Yield model that incorrectly required a rain events table when the climate zone mode was in use.
  • Fixed a broken link to local and online user documentation from the Seasonal Water Yield model from the model’s user interface.

3.4.3 (2018-03-26)

  • Fixed a critical issue in the carbon model UI that would incorrectly state the user needed a “REDD Priority Raster” when none was required.
  • Fixed an issue in annual water yield model that required subwatersheds even though it is an optional field.
  • Fixed an issue in wind energy UI that was incorrectly validating most of the inputs.

3.4.2 (2017-12-15)

  • Fixed a cross-platform issue with the UI where logfiles could not be dropped onto UI windows.
  • Model arguments loaded from logfiles are now cast to their correct literal value. This addresses an issue where some models containing boolean inputs could not have their parameters loaded from logfiles.
  • Fixed an issue where the Pollination Model’s UI required a farm polygon. It should have been optional and now it is.
  • Fixing an issue with the documentation and forums links on the InVEST model windows. The links now correctly link to the documentation page or forums as needed.
  • Fixing an issue with the FileSystemRunDialog where pressing the ‘X’ button in the corner of the window would close the window, but not reset its state. The window’s state is now reset whenever the window is closed (and the window cannot be closed when the model is running)

3.4.1 (2017-12-11)

  • In the Coastal Blue Carbon model, the interest_rate parameter has been renamed to inflation_rate.
  • Fixed issues with sample parameter sets for InVEST Habitat Quality, Habitat Risk Assessment, Coastal Blue Carbon, and Coastal Blue Carbon Preprocessors. All sample parameter sets now have the correct paths to the model’s input files, and correctly note the name of the model that they apply to.
  • Added better error checking to the SDR model for missing ws_id and invalid ws_id values such as None or some non-integer value. Also added tests for the SDR validation module.

3.4.0 (2017-12-03)

  • Fixed an issue with most InVEST models where the suffix was not being reflected in the output filenames. This was due to a bug in the InVEST UI, where the suffix args key was assumed to be 'suffix'. Instances of InVESTModel now accept a keyword argument to defined the suffix args key.
  • Fixed an issue/bug in Seasonal Water Yield that would occur when a user provided a datastack that had nodata values overlapping with valid DEM locations. Previously this would generate an NaN for various biophysical values at that pixel and cascade it downslope. Now any question of nodata on a valid DEM pixel is treated as “0”. This will make serious visual artifacts on the output, but should help users pinpoint the source of bad data rather than crash.
  • Refactored all but routing components of SDR to use PyGeoprocessing 0.5.0 and laid a consistent raster floating point type of ‘float32’. This will cause numerically insignificant differences between older versions of SDR and this one. But differences are well within the tolerance of the overall error of the model and expected error rate of data. Advantages are smaller disk footprint per run, cleaner and more maintainable design, and a slight performance increase.
  • Bug fixed in SDR that would align the output raster stack to match with the landcover pixel stack even though the rest of the rasters are scaled and clipped to the DEM.
  • When loading parameters from a datastack, parameter set or logfile, the UI will check that the model that created the file being loaded matches the name of the model that is currently running. If there is a mismatch, a dialog is presented for the user to confirm or cancel the loading of parameters. Logfiles from IUI (which do not have clearly-recorded modelname or InVEST version information) can still have their arguments parsed, but the resulting model name and InVEST version will be set to "UNKNOWN".
  • Data Stack files (*.invest.json, *.invest.tar.gz) can now be dragged and dropped on an InVEST model window, which will prompt the UI to load that parameter set.
  • Spatial inputs to Coastal Blue Carbon are now aligned as part of the model. This resolves a longstanding issue with the model where inputs would need to perfectly overlap (even down to pixel indices), or else the model would yield strange results.
  • The InVEST UI now contains a submenu for opening a recently-opened datastack. This submenu is automatically populated with the 10 most recently-opened datastacks for the current model.
  • Removed vendored natcap.invest.dbfpy subpackage.
  • Removed deprecated natcap.invest.fileio module.
  • Removed natcap.invest.iui UI subpackage in favor of a new UI framework found at natcap.invest.ui. This new UI features a greatly improved API, good test coverage, support for Qt4 and Qt5, and includes updates to all InVEST models to support validation of model arguments from a python script, independent of the UI.
  • Updated core model of seasonal water yield to allow for negative L_avail.
  • Updated RouteDEM to allow for file suffixes, finer control over what DEM routing algorithms to run, and removal of the multiple stepped stream threshold classification.
  • Redesign/refactor of pollination model. Long term bugs in the model are resolved, managed pollinators added, and many simplifications to the end user’s experience. The updated user’s guide chapter is available here: http://data.naturalcapitalproject.org/nightly-build/invest-users-guide/html/croppollination.html
  • Scenario Generator - Rule Based now has an optional input to define a seed. This input is used to seed the random shuffling of parcels that have equal priorities.
  • InVEST on mac is now distributed as a single application bundle, allowing InVEST to run as expected on mac OSX Sierra. Individual models are selected and launched from a new launcher window.
  • The InVEST CLI now has a GUI model launcher: $ invest launcher
  • Updated the Coastal Blue Carbon model to improve handling of blank lines in input CSV tables and improve memory efficiency of the current implementation.
  • Improved the readability of a cryptic error message in Coastal Vulnerability that is normally raised when the depth threshold is too high or the exposure proportion is too low to detect any shoreline segments.
  • Adding InVEST HTML documentation to the Mac disk image distribution.
  • Upgrading dependency of PyGeoprocessing to 0.3.3. This fixes a memory leak associated with any model that aggregates rasters over complicated overlapping polygons.
  • Adding sample data to Blue Carbon model that were missing.
  • Deprecating the InVEST Marine Water Quality model. This also removes InVEST’s dependancy on the pyamg package which has been removed from REQUIREMENTS.TXT.
  • Deprecating the ArcGIS-based Coastal Protection model and ArcGIS-based data-preprocessing scripts. The toolbox and scripts may still be found at https://bitbucket.org/natcap/invest.arcgis.
  • Fixing an issue in the carbon edge effect model that caused output values in the shapefile to be rounded to the nearest integer.
  • Fixing issue in SDR model that would occasionally cause users to see errors about field widths in the output shapefile generation.
  • Updated the erodibility sample raster that ships with InVEST for the SDR model. The old version was in US units, in this version we convert to SI units as the model requires, and clipped the raster to the extents of the other stack to save disk space.

3.3.3 (2017-02-06)

  • Fixed an issue in the UI where the carbon model wouldn’t accept negative numbers in the price increase of carbon.
  • RouteDEM no longer produces a “tiled_dem.tif” file since that functionality is being deprecated in PyGeoprocessing.
  • Fixing an issue in SDR where the optional drainage layer would not be used in most of the SDR biophysical calculations.
  • Refactoring so water yield pixels with Kc and et0 equal to be 0 now yields a 0.0 value of water yield on that pixel rather than nodata.
  • Light optimization refactor of wind energy model that improves runtimes in some cases by a factor of 2-3.
  • Performance optimizations to HRA that improve runtimes by approximately 30%.
  • Fixed a broken UI link to Seasonal Water Yield’s user’s guide.
  • Fixed an issue with DelineateIT that caused ArcGIS users to see both the watershed and inverse watershed polygons when viewing the output of the tool.
  • Upgrading dependency to PyGeoprocessing 0.3.2.
  • Fixed an issue with SDR that caused the LS factor to be an order of magnitue too high in areas where the slope was greater than 9%. In our sample case this caused sediment export estimates to be about 6% too high, but in cases where analyses are run over steep slopes the error would have been greater.
  • paver check now warns if the PYTHONHOME environment variable is set.
  • API docs now correctly reflect installation steps needed for python development headers on linux.
  • Fixed a side effect in the InVEST user interface that would cause tempfile.tempdir to be set and then not be reset after a model run is finished.
  • The InVEST user interface will now record GDAL/OGR log messages in the log messages window and in the logfile written to the workspace.
  • Updated branding and usability of the InVEST installer for Windows, and the Mac Disk Image (.dmg).

3.3.2 (2016-10-17)

  • Partial test coverage for HRA model.
  • Full test coverage for Overlap Analysis model.
  • Full test coverage for Finfish Aquaculture.
  • Full test coverage for DelineateIT.
  • Full test coverage for RouteDEM.
  • Fixed an issue in Habitat Quality where an error in the sample table or malformed threat raster names would display a confusing message to the user.
  • Full test coverage for scenario generator proximity model.
  • Patching an issue in seasonal water yield that causes an int overflow error if the user provides a floating point landcover map and the nodata value is outside of the range of an int64.
  • Full test coverage for the fisheries model.
  • Patched an issue that would cause the Seasonal Water Edge model to crash when the curve number was 100.
  • Patching a critical issue with forest carbon edge that would give incorrect results for edge distance effects.
  • Patching a minor issue with forest carbon edge that would cause the model to crash if only one interpolation point were selected.
  • Full test coverage for pollination model.
  • Removed “farms aggregation” functionality from the InVEST pollination model.
  • Full test coverage for the marine water quality model.
  • Full test coverage for GLOBIO model.
  • Full test coverage for carbon forest edge model.
  • Upgraded SciPy dependancy to 0.16.1.
  • Patched bug in NDR that would cause a phosphorus density to be reported per pixel rather than total amount of phosporous in a pixel.
  • Corrected an issue with the uses of buffers in the euclidean risk function of Habitat Risk Assessment. (issue #3564)
  • Complete code coverage tests for Habitat Quality model.
  • Corrected an issue with the Fisheries_Inputs.csv sample table used by Overlap Analysis. (issue #3548)
  • Major modifications to Terrestrial Carbon model to include removing the harvested wood product pool, uncertainty analysis, and updated efficient raster calculations for performance.
  • Fixed an issue in GLOBIO that would cause model runs to crash if the AOI marked as optional was not present.
  • Removed the deprecated and incomplete Nearshore Wave and Erosion model (natcap.invest.nearshore_wave_and_erosion).
  • Removed the deprecated Timber model (natcap.invest.timber).
  • Fixed an issue where seasonal water yield would raise a divide by zero error if a watershed polygon didn’t cover a valid data region. Now sets aggregation quantity to zero and reports a warning in the log.
  • natcap.invest.utils.build_file_registry now raises a ValueError if a path is not a string or list of strings.
  • Fixed issues in NDR that would indicate invalid values were being processed during runtimes by skipping the invalid calculations in the first place rather than calculating them and discarding after the fact.
  • Complete code coverage tests for NDR model.
  • Minor (~10% speedup) performance improvements to NDR.
  • Added functionality to recreation model so that the monthly_table.csv file now receives a file suffix if one is provided by the user.
  • Fixed an issue in SDR where the m exponent was calculated incorrectly in many situations resulting in an error of about 1% in total export.
  • Fixed an issue in SDR that reported runtime overflow errors during normal processing even though the model completed without other errors.

3.3.1 (2016-06-13)

  • Refactored API documentation for readability, organization by relevant topics, and to allow docs to build on invest.readthedocs.io,
  • Installation of natcap.invest now requires natcap.versioner. If this is not available on the system at runtime, setuptools will make it available at runtime.
  • InVEST Windows installer now includes HISTORY.rst as the changelog instead of the old InVEST_Updates_<version> files.
  • Habitat suitability model is generalized and released as an API only accessible model. It can be found at natcap.invest.habitat_suitability.execute. This model replaces the oyster habitat suitability model.
    • The refactor of this model requires an upgrade to numpy >= 1.11.0.
  • Fixed a crash in the InVEST CLI where calling invest without a parameter would raise an exception on linux-based systems. (Issue #3528)
  • Patched an issue in Seasonal Water Yield model where a nodata value in the landcover map that was equal to MAX_INT would cause an overflow error/crash.
  • InVEST NSIS installer will now optionally install the Microsoft Visual C++ 2008 redistributable on Windows 7 or earlier. This addresses a known issue on Windows 7 systems when importing GDAL binaries (Issue #3515). Users opting to install this redistributable agree to abide by the terms and conditions therein.
  • Removed the deprecated subpackage natcap.invest.optimization.
  • Updated the InVEST license to legally define the Natural Capital Project.
  • Corrected an issue in Coastal Vulnerability where an output shapefile was being recreated for each row, and where field values were not being stored correctly.
  • Updated Scenario Generator model to add basic testing, file registry support, PEP8 and PEP257 compliance, and to fix several bugs.
  • Updated Crop Production model to add a simplified UI, faster runtime, and more testing.

3.3.0 (2016-03-14)

  • Refactored Wind Energy model to use a CSV input for wind data instead of a Binary file.
  • Redesigned InVEST recreation model for a single input streamlined interface, advanced analytics, and refactored outputs. While the model is still based on “photo user days” old model runs are not backward compatable with the new model or interface. See the Recreation Model user’s guide chapter for details.
    • The refactor of this model requires an upgrade to GDAL >=1.11.0 <2.0 and numpy >= 1.10.2.
  • Removed nutrient retention (water purification) model from InVEST suite and replaced it with the nutrient delivery ratio (NDR) model. NDR has been available in development relseases, but has now officially been added to the set of Windows Start Menu models and the “under development” tag in its users guide has been removed. See the InVEST user’s guide for details between the differences and advantages of NDR over the old nutrient model.
  • Modified NDR by adding a required “Runoff Proxy” raster to the inputs. This allows the model to vary the relative intensity of nutrient runoff based on varying precipitation variability.
  • Fixed a bug in the Area Change rule of the Rule-Based Scenario Generator, where units were being converted incorrectly. (Issue #3472) Thanks to Fosco Vesely for this fix.
  • InVEST Seasonal Water Yield model released.
  • InVEST Forest Carbon Edge Effect model released.
  • InVEST Scenario Generator: Proximity Based model released and renamed the previous “Scenario Generator” to “Scenario Generator: Rule Based”.
  • Implemented a blockwise exponential decay kernel generation function, which is now used in the Pollination and Habitat Quality models.
  • GLOBIO now uses an intensification parameter and not a map to average all agriculture across the GLOBIO 8 and 9 classes.
  • GLOBIO outputs modified so core outputs are in workspace and intermediate outputs are in a subdirectory called ‘intermediate_outputs’.
  • Fixed a crash with the NDR model that could occur if the DEM and landcover maps were different resolutions.
  • Refactored all the InVEST model user interfaces so that Workspace defaults to the user’s home “Documents” directory.
  • Fixed an HRA bug where stessors with a buffer of zero were being buffered by 1 pixel
  • HRA enhancement which creates a common raster to burn all input shapefiles onto, ensuring consistent alignment.
  • Fixed an issue in SDR model where a landcover map that was smaller than the DEM would create extraneous “0” valued cells.
  • New HRA feature which allows for “NA” values to be entered into the “Ratings” column for a habitat / stressor pair in the Criteria Ratings CSV. If ALL ratings are set to NA, the habitat / stressor will be treated as having no interaction. This means in the model, that there will be no overlap between the two sources. All rows parameters with an NA rating will not be used in calculating results.
  • Refactored Coastal Blue Carbon model for greater speed, maintainability and clearer documentation.
  • Habitat Quality bug fix when given land cover rasters with different pixel sizes than threat rasters. Model would use the wrong pixel distance for the convolution kernel.
  • Light refactor of Timber model. Now using CSV input attribute file instead of DBF file.
  • Fixed clipping bug in Wave Energy model that was not properly clipping polygons correctly. Found when using global data.
  • Made the following changes / updates to the coastal vulnerability model:
    • Fixed a bug in the model where the geomorphology ranks were not always being used correctly.
    • Removed the HTML summary results output and replaced with a link to a dashboard that helps visualize and interpret CV results.
    • Added a point shapefile output: ‘outputs/coastal_exposure.shp’ that is a shapefile representation of the corresponding CSV table.
    • The model UI now requires the ‘Relief’ input. No longer optional.
    • CSV outputs and Shapefile outputs based on rasters now have x, y coorinates of the center of the pixel instead of top left of the pixel.
  • Turning setuptools’ zip_safe to False for consistency across the Natcap Namespace.
  • GLOBIO no longer requires user to specify a keyfield in the AOI.
  • New feature to GLOBIO to summarize MSA by AOI.
  • New feature to GLOBIO to use a user defined MSA parameter table to do the MSA thresholds for infrastructure, connectivity, and landuse type
  • Documentation to the GLOBIO code base including the large docstring for ‘execute’.

3.2.0 (2015-05-31)

InVEST 3.2.0 is a major release with the addition of several experimental models and tools as well as an upgrade to the PyGeoprocessing core:

  • Upgrade to PyGeoprocessing v0.3.0a1 for miscelaneous performance improvements to InVEST’s core geoprocessing routines.
  • An alpha unstable build of the InVEST crop production model is released with partial documentation and sample data.
  • A beta build of the InVEST fisheries model is released with documentation and sample data.
  • An alpha unstable build of the nutrient delivery ratio (NDR) model is available directly under InVEST’s instalation directory at invest-x86/invest_ndr.exe; eventually this model will replace InVEST’s current “Nutrient” model. It is currently undocumented and unsupported but inputs are similar to that of InVEST’s SDR model.
  • An alpha unstable build of InVEST’s implementation of GLOBIO is available directly under InVEST’s instalation directory at invest-x86/invest_globio.exe. It is currently undocumented but sample data are provided.
  • DelinateIT, a watershed delination tool based on PyGeoprocessing’s d-infinity flow algorithm is released as a standalone tool in the InVEST repository with documentation and sample data.
  • Miscelaneous performance patches and bug fixes.

3.1.3 (2015-04-23)

InVEST 3.1.3 is a hotfix release patching a memory blocking issue resolved in PyGeoprocessing version 0.2.1. Users might have experienced slow runtimes on SDR or other routed models.

3.1.2 (2015-04-15)

InVEST 3.1.2 is a minor release patching issues mostly related to the freshwater routing models and signed GDAL Byte datasets.

  • Patching an issue where some projections were not regognized and InVEST reported an UnprojectedError.
  • Updates to logging that make it easier to capture logging messages when scripting InVEST.
  • Shortened water yield user interface height so it doesn’t waste whitespace.
  • Update PyGeoprocessing dependency to version 0.2.0.
  • Fixed an InVEST wide issue related to bugs stemming from the use of signed byte raster inputs that resulted in nonsensical outputs or KeyErrors.
  • Minor performance updates to carbon model.
  • Fixed an issue where DEMS with 32 bit ints and INT_MAX as the nodata value nodata value incorrectly treated the nodata value in the raster as a very large DEM value ultimately resulting in rasters that did not drain correctly and empty flow accumulation rasters.
  • Fixed an issue where some reservoirs whose edges were clipped to the edge of the watershed created large plateaus with no drain except off the edge of the defined raster. Added a second pass in the plateau drainage algorithm to test for these cases and drains them to an adjacent nodata area if they occur.
  • Fixed an issue in the Fisheries model where the Results Suffix input was invariably initializing to an empty string.
  • Fixed an issue in the Blue Carbon model that prevented the report from being generated in the outputs file.

3.1.1 (2015-03-13)

InVEST 3.1.1 is a major performance and memory bug patch to the InVEST toolsuite. We recommend all users upgrade to this version.

  • Fixed an issue surrounding reports of SDR or Nutrient model outputs of zero values, nodata holes, excessive runtimes, or out of memory errors. Some of those problems happened to be related to interesting DEMs that would break the flat drainage algorithm we have inside RouteDEM that adjusted the heights of those regions to drain away from higher edges and toward lower edges, and then pass the height adjusted dem to the InVEST model to do all its model specific calculations. Unfortunately this solution was not amenable to some degenerate DEM cases and we have now adjusted the algorithm to treat each plateau in the DEM as its own separate region that is processed independently from the other regions. This decreases memory use so we never effectively run out of memory at a minor hit to overall runtime. We also now adjust the flow direction directly instead of adjust the dem itself. This saves us from having to modify the DEM and potentially get it into a state where a drained plateau would be higher than its original pixel neighbors that used to drain into it.

There are side effects that result in sometimes large changes to un calibrated runs of SDR or nutrient. These are related to slightly different flow directions across the landscape and a bug fix on the distance to stream calculation.

  • InVEST geoprocessing now uses the PyGeoprocessing package (v0.1.4) rather than the built in functionality that used to be in InVEST. This will not affect end users of InVEST but may be of interest to users who script InVEST calls who want a standalone Python processing package for raster stack math and hydrological routing. The project is hosted at https://bitbucket.org/richpsharp/pygeoprocessing.
  • Fixed an marine water quality issue where users could input AOIs that were unprojected, but output pixel sizes were specified in meters. Really the output pixel size should be in the units of the polygon and are now specified as such. Additionally an exception is raised if the pixel size is too small to generate a numerical solution that is no longer a deep scipy error.
  • Added a suffix parameter to the timber and marine water quality models that append a user defined string to the output files; consistent with most of the other InVEST models.
  • Fixed a user interface issue where sometimes the InVEST model run would not open a windows explorer to the user’s workspace. Instead it would open to C:User[..]My Documents. This would often happen if there were spaces in the the workspace name or “/” characters in the path.
  • Fixed an error across all InVEST models where a specific combination of rasters of different cell sizes and alignments and unsigned data types could create errors in internal interpolation of the raster stacks. Often these would appear as ‘KeyError: 0’ across a variety of contexts. Usually the ‘0’ was an erroneous value introduced by a faulty interpolation scheme.
  • Fixed a MemoryError that could occur in the pollination and habitat quality models when the the base landcover map was large and the biophysical properties table allowed the effect to be on the order of that map. Now can use any raster or range values with only a minor hit to runtime performance.
  • Fixed a serious bug in the plateau resolution algorithm that occurred on DEMs with large plateau areas greater than 10x10 in size. The underlying 32 bit floating point value used to record small height offsets did not have a large enough precision to differentiate between some offsets thus creating an undefined flow direction and holes in the flow accumulation algorithm.
  • Minor performance improvements in the routing core, in some cases decreasing runtimes by 30%.
  • Fixed a minor issue in DEM resolution that occurred when a perfect plateau was encountered. Rather that offset the height so the plateau would drain, it kept the plateau at the original height. This occurred because the uphill offset was nonexistent so the algorithm assumed no plateau resolution was needed. Perfect plateaus now drain correctly. In practice this kind of DEM was encountered in areas with large bodies of water where the remote sensing algorithm would classify the center of a lake 1 meter higher than the rest of the lake.
  • Fixed a serious routing issue where divergent flow directions were not getting accumulated 50% of the time. Related to a division speed optimization that fell back on C-style modulus which differs from Python.
  • InVEST SDR model thresholded slopes in terms of radians, not percent thus clipping the slope tightly between 0.001 and 1%. The model now only has a lower threshold of 0.00005% for the IC_0 factor, and no other thresholds. We believe this was an artifact left over from an earlier design of the model.
  • Fixed a potential memory inefficiency in Wave Energy Model when computing the percentile rasters. Implemented a new memory efficient percentile algorithm and updated the outputs to reflect the new open source framework of the model. Now outputting csv files that describe the ranges and meaning of the percentile raster outputs.
  • Fixed a bug in Habitat Quality where the future output “quality_out_f.tif” was not reflecting the habitat value given in the sensitivity table for the specified landcover types.

3.1.0 (2014-11-19)

InVEST 3.1.0 (http://www.naturalcapitalproject.org/download.html) is a major software and science milestone that includes an overhauled sedimentation model, long awaited fixes to exponential decay routines in habitat quality and pollination, and a massive update to the underlying hydrological routing routines. The updated sediment model, called SDR (sediment delivery ratio), is part of our continuing effort to improve the science and capabilities of the InVEST tool suite. The SDR model inputs are backwards comparable with the InVEST 3.0.1 sediment model with two additional global calibration parameters and removed the need for the retention efficiency parameter in the biophysical table; most users can run SDR directly with the data they have prepared for previous versions. The biophysical differences between the models are described in a section within the SDR user’s guide and represent a superior representation of the hydrological connectivity of the watershed, biophysical parameters that are independent of cell size, and a more accurate representation of sediment retention on the landscape. Other InVEST improvements to include standard bug fixes, performance improvements, and usability features which in part are described below:

  • InVEST Sediment Model has been replaced with the InVEST Sediment Delivery Ratio model. See the SDR user’s guide chapter for the difference between the two.
  • Fixed an issue in the pollination model where the exponential decay function decreased too quickly.
  • Fixed an issue in the habitat quality model where the exponential decay function decreased too quickly and added back linear decay as an option.
  • Fixed an InVEST wide issue where some input rasters that were signed bytes did not correctly map to their negative nodata values.
  • Hydropower input rasters have been normalized to the LULC size so sampling error is the same for all the input watersheds.
  • Adding a check to make sure that input biophysical parameters to the water yield model do not exceed invalid scientific ranges.
  • Added a check on nutrient retention in case the upstream water yield was less than 1 so that the log value did not go negative. In that case we clamp upstream water yield to 0.
  • A KeyError issue in hydropower was resolved that occurred when the input rasters were at such a coarse resolution that at least one pixel was completely contained in each watershed. Now a value of -9999 will be reported for watersheds that don’t contain any valid data.
  • An early version of the monthly water yield model that was erroneously included in was in the installer; it was removed in this version.
  • Python scripts necessary for running the ArcGIS version of Coastal Protection were missing. They’ve since been added back to the distribution.
  • Raster calculations are now processed by raster block sizes. Improvements in raster reads and writes.
  • Fixed an issue in the routing core where some wide DEMs would cause out of memory errors.
  • Scenario generator marked as stable.
  • Fixed bug in HRA where raster extents of shapefiles were not properly encapsulating the whole AOI.
  • Fixed bug in HRA where any number of habitats over 4 would compress the output plots. Now extends the figure so that all plots are correctly scaled.
  • Fixed a bug in HRA where the AOI attribute ‘name’ could not be an int. Should now accept any type.
  • Fixed bug in HRA which re-wrote the labels if it was run immediately without closing the UI.
  • Fixed nodata masking bug in Water Yield when raster extents were less than that covered by the watershed.
  • Removed hydropower calibration parameter form water yield model.
  • Models that had suffixes used to only allow alphanumeric characters. Now all suffix types are allowed.
  • A bug in the core platform that would occasionally cause routing errors on irregularly pixel sized rasters was fixed. This often had the effect that the user would see broken streams and/or nodata values scattered through sediment or nutrient results.
  • Wind Energy:
    • Added new framework for valuation component. Can now input a yearly price table that spans the lifetime of the wind farm. Also if no price table is made, can specify a price for energy and an annual rate of change.
    • Added new memory efficient distance transform functionality
    • Added ability to leave out ‘landing points’ in ‘grid connection points’ input. If not landing points are found, it will calculate wind farm directly to grid point distances
  • Error message added in Wave Energy if clip shape has no intersection
  • Fixed an issue where the data type of the nodata value in a raster might be different than the values in the raster. This was common in the case of 64 bit floating point values as nodata when the underlying raster was 32 bit. Now nodata values are cast to the underlying types which improves the reliability of many of the InVEST models.

3.0.1 (2014-05-19)

  • Blue Carbon model released.
  • HRA UI now properly reflects that the Resolution of Analysis is in meters, not meters squared, and thus will be applied as a side length for a raster pixel.
  • HRA now accepts CSVs for ratings scoring that are semicolon separated as well as comma separated.
  • Fixed a minor bug in InVEST’s geoprocessing aggregate core that now consistently outputs correct zonal stats from the underlying pixel level hydro outputs which affects the water yield, sediment, and nutrient models.
  • Added compression to InVEST output geotiff files. In most cases this reduces output disk usage by a factor of 5.
  • Fixed an issue where CSVs in the sediment model weren’t open in universal line read mode.
  • Fixed an issue where approximating whether pixel edges were the same size was not doing an approximately equal function.
  • Fixed an issue that made the CV model crash when the coastline computed from the landmass didn’t align perfectly with that defined in the geomorphology layer.
  • Fixed an issue in the CV model where the intensity of local wave exposure was very low, and yielded zero local wave power for the majority of coastal segments.
  • Fixed an issue where the CV model crashes if a coastal segment is at the edge of the shore exposure raster.
  • Fixed the exposure of segments surrounded by land that appeared as exposed when their depth was zero.
  • Fixed an issue in the CV model where the natural habitat values less than 5 were one unit too low, leading to negative habitat values in some cases.
  • Fixed an exponent issue in the CV model where the coastal vulnerability index was raised to a power that was too high.
  • Fixed a bug in the Scenic Quality model that prevented it from starting, as well as a number of other issues.
  • Updated the pollination model to conform with the latest InVEST geoprocessing standards, resulting in an approximately 33% speedup.
  • Improved the UI’s ability to remember the last folder visited, and to have all file and folder selection dialogs have access to this information.
  • Fixed an issue in Marine Water Quality where the UV points were supposed to be optional, but instead raised an exception when not passed in.

3.0.0 (2014-03-23)

The 3.0.0 release of InVEST represents a shift away from the ArcGIS to the InVEST standalone computational platform. The only exception to this shift is the marine coastal protection tier 1 model which is still supported in an ArcGIS toolbox and has no InVEST 3.0 standalone at the moment. Specific changes are detailed below

  • A standalone version of the aesthetic quality model has been developed and packaged along with this release. The standalone outperforms the ArcGIS equivalent and includes a valuation component. See the user’s guide for details.
  • The core water routing algorithms for the sediment and nutrient models have been overhauled. The routing algorithms now correctly adjust flow in plateau regions, address a bug that would sometimes not route large sections of a DEM, and has been optimized for both run time and memory performance. In most cases the core d-infinity flow accumulation algorithm out performs TauDEM. We have also packaged a simple interface to these algorithms in a standalone tool called RouteDEM; the functions can also be referenced from the scripting API in the invest_natcap.routing package.
  • The sediment and nutrient models are now at a production level release. We no longer support the ArcGIS equivalent of these models.
  • The sediment model has had its outputs simplified with major changes including the removal of the ‘pixel mean’ outputs, a direct output of the pixel level export and retention maps, and a single output shapefile whose attribute table contains aggregations of sediment output values. Additionally all inputs to the sediment biophysical table including p, c, and retention coefficients are now expressed as a proportion between 0 and 1; the ArcGIS model had previously required those inputs were integer values between 0 and 1000. See the “Interpreting Results” section of sediment model for full details on the outputs.
  • The nutrient model has had a similar overhaul to the sediment model including a simplified output structure with many key outputs contained in the attribute table of the shapefile. Retention coefficients are also expressed in proportions between 0 and 1. See the “Interpreting Results” section of nutrient model for full details on the outputs.
  • Fixed a bug in Habitat Risk Assessment where the HRA module would incorrectly error if a criteria with a 0 score (meant to be removed from the assessment) had a 0 data quality or weight.
  • Fixed a bug in Habitat Risk Assessment where the average E/C/Risk values across the given subregion were evaluating to negative numbers.
  • Fixed a bug in Overlap Analysis where Human Use Hubs would error if run without inter-activity weighting, and Intra-Activity weighting would error if run without Human Use Hubs.
  • The runtime performance of the hydropower water yield model has been improved.
  • Released InVEST’s implementation of the D-infinity flow algorithm in a tool called RouteDEM available from the start menu.
  • Unstable version of blue carbon available.
  • Unstable version of scenario generator available.
  • Numerous other minor bug fixes and performance enhacnements.

2.6.0 (2013-12-16)

The 2.6.0 release of InVEST removes most of the old InVEST models from the Arc toolbox in favor of the new InVEST standalone models. While we have been developing standalone equivalents for the InVEST Arc models since version 2.3.0, this is the first release in which we removed support for the deprecated ArcGIS versions after an internal review of correctness, performance, and stability on the standalones. Additionally, this is one of the last milestones before the InVEST 3.0.0 release later next year which will transition InVEST models away from strict ArcGIS dependence to a standalone form.

Specifically, support for the following models have been moved from the ArcGIS toolbox to their Windows based standalones: (1) hydropower/water yield, (2) finfish aquaculture, (3) coastal protection tier 0/coastal vulnerability, (4) wave energy, (5) carbon, (6) habitat quality/biodiversity, (7) pollination, (8) timber, and (9) overlap analysis. Additionally, documentation references to ArcGIS for those models have been replaced with instructions for launching standalone InVEST models from the Windows start menu.

This release also addresses minor bugs, documentation updates, performance tweaks, and new functionality to the toolset, including:

  • A Google doc to provide guidance for scripting the InVEST standalone models: https://docs.google.com/document/d/158WKiSHQ3dBX9C3Kc99HUBic0nzZ3MqW3CmwQgvAqGo/edit?usp=sharing
  • Fixed a bug in the sample data that defined Kc as a number between 0 and 1000 instead of a number between 0 and 1.
  • Link to report an issue now takes user to the online forums rather than an email address.
  • Changed InVEST Sediment model standalone so that retention values are now between 0 and 1 instead of 0 and 100.
  • Fixed a bug in Biodiversity where if no suffix were entered output filenames would have a trailing underscore (_) behind them.
  • Added documentation to the water purification/nutrient retention model documentation about the standalone outputs since they differ from the ArcGIS version of the model.
  • Fixed an issue where the model would try to move the logfile to the workspace after the model run was complete and Windows would erroneously report that the move failed.
  • Removed the separation between marine and freshwater terrestrial models in the user’s guide. Now just a list of models.
  • Changed the name of InVEST “Biodiversity” model to “Habitat Quality” in the module names, start menu, user’s guide, and sample data folders.
  • Minor bug fixes, performance enhancements, and better error reporting in the internal infrastructure.
  • HRA risk in the unstable standalone is calculated differently from the last release. If there is no spatial overlap within a cell, there is automatically a risk of 0. This also applies to the E and C intermediate files for a given pairing. If there is no spatial overlap, E and C will be 0 where there is only habitat. However, we still create a recovery potential raster which has habitat- specific risk values, even without spatial overlap of a stressor. HRA shapefile outputs for high, medium, low risk areas are now calculated using a user-defined maximum number of overlapping stressors, rather than all potential stressors. In the HTML subregion averaged output, we now attribute what portion of risk to a habitat comes from each habitat-stressor pairing. Any pairings which don’t overlap will have an automatic risk of 0.
  • Major changes to Water Yield : Reservoir Hydropower Production. Changes include an alternative equation for calculating Actual Evapotranspiration (AET) for non-vegetated land cover types including wetlands. This allows for a more accurate representation of processes on land covers such as urban, water, wetlands, where root depth values aren’t applicable. To differentiate between the two equations a column ‘LULC_veg’ has been added to the Biophysical table in Hydropower/input/biophysical_table.csv. In this column a 1 indicates vegetated and 0 indicates non-vegetated.
  • The output structure and outputs have also change in Water Yield : Reservoir Hydropower Production. There is now a folder ‘output’ that contains all output files including a sub directory ‘per_pixel’ which has three pixel raster outputs. The subwatershed results are only calculated for the water yield portion and those results can be found as a shapefile, ‘subwatershed_results.shp’, and CSV file, ‘subwatershed_results.csv’. The watershed results can be found in similar files: watershed_results.shp and watershed_results.csv. These two files for the watershed outputs will aggregate the Scarcity and Valuation results as well.
  • The evapotranspiration coefficients for crops, Kc, has been changed to a decimal input value in the biophysical table. These values used to be multiplied by 1000 so that they were in integer format, that pre processing step is no longer necessary.
  • Changing support from richsharp@stanford.edu to the user support forums at http://ncp-yamato.stanford.edu/natcapforums.

2.5.6 (2013-09-06)

The 2.5.6 release of InVEST that addresses minor bugs, performance tweaks, and new functionality of the InVEST standalone models. Including:

  • Change the changed the Carbon biophysical table to use code field name from LULC to lucode so it is consistent with the InVEST water yield biophysical table.
  • Added Monte Carlo uncertainty analysis and documentation to finfish aquaculture model.
  • Replaced sample data in overlap analysis that was causing the model to crash.
  • Updates to the overlap analysis user’s guide.
  • Added preprocessing toolkit available under C:{InVEST install directory}utils
  • Biodiversity Model now exits gracefully if a threat raster is not found in the input folder.
  • Wind Energy now uses linear (bilinear because its over 2D space?) interpolation.
  • Wind Energy has been refactored to current API.
  • Potential Evapotranspiration input has been properly named to Reference Evapotranspiration.
  • PET_mn for Water Yield is now Ref Evapotranspiration times Kc (evapotranspiration coefficient).
  • The soil depth field has been renamed ‘depth to root restricting layer’ in both the hydropower and nutrient retention models.
  • ETK column in biophysical table for Water Yield is now Kc.
  • Added help text to Timber model.
  • Changed the behavior of nutrient retention to return nodata values when the mean runoff index is zero.
  • Fixed an issue where the hydropower model didn’t use the suffix inputs.
  • Fixed a bug in Biodiversity that did not allow for numerals in the threat names and rasters.
  • Updated routing algorithm to use a modern algorithm for plateau direction resolution.
  • Fixed an issue in HRA where individual risk pixels weren’t being calculated correctly.
  • HRA will now properly detect in the preprocessed CSVs when criteria or entire habitat-stressor pairs are not desired within an assessment.
  • Added an infrastructure feature so that temporary files are created in the user’s workspace rather than at the system level folder.  This lets users work in a secondary workspace on a USB attached hard drive and use the space of that drive, rather than the primary operating system drive.

2.5.5 (2013-08-06)

The 2.5.5 release of InVEST that addresses minor bugs, performance tweaks, and new functionality of the InVEST standalone models. Including:

  • Production level release of the 3.0 Coastal Vulnerability model.
    • This upgrades the InVEST 2.5.4 version of the beta standalone CV to a full release with full users guide. This version of the CV model should be used in all cases over its ArcGIS equivalent.
  • Production level release of the Habitat Risk Assessment model.
    • This release upgrades the InVEST 2.5.4 beta version of the standalone habitat risk assessment model. It should be used in all cases over its ArcGIS equivalent.
  • Uncertainty analysis in Carbon model (beta)
    • Added functionality to assess uncertainty in sequestration and emissions given known uncertainty in carbon pool stocks. Users can now specify standard deviations of carbon pools with normal distributions as well as desired uncertainty levels. New outputs include masks for regions which both sequester and emit carbon with a high probability of confidence. Please see the “Uncertainty Analysis” section of the carbon user’s guide chapter for more information.
  • REDD+ Scenario Analysis in Carbon model (beta)
    • Additional functionality to assist users evaluating REDD and REDD+ scenarios in the carbon model. The uncertainty analysis functionality can also be used with these scenarios. Please see the “REDD Scenario Analysis” section of the carbon user’s guide chapter for more information.
  • Uncertainty analysis in Finfish Aquaculture model (beta)
    • Additionally functionality to account for uncertainty in alpha and beta growth parameters as well as histogram plots showing the distribution of harvest weights and net present value. Uncertainty analysis is performed through Monte Carlo runs that normally sample the growth parameters.
  • Streamlined Nutrient Retention model functionality
    • The nutrient retention module no longer requires users to explicitly run the water yield model. The model now seamlessly runs water yield during execution.
  • Beta release of the recreation model
    • The recreation is available for beta use with limited documentation.
  • Full release of the wind energy model
    • Removing the ‘beta’ designation on the wind energy model.

Known Issues:

  • Flow routing in the standalone sediment and nutrient models has a bug that prevents routing in some (not all) landscapes. This bug is related to resolving d-infinity flow directions across flat areas. We are implementing the solution in Garbrecht and Martx (1997). In the meanwhile the sediment and nutrient models are still marked as beta until this issue is resolved.

2.5.4 (2013-06-07)

This is a minor release of InVEST that addresses numerous minor bugs and performance tweaks in the InVEST 3.0 models. Including:

  • Refactor of Wave Energy Model:
    • Combining the Biophysical and Valuation modules into one.
    • Adding new data for the North Sea and Australia
    • Fixed a bug where elevation values that were equal to or greater than zero were being used in calculations.
    • Fixed memory issues when dealing with large datasets.
    • Updated core functions to remove any use of depracated functions
  • Performance updates to the carbon model.

  • Nodata masking fix for rarity raster in Biodiversity Model.
    • When computing rarity from a base landuse raster and current or future landuse raster, the intersection of the two was not being properly taken.
  • Fixes to the flow routing algorithms in the sediment and nutrient retention models in cases where stream layers were burned in by ArcGIS hydro tools. In those cases streams were at the same elevation and caused routing issues.

  • Fixed an issue that affected several InVEST models that occured when watershed polygons were too small to cover a pixel. Excessively small watersheds are now handled correctly

  • Arc model deprecation. We are deprecating the following ArcGIS versions of our InVEST models in the sense we recommend ALL users use the InVEST standalones over the ArcGIS versions, and the existing ArcGIS versions of these models will be removed entirely in the next release.

    • Timber
    • Carbon
    • Pollination
    • Biodiversity
    • Finfish Aquaculture

Known Issues:

  • Flow routing in the standalone sediment and nutrient models has a bug that prevents routing in several landscapes. We’re not certain of the nature of the bug at the moment, but we will fix by the next release. Thus, sediment and nutrient models are marked as (beta) since in some cases the DEM routes correctly.

2.5.3 (2013-03-21)

This is a minor release of InVEST that fixes an issue with the HRA model that caused ArcGIS versions of the model to fail when calculating habitat maps for risk hotspots. This upgrade is strongly recommended for users of InVEST 2.5.1 or 2.5.2.

2.5.2 (2013-03-17)

This is a minor release of InVEST that fixes an issue with the HRA sample data that caused ArcGIS versions of the model to fail on the training data. There is no need to upgrade for most users unless you are doing InVEST training.

2.5.1 (2013-03-12)

This is a minor release of InVEST that does not add any new models, but does add additional functionality, stability, and increased performance to one of the InVEST 3.0 standalones:

  • Pollination 3.0 Beta:
    • Fixed a bug where Windows users of InVEST could run the model, but most raster outputs were filled with nodata values.

Additionally, this minor release fixes a bug in the InVEST user interface where collapsible containers became entirely non-interactive.

2.5.0 (2013-03-08)

This a major release of InVEST that includes new standalone versions (ArcGIS is not required) our models as well as additional functionality, stability, and increased performance to many of the existing models. This release is timed to support our group’s annual training event at Stanford University. We expect to release InVEST 2.5.1 a couple of weeks after to address any software issues that arise during the training. See the release notes below for details of the release, and please contact richsharp@stanford.edu for any issues relating to software:

  • new Sediment 3.0 Beta:
    • This is a standalone model that executes an order of magnitude faster than the original ArcGIS model, but may have memory issues with larger datasets. This fix is scheduled for the 2.5.1 release of InVEST.
    • Uses a d-infinity flow algorithm (ArcGIS version uses D8).
    • Includes a more accurate LS factor.
    • Outputs are now summarized by polygon rather than rasterized polygons. Users can view results directly as a table rather than sampling a GIS raster.
  • new Nutrient 3.0 Beta:
    • This is a standalone model that executes an order of magnitude faster than the original ArcGIS model, but may have memory issues with larger datasets. This fix is scheduled for the 2.5.1 release of InVEST.
    • Uses a d-infinity flow algorithm (ArcGIS version uses D8).
    • Includes a more accurate LS factor.
    • Outputs are now summarized by polygon rather than rasterized polygons. Users can view results directly as a table rather than sampling a GIS raster.
  • new Wind Energy:
    • A new offshore wind energy model. This is a standalone-only model available under the windows start menu.
  • new Recreation Alpha:
    • This is a working demo of our soon to be released future land and near shore recreation model. The model itself is incomplete and should only be used as a demo or by NatCap partners that know what they’re doing.
  • new Habitat Risk Assessment 3.0 Alpha:
    • This is a working demo of our soon to be released 3.0 version of habitat risk assessment. The model itself is incomplete and should only be used as a demo or by NatCap partners that know what they’re doing. Users that need to use the habitat risk assessment should use the ArcGIS version of this model.
  • Improvements to the InVEST 2.x ArcGIS-based toolset:
    • Bug fixes to the ArcGIS based Coastal Protection toolset.
  • Removed support for the ArcGIS invest_VERSION.mxd map. We expect to transition the InVEST toolset exclusive standalone tools in a few months. In preparation of this we are starting to deprecate parts of our old ArcGIS toolset including this ArcMap document. The InVEST ArcToolbox is still available in C:InVEST_2_5_0invest_250.tbx.
  • Known issues:
    • The InVEST 3.0 standalones generate open source GeoTiffs as outputs rather than the proprietary ESRI Grid format. ArcGIS 9.3.1 occasionally displays these rasters incorrectly. We have found that these layers can be visualized in ArcGIS 9.3.1 by following convoluted steps: Right Click on the layer and select Properties; click on the Symbology tab; select Stretch, agree to calculate a histogram (this will create an .aux file that Arc can use for visualization), click “Ok”, remove the raster from the layer list, then add it back. As an alternative, we suggest using an open source GIS Desktop Tool like Quantum GIS or ArcGIS version 10.0 or greater.
  • The InVEST 3.0 carbon model will generate inaccurate sequestration results if the extents of the current and future maps don’t align. This will be fixed in InVEST 2.5.1; in the meanwhile a workaround is to clip both LULCs so they have identical overlaps.
  • A user reported an unstable run of InVEST 3.0 water yield. We are not certain what is causing the issue, but we do have a fix that will go out in InVEST 2.5.1.
  • At the moment the InVEST standalones do not run on Windows XP. This appears to be related to an incompatibility between Windows XP and GDAL, the an open source gis library we use to create and read GIS data. At the moment we are uncertain if we will be able to fix this bug in future releases, but will pass along more information in the future.

2.4.5 (2013-02-01)

This is a minor release of InVEST that does not add any new models, but does add additional functionality, stability, and increased performance to many of the InVEST 3.0 standalones:

  • Pollination 3.0 Beta:
    • Greatly improved memory efficiency over previous versions of this model.
    • 3.0 Beta Pollination Biophysical and Valuation have been merged into a single tool, run through a unified user interface.
    • Slightly improved runtime through the use of newer core InVEST GIS libraries.
    • Optional ability to weight different species individually. This feature adds a column to the Guilds table that allows the user to specify a relative weight for each species, which will be used before combining all species supply rasters.
    • Optional ability to aggregate pollinator abundances at specific points provided by an optional points shapefile input.
    • Bugfix: non-agricultural pixels are set to a value of 0.0 to indicate no value on the farm value output raster.
    • Bugfix: sup_val_<beename>_<scenario>.tif rasters are now saved to the intermediate folder inside the user’s workspace instead of the output folder.
  • Carbon Biophysical 3.0 Beta:
    • Tweaked the user interface to require the user to provide a future LULC raster when the ‘Calculate Sequestration’ checkbox is checked.
    • Fixed a bug that restricted naming of harvest layers. Harvest layers are now selected simply by taking the first available layer.
  • Better memory efficiency in hydropower model.
  • Better support for unicode filepaths in all 3.0 Beta user interfaces.
  • Improved state saving and retrieval when loading up previous-run parameters in all 3.0 Beta user interfaces.
  • All 3.0 Beta tools now report elapsed time on completion of a model.
  • All 3.0 Beta tools now provide disk space usage reports on completion of a model.
  • All 3.0 Beta tools now report arguments at the top of each logfile.
  • Biodiversity 3.0 Beta: The half-saturation constant is now allowed to be a positive floating-point number.
  • Timber 3.0 Beta: Validation has been added to the user interface for this tool for all tabular and shapefile inputs.
  • Fixed some typos in Equation 1 in the Finfish Aquaculture user’s guide.
  • Fixed a bug where start menu items were not getting deleted during an InVEST uninstall.
  • Added a feature so that if the user selects to download datasets but the datasets don’t successfully download the installation alerts the user and continues normally.
  • Fixed a typo with tau in aquaculture guide, originally said 0.8, really 0.08.
  • Improvements to the InVEST 2.x ArcGIS-based toolset:
    • Minor bugfix to Coastal Vulnerability, where an internal unit of measurements was off by a couple digits in the Fetch Calculator.
    • Minor fixes to various helper tools used in InVEST 2.x models.
    • Outputs for Hargreaves are now saved as geoTIFFs.
    • Thornwaite allows more flexible entering of hours of sunlight.

2.4.4 (2012-10-24)

  • Fixes memory errors experienced by some users in the Carbon Valuation 3.0 Beta model.
  • Minor improvements to logging in the InVEST User Interface
  • Fixes an issue importing packages for some officially-unreleased InVEST models.

2.4.3 (2012-10-19)

  • Fixed a minor issue with hydropower output vaulation rasters whose statistics were not pre-calculated. This would cause the range in ArcGIS to show ther rasters at -3e38 to 3e38.
  • The InVEST installer now saves a log of the installation process to InVEST_<version>install_log.txt
  • Fixed an issue with Carbon 3.0 where carbon output values were incorrectly calculated.
  • Added a feature to Carbon 3.0 were total carbon stored and sequestered is output as part of the running log.
  • Fixed an issue in Carbon 3.0 that would occur when users had text representations of floating point numbers in the carbon pool dbf input file.
  • Added a feature to all InVEST 3.0 models to list disk usage before and after each run and in most cases report a low free space error if relevant.

2.4.2 (2012-10-15)

  • Fixed an issue with the ArcMap document where the paths to default data were not saved as relative paths. This caused the default data in the document to not be found by ArcGIS.
  • Introduced some more memory-efficient processing for Biodiversity 3.0 Beta. This fixes an out-of-memory issue encountered by some users when using very large raster datasets as inputs.

2.4.1 (2012-10-08)

  • Fixed a compatibility issue with ArcGIS 9.3 where the ArcMap and ArcToolbox were unable to be opened by Arc 9.3.

2.4.0 (2012-10-05)

Changes in InVEST 2.4.0

General:

This is a major release which releases two additional beta versions of the InVEST models in the InVEST 3.0 framework. Additionally, this release introduces start menu shortcuts for all available InVEST 3.0 beta models. Existing InVEST 2.x models can still be found in the included Arc toolbox.

Existing InVEST models migrated to the 3.0 framework in this release include:

  • Biodiversity 3.0 Beta
    • Minor bug fixes and usability enhancements
    • Runtime decreased by a factor of 210
  • Overlap Analysis 3.0 Beta
    • In most cases runtime decreased by at least a factor of 15
    • Minor bug fixes and usability enhancements
    • Split into two separate tools:
      • Overlap Analysis outputs rasters with individually-weighted pixels
      • Overlap Analysis: Management Zones produces a shapefile output.
    • Updated table format for input activity CSVs
    • Removed the “grid the seascape” step

Updates to ArcGIS models:

  • Coastal vulnerability
    • Removed the “structures” option
    • Minor bug fixes and usability enhancements
  • Coastal protection (erosion protection)
    • Incorporated economic valuation option
    • Minor bug fixes and usability enhancements

Additionally there are a handful of minor fixes and feature enhancements:

  • InVEST 3.0 Beta standalones (identified by a new InVEST icon) may be run from the Start Menu (on windows navigate to Start Menu -> All Programs -> InVEST 2.4.0
  • Bug fixes for the calculation of raster statistics.
  • InVEST 3.0 wave energy no longer requires an AOI for global runs, but encounters memory issues on machines with less than 4GB of RAM. This is a known issue that will be fixed in a minor release.
  • Minor fixes to several chapters in the user’s guide.
  • Minor bug fix to the 3.0 Carbon model: harvest maps are no longer required inputs.
  • Other minor bug fixes and runtime performance tweaks in the 3.0 framework.
  • Improved installer allows users to remove InVEST from the Windows Add/Remove programs menu.
  • Fixed a visualization bug with wave energy where output rasters did not have the min/max/stdev calculations on them. This made the default visualization in arc be a gray blob.

2.3.0 (2012-08-02)

Changes in InVEST 2.3.0

General:

This is a major release which releases several beta versions of the InVEST models in the InVEST 3.0 framework. These models run as standalones, but a GIS platform is needed to edit and view the data inputs and outputs. Until InVEST 3.0 is released the original ArcGIS based versions of these tools will remain the release.

Existing InVEST models migrated to the 3.0 framework in this release include:

  • Reservoir Hydropower Production 3.0 beta
    • Minor bug fixes.
  • Finfish Aquaculture
    • Minor bug fixes and usability enhancements.
  • Wave Energy 3.0 beta
    • Runtimes for non-global runs decreased by a factor of 7
    • Minor bugs in interpolation that exist in the 2.x model is fixed in 3.0 beta.
  • Crop Pollination 3.0 beta
    • Runtimes decreased by a factor of over 10,000

This release also includes the new models which only exist in the 3.0 framework:

  • Marine Water Quality 3.0 alpha with a preliminary user’s guide.

InVEST models in the 3.0 framework from previous releases that now have a standalone executable include:

  • Managed Timber Production Model
  • Carbon Storage and Sequestration

Additionally there are a handful of other minor fixes and feature enhancements since the previous release:

  • Minor bug fix to 2.x sedimentation model that now correctly calculates slope exponentials.
  • Minor fixes to several chapters in the user’s guide.
  • The 3.0 version of the Carbon model now can value the price of carbon in metric tons of C or CO2.
  • Other minor bug fixes and runtime performance tweaks in the 3.0 framework.

2.2.2 (2012-03-03)

Changes in InVEST 2.2.2

General:

This is a minor release which fixes the following defects:

-Fixed an issue with sediment retention model where large watersheds
allowed loading per cell was incorrectly rounded to integer values.
-Fixed bug where changing the threshold didn’t affect the retention output
because function was incorrectly rounded to integer values.

-Added total water yield in meters cubed to to output table by watershed.

-Fixed bug where smaller than default (2000) resolutions threw an error about
not being able to find the field in “unitynew”. With non-default resolution, “unitynew” was created without an attribute table, so one was created by force.
-Removed mention of beta state and ecoinformatics from header of software
license.
-Modified overlap analysis toolbox so it reports an error directly in the
toolbox if the workspace name is too long.

2.2.1 (2012-01-26)

Changes in InVEST 2.2.1

General:

This is a minor release which fixes the following defects:

-A variety of miscellaneous bugs were fixed that were causing crashes of the Coastal Protection model in Arc 9.3. -Fixed an issue in the Pollination model that was looking for an InVEST1005 directory. -The InVEST “models only” release had an entry for the InVEST 3.0 Beta tools, but was missing the underlying runtime. This has been added to the models only 2.2.1 release at the cost of a larger installer. -The default InVEST ArcMap document wouldn’t open in ArcGIS 9.3. It can now be opened by Arc 9.3 and above. -Minor updates to the Coastal Protection user’s guide.

2.2.0 (2011-12-22)

In this release we include updates to the habitat risk assessment model, updates to Coastal Vulnerability Tier 0 (previously named Coastal Protection), and a new tier 1 Coastal Vulnerability tool. Additionally, we are releasing a beta version of our 3.0 platform that includes the terrestrial timber and carbon models.

See the “Marine Models” and “InVEST 3.0 Beta” sections below for more details.

Marine Models

  1. Marine Python Extension Check

    This tool has been updated to include extension requirements for the new Coastal Protection T1 model. It also reflects changes to the Habitat Risk Assessment and Coastal Protection T0 models, as they no longer require the PythonWin extension.

  2. Habitat Risk Assessment (HRA)

    This model has been updated and is now part of three-step toolset. The first step is a new Ratings Survey Tool which eliminates the need for Microsoft Excel when users are providing habitat-stressor ratings. This Survey Tool now allows users to up- and down-weight the importance of various criteria. For step 2, a copy of the Grid the Seascape tool has been placed in the HRA toolset. In the last step, users will run the HRA model which includes the following updates:

    • New habitat outputs classifying risk as low, medium, and high
    • Model run status updates (% complete) in the message window
    • Improved habitat risk plots embedded in the output HTML
  3. Coastal Protection

    This module is now split into sub-models, each with two parts. The first sub-model is Coastal Vulnerability (Tier 0) and the new addition is Coastal Protection (Tier 1).

    Coastal Vulnerability (T0) Step 1) Fetch Calculator - there are no updates to this tool. Step 2) Vulnerability Index

    • Wave Exposure: In this version of the model, we define wave exposure for sites facing the open ocean as the maximum of the weighted average of wave’s power coming from the ocean or generated by local winds. We weight wave power coming from each of the 16 equiangular sector by the percent of time that waves occur in that sector, and based on whether or not fetch in that sector exceeds 20km. For sites that are sheltered, wave exposure is the average of wave power generated by the local storm winds weighted by the percent occurrence of those winds in each sector. This new method takes into account the seasonality of wind and wave patterns (storm waves generally come from a preferential direction), and helps identify regions that are not exposed to powerful waves although they are open to the ocean (e.g. the leeside of islands).
    • Natural Habitats: The ranking is now computed using the rank of all natural habitats present in front of a segment, and we weight the lowest ranking habitat 50% more than all other habitats. Also, rankings and protective distance information are to be provided by CSV file instead of Excel. With this new method, shoreline segments that have more habitats than others will have a lower risk of inundation and/or erosion during storms.
    • Structures: The model has been updated to now incorporate the presence of structures by decreasing the ranking of shoreline segments that adjoin structures.

    Coastal Protection (T1) - This is a new model which plots the amount of sandy beach erosion or consolidated bed scour that backshore regions experience in the presence or absence of natural habitats. It is composed of two steps: a Profile Generator and Nearshore Waves and Erosion. It is recommended to run the Profile Generator before the Nearshore Waves and Erosion model.

    Step 1) Profile Generator: This tool helps the user generate a 1-dimensional bathymetric and topographic profile perpendicular to the shoreline at the user-defined location. This model provides plenty of guidance for building backshore profiles for beaches, marshes and mangroves. It will help users modify bathymetry profiles that they already have, or can generate profiles for sandy beaches if the user has not bathymetric data. Also, the model estimates and maps the location of natural habitats present in front of the region of interest. Finally, it provides sample wave and wind data that can be later used in the Nearshore Waves and Erosion model, based on computed fetch values and default Wave Watch III data.

    Step 2) Nearshore Waves and Erosion: This model estimates profiles of beach erosion or values of rates of consolidated bed scour at a site as a function of the type of habitats present in the area of interest. The model takes into account the protective effects of vegetation, coral and oyster reefs, and sand dunes. It also shows the difference of protection provided when those habitats are present, degraded, or gone.

  4. Aesthetic Quality

    This model no longer requires users to provide a projection for Overlap Analysis. Instead, it uses the projection from the user-specified Area of Interest (AOI) polygon. Additionally, the population estimates for this model have been fixed.

InVEST 3.0 Beta

The 2.2.0 release includes a preliminary version of our InVEST 3.0 beta platform. It is included as a toolset named “InVEST 3.0 Beta” in the InVEST220.tbx. It is currently only supported with ArcGIS 10. To launch an InVEST 3.0 beta tool, double click on the desired tool in the InVEST 3.0 toolset then click “Ok” on the Arc toolbox screen that opens. The InVEST 3.0 tool panel has inputs very similar to the InVEST 2.2.0 versions of the tools with the following modifications:

InVEST 3.0 Carbon:
  • Fixes a minor bug in the 2.2 version that ignored floating point values in carbon pool inputs.
  • Separation of carbon model into a biophysical and valuation model.
  • Calculates carbon storage and sequestration at the minimum resolution of the input maps.
  • Runtime efficiency improved by an order of magnitude.
  • User interface streamlined including dynamic activation of inputs based on user preference, direct link to documentation, and recall of inputs based on user’s previous run.
InVEST 3.0 Timber:
  • User interface streamlined including dynamic activation of inputs based on user preference, direct link to documentation, and recall of inputs based on user’s previous run.

2.1.1 (2011-10-17)

Changes in InVEST 2.1.1

General:

This is a minor release which fixes the following defects:

-A truncation error was fixed on nutrient retention and sedimentation model that involved division by the number of cells in a watershed. Now correctly calculates floating point division. -Minor typos were fixed across the user’s guide.

2.1 Beta (2011-05-11)

Updates to InVEST Beta

InVEST 2.1 . Beta

Changes in InVEST 2.1

General:

1. InVEST versioning We have altered our versioning scheme. Integer changes will reflect major changes (e.g. the addition of marine models warranted moving from 1.x to 2.0). An increment in the digit after the primary decimal indicates major new features (e.g the addition of a new model) or major revisions. For example, this release is numbered InVEST 2.1 because two new models are included). We will add another decimal to reflect minor feature revisions or bug fixes. For example, InVEST 2.1.1 will likely be out soon as we are continually working to improve our tool. 2. HTML guide With this release, we have migrated the entire InVEST users. guide to an HTML format. The HTML version will output a pdf version for use off-line, printing, etc.

MARINE MODELS

1.Marine Python Extension Check

-This tool has been updated to allow users to select the marine models they intend to run. Based on this selection, it will provide a summary of which Python and ArcGIS extensions are necessary and if the Python extensions have been successfully installed on the user.s machine.

2.Grid the Seascape (GS)

-This tool has been created to allow marine model users to generate an seascape analysis grid within a specified area of interest (AOI).

-It only requires an AOI and cell size (in meters) as inputs, and produces a polygon grid which can be used as inputs for the Habitat Risk Assessment and Overlap Analysis models.

  1. Coastal Protection
  • This is now a two-part model for assessing Coastal Vulnerability. The first part is a tool for calculating fetch and the second maps the value of a Vulnerability Index, which differentiates areas with relatively high or low exposure to erosion and inundation during storms.
  • The model has been updated to now incorporate coastal relief and the protective influence of up to eight natural habitat input layers.
  • A global Wave Watch 3 dataset is also provided to allow users to quickly generate rankings for wind and wave exposure worldwide.
  1. Habitat Risk Assessment (HRA)

This new model allows users to assess the risk posed to coastal and marine habitats by human activities and the potential consequences of exposure for the delivery of ecosystem services and biodiversity. The HRA model is suited to screening the risk of current and future human activities in order to prioritize management strategies that best mitigate risk.

  1. Overlap Analysis

This new model maps current human uses in and around the seascape and summarizes the relative importance of various regions for particular activities. The model was designed to produce maps that can be used to identify marine and coastal areas that are most important for human use, in particular recreation and fisheries, but also other activities.

FRESHWATER MODELS

All Freshwater models now support ArcMap 10.

Sample data:

  1. Bug fix for error in Water_Tables.mdb Biophysical table where many field values were shifted over one column relative to the correct field name.
  2. Bug fix for incorrect units in erosivity layer.

Hydropower:

1.In Water Yield, new output tables have been added containing mean biophysical outputs (precipitation, actual and potential evapotranspiration, water yield) for each watershed and sub-watershed.

Water Purification:

  1. The Water Purification Threshold table now allows users to specify separate thresholds for nitrogen and phosphorus. Field names thresh_n and thresh_p replace the old ann_load.
  2. The Nutrient Retention output tables nutrient_watershed.dbf and nutrient_subwatershed.dbf now include a column for nutrient retention per watershed/sub-watershed.
  3. In Nutrient Retention, some output file names have changed.
  4. The user’s guide has been updated to explain more accurately the inclusion of thresholds in the biophysical service estimates.

Sedimentation:

  1. The Soil Loss output tables sediment_watershed.dbf and sediment_subwatershed.dbf now include a column for sediment retention per watershed/sub-watershed.
  2. In Soil Loss, some output file names have changed.
  3. The default input value for Slope Threshold is now 75.
  4. The user’s guide has been updated to explain more accurately the inclusion of thresholds in the biophysical service estimates.
  5. Valuation: Bug fix where the present value was not being applied correctly.

2.0 Beta (2011-02-14)

Changes in InVEST 2.0

InVEST 1.005 is a minor release with the following modification:

  1. Aesthetic Quality

    This new model allows users to determine the locations from which new nearshore or offshore features can be seen. It generates viewshed maps that can be used to identify the visual footprint of new offshore development.

  2. Coastal Vulnerability

    This new model produces maps of coastal human populations and a coastal exposure to erosion and inundation index map. These outputs can be used to understand the relative contributions of different variables to coastal exposure and to highlight the protective services offered by natural habitats.

  3. Aquaculture

    This new model is used to evaluate how human activities (e.g., addition or removal of farms, changes in harvest management practices) and climate change (e.g., change in sea surface temperature) may affect the production and economic value of aquacultured Atlantic salmon.

  4. Wave Energy

    This new model provides spatially explicit information, showing potential areas for siting Wave Energy conversion (WEC) facilities with the greatest energy production and value. This site- and device-specific information for the WEC facilities can then be used to identify and quantify potential trade-offs that may arise when siting WEC facilities.

  5. Avoided Reservoir Sedimentation

    • The name of this model has been changed to the Sediment Retention model.
    • We have added a water quality valuation model for sediment retention. The user now has the option to select avoided dredge cost analysis, avoided water treatment cost analysis or both. The water quality valuation approach is the same as that used in the Water Purification: Nutrient Retention model.
    • The threshold information for allowed sediment loads (TMDL, dead volume, etc.) are now input in a stand alone table instead of being included in the valuation table. This adjusts the biophysical service output for any social allowance of pollution. Previously, the adjustment was only done in the valuation model.
    • The watersheds and sub-watershed layers are now input as shapefiles instead of rasters.
    • Final outputs are now aggregated to the sub-basin scale. The user must input a sub-basin shapefile. We provide the Hydro 1K dataset as a starting option. See users guide for changes to many file output names.
    • Users are strongly advised not to interpret pixel-scale outputs for hydrological understanding or decision-making of any kind. Pixel outputs should only be used for calibration/validation or model checking.
  6. Hydropower Production

    • The watersheds and sub-watershed layers are now input as shapefiles instead of rasters.
    • Final outputs are now aggregated to the sub-basin scale. The user must input a sub-basin shapefile. We provide the Hydro 1K dataset as a starting option. See users guide for changes to many file output names.
    • Users are strongly advised not to interpret pixel-scale outputs for hydrological understanding or decision-making of any kind. Pixel outputs should only be used for calibration/validation or model checking.
    • The calibration constant for each watershed is now input in a stand-alone table instead of being included in the valuation table. This makes running the water scarcity model simpler.
  7. Water Purification: Nutrient Retention

    • The threshold information for allowed pollutant levels (TMDL, etc.) are now input in a stand alone table instead of being included in the valuation table. This adjusts the biophysical service output for any social allowance of pollution. Previously, the adjustment was only done in the valuation model.
    • The watersheds and sub-watershed layers are now input as shapefiles instead of rasters.
    • Final outputs are now aggregated to the sub-basin scale. The user must input a sub-basin shapefile. We provide the Hydro 1K dataset as a starting option. See users guide for changes to many file output names.
    • Users are strongly advised not to interpret pixel-scale outputs for hydrological understanding or decision-making of any kind. Pixel outputs should only be used for calibration/validation or model checking.
  8. Carbon Storage and Sequestration

    The model now outputs an aggregate sum of the carbon storage.

  9. Habitat Quality and Rarity

    This model had an error while running ReclassByACII if the land cover codes were not sorted alphabetically. This has now been corrected and it sorts the reclass file before running the reclassification

    The model now outputs an aggregate sum of the habitat quality.

  10. Pollination

    In this version, the pollination model accepts an additional parameter which indicated the proportion of a crops yield that is attributed to wild pollinators.

Tutorial: Batch Processing on Windows

Introduction

These are the steps that will need to be taken in order to use the batch scripting framework for InVEST models available in the natcap.invest python package.

For those wishing to do batch-processing with InVEST without setting up a Python scripting environment, see The InVEST CLI for examples of how to run InVEST models from the command-line.

Setting up your Python environment

  1. Install Python 3.6 or later.

    Python can be downloaded from here. When installing, be sure to allow python.exe to be added to the path in the installation options.

  2. Put pip on the PATH.

    The pip utility for installing python packages is already included with Python 2.7.9 and later. Be sure to add C:\Python37\Scripts (or your custom install location) to the Windows PATH environment variable so that pip can be called from the command line without needing to use its full path.

    After this is done (and you’ve opened a new command-line window), you will be able to use pip at the command-line to install packages like so:

    > pip install <packagename>
    
  3. Install packages needed to run InVEST.

    Most (maybe even all) of these packages can be downloaded as precompiled wheels from Christoph Gohlke’s build page. Others should be able to be installed via pip install <packagename>.

    #
    # Any lines with "# pip-only" at the end will be processed by
    # scripts/convert-requirements-to-conda-yml.py as though it can only be found
    # on pip.
    
    GDAL>=2.0,<3.0
    Pyro4==4.77  # pip-only
    pandas>=1.0
    numpy>=1.11.0,!=1.16.0
    Rtree>=0.8.2,!=0.9.1
    scipy>=0.16.1,<1.5.0
    Shapely>=1.6.4,<1.7.0
    pygeoprocessing>=1.9.2,<2.0  # pip-only
    taskgraph[niced_processes]>=0.9.1
    psutil>=5.6.6
    chardet>=3.0.4
    xlrd>=1.2.0
    xlwt
    
  4. Install the InVEST python package

    4a. Download a release of the natcap.invest python package.

    4b. Install the downloaded python package..

Creating Sample Python Scripts

  1. Launch InVEST Model

    Once an InVEST model is selected for scripting, launch that model from the Windows Start menu. This example in this guide follows the NDR model.

  2. Fill in InVEST Model Input Parameters

    Once the user interface loads, populate the inputs in the model likely to be used in the Python script. For testing purposes the default InVEST’s data is appropriate. However, if a user wishes to write a batch for several InVEST runs, it would be reasonable to populate the user interface with data for the first run.

  3. Generate a sample Python Script from the User Interface

    Open the Development menu at the top of the user interface and select “Save to python script…” and save the file to a known location.

2w7pilj.png

  1. Execute the script in the InVEST Python Environment

    Launch a Windows PowerShell from the Start menu (type “powershell” in the search box), then invoke the Python interpreter on the InVEST Python script from that shell. In this example the Python interpreter is installed in C:\Python37\python.exe and the script was saved in C:\Users\rpsharp\Desktop\ndr.py, thus the command to invoke the interpreter is:

    > C:\Python37\python.exe C:\Users\rpsharp\Desktop\ndr.py
    

34ecba0.png

  1. Output Results

    As the model executes, status information will be printed to the console. Once complete, model results can be found in the workspace folder selected during the initial configuration.

Modifying a Python Script

InVEST Python scripts consist of two sections:

  • The argument dictionary that represents the model’s user interface input boxes and parameters.
  • The call to the InVEST model itself.

For reference, consider the following script generated by the Nutrient model with default data inputs:

"""
This is a saved model run from natcap.invest.ndr.ndr.
Generated: Mon 16 May 2016 03:52:59 PM
InVEST version: 3.3.0
"""

import natcap.invest.ndr.ndr

args = {
        u'k_param': u'2',
        u'runoff_proxy_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\precip',
        u'subsurface_critical_length_n': u'150',
        u'subsurface_critical_length_p': u'150',
        u'subsurface_eff_n': u'0.8',
        u'subsurface_eff_p': u'0.8',
        u'threshold_flow_accumulation': u'1000',
        u'biophysical_table_uri': u'C:\InVEST_3.3.0_x86\WP_Nutrient_Retention\Input\water_biophysical_table.csv',
        u'calc_n': True,
        u'calc_p': True,
        u'suffix': '',
        u'dem_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\dem',
        u'lulc_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\landuse_90',
        u'watersheds_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\watersheds.shp',
        u'workspace_dir': u'C:\InVEST_3.3.0_x86\ndr_workspace',
}

if __name__ == '__main__':
    natcap.invest.ndr.ndr.execute(args)

Elements to note:

  • Parameter Python Dictionary: Key elements include the ‘args’ dictionary. Note the similarities between the key values such as ‘workspace_dir’ and the equivalent “Workspace” input parameter in the user interface. Every key in the ‘args’ dictionary has a corresponding reference in the user interface.

95zj7p.png

In the example below we’ll modify the script to execute the nutrient model for a parameter study of ‘threshold_flow_accumulation’.

  • Execution of the InVEST model: The InVEST API invokes models with a consistent syntax where the module name that contains the InVEST model is listed first and is followed by a function called ‘execute’ that takes a single parameter called ‘args’. This parameter is the dictionary of input parameters discussed above. In this example, the line

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

executes the nutrient model end-to-end. If the user wishes to make batch calls to InVEST, this line will likely be placed inside a loop.

Example: Threshold Flow Accumulation Parameter Study

This example executes the InVEST NDR model on 10 values of threshold accumulation stepping from 500 to 1000 pixels in steps of 50. To modify the script above, replace the execution call with the following loop:

#Loops through the values 500, 550, 600, ... 1000
for threshold_flow_accumulation in range(500, 1001, 50):
    #set the accumulation threshold to the current value in the loop
    args['threshold_flow_accumulation'] = threshold_flow_accumulation
    #set the suffix to be accum### for the current threshold_flow_accumulation
    args['suffix'] = 'accum' + str(threshold_flow_accumulation)
    natcap.invest.ndr.ndr.execute(args)

This loop executes the InVEST nutrient model 10 times for accumulation values 500, 550, 600, ... 1000 and adds a suffix to the output files so results can be distinguished.

Example: Invoke NDR Model on a directory of Land Cover Maps

In this case we invoke the InVEST nutrient model on a directory of land cover data located at C:UserRichDesktoplandcover_data. As in the previous example, replace the last line in the UI generated Python script with:

import os
landcover_dir = r'C:\User\Rich\Desktop\landcover_data'
#Loop over all the filenames in the landcover dir
for landcover_file in os.listdir(landcover_dir):
    #Point the landuse uri parameter at the directory+filename
    args['lulc_uri'] = os.path.join(landcover_dir, landcover_file)
    #Make a useful suffix so we can differentiate the results
    args['suffix'] = 'landmap' + os.path.splitext(landcover_file)[0]
    #call the nutrient model
    natcap.invest.ndr.ndr.execute(args)

This loop covers all the files located in C:\User\Rich\Desktop\landcover_data and updates the relevant lulc_uri key in the args dictionary to each of those files during execution as well as making a useful suffix so output files can be distinguished from each other.

Example: Saving model log messages to a file

There are many cases where you may want or need to capture all of the log messages generated by the model. When we run models through the InVEST user interface application, the UI captures all of this logging and saves it to a logfile. We can replicate this behavior through the python logging package, by adding the following code just after the import statements in the example script.

import logging
import pygeoprocessing

# Write all NDR log messages to logfile.txt
MODEL_LOGGER = logging.getLogger('natcap.invest.ndr')
handler = logging.FileHandler('logfile.txt')
MODEL_LOGGER.addHandler(handler)

# log pygeoprocessing messages to the same logfile
PYGEO_LOGGER = logging.getLogger('pygeoprocessing')
PYGEO_LOGGER.addHandler(handler)

This will capture all logging generated by the ndr model and by pygeoprocessing, writing all messages to logfile.txt. While this is a common use case, the logging package provides functionality for many more complex logging features. For more advanced use of the python logging module, refer to the Python project’s Logging Cookbook

Summary

The InVEST scripting framework was designed to assist InVEST users in automating batch runs or adding custom functionality to the existing InVEST software suite. Support questions can be directed to the NatCap support forums at http://community.naturalcapitalproject.org.

API Reference

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.

API Reference

Note

For the function documentation of available models, see InVEST Model Entry Points.

natcap

natcap package
Subpackages
natcap.invest package
Subpackages
natcap.invest.coastal_blue_carbon package
Submodules
natcap.invest.coastal_blue_carbon.coastal_blue_carbon module
natcap.invest.coastal_blue_carbon.preprocessor module
Module contents

Coastal Blue Carbon package.

natcap.invest.finfish_aquaculture package
Submodules
natcap.invest.finfish_aquaculture.finfish_aquaculture module
natcap.invest.finfish_aquaculture.finfish_aquaculture_core module

Implementation of the aquaculture calculations, and subsequent outputs. This will pull from data passed in by finfish_aquaculture.

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.calc_farm_cycles(outplant_buffer, a, b, tau, water_temp_dict, farm_op_dict, dur)
Input:
outplant_buffer: The number of days surrounding the outplant day during
which the fish growth cycle can still be started.
a: Growth parameter alpha. Float used as a scaler in the fish growth
equation.
b: Growth paramater beta. Float used as an exponential multiplier in
the fish growth equation.
water_temp_dict: 2D dictionary which contains temperature values for
farms. The outer keys are calendar days as strings, and the inner are farm numbers as strings.
farm_op_dict: 2D dictionary which contains individual operating
parameters for each farm. The outer key is farm number as a string, and the inner is string descriptors of each parameter.
dur: Float which describes the length for the growth simulation to run
in years.

Returns cycle_history where:

cycle_history: Dictionary which contains mappings from farms to a

history of growth for each cycle completed on that farm. These entries are formatted as follows…

Farm->List of Type (day of outplanting,day of harvest, fish weight
(grams))
natcap.invest.finfish_aquaculture.finfish_aquaculture_core.calc_hrv_weight(farm_op_dict, frac, mort, cycle_history)
Input:
farm_op_dict: 2D dictionary which contains individual operating
parameters for each farm. The outer key is farm number as a string, and the inner is string descriptors of each parameter.
frac: A float representing the fraction of the fish that remains after
processing.
mort: A float referring to the daily mortality rate of fishes on an
aquaculture farm.
cycle_history: Farm->List of Type (day of outplanting,
day of harvest, fish weight (grams))
Returns a tuple (curr_cycle_totals,indiv_tpw_totals) where:
curr_cycle_totals_: dictionary which will hold a mapping from every
farm (as identified by farm_ID) to the total processed weight of each farm
indiv_tpw_totals: dictionary which will hold a farm->list mapping,
where the list holds the individual tpw for all cycles that the farm completed
natcap.invest.finfish_aquaculture.finfish_aquaculture_core.compute_uncertainty_data(args, output_dir)

Does uncertainty analysis via a Monte Carlo simulation.

Returns: -a dict containining statistical results (mean and std deviation) The dict has farm IDs as outer keys, and result types (e.g. ‘value’, ‘weight’, and ‘cycles’) as inner keys.

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.create_HTML_table(output_dir, args, cycle_history, sum_hrv_weight, hrv_weight, farms_npv, value_history, uncertainty_stats)
Inputs:
output_dir: The directory in which we will be creating our .html file
output.
cycle_history: dictionary mapping farm ID->list of tuples, each of
which contains 3 things- (day of outplanting, day of harvest,
harvest weight of a single fish in grams)
sum_hrv_weight: dictionary which holds a mapping from farm ID->total
processed weight of each farm
hrv_weight: dictionary which holds a farm->list mapping, where the list
holds the individual tpw for all cycles that the farm completed
do_valuation: boolean variable that says whether or not valuation is
desired
farms_npv: dictionary with a farm-> float mapping, where each float is
the net processed value of the fish processed on that farm, in $1000s of dollars.
value_history: dictionary which holds a farm->list mapping, where the
list holds tuples containing (Net Revenue, Net Present Value) for each cycle completed by that farm
Output:
HTML file: contains 3 tables that summarize inputs and outputs for the

duration of the model. - Input Table: Farm Operations provided data, including Farm ID #,

Cycle Number, weight of fish at start, weight of fish at harvest, number of fish in farm, start day for growing, and length of fallowing period
  • Output Table 1: Farm Harvesting data, including a summary table
    for each harvest cycle of each farm. Will show Farm ID, cycle number, days since outplanting date, harvested weight, net revenue, outplant day, and year.
  • Output Table 2: Model outputs for each farm, including Farm ID,
    net present value, number of completed harvest cycles, and total volume harvested.

Returns nothing.

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.do_monte_carlo_simulation(args)

Performs a Monte Carlo simulation and returns the results.

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

‘ Runs the biophysical and valuation parts of the finfish aquaculture model. This will output: 1. a shape file showing farm locations w/ addition of # of harvest cycles,

total processed weight at that farm, and if valuation is true, total discounted net revenue at each farm location.
  1. Three HTML tables summarizing all model I/O- summary of user-provided
    data, summary of each harvest cycle, and summary of the outputs/farm
  2. A .txt file that is named according to the date and time the model is
    run, which lists the values used during that run

Data in args should include the following: –Biophysical Arguments– args: a python dictionary containing the following data: args[‘workspace_dir’]- The directory in which to place all result files. args[‘ff_farm_file’]- An open shape file containing the locations of

individual fisheries
args[‘farm_ID’]- column heading used to describe individual farms. Used to
link GIS location data to later inputs.
args[‘g_param_a’]- Growth parameter alpha, used in modeling fish growth,
should be int or a float.
args[‘g_param_b’]- Growth parameter beta, used in modeling fish growth,
should be int or a float.
args[‘water_temp_dict’]- A dictionary which links a specific date to the

farm numbers, and their temperature values on that day. (Note: in this case, the outer keys 1 and 2 are calendar days out of 365, starting with January 1 (day 0), and the inner 1, 2, and 3 are farm numbers.)

Format: {‘0’: ‘{‘1’: ‘8.447, ‘2’: ‘8.447’, ‘3’:‘8.947’, …}’ ,
‘1’: ‘{‘1’: ‘8.406, ‘2’: ‘8.406’, ‘3’:‘8.906’, …}’ ,

. . . . . . . . . }

args[‘farm_op_dict’]- Dictionary which links a specific farm ID # to

another dictionary containing operating parameters mapped to their value for that particular farm (Note: in this case, the 1 and 2 are farm ID’s, not dates out of 365.)

Format: {‘1’: ‘{‘Wt of Fish’: ‘0.06’, ‘Tar Weight’: ‘5.4’, …}’,
‘2’: ‘{‘Wt of Fish’: ‘0.06’, ‘Tar Weight’: ‘5.4’, …}’, . . . . . . . . . }
args[‘frac_post_process’]- the fraction of edible fish left after
processing is done to remove undesirable parts
args[‘mort_rate_daily’]- mortality rate among fish in a year, divided by
365

args[‘duration’]- duration of the simulation, in years args[‘outplant_buffer’] - This value will allow the outplant start day to

be flexible plus or minus the number of days specified here.

–Valuation arguments– args[‘do_valuation’]- boolean indicating whether or not to run the

valuation process

args[‘p_per_kg’]: Market price per kilogram of processed fish args[‘frac_p’]: Fraction of market price that accounts for costs rather

than profit

args[‘discount’]: Daily market discount rate

returns nothing

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.valuation(price_per_kg, frac_mrkt_price, discount, hrv_weight, cycle_history)

This performs the valuation calculations, and returns tuple containing a dictionary with a farm-> float mapping, where each float is the net processed value of the fish processed on that farm, in $1000s of dollars, and a dictionary containing a farm-> list mapping, where each entry in the list is a tuple of (Net Revenue, Net Present Value) for every cycle on that farm.

Inputs:
price_per_kg: Float representing the price per kilogram of finfish for
valuation purposes.
frac_mrkt_price: Float that represents the fraction of market price
that is attributable to costs.

discount: Float that is the daily market discount rate. cycle_hisory: Farm->List of Type (day of outplanting,

day of harvest, fish weight (grams))

hrv_weight: Farm->List of TPW for each cycle (kilograms)

Returns a tuple (val_history, valuations):
val_history: dictionary which will hold a farm->list mapping, where the
list holds tuples containing (Net Revenue, Net Present Value) for each cycle completed by that farm
valuations: dictionary with a farm-> float mapping, where each float is
the net processed value of the fish processed on that farm
Module contents
natcap.invest.fisheries package
Submodules
natcap.invest.fisheries.fisheries module
natcap.invest.fisheries.fisheries_hst module
natcap.invest.fisheries.fisheries_hst_io module

The Fisheries Habitat Scenarios Tool IO module contains functions for handling inputs and outputs

natcap.invest.fisheries.fisheries_hst_io.fetch_args(args)

Fetches input arguments from the user, verifies for correctness and completeness, and returns a list of variables dictionaries

Parameters:args (dictionary) – arguments from the user (same as Fisheries Preprocessor entry point)
Returns:dictionary containing necessary variables
Return type:vars_dict (dictionary)
Raises:ValueError – parameter mismatch between Population and Habitat CSV files

Example Returns:

vars_dict = {
    'workspace_dir': 'path/to/workspace_dir/',
    'output_dir': 'path/to/output_dir/',
    'sexsp': 2,
    'gamma': 0.5,

    # Pop Vars
    'population_csv_path': 'path/to/csv_path',
    'Surv_nat_xsa': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Classes': np.array([...]),
    'Class_vectors': {
        'Vulnfishing': np.array([...], [...]),
        'Maturity': np.array([...], [...]),
        'Duration': np.array([...], [...]),
        'Weight': np.array([...], [...]),
        'Fecundity': np.array([...], [...]),
    },
    'Regions': np.array([...]),
    'Region_vectors': {
        'Exploitationfraction': np.array([...]),
        'Larvaldispersal': np.array([...]),
    },

    # Habitat Vars
    'habitat_chg_csv_path': 'path/to/csv',
    'habitat_dep_csv_path': 'path/to/csv',
    'Habitats': ['habitat1', 'habitat2', ...],
    'Hab_classes': ['class1', 'class2', ...],
    'Hab_regions': ['region1', 'region2', ...],
    'Hab_chg_hx': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Hab_dep_ha': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Hab_class_mvmt_a': np.array([...]),
    'Hab_dep_num_a': np.array([...]),
}
natcap.invest.fisheries.fisheries_hst_io.read_habitat_chg_csv(args)

Parses and verifies a Habitat Change Parameters CSV file and returns a dictionary of information related to the interaction between a species and the given habitats.

Parses the Habitat Change Parameters CSV file for the following vectors:

  • Names of Habitats and Regions
  • Habitat Area Change
Parameters:

args (dictionary) – arguments from the user (same as Fisheries HST entry point)

Returns:

dictionary containing necessary

variables

Return type:

habitat_chg_dict (dictionary)

Raises:
  • MissingParameter – required parameter not included
  • ValueError – values are out of bounds or of wrong type
  • IndexError – likely a file formatting issue

Example Returns:

habitat_chg_dict = {
    'Habitats': ['habitat1', 'habitat2', ...],
    'Hab_regions': ['region1', 'region2', ...],
    'Hab_chg_hx': np.array(
        [[[...], [...]], [[...], [...]], ...]),
}
natcap.invest.fisheries.fisheries_hst_io.read_habitat_dep_csv(args)

Parses and verifies a Habitat Dependency Parameters CSV file and returns a dictionary of information related to the interaction between a species and the given habitats.

Parses the Habitat Parameters CSV file for the following vectors:

  • Names of Habitats and Classes
  • Habitat-Class Dependency

The following vectors are derived from the information given in the file:

  • Classes where movement between habitats occurs
  • Number of habitats that a particular class depends upon
Parameters:

args (dictionary) – arguments from the user (same as Fisheries HST entry point)

Returns:

dictionary containing necessary

variables

Return type:

habitat_dep_dict (dictionary)

Raises:
  • MissingParameter - required parameter not included
  • ValueError - values are out of bounds or of wrong type
  • IndexError - likely a file formatting issue

Example Returns:

habitat_dep_dict = {
    'Habitats': ['habitat1', 'habitat2', ...],
    'Hab_classes': ['class1', 'class2', ...],
    'Hab_dep_ha': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Hab_class_mvmt_a': np.array([...]),
    'Hab_dep_num_a': np.array([...]),
}
natcap.invest.fisheries.fisheries_hst_io.read_population_csv(args)

Parses and verifies a single Population Parameters CSV file

Parses and verifies inputs from the Population Parameters CSV file. If not all necessary vectors are included, the function will raise a MissingParameter exception. Survival matrix will be arranged by class-elements, 2nd dim: sex, and 3rd dim: region. Class vectors will be arranged by class-elements, 2nd dim: sex (depending on whether model is sex-specific) Region vectors will be arraged by region-elements, sex-agnostic.

Parameters:

args (dictionary) – arguments provided by user

Returns:

dictionary containing verified population

arguments

Return type:

pop_dict (dictionary)

Raises:
  • MissingParameter – required parameter not included
  • ValueError – values are out of bounds or of wrong type

Example Returns:

pop_dict = {
    'population_csv_path': 'path/to/csv',
    'Surv_nat_xsa': np.array(
        [[...], [...]], [[...], [...]], ...),

    # Class Vectors
    'Classes': np.array([...]),
    'Class_vector_names': [...],
    'Class_vectors': {
        'Vulnfishing': np.array([...], [...]),
        'Maturity': np.array([...], [...]),
        'Duration': np.array([...], [...]),
        'Weight': np.array([...], [...]),
        'Fecundity': np.array([...], [...]),
    },

    # Region Vectors
    'Regions': np.array([...]),
    'Region_vector_names': [...],
    'Region_vectors': {
        'Exploitationfraction': np.array([...]),
        'Larvaldispersal': np.array([...]),
    },
}
natcap.invest.fisheries.fisheries_hst_io.save_population_csv(vars_dict)

Creates a new Population Parameters CSV file based the provided inputs.

Parameters:vars_dict (dictionary) – variables generated by preprocessor arguments and run.

Example Args:

args = {
    'workspace_dir': 'path/to/workspace_dir/',
    'output_dir': 'path/to/output_dir/',
    'sexsp': 2,
    'population_csv_path': 'path/to/csv',  # original csv file
    'Surv_nat_xsa': np.ndarray([...]),
    'Surv_nat_xsa_mod': np.ndarray([...]),

    # Class Vectors
    'Classes': np.array([...]),
    'Class_vector_names': [...],
    'Class_vectors': {
        'Vulnfishing': np.array([...], [...]),
        'Maturity': np.array([...], [...]),
        'Duration': np.array([...], [...]),
        'Weight': np.array([...], [...]),
        'Fecundity': np.array([...], [...]),
    },

    # Region Vectors
    'Regions': np.array([...]),
    'Region_vector_names': [...],
    'Region_vectors': {
        'Exploitationfraction': np.array([...]),
        'Larvaldispersal': np.array([...]),
    },

    # other arguments are ignored ...
}

Note

  • Creates a modified Population Parameters CSV file located in the ‘workspace/output/’ folder
  • Currently appends ‘_modified’ to original filename for new filename
natcap.invest.fisheries.fisheries_io module

The Fisheries IO module contains functions for handling inputs and outputs

exception natcap.invest.fisheries.fisheries_io.MissingParameter

Bases: ValueError

An exception class that may be raised when a necessary parameter is not provided by the user.

natcap.invest.fisheries.fisheries_io.create_outputs(vars_dict)

Creates outputs from variables generated in the run_population_model() function in the fisheries_model module

Creates the following:

  • Results CSV File
  • Results HTML Page
  • Results Shapefile (if provided)
  • Intermediate CSV File
Parameters:vars_dict (dictionary) – contains variables generated by model run
natcap.invest.fisheries.fisheries_io.fetch_args(args, create_outputs=True)

Fetches input arguments from the user, verifies for correctness and completeness, and returns a list of variables dictionaries

Parameters:args (dictionary) – arguments from the user
Returns:
set of variable dictionaries for each
model
Return type:model_list (list)

Example Returns:

model_list = [
    {
        'workspace_dir': 'path/to/workspace_dir',
        'results_suffix': 'scenario_name',
        'output_dir': 'path/to/output_dir',
        'aoi_vector_path': 'path/to/aoi_vector_path',
        'total_timesteps': 100,
        'population_type': 'Stage-Based',
        'sexsp': 2,
        'harvest_units': 'Individuals',
        'do_batch': False,
        'spawn_units': 'Weight',
        'total_init_recruits': 100.0,
        'recruitment_type': 'Ricker',
        'alpha': 32.4,
        'beta': 54.2,
        'total_recur_recruits': 92.1,
        'migr_cont': True,
        'val_cont': True,
        'frac_post_process': 0.5,
        'unit_price': 5.0,

        # Pop Params
        'population_csv_path': 'path/to/csv_path',
        'Survnaturalfrac': numpy.array(
            [[[...], [...]], [[...], [...]], ...]),
        'Classes': numpy.array([...]),
        'Vulnfishing': numpy.array([...], [...]),
        'Maturity': numpy.array([...], [...]),
        'Duration': numpy.array([...], [...]),
        'Weight': numpy.array([...], [...]),
        'Fecundity': numpy.array([...], [...]),
        'Regions': numpy.array([...]),
        'Exploitationfraction': numpy.array([...]),
        'Larvaldispersal': numpy.array([...]),

        # Mig Params
        'migration_dir': 'path/to/mig_dir',
        'Migration': [numpy.matrix, numpy.matrix, ...]
    },
    {
        ...  # additional dictionary doesn't exist when 'do_batch'
             # is false
    }
]

Note

This function receives an unmodified ‘args’ dictionary from the user

natcap.invest.fisheries.fisheries_io.read_migration_tables(args, class_list, region_list)

Parses, verifies and orders list of migration matrices necessary for program.

Parameters:
  • args (dictionary) – same args as model entry point
  • class_list (list) – list of class names
  • region_list (list) – list of region names
Returns:

see example below

Return type:

mig_dict (dictionary)

Example Returns:

mig_dict = {
    'Migration': [numpy.matrix, numpy.matrix, ...]
}

Note

If migration matrices are not provided for all classes, the function will generate identity matrices for missing classes

natcap.invest.fisheries.fisheries_io.read_population_csv(args, path)

Parses and verifies a single Population Parameters CSV file

Parses and verifies inputs from the Population Parameters CSV file. If not all necessary vectors are included, the function will raise a MissingParameter exception. Survival matrix will be arranged by class-elements, 2nd dim: sex, and 3rd dim: region. Class vectors will be arranged by class-elements, 2nd dim: sex (depending on whether model is sex-specific) Region vectors will be arraged by region-elements, sex-agnostic.

Parameters:
  • args (dictionary) – arguments provided by user
  • path (string) – the particular Population Parameters CSV file to parse and verifiy
Returns:

dictionary containing verified population

arguments

Return type:

pop_dict (dictionary)

Example Returns:

pop_dict = {
    'population_csv_path': 'path/to/csv',
    'Survnaturalfrac': numpy.array(
        [[...], [...]], [[...], [...]], ...),

    # Class Vectors
    'Classes': numpy.array([...]),
    'Vulnfishing': numpy.array([...], [...]),
    'Maturity': numpy.array([...], [...]),
    'Duration': numpy.array([...], [...]),
    'Weight': numpy.array([...], [...]),
    'Fecundity': numpy.array([...], [...]),

    # Region Vectors
    'Regions': numpy.array([...]),
    'Exploitationfraction': numpy.array([...]),
    'Larvaldispersal': numpy.array([...]),
}
natcap.invest.fisheries.fisheries_io.read_population_csvs(args)

Parses and verifies the Population Parameters CSV files

Parameters:args (dictionary) – arguments provided by user
Returns:
list of dictionaries containing verified population
arguments
Return type:pop_list (list)

Example Returns:

pop_list = [
    {
        'Survnaturalfrac': numpy.array(
            [[...], [...]], [[...], [...]], ...),

        # Class Vectors
        'Classes': numpy.array([...]),
        'Vulnfishing': numpy.array([...], [...]),
        'Maturity': numpy.array([...], [...]),
        'Duration': numpy.array([...], [...]),
        'Weight': numpy.array([...], [...]),
        'Fecundity': numpy.array([...], [...]),

        # Region Vectors
        'Regions': numpy.array([...]),
        'Exploitationfraction': numpy.array([...]),
        'Larvaldispersal': numpy.array([...]),
    },
    {
        ...
    }
]
natcap.invest.fisheries.fisheries_model module

The Fisheries Model module contains functions for running the model

Variable Suffix Notation: t: time x: area/region a: age/class s: sex

natcap.invest.fisheries.fisheries_model.initialize_vars(vars_dict)

Initializes variables for model run

Parameters:vars_dict (dictionary) – verified arguments and variables
Returns:modified vars_dict with additional variables
Return type:vars_dict (dictionary)

Example Returns:

vars_dict = {
    # (original vars)

    'Survtotalfrac': np.array([...]),  # a,s,x
    'G_survtotalfrac': np.array([...]),  # (same)
    'P_survtotalfrac': np.array([...]),  # (same)
    'N_tasx': np.array([...]),  # Index Order: t,a,s,x
    'H_tx': np.array([...]), # t,x
    'V_tx': np.array([...]), # t,x
    'Spawners_t': np.array([...]),
}
natcap.invest.fisheries.fisheries_model.run_population_model(vars_dict, init_cond_func, cycle_func, harvest_func)

Runs the model

Parameters:
  • vars_dict (dictionary) –
  • init_cond_func (lambda function) – sets initial conditions
  • cycle_func (lambda function) – computes numbers for the next time step
  • harvest_func (lambda function) – computes harvest and valuation
Returns:

vars_dict (dictionary)

Example Returned Dictionary:

{
    # (other items)
    ...
    'N_tasx': np.array([...]),  # Index Order: time, class, sex, region
    'H_tx': np.array([...]),  # Index Order: time, region
    'V_tx': np.array([...]),  # Index Order: time, region
    'Spawners_t': np,array([...]),
    'equilibrate_timestep': <int>,
}
natcap.invest.fisheries.fisheries_model.set_cycle_func(vars_dict, rec_func)

Creates a function to run a single cycle in the model

Parameters:
  • vars_dict (dictionary) –
  • rec_func (lambda function) – recruitment function

Example Output of Returned Cycle Function:

N_asx = np.array([...])
spawners = <int>

N_next, spawners = cycle_func(N_prev)
natcap.invest.fisheries.fisheries_model.set_harvest_func(vars_dict)

Creates harvest function that calculates the given harvest and valuation of the fisheries population over each time step for a given region. Returns None if harvest isn’t selected by user.

Example Outputs of Returned Harvest Function:

H_x, V_x = harv_func(N_tasx)

H_x = np.array([3.0, 4.5, 2.5, ...])
V_x = np.array([6.0, 9.0, 5.0, ...])
natcap.invest.fisheries.fisheries_model.set_init_cond_func(vars_dict)

Creates a function to set the initial conditions of the model

Parameters:vars_dict (dictionary) – variables
Returns:initial conditions function
Return type:init_cond_func (lambda function)

Example Return Array:

N_asx = np.ndarray([...])
natcap.invest.fisheries.fisheries_model.set_recru_func(vars_dict)

Creates recruitment function that calculates the number of recruits for class 0 at time t for each region (currently sex agnostic). Also returns number of spawners

Parameters:vars_dict (dictionary) –
Returns:recruitment function
Return type:rec_func (function)

Example Output of Returned Recruitment Function:

N_next[0], spawners = rec_func(N_prev)
Module contents
natcap.invest.hydropower package
Submodules
natcap.invest.hydropower.hydropower_water_yield module
Module contents
natcap.invest.ndr package
Submodules
natcap.invest.ndr.ndr module
natcap.invest.ndr.ndr_core module
Module contents
natcap.invest.recreation package
Submodules
natcap.invest.recreation.buffered_numpy_disk_map module

Buffered file manager module.

class natcap.invest.recreation.buffered_numpy_disk_map.BufferedNumpyDiskMap(manager_filename, max_bytes_to_buffer)

Bases: object

Persistent object to append and read numpy arrays to unique keys.

This object is abstractly a key/value pair map where the operations are to append, read, and delete numpy arrays associated with those keys. The object attempts to keep data in RAM as much as possible and saves data to files on disk to manage memory and persist between instantiations.

append(array_id, array_data)

Append data to the file.

Parameters:
  • array_id (int) – unique key to identify the array node
  • array_data (numpy.ndarray) – data to append to node.
Returns:

None

delete(array_id)

Delete node array_id from disk and cache.

flush()

Method to flush data in memory to disk.

read(array_id)

Read the entirety of the file.

Internally this might mean that part of the file is read from disk and the end from the buffer or any combination of those.

Parameters:array_id (string) – unique node id to read
Returns:contents of node as a numpy.ndarray.
natcap.invest.recreation.out_of_core_quadtree module
natcap.invest.recreation.recmodel_client module
natcap.invest.recreation.recmodel_server module
natcap.invest.recreation.recmodel_workspace_fetcher module

InVEST recreation workspace fetcher.

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

Fetch workspace from remote server.

After the call a .zip file exists at args[‘workspace_dir’] named args[‘workspace_id’] + ‘.zip’ and contains the zipped workspace of that model run.

Parameters:
  • args['workspace_dir'] (string) – path to workspace directory
  • args['hostname'] (string) – FQDN to recreation server
  • args['port'] (string or int) – port on hostname for recreation server
  • args['workspace_id'] (string) – workspace identifier
Returns:

None

Module contents
natcap.invest.reporting package
Submodules
natcap.invest.reporting.html module

Utilities for creating simple HTML report files.

class natcap.invest.reporting.html.Element(tag, content='', end_tag=True, **attrs)

Bases: object

Represents a generic HTML element.

Any Element object can be passed to HTMLDocument.add()

Example

doc = html.HTMLDocument(…) details_elem = doc.add(html.Element(‘details’)) details_elem.add(

html.Element(‘img’, src=’images/my_pic.png’, end_tag=False))
add(elem)

Add a child element (which is returned for convenience).

html()

Returns an HTML string for this element (and its children).

class natcap.invest.reporting.html.HTMLDocument(uri, title, header)

Bases: object

Utility class for creating simple HTML files.

Example usage:

# Create the document object. doc = html.HTMLDocument(‘myfile.html’, ‘My Page’, ‘A Page About Me’)

# Add some text. doc.write_header(‘My Early Life’) doc.write_paragraph(‘I lived in a small barn.’)

# Add a table. table = doc.add(html.Table()) table.add_row([‘Age’, ‘Weight’], is_header=True) table.add_row([‘1 year’, ‘20 pounds’]) table.add_row([‘2 years’, ‘40 pounds’])

# Add an arbitrary HTML element. # Note that the HTML ‘img’ element doesn’t have an end tag. doc.add(html.Element(‘img’, src=’images/my_pic.png’, end_tag=False))

# Create the file. doc.flush()

add(elem)

Add an arbitrary element to the body of the document.

elem - any object that has a method html() to output HTML markup

Return the added element for convenience.

flush()

Create a file with the contents of this document.

insert_table_of_contents(max_header_level=2)

Insert an auto-generated table of contents.

The table of contents is based on the headers in the document.

write_header(text, level=2)

Convenience method to write a header.

write_paragraph(text)

Convenience method to write a paragraph.

class natcap.invest.reporting.html.Table(**attr)

Bases: object

Represents and renders HTML tables.

add_row(cells, is_header=False, cell_attr=None, do_formatting=True)

Writes a table row with the given cell data.

cell_attr - attributes for each cell. If provided, it must be the
same length as cells. Each entry should be a dictionary mapping attribute key to value.
add_two_level_header(outer_headers, inner_headers, row_id_header)

Adds a two level header to the table.

In this header, each outer header appears on the top row, and each inner header appears once beneath each outer header.

For example, the following code:

table.add_two_level_header(
outer_headers=[‘Weight’, ‘Value’], inner_headers=[‘Mean, Standard deviation’], row_id_header=’Farm ID’)

produces the following header:

Weight Value

Farm ID Mean Standard Deviation Mean Standard deviation

html()

Return the HTML string for the table.

natcap.invest.reporting.html.cell_format(data)

Formats the data to put in a table cell.

natcap.invest.reporting.table_generator module

A helper module for generating html tables that are represented as Strings

natcap.invest.reporting.table_generator.add_checkbox_column(col_list, row_list, checkbox_pos=1)

Insert a new column into the list of column dictionaries so that it is the second column dictionary found in the list. Also add the checkbox column header to the list of row dictionaries and subsequent checkbox value

‘col_list’- a list of dictionaries that defines the column

structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘row_list’ - a list of dictionaries that represent the rows. Each

dictionaries keys should match the column names found in ‘col_list’ (required) Example: [{col_name_1: value, col_name_2: value, …},

{col_name_1: value, col_name_2: value, …}, …]
checkbox_pos - an integer for the position of the checkbox
column. Defaulted at 1 (optional)
returns - a tuple of the updated column and rows list of dictionaries
in that order
natcap.invest.reporting.table_generator.add_totals_row(col_headers, total_list, total_name, checkbox_total, tdata_tuples)

Construct a totals row as an html string. Creates one row element with data where the row gets a class name and the data get a class name if the corresponding column is a totalable column

col_headers - a list of the column headers in order (required)

total_list - a list of booleans that corresponds to ‘col_headers’ and
indicates whether a column should be totaled (required)
total_name - a string for the name of the total row, ex: ‘Total’, ‘Sum’
(required)
checkbox_total - a boolean value that distinguishes whether a checkbox
total row is being added or a regular total row. Checkbox total row is True. This will determine the row class name and row data class name (required)
tdata_tuples - a list of tuples where the first index in the tuple is a
boolean which indicates if a table data element has a attribute class. The second index is the String value of that class or None (required)
return - a string representing the html contents of a row which should
later be used in a ‘tfoot’ element
natcap.invest.reporting.table_generator.generate_table(table_dict, attributes=None)

Takes in a dictionary representation of a table and generates a String of the the table in the form of hmtl

table_dict - a dictionary with the following arguments:
‘cols’- a list of dictionaries that defines the column

structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘attr’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attr’: {‘class’: ‘offsets’}
‘td_class’ - a String to assign as a class name to
the table data tags under the column. Each table data tag under the column will have a class attribute assigned to ‘td_class’ value (optional)
‘rows’ - a list of dictionaries that represent the rows. Each

dictionaries keys should match the column names found in ‘cols’ (possibly empty list) (required) Example: [{col_name_1: value, col_name_2: value, …},

{col_name_1: value, col_name_2: value, …}, …]
‘checkbox’ - a boolean value for whether there should be a
checkbox column. If True a ‘selected total’ row will be added to the bottom of the table that will show the total of the columns selected (optional)
‘checkbox_pos’ - an integer value for in which column
position the the checkbox column should appear (optional)
‘total’- a boolean value for whether there should be a constant
total row at the bottom of the table that sums the column values (optional)
‘attributes’ - a dictionary of html table attributes. The attribute
name is the key which gets set to the value of the key. (optional) Example: {‘class’: ‘sorttable’, ‘id’: ‘parcel_table’}

returns - a string representing an html table

natcap.invest.reporting.table_generator.get_dictionary_values_ordered(dict_list, key_name)

Generate a list, with values from ‘key_name’ found in each dictionary in the list of dictionaries ‘dict_list’. The order of the values in the returned list match the order they are retrieved from ‘dict_list’

dict_list - a list of dictionaries where each dictionary has the same
keys. Each dictionary should have at least one key:value pair with the key being ‘key_name’ (required)
key_name - a String or Int for the key name of interest in the
dictionaries (required)
return - a list of values from ‘key_name’ in ascending order based
on ‘dict_list’ keys
natcap.invest.reporting.table_generator.get_row_data(row_list, col_headers)

Construct the rows in a 2D List from the list of dictionaries, using col_headers to properly order the row data.

‘row_list’ - a list of dictionaries that represent the rows. Each

dictionaries keys should match the column names found in ‘col_headers’. The rows will be ordered the same as they are found in the dictionary list (required) Example: [{‘col_name_1’:‘9/13’, ‘col_name_3’:’expensive’,

‘col_name_2’:’chips’},
{‘col_name_1’:‘3/13’, ‘col_name_2’:’cheap’,
‘col_name_3’:’peanuts’},
{‘col_name_1’:‘5/12’, ‘col_name_2’:’moderate’,
‘col_name_3’:’mints’}]
col_headers - a List of the names of the column headers in order
example : [col_name_1, col_name_2, col_name_3…]

return - a 2D list with each inner list representing a row

Module contents

natcap.invest.reporting package.

natcap.invest.reporting.add_head_element(param_args)

Generates a string that represents a valid element in the head section of an html file. Currently handles ‘style’ and ‘script’ elements, where both the script and style are locally embedded

param_args - a dictionary that holds the following arguments:

param_args[‘format’] - a string representing the type of element to
be added. Currently : ‘script’, ‘style’ (required)
param_args[‘data_src’] - a string URI path for the external source
of the element OR a String representing the html (DO NOT include html tags, tags are automatically generated). If a URI the file is read in as a String. (required)
param_args[‘input_type’] - ‘Text’ or ‘File’. Determines how the
input from ‘data_src’ is handled (required)
‘attributes’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attributes’: {‘class’: ‘offsets’}

returns - a string representation of the html head element

natcap.invest.reporting.add_text_element(param_args)

Generates a string that represents a html text block. The input string should be wrapped in proper html tags

param_args - a dictionary with the following arguments:

param_args[‘text’] - a string

returns - a string

natcap.invest.reporting.build_table(param_args)

Generates a string representing a table in html format.

param_args - a dictionary that has the parameters for building up the

html table. The dictionary includes the following:

‘attributes’ - a dictionary of html table attributes. The attribute
name is the key which gets set to the value of the key. (optional) Example: {‘class’: ‘sorttable’, ‘id’: ‘parcel_table’}
param_args[‘sortable’] - a boolean value that determines whether the
table should be sortable (required)
param_args[‘data_type’] - a string depicting the type of input to
build the table from. Either ‘shapefile’, ‘csv’, or ‘dictionary’ (required)
param_args[‘data’] - a URI to a csv or shapefile OR a list of

dictionaries. If a list of dictionaries the data should be represented in the following format: (required)

[{col_name_1: value, col_name_2: value, …},
{col_name_1: value, col_name_2: value, …}, …]
param_args[‘key’] - a string that depicts which column (csv) or
field (shapefile) will be the unique key to use in extracting the data into a dictionary. (required for ‘data_type’ ‘shapefile’ and ‘csv’)
param_args[‘columns’] - a list of dictionaries that defines the

column structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘attr’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attr’: {‘class’: ‘offsets’}
‘td_class’ - a String to assign as a class name to
the table data tags under the column. Each table data tag under the column will have a class attribute assigned to ‘td_class’ value (optional)
param_args[‘total’] - a boolean value where if True a constant
total row will be placed at the bottom of the table that sums the columns (required)

returns - a string that represents an html table

natcap.invest.reporting.data_dict_to_list(data_dict)

Abstract out inner dictionaries from data_dict into a list, where the inner dictionaries are added to the list in the order of their sorted keys

data_dict - a dictionary with unique keys pointing to dictionaries.
Could be empty (required)

returns - a list of dictionaries, or empty list if data_dict is empty

natcap.invest.reporting.extract_datasource_table_by_key(datasource_uri, key_field)

Return vector attribute table of first layer as dictionary.

Create a dictionary lookup table of the features in the attribute table of the datasource referenced by datasource_uri.

Parameters:
  • datasource_uri (string) – a uri to an OGR datasource
  • key_field – a field in datasource_uri that refers to a key value for each row such as a polygon id.
Returns:

returns a dictionary of the

form {key_field_0: {field_0: value0, field_1: value1}…}

Return type:

attribute_dictionary (dict)

natcap.invest.reporting.generate_report(args)

Generate an html page from the arguments given in ‘reporting_args’

reporting_args[title] - a string for the title of the html page
(required)
reporting_args[sortable] - a boolean value indicating whether
the sorttable.js library should be added for table sorting functionality (optional)
reporting_args[totals] - a boolean value indicating whether
the totals_function.js script should be added for table totals functionality (optional)
reporting_args[out_uri] - a URI to the output destination for the html
page (required)
reporting_args[elements] - a list of dictionaries that represent html

elements to be added to the html page. (required) If no elements are provided (list is empty) a blank html page will be generated. The 3 main element types are ‘table’, ‘head’, and ‘text’. All elements share the following arguments:

‘type’ - a string that depicts the type of element being add.
Currently ‘table’, ‘head’, and ‘text’ are defined (required)
‘section’ - a string that depicts whether the element belongs
in the body or head of the html page. Values: ‘body’ | ‘head’ (required)

Table element dictionary has at least the following additional arguments:

‘attributes’ - a dictionary of html table attributes. The
attribute name is the key which gets set to the value of the key. (optional) Example: {‘class’: ‘sorttable’, ‘id’: ‘parcel_table’}
‘sortable’ - a boolean value for whether the tables columns
should be sortable (required)
‘checkbox’ - a boolean value for whether there should be a
checkbox column. If True a ‘selected total’ row will be added to the bottom of the table that will show the total of the columns selected (optional)
‘checkbox_pos’ - an integer value for in which column
position the the checkbox column should appear (optional)
‘data_type’ - one of the following string values:
‘shapefile’|’hg csv’|’dictionary’. Depicts the type of data structure to build the table from (required)
‘data’ - either a list of dictionaries if ‘data_type’ is

‘dictionary’ or a URI to a CSV table or shapefile if ‘data_type’ is ‘shapefile’ or ‘csv’ (required). If a list of dictionaries, each dictionary should have keys that represent the columns, where each dictionary is a row (list could be empty) How the rows are ordered are defined by their index in the list. Formatted example: [{col_name_1: value, col_name_2: value, …},

{col_name_1: value, col_name_2: value, …}, …]
‘key’ - a string that defines which column or field should be
used as the keys for extracting data from a shapefile or csv table ‘key_field’. (required for ‘data_type’ = ‘shapefile’ | ‘csv’)
‘columns’- a list of dictionaries that defines the column

structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘attr’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attr’: {‘class’: ‘offsets’}
‘td_class’ - a String to assign as a class name to
the table data tags under the column. Each table data tag under the column will have a class attribute assigned to ‘td_class’ value (optional)
‘total’- a boolean value for whether there should be a constant
total row at the bottom of the table that sums the column values (optional)

Head element dictionary has at least the following additional arguments:

‘format’ - a string representing the type of head element being
added. Currently ‘script’ (javascript) and ‘style’ (css style) accepted (required)
‘data_src’- a URI to the location of the external file for
either the ‘script’ or the ‘style’ OR a String representing the html script or style (DO NOT include the tags) (required)
‘input_type’ - a String, ‘File’ or ‘Text’ that refers to how
‘data_src’ is being passed in (URI vs String) (required).
‘attributes’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attributes’: {‘id’: ‘muni_data’}

Text element dictionary has at least the following additional arguments:

‘text’- a string to add as a paragraph element in the html page
(required)

returns - nothing

natcap.invest.reporting.write_html(html_obj, out_uri)

Write an html file to ‘out_uri’ from html element represented as strings in ‘html_obj’

html_obj - a dictionary with two keys, ‘head’ and ‘body’, that point to

lists. The list for each key is a list of the htmls elements as strings (required) example: {‘head’:[‘elem_1’, ‘elem_2’,…],

‘body’:[‘elem_1’, ‘elem_2’,…]}

out_uri - a URI for the output html file

returns - nothing

natcap.invest.scenic_quality package
Submodules
natcap.invest.scenic_quality.scenic_quality module
natcap.invest.scenic_quality.viewshed module
Module contents
natcap.invest.sdr package
Submodules
natcap.invest.sdr.sdr module
natcap.invest.sdr.sdr_core module
Module contents
natcap.invest.seasonal_water_yield package
Submodules
natcap.invest.seasonal_water_yield.seasonal_water_yield module
natcap.invest.seasonal_water_yield.seasonal_water_yield_core module
Module contents
natcap.invest.ui package
Submodules
natcap.invest.ui.carbon module
natcap.invest.ui.cbc module
natcap.invest.ui.coastal_vulnerability module
natcap.invest.ui.crop_production module
natcap.invest.ui.delineateit module
natcap.invest.ui.execution module
natcap.invest.ui.finfish module
natcap.invest.ui.fisheries module
natcap.invest.ui.forest_carbon module
natcap.invest.ui.globio module
natcap.invest.ui.habitat_quality module
natcap.invest.ui.hra module
natcap.invest.ui.hydropower module
natcap.invest.ui.inputs module
natcap.invest.ui.launcher module
natcap.invest.ui.model module
natcap.invest.ui.ndr module
natcap.invest.ui.pollination module
natcap.invest.ui.recreation module
natcap.invest.ui.routedem module
natcap.invest.ui.scenario_gen module
natcap.invest.ui.scenic_quality module
natcap.invest.ui.sdr module
natcap.invest.ui.seasonal_water_yield module
natcap.invest.ui.urban_cooling_model module
natcap.invest.ui.urban_flood_risk_mitigation module
natcap.invest.ui.usage module

Module to that provides functions for usage logging.

natcap.invest.ui.usage.log_run(module, args)

Context manager to log an InVEST model run and exit status.

Parameters:
  • module (string) – The string module name that identifies the model.
  • args (dict) – The full args dictionary.
Returns:

None

natcap.invest.ui.wave_energy module
natcap.invest.ui.wind_energy module
Module contents
Submodules
natcap.invest.carbon module
natcap.invest.cli module

Single entry point for all InVEST applications.

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 possibly-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_json()

Build a json object of relevant information for the CLI.

The json object returned uses the human-readable model names for keys and the values are another dict containing the internal python name of the model and the aliases recognized by the CLI.

Returns:A string representation of the JSON object.
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(user_args=None)

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

natcap.invest.coastal_vulnerability module
natcap.invest.crop_production_percentile module
natcap.invest.crop_production_regression module
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.delineateit module
natcap.invest.forest_carbon_edge_effect module
natcap.invest.globio module
natcap.invest.habitat_quality module
natcap.invest.hra module
natcap.invest.pollination module
natcap.invest.routedem module
natcap.invest.scenario_gen_proximity module
natcap.invest.urban_cooling_model module
natcap.invest.urban_flood_risk_mitigation 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, column_list=None, to_lower=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.

If an entire row is NA/NaN (including key_field) then it is dropped from the table and a warning is given of the dropped rows.

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 and sets the row index.
  • column_list (list) – a list of column names to subset from the CSV file, default=None
  • to_lower (bool) – if True, converts all unicode in the CSV, including headers and values to lowercase, otherwise uses raw string values. default=True.
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)

Raise:
ValueError
If ValueError occurs during conversion to dictionary.
KeyError
If key_field is not present during set_index call.
natcap.invest.utils.capture_gdal_logging()

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(logfile, exclude_threads=None, logging_level=0, log_fmt='%(asctime)s %(module)s.%(funcName)s(%(lineno)d) %(levelname)s %(message)s', date_fmt=None)

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 (string) – The logging date format string to use. If not provided, ISO8601 format 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(workspace, name, logging_level=0, exclude_threads=None)
natcap.invest.utils.sandbox_tempdir(suffix='', prefix='tmp', dir=None)

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
natcap.invest.wave_energy module
natcap.invest.wind_energy module
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.

Module contents

Indices and tables

Ecosystem Service Analysis Tools

Coastal Protection Package

Coastal Vulnerability
Coastal Vulnerability Core
Coastal Vulnerability Cython Core
Coastal Vulnerability Post Processing
Module contents

Final Ecosystem Services

Coastal Blue Carbon Package

Model Entry Point
Coastal Blue Carbon
Preprocessor
Module contents

Coastal Blue Carbon package.

Carbon Package

Model Entry Point
Carbon Combined
Carbon Biophysical
Carbon Valuation
Carbon Utilities
Module contents

Crop Production Package

Model Entry Point
Crop Production IO Module
Crop Production Model Module
Module contents

Finfish Aquaculture Package

Model Entry Point
Finfish Aquaculture
Finfish Aquaculture Core

Implementation of the aquaculture calculations, and subsequent outputs. This will pull from data passed in by finfish_aquaculture.

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.calc_farm_cycles(outplant_buffer, a, b, tau, water_temp_dict, farm_op_dict, dur)
Input:
outplant_buffer: The number of days surrounding the outplant day during
which the fish growth cycle can still be started.
a: Growth parameter alpha. Float used as a scaler in the fish growth
equation.
b: Growth paramater beta. Float used as an exponential multiplier in
the fish growth equation.
water_temp_dict: 2D dictionary which contains temperature values for
farms. The outer keys are calendar days as strings, and the inner are farm numbers as strings.
farm_op_dict: 2D dictionary which contains individual operating
parameters for each farm. The outer key is farm number as a string, and the inner is string descriptors of each parameter.
dur: Float which describes the length for the growth simulation to run
in years.

Returns cycle_history where:

cycle_history: Dictionary which contains mappings from farms to a

history of growth for each cycle completed on that farm. These entries are formatted as follows…

Farm->List of Type (day of outplanting,day of harvest, fish weight
(grams))
natcap.invest.finfish_aquaculture.finfish_aquaculture_core.calc_hrv_weight(farm_op_dict, frac, mort, cycle_history)
Input:
farm_op_dict: 2D dictionary which contains individual operating
parameters for each farm. The outer key is farm number as a string, and the inner is string descriptors of each parameter.
frac: A float representing the fraction of the fish that remains after
processing.
mort: A float referring to the daily mortality rate of fishes on an
aquaculture farm.
cycle_history: Farm->List of Type (day of outplanting,
day of harvest, fish weight (grams))
Returns a tuple (curr_cycle_totals,indiv_tpw_totals) where:
curr_cycle_totals_: dictionary which will hold a mapping from every
farm (as identified by farm_ID) to the total processed weight of each farm
indiv_tpw_totals: dictionary which will hold a farm->list mapping,
where the list holds the individual tpw for all cycles that the farm completed
natcap.invest.finfish_aquaculture.finfish_aquaculture_core.compute_uncertainty_data(args, output_dir)

Does uncertainty analysis via a Monte Carlo simulation.

Returns: -a dict containining statistical results (mean and std deviation) The dict has farm IDs as outer keys, and result types (e.g. ‘value’, ‘weight’, and ‘cycles’) as inner keys.

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.create_HTML_table(output_dir, args, cycle_history, sum_hrv_weight, hrv_weight, farms_npv, value_history, uncertainty_stats)
Inputs:
output_dir: The directory in which we will be creating our .html file
output.
cycle_history: dictionary mapping farm ID->list of tuples, each of
which contains 3 things- (day of outplanting, day of harvest,
harvest weight of a single fish in grams)
sum_hrv_weight: dictionary which holds a mapping from farm ID->total
processed weight of each farm
hrv_weight: dictionary which holds a farm->list mapping, where the list
holds the individual tpw for all cycles that the farm completed
do_valuation: boolean variable that says whether or not valuation is
desired
farms_npv: dictionary with a farm-> float mapping, where each float is
the net processed value of the fish processed on that farm, in $1000s of dollars.
value_history: dictionary which holds a farm->list mapping, where the
list holds tuples containing (Net Revenue, Net Present Value) for each cycle completed by that farm
Output:
HTML file: contains 3 tables that summarize inputs and outputs for the

duration of the model. - Input Table: Farm Operations provided data, including Farm ID #,

Cycle Number, weight of fish at start, weight of fish at harvest, number of fish in farm, start day for growing, and length of fallowing period
  • Output Table 1: Farm Harvesting data, including a summary table
    for each harvest cycle of each farm. Will show Farm ID, cycle number, days since outplanting date, harvested weight, net revenue, outplant day, and year.
  • Output Table 2: Model outputs for each farm, including Farm ID,
    net present value, number of completed harvest cycles, and total volume harvested.

Returns nothing.

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.do_monte_carlo_simulation(args)

Performs a Monte Carlo simulation and returns the results.

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

‘ Runs the biophysical and valuation parts of the finfish aquaculture model. This will output: 1. a shape file showing farm locations w/ addition of # of harvest cycles,

total processed weight at that farm, and if valuation is true, total discounted net revenue at each farm location.
  1. Three HTML tables summarizing all model I/O- summary of user-provided
    data, summary of each harvest cycle, and summary of the outputs/farm
  2. A .txt file that is named according to the date and time the model is
    run, which lists the values used during that run

Data in args should include the following: –Biophysical Arguments– args: a python dictionary containing the following data: args[‘workspace_dir’]- The directory in which to place all result files. args[‘ff_farm_file’]- An open shape file containing the locations of

individual fisheries
args[‘farm_ID’]- column heading used to describe individual farms. Used to
link GIS location data to later inputs.
args[‘g_param_a’]- Growth parameter alpha, used in modeling fish growth,
should be int or a float.
args[‘g_param_b’]- Growth parameter beta, used in modeling fish growth,
should be int or a float.
args[‘water_temp_dict’]- A dictionary which links a specific date to the

farm numbers, and their temperature values on that day. (Note: in this case, the outer keys 1 and 2 are calendar days out of 365, starting with January 1 (day 0), and the inner 1, 2, and 3 are farm numbers.)

Format: {‘0’: ‘{‘1’: ‘8.447, ‘2’: ‘8.447’, ‘3’:‘8.947’, …}’ ,
‘1’: ‘{‘1’: ‘8.406, ‘2’: ‘8.406’, ‘3’:‘8.906’, …}’ ,

. . . . . . . . . }

args[‘farm_op_dict’]- Dictionary which links a specific farm ID # to

another dictionary containing operating parameters mapped to their value for that particular farm (Note: in this case, the 1 and 2 are farm ID’s, not dates out of 365.)

Format: {‘1’: ‘{‘Wt of Fish’: ‘0.06’, ‘Tar Weight’: ‘5.4’, …}’,
‘2’: ‘{‘Wt of Fish’: ‘0.06’, ‘Tar Weight’: ‘5.4’, …}’, . . . . . . . . . }
args[‘frac_post_process’]- the fraction of edible fish left after
processing is done to remove undesirable parts
args[‘mort_rate_daily’]- mortality rate among fish in a year, divided by
365

args[‘duration’]- duration of the simulation, in years args[‘outplant_buffer’] - This value will allow the outplant start day to

be flexible plus or minus the number of days specified here.

–Valuation arguments– args[‘do_valuation’]- boolean indicating whether or not to run the

valuation process

args[‘p_per_kg’]: Market price per kilogram of processed fish args[‘frac_p’]: Fraction of market price that accounts for costs rather

than profit

args[‘discount’]: Daily market discount rate

returns nothing

natcap.invest.finfish_aquaculture.finfish_aquaculture_core.valuation(price_per_kg, frac_mrkt_price, discount, hrv_weight, cycle_history)

This performs the valuation calculations, and returns tuple containing a dictionary with a farm-> float mapping, where each float is the net processed value of the fish processed on that farm, in $1000s of dollars, and a dictionary containing a farm-> list mapping, where each entry in the list is a tuple of (Net Revenue, Net Present Value) for every cycle on that farm.

Inputs:
price_per_kg: Float representing the price per kilogram of finfish for
valuation purposes.
frac_mrkt_price: Float that represents the fraction of market price
that is attributable to costs.

discount: Float that is the daily market discount rate. cycle_hisory: Farm->List of Type (day of outplanting,

day of harvest, fish weight (grams))

hrv_weight: Farm->List of TPW for each cycle (kilograms)

Returns a tuple (val_history, valuations):
val_history: dictionary which will hold a farm->list mapping, where the
list holds tuples containing (Net Revenue, Net Present Value) for each cycle completed by that farm
valuations: dictionary with a farm-> float mapping, where each float is
the net processed value of the fish processed on that farm
Module contents

Fisheries Package

Fisheries Model Entry Point
Fisheries IO Module

The Fisheries IO module contains functions for handling inputs and outputs

exception natcap.invest.fisheries.fisheries_io.MissingParameter

Bases: ValueError

An exception class that may be raised when a necessary parameter is not provided by the user.

natcap.invest.fisheries.fisheries_io.create_outputs(vars_dict)

Creates outputs from variables generated in the run_population_model() function in the fisheries_model module

Creates the following:

  • Results CSV File
  • Results HTML Page
  • Results Shapefile (if provided)
  • Intermediate CSV File
Parameters:vars_dict (dictionary) – contains variables generated by model run
natcap.invest.fisheries.fisheries_io.fetch_args(args, create_outputs=True)

Fetches input arguments from the user, verifies for correctness and completeness, and returns a list of variables dictionaries

Parameters:args (dictionary) – arguments from the user
Returns:
set of variable dictionaries for each
model
Return type:model_list (list)

Example Returns:

model_list = [
    {
        'workspace_dir': 'path/to/workspace_dir',
        'results_suffix': 'scenario_name',
        'output_dir': 'path/to/output_dir',
        'aoi_vector_path': 'path/to/aoi_vector_path',
        'total_timesteps': 100,
        'population_type': 'Stage-Based',
        'sexsp': 2,
        'harvest_units': 'Individuals',
        'do_batch': False,
        'spawn_units': 'Weight',
        'total_init_recruits': 100.0,
        'recruitment_type': 'Ricker',
        'alpha': 32.4,
        'beta': 54.2,
        'total_recur_recruits': 92.1,
        'migr_cont': True,
        'val_cont': True,
        'frac_post_process': 0.5,
        'unit_price': 5.0,

        # Pop Params
        'population_csv_path': 'path/to/csv_path',
        'Survnaturalfrac': numpy.array(
            [[[...], [...]], [[...], [...]], ...]),
        'Classes': numpy.array([...]),
        'Vulnfishing': numpy.array([...], [...]),
        'Maturity': numpy.array([...], [...]),
        'Duration': numpy.array([...], [...]),
        'Weight': numpy.array([...], [...]),
        'Fecundity': numpy.array([...], [...]),
        'Regions': numpy.array([...]),
        'Exploitationfraction': numpy.array([...]),
        'Larvaldispersal': numpy.array([...]),

        # Mig Params
        'migration_dir': 'path/to/mig_dir',
        'Migration': [numpy.matrix, numpy.matrix, ...]
    },
    {
        ...  # additional dictionary doesn't exist when 'do_batch'
             # is false
    }
]

Note

This function receives an unmodified ‘args’ dictionary from the user

natcap.invest.fisheries.fisheries_io.read_migration_tables(args, class_list, region_list)

Parses, verifies and orders list of migration matrices necessary for program.

Parameters:
  • args (dictionary) – same args as model entry point
  • class_list (list) – list of class names
  • region_list (list) – list of region names
Returns:

see example below

Return type:

mig_dict (dictionary)

Example Returns:

mig_dict = {
    'Migration': [numpy.matrix, numpy.matrix, ...]
}

Note

If migration matrices are not provided for all classes, the function will generate identity matrices for missing classes

natcap.invest.fisheries.fisheries_io.read_population_csv(args, path)

Parses and verifies a single Population Parameters CSV file

Parses and verifies inputs from the Population Parameters CSV file. If not all necessary vectors are included, the function will raise a MissingParameter exception. Survival matrix will be arranged by class-elements, 2nd dim: sex, and 3rd dim: region. Class vectors will be arranged by class-elements, 2nd dim: sex (depending on whether model is sex-specific) Region vectors will be arraged by region-elements, sex-agnostic.

Parameters:
  • args (dictionary) – arguments provided by user
  • path (string) – the particular Population Parameters CSV file to parse and verifiy
Returns:

dictionary containing verified population

arguments

Return type:

pop_dict (dictionary)

Example Returns:

pop_dict = {
    'population_csv_path': 'path/to/csv',
    'Survnaturalfrac': numpy.array(
        [[...], [...]], [[...], [...]], ...),

    # Class Vectors
    'Classes': numpy.array([...]),
    'Vulnfishing': numpy.array([...], [...]),
    'Maturity': numpy.array([...], [...]),
    'Duration': numpy.array([...], [...]),
    'Weight': numpy.array([...], [...]),
    'Fecundity': numpy.array([...], [...]),

    # Region Vectors
    'Regions': numpy.array([...]),
    'Exploitationfraction': numpy.array([...]),
    'Larvaldispersal': numpy.array([...]),
}
natcap.invest.fisheries.fisheries_io.read_population_csvs(args)

Parses and verifies the Population Parameters CSV files

Parameters:args (dictionary) – arguments provided by user
Returns:
list of dictionaries containing verified population
arguments
Return type:pop_list (list)

Example Returns:

pop_list = [
    {
        'Survnaturalfrac': numpy.array(
            [[...], [...]], [[...], [...]], ...),

        # Class Vectors
        'Classes': numpy.array([...]),
        'Vulnfishing': numpy.array([...], [...]),
        'Maturity': numpy.array([...], [...]),
        'Duration': numpy.array([...], [...]),
        'Weight': numpy.array([...], [...]),
        'Fecundity': numpy.array([...], [...]),

        # Region Vectors
        'Regions': numpy.array([...]),
        'Exploitationfraction': numpy.array([...]),
        'Larvaldispersal': numpy.array([...]),
    },
    {
        ...
    }
]
Fisheries Model Module

The Fisheries Model module contains functions for running the model

Variable Suffix Notation: t: time x: area/region a: age/class s: sex

natcap.invest.fisheries.fisheries_model.initialize_vars(vars_dict)

Initializes variables for model run

Parameters:vars_dict (dictionary) – verified arguments and variables
Returns:modified vars_dict with additional variables
Return type:vars_dict (dictionary)

Example Returns:

vars_dict = {
    # (original vars)

    'Survtotalfrac': np.array([...]),  # a,s,x
    'G_survtotalfrac': np.array([...]),  # (same)
    'P_survtotalfrac': np.array([...]),  # (same)
    'N_tasx': np.array([...]),  # Index Order: t,a,s,x
    'H_tx': np.array([...]), # t,x
    'V_tx': np.array([...]), # t,x
    'Spawners_t': np.array([...]),
}
natcap.invest.fisheries.fisheries_model.run_population_model(vars_dict, init_cond_func, cycle_func, harvest_func)

Runs the model

Parameters:
  • vars_dict (dictionary) –
  • init_cond_func (lambda function) – sets initial conditions
  • cycle_func (lambda function) – computes numbers for the next time step
  • harvest_func (lambda function) – computes harvest and valuation
Returns:

vars_dict (dictionary)

Example Returned Dictionary:

{
    # (other items)
    ...
    'N_tasx': np.array([...]),  # Index Order: time, class, sex, region
    'H_tx': np.array([...]),  # Index Order: time, region
    'V_tx': np.array([...]),  # Index Order: time, region
    'Spawners_t': np,array([...]),
    'equilibrate_timestep': <int>,
}
natcap.invest.fisheries.fisheries_model.set_cycle_func(vars_dict, rec_func)

Creates a function to run a single cycle in the model

Parameters:
  • vars_dict (dictionary) –
  • rec_func (lambda function) – recruitment function

Example Output of Returned Cycle Function:

N_asx = np.array([...])
spawners = <int>

N_next, spawners = cycle_func(N_prev)
natcap.invest.fisheries.fisheries_model.set_harvest_func(vars_dict)

Creates harvest function that calculates the given harvest and valuation of the fisheries population over each time step for a given region. Returns None if harvest isn’t selected by user.

Example Outputs of Returned Harvest Function:

H_x, V_x = harv_func(N_tasx)

H_x = np.array([3.0, 4.5, 2.5, ...])
V_x = np.array([6.0, 9.0, 5.0, ...])
natcap.invest.fisheries.fisheries_model.set_init_cond_func(vars_dict)

Creates a function to set the initial conditions of the model

Parameters:vars_dict (dictionary) – variables
Returns:initial conditions function
Return type:init_cond_func (lambda function)

Example Return Array:

N_asx = np.ndarray([...])
natcap.invest.fisheries.fisheries_model.set_recru_func(vars_dict)

Creates recruitment function that calculates the number of recruits for class 0 at time t for each region (currently sex agnostic). Also returns number of spawners

Parameters:vars_dict (dictionary) –
Returns:recruitment function
Return type:rec_func (function)

Example Output of Returned Recruitment Function:

N_next[0], spawners = rec_func(N_prev)
Fisheries Habitat Scenario Tool Module
Fisheries Habitat Scenario Tool IO Module

The Fisheries Habitat Scenarios Tool IO module contains functions for handling inputs and outputs

natcap.invest.fisheries.fisheries_hst_io.fetch_args(args)

Fetches input arguments from the user, verifies for correctness and completeness, and returns a list of variables dictionaries

Parameters:args (dictionary) – arguments from the user (same as Fisheries Preprocessor entry point)
Returns:dictionary containing necessary variables
Return type:vars_dict (dictionary)
Raises:ValueError – parameter mismatch between Population and Habitat CSV files

Example Returns:

vars_dict = {
    'workspace_dir': 'path/to/workspace_dir/',
    'output_dir': 'path/to/output_dir/',
    'sexsp': 2,
    'gamma': 0.5,

    # Pop Vars
    'population_csv_path': 'path/to/csv_path',
    'Surv_nat_xsa': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Classes': np.array([...]),
    'Class_vectors': {
        'Vulnfishing': np.array([...], [...]),
        'Maturity': np.array([...], [...]),
        'Duration': np.array([...], [...]),
        'Weight': np.array([...], [...]),
        'Fecundity': np.array([...], [...]),
    },
    'Regions': np.array([...]),
    'Region_vectors': {
        'Exploitationfraction': np.array([...]),
        'Larvaldispersal': np.array([...]),
    },

    # Habitat Vars
    'habitat_chg_csv_path': 'path/to/csv',
    'habitat_dep_csv_path': 'path/to/csv',
    'Habitats': ['habitat1', 'habitat2', ...],
    'Hab_classes': ['class1', 'class2', ...],
    'Hab_regions': ['region1', 'region2', ...],
    'Hab_chg_hx': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Hab_dep_ha': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Hab_class_mvmt_a': np.array([...]),
    'Hab_dep_num_a': np.array([...]),
}
natcap.invest.fisheries.fisheries_hst_io.read_habitat_chg_csv(args)

Parses and verifies a Habitat Change Parameters CSV file and returns a dictionary of information related to the interaction between a species and the given habitats.

Parses the Habitat Change Parameters CSV file for the following vectors:

  • Names of Habitats and Regions
  • Habitat Area Change
Parameters:

args (dictionary) – arguments from the user (same as Fisheries HST entry point)

Returns:

dictionary containing necessary

variables

Return type:

habitat_chg_dict (dictionary)

Raises:
  • MissingParameter – required parameter not included
  • ValueError – values are out of bounds or of wrong type
  • IndexError – likely a file formatting issue

Example Returns:

habitat_chg_dict = {
    'Habitats': ['habitat1', 'habitat2', ...],
    'Hab_regions': ['region1', 'region2', ...],
    'Hab_chg_hx': np.array(
        [[[...], [...]], [[...], [...]], ...]),
}
natcap.invest.fisheries.fisheries_hst_io.read_habitat_dep_csv(args)

Parses and verifies a Habitat Dependency Parameters CSV file and returns a dictionary of information related to the interaction between a species and the given habitats.

Parses the Habitat Parameters CSV file for the following vectors:

  • Names of Habitats and Classes
  • Habitat-Class Dependency

The following vectors are derived from the information given in the file:

  • Classes where movement between habitats occurs
  • Number of habitats that a particular class depends upon
Parameters:

args (dictionary) – arguments from the user (same as Fisheries HST entry point)

Returns:

dictionary containing necessary

variables

Return type:

habitat_dep_dict (dictionary)

Raises:
  • MissingParameter - required parameter not included
  • ValueError - values are out of bounds or of wrong type
  • IndexError - likely a file formatting issue

Example Returns:

habitat_dep_dict = {
    'Habitats': ['habitat1', 'habitat2', ...],
    'Hab_classes': ['class1', 'class2', ...],
    'Hab_dep_ha': np.array(
        [[[...], [...]], [[...], [...]], ...]),
    'Hab_class_mvmt_a': np.array([...]),
    'Hab_dep_num_a': np.array([...]),
}
natcap.invest.fisheries.fisheries_hst_io.read_population_csv(args)

Parses and verifies a single Population Parameters CSV file

Parses and verifies inputs from the Population Parameters CSV file. If not all necessary vectors are included, the function will raise a MissingParameter exception. Survival matrix will be arranged by class-elements, 2nd dim: sex, and 3rd dim: region. Class vectors will be arranged by class-elements, 2nd dim: sex (depending on whether model is sex-specific) Region vectors will be arraged by region-elements, sex-agnostic.

Parameters:

args (dictionary) – arguments provided by user

Returns:

dictionary containing verified population

arguments

Return type:

pop_dict (dictionary)

Raises:
  • MissingParameter – required parameter not included
  • ValueError – values are out of bounds or of wrong type

Example Returns:

pop_dict = {
    'population_csv_path': 'path/to/csv',
    'Surv_nat_xsa': np.array(
        [[...], [...]], [[...], [...]], ...),

    # Class Vectors
    'Classes': np.array([...]),
    'Class_vector_names': [...],
    'Class_vectors': {
        'Vulnfishing': np.array([...], [...]),
        'Maturity': np.array([...], [...]),
        'Duration': np.array([...], [...]),
        'Weight': np.array([...], [...]),
        'Fecundity': np.array([...], [...]),
    },

    # Region Vectors
    'Regions': np.array([...]),
    'Region_vector_names': [...],
    'Region_vectors': {
        'Exploitationfraction': np.array([...]),
        'Larvaldispersal': np.array([...]),
    },
}
natcap.invest.fisheries.fisheries_hst_io.save_population_csv(vars_dict)

Creates a new Population Parameters CSV file based the provided inputs.

Parameters:vars_dict (dictionary) – variables generated by preprocessor arguments and run.

Example Args:

args = {
    'workspace_dir': 'path/to/workspace_dir/',
    'output_dir': 'path/to/output_dir/',
    'sexsp': 2,
    'population_csv_path': 'path/to/csv',  # original csv file
    'Surv_nat_xsa': np.ndarray([...]),
    'Surv_nat_xsa_mod': np.ndarray([...]),

    # Class Vectors
    'Classes': np.array([...]),
    'Class_vector_names': [...],
    'Class_vectors': {
        'Vulnfishing': np.array([...], [...]),
        'Maturity': np.array([...], [...]),
        'Duration': np.array([...], [...]),
        'Weight': np.array([...], [...]),
        'Fecundity': np.array([...], [...]),
    },

    # Region Vectors
    'Regions': np.array([...]),
    'Region_vector_names': [...],
    'Region_vectors': {
        'Exploitationfraction': np.array([...]),
        'Larvaldispersal': np.array([...]),
    },

    # other arguments are ignored ...
}

Note

  • Creates a modified Population Parameters CSV file located in the ‘workspace/output/’ folder
  • Currently appends ‘_modified’ to original filename for new filename
Module contents

Hydropower Package

Model Entry Point
Hydropower Water Yield
Module contents

Monthly Water Yield Package

Monthly Water Yield
Monthly Water Yield Cython Core
Module contents

Nutrient Delivery Ratio Package

Model Entry Point
Nutrient Delivery Ratio
Module contents

Pollination Package

Model Entry Point
Overlap Analysis
Overlap Analysis Core
Overlap Analysis Management Zone
Overlap Analysis Management Zone Core
Module contents

Recreation Package

Model Entry Point
Recreation Server
Recreation Client
Recreation Workspace Fetcher

InVEST recreation workspace fetcher.

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

Fetch workspace from remote server.

After the call a .zip file exists at args[‘workspace_dir’] named args[‘workspace_id’] + ‘.zip’ and contains the zipped workspace of that model run.

Parameters:
  • args['workspace_dir'] (string) – path to workspace directory
  • args['hostname'] (string) – FQDN to recreation server
  • args['port'] (string or int) – port on hostname for recreation server
  • args['workspace_id'] (string) – workspace identifier
Returns:

None

Scenic Quality Package

Model Entry Point
Scenic Quality
Scenic Quality Core
Scenic Quality Cython Core
Grass Examples
Los Sextante
Viewshed Grass
Viewshed Sextante
Module contents

Sediment Delivery Ratio Package

Model Entry Point
Sediment Delivery Ratio
Module contents

Wave Energy Package

Model Entry Point
Wave Energy
Module contents

Wind Energy Package

Model Entry Point
Wave Energy
Module contents

Supporting Ecosystem Services

Habitat Quality Package

Model Entry Point
Habitat Quality
Module contents

Habitat Risk Assessment Package

Model Entry Point
Habitat Risk Assessment
Habitat Risk Assessment Core
Habitat Risk Assessment Pre-processor
Module contents

Utilities

Reporting Package

Table Generator

A helper module for generating html tables that are represented as Strings

natcap.invest.reporting.table_generator.add_checkbox_column(col_list, row_list, checkbox_pos=1)

Insert a new column into the list of column dictionaries so that it is the second column dictionary found in the list. Also add the checkbox column header to the list of row dictionaries and subsequent checkbox value

‘col_list’- a list of dictionaries that defines the column

structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘row_list’ - a list of dictionaries that represent the rows. Each

dictionaries keys should match the column names found in ‘col_list’ (required) Example: [{col_name_1: value, col_name_2: value, …},

{col_name_1: value, col_name_2: value, …}, …]
checkbox_pos - an integer for the position of the checkbox
column. Defaulted at 1 (optional)
returns - a tuple of the updated column and rows list of dictionaries
in that order
natcap.invest.reporting.table_generator.add_totals_row(col_headers, total_list, total_name, checkbox_total, tdata_tuples)

Construct a totals row as an html string. Creates one row element with data where the row gets a class name and the data get a class name if the corresponding column is a totalable column

col_headers - a list of the column headers in order (required)

total_list - a list of booleans that corresponds to ‘col_headers’ and
indicates whether a column should be totaled (required)
total_name - a string for the name of the total row, ex: ‘Total’, ‘Sum’
(required)
checkbox_total - a boolean value that distinguishes whether a checkbox
total row is being added or a regular total row. Checkbox total row is True. This will determine the row class name and row data class name (required)
tdata_tuples - a list of tuples where the first index in the tuple is a
boolean which indicates if a table data element has a attribute class. The second index is the String value of that class or None (required)
return - a string representing the html contents of a row which should
later be used in a ‘tfoot’ element
natcap.invest.reporting.table_generator.generate_table(table_dict, attributes=None)

Takes in a dictionary representation of a table and generates a String of the the table in the form of hmtl

table_dict - a dictionary with the following arguments:
‘cols’- a list of dictionaries that defines the column

structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘attr’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attr’: {‘class’: ‘offsets’}
‘td_class’ - a String to assign as a class name to
the table data tags under the column. Each table data tag under the column will have a class attribute assigned to ‘td_class’ value (optional)
‘rows’ - a list of dictionaries that represent the rows. Each

dictionaries keys should match the column names found in ‘cols’ (possibly empty list) (required) Example: [{col_name_1: value, col_name_2: value, …},

{col_name_1: value, col_name_2: value, …}, …]
‘checkbox’ - a boolean value for whether there should be a
checkbox column. If True a ‘selected total’ row will be added to the bottom of the table that will show the total of the columns selected (optional)
‘checkbox_pos’ - an integer value for in which column
position the the checkbox column should appear (optional)
‘total’- a boolean value for whether there should be a constant
total row at the bottom of the table that sums the column values (optional)
‘attributes’ - a dictionary of html table attributes. The attribute
name is the key which gets set to the value of the key. (optional) Example: {‘class’: ‘sorttable’, ‘id’: ‘parcel_table’}

returns - a string representing an html table

natcap.invest.reporting.table_generator.get_dictionary_values_ordered(dict_list, key_name)

Generate a list, with values from ‘key_name’ found in each dictionary in the list of dictionaries ‘dict_list’. The order of the values in the returned list match the order they are retrieved from ‘dict_list’

dict_list - a list of dictionaries where each dictionary has the same
keys. Each dictionary should have at least one key:value pair with the key being ‘key_name’ (required)
key_name - a String or Int for the key name of interest in the
dictionaries (required)
return - a list of values from ‘key_name’ in ascending order based
on ‘dict_list’ keys
natcap.invest.reporting.table_generator.get_row_data(row_list, col_headers)

Construct the rows in a 2D List from the list of dictionaries, using col_headers to properly order the row data.

‘row_list’ - a list of dictionaries that represent the rows. Each

dictionaries keys should match the column names found in ‘col_headers’. The rows will be ordered the same as they are found in the dictionary list (required) Example: [{‘col_name_1’:‘9/13’, ‘col_name_3’:’expensive’,

‘col_name_2’:’chips’},
{‘col_name_1’:‘3/13’, ‘col_name_2’:’cheap’,
‘col_name_3’:’peanuts’},
{‘col_name_1’:‘5/12’, ‘col_name_2’:’moderate’,
‘col_name_3’:’mints’}]
col_headers - a List of the names of the column headers in order
example : [col_name_1, col_name_2, col_name_3…]

return - a 2D list with each inner list representing a row

HTML
Module contents

natcap.invest.reporting package.

natcap.invest.reporting.add_head_element(param_args)

Generates a string that represents a valid element in the head section of an html file. Currently handles ‘style’ and ‘script’ elements, where both the script and style are locally embedded

param_args - a dictionary that holds the following arguments:

param_args[‘format’] - a string representing the type of element to
be added. Currently : ‘script’, ‘style’ (required)
param_args[‘data_src’] - a string URI path for the external source
of the element OR a String representing the html (DO NOT include html tags, tags are automatically generated). If a URI the file is read in as a String. (required)
param_args[‘input_type’] - ‘Text’ or ‘File’. Determines how the
input from ‘data_src’ is handled (required)
‘attributes’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attributes’: {‘class’: ‘offsets’}

returns - a string representation of the html head element

natcap.invest.reporting.add_text_element(param_args)

Generates a string that represents a html text block. The input string should be wrapped in proper html tags

param_args - a dictionary with the following arguments:

param_args[‘text’] - a string

returns - a string

natcap.invest.reporting.build_table(param_args)

Generates a string representing a table in html format.

param_args - a dictionary that has the parameters for building up the

html table. The dictionary includes the following:

‘attributes’ - a dictionary of html table attributes. The attribute
name is the key which gets set to the value of the key. (optional) Example: {‘class’: ‘sorttable’, ‘id’: ‘parcel_table’}
param_args[‘sortable’] - a boolean value that determines whether the
table should be sortable (required)
param_args[‘data_type’] - a string depicting the type of input to
build the table from. Either ‘shapefile’, ‘csv’, or ‘dictionary’ (required)
param_args[‘data’] - a URI to a csv or shapefile OR a list of

dictionaries. If a list of dictionaries the data should be represented in the following format: (required)

[{col_name_1: value, col_name_2: value, …},
{col_name_1: value, col_name_2: value, …}, …]
param_args[‘key’] - a string that depicts which column (csv) or
field (shapefile) will be the unique key to use in extracting the data into a dictionary. (required for ‘data_type’ ‘shapefile’ and ‘csv’)
param_args[‘columns’] - a list of dictionaries that defines the

column structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘attr’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attr’: {‘class’: ‘offsets’}
‘td_class’ - a String to assign as a class name to
the table data tags under the column. Each table data tag under the column will have a class attribute assigned to ‘td_class’ value (optional)
param_args[‘total’] - a boolean value where if True a constant
total row will be placed at the bottom of the table that sums the columns (required)

returns - a string that represents an html table

natcap.invest.reporting.data_dict_to_list(data_dict)

Abstract out inner dictionaries from data_dict into a list, where the inner dictionaries are added to the list in the order of their sorted keys

data_dict - a dictionary with unique keys pointing to dictionaries.
Could be empty (required)

returns - a list of dictionaries, or empty list if data_dict is empty

natcap.invest.reporting.extract_datasource_table_by_key(datasource_uri, key_field)

Return vector attribute table of first layer as dictionary.

Create a dictionary lookup table of the features in the attribute table of the datasource referenced by datasource_uri.

Parameters:
  • datasource_uri (string) – a uri to an OGR datasource
  • key_field – a field in datasource_uri that refers to a key value for each row such as a polygon id.
Returns:

returns a dictionary of the

form {key_field_0: {field_0: value0, field_1: value1}…}

Return type:

attribute_dictionary (dict)

natcap.invest.reporting.generate_report(args)

Generate an html page from the arguments given in ‘reporting_args’

reporting_args[title] - a string for the title of the html page
(required)
reporting_args[sortable] - a boolean value indicating whether
the sorttable.js library should be added for table sorting functionality (optional)
reporting_args[totals] - a boolean value indicating whether
the totals_function.js script should be added for table totals functionality (optional)
reporting_args[out_uri] - a URI to the output destination for the html
page (required)
reporting_args[elements] - a list of dictionaries that represent html

elements to be added to the html page. (required) If no elements are provided (list is empty) a blank html page will be generated. The 3 main element types are ‘table’, ‘head’, and ‘text’. All elements share the following arguments:

‘type’ - a string that depicts the type of element being add.
Currently ‘table’, ‘head’, and ‘text’ are defined (required)
‘section’ - a string that depicts whether the element belongs
in the body or head of the html page. Values: ‘body’ | ‘head’ (required)

Table element dictionary has at least the following additional arguments:

‘attributes’ - a dictionary of html table attributes. The
attribute name is the key which gets set to the value of the key. (optional) Example: {‘class’: ‘sorttable’, ‘id’: ‘parcel_table’}
‘sortable’ - a boolean value for whether the tables columns
should be sortable (required)
‘checkbox’ - a boolean value for whether there should be a
checkbox column. If True a ‘selected total’ row will be added to the bottom of the table that will show the total of the columns selected (optional)
‘checkbox_pos’ - an integer value for in which column
position the the checkbox column should appear (optional)
‘data_type’ - one of the following string values:
‘shapefile’|’hg csv’|’dictionary’. Depicts the type of data structure to build the table from (required)
‘data’ - either a list of dictionaries if ‘data_type’ is

‘dictionary’ or a URI to a CSV table or shapefile if ‘data_type’ is ‘shapefile’ or ‘csv’ (required). If a list of dictionaries, each dictionary should have keys that represent the columns, where each dictionary is a row (list could be empty) How the rows are ordered are defined by their index in the list. Formatted example: [{col_name_1: value, col_name_2: value, …},

{col_name_1: value, col_name_2: value, …}, …]
‘key’ - a string that defines which column or field should be
used as the keys for extracting data from a shapefile or csv table ‘key_field’. (required for ‘data_type’ = ‘shapefile’ | ‘csv’)
‘columns’- a list of dictionaries that defines the column

structure for the table (required). The order of the columns from left to right is depicted by the index of the column dictionary in the list. Each dictionary in the list has the following keys and values:

‘name’ - a string for the column name (required) ‘total’ - a boolean for whether the column should be

totaled (required)
‘attr’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attr’: {‘class’: ‘offsets’}
‘td_class’ - a String to assign as a class name to
the table data tags under the column. Each table data tag under the column will have a class attribute assigned to ‘td_class’ value (optional)
‘total’- a boolean value for whether there should be a constant
total row at the bottom of the table that sums the column values (optional)

Head element dictionary has at least the following additional arguments:

‘format’ - a string representing the type of head element being
added. Currently ‘script’ (javascript) and ‘style’ (css style) accepted (required)
‘data_src’- a URI to the location of the external file for
either the ‘script’ or the ‘style’ OR a String representing the html script or style (DO NOT include the tags) (required)
‘input_type’ - a String, ‘File’ or ‘Text’ that refers to how
‘data_src’ is being passed in (URI vs String) (required).
‘attributes’ - a dictionary that has key value pairs for
optional tag attributes (optional). Ex: ‘attributes’: {‘id’: ‘muni_data’}

Text element dictionary has at least the following additional arguments:

‘text’- a string to add as a paragraph element in the html page
(required)

returns - nothing

natcap.invest.reporting.write_html(html_obj, out_uri)

Write an html file to ‘out_uri’ from html element represented as strings in ‘html_obj’

html_obj - a dictionary with two keys, ‘head’ and ‘body’, that point to

lists. The list for each key is a list of the htmls elements as strings (required) example: {‘head’:[‘elem_1’, ‘elem_2’,…],

‘body’:[‘elem_1’, ‘elem_2’,…]}

out_uri - a URI for the output html file

returns - nothing