Skip to content

Commit c0735eb

Browse files
committed
Merge remote-tracking branch 'upstream/main' into feature/geometamaker
2 parents f11c624 + e6bcf8a commit c0735eb

File tree

7 files changed

+113
-129
lines changed

7 files changed

+113
-129
lines changed

HISTORY.rst

+4
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ Unreleased Changes
4444
``pygeoprocessing.get_raster_info`` and
4545
``pygeoprocessing.get_vector_info``.
4646
https://github.com/natcap/invest/issues/1645
47+
* The scripting page of the InVEST API documentation has been updated to
48+
reflect changes in how InVEST is installed on modern systems, and also to
49+
include images of the InVEST workbench instead of just broken links.
50+
https://github.com/natcap/invest/issues/1660
4751
* Workbench
4852
* Several small updates to the model input form UI to improve usability
4953
and visual consistency (https://github.com/natcap/invest/issues/912).

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
DATA_DIR := data
33
GIT_SAMPLE_DATA_REPO := https://bitbucket.org/natcap/invest-sample-data.git
44
GIT_SAMPLE_DATA_REPO_PATH := $(DATA_DIR)/invest-sample-data
5-
GIT_SAMPLE_DATA_REPO_REV := ab8c74a62a93fd0019de2bca064abc0a5a07afab
5+
GIT_SAMPLE_DATA_REPO_REV := 0f8b41557753dad3670ba8220f41650b51435a93
66

77
GIT_TEST_DATA_REPO := https://bitbucket.org/natcap/invest-test-data.git
88
GIT_TEST_DATA_REPO_PATH := $(DATA_DIR)/invest-test-data

doc/api-docs/conf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@
187187
natcap.invest.carbon.execute(args)
188188
189189
For examples of scripting a model run, or multiple successive model runs,
190-
see :ref:`CreatingSamplePythonScripts`.
190+
see :ref:`CreatingPythonScripts`.
191191
192192
193193
.. contents:: Available Models and Tools:

doc/api-docs/scripting.rst

+106-126
Original file line numberDiff line numberDiff line change
@@ -20,98 +20,71 @@ InVEST models from the command-line.
2020
Setting up your Python environment
2121
==================================
2222

23-
1. **Install Python 3.6 or later.**
23+
We recommend using the ``conda`` or ``mamba`` package manager to create an
24+
environment. The easiest way to do so is to execute the following command::
2425

25-
Python can be `downloaded from here <https://www.python.org/downloads/>`_. When installing,
26-
be sure to allow ``python.exe`` to be added to the path in the installation options.
26+
mamba create -n invest-env -c conda-forge natcap.invest
2727

28+
This will create a new environment called ``invest-env`` with the latest
29+
released versions of python and ``natcap.invest``, as well as all dependencies
30+
needed to execute ``natcap.invest``.
2831

29-
2. **Put pip on the PATH.**
32+
Alternate installation methods are available. Please see the :ref:`installing`
33+
guide for further instructions on setting up your python environment and
34+
installing the ``natcap.invest`` package.
3035

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

36-
After this is done (and you've opened a new command-line window), you will be
37-
able to use ``pip`` at the command-line to install packages like so::
38+
=======================
39+
Creating Python Scripts
40+
=======================
3841

39-
> pip install <packagename>
42+
1. **Launch InVEST Workbench and Open the Selected Model**
4043

41-
3. **Install packages needed to run InVEST.**
42-
43-
Most (maybe even all) of these packages can be downloaded as precompiled
44-
wheels from `Christoph Gohlke's build page <http://www.lfd.uci.edu/~gohlke/pythonlibs/>`_.
45-
Others should be able to be installed via ``pip install <packagename>``.
46-
47-
.. This ..include:: part will automatically pull the contents of requirements.txt
48-
and include the file from line 9 through the end.
49-
50-
.. include:: ../../requirements.txt
51-
:literal:
52-
:start-line: 9
53-
54-
55-
4. **Install the InVEST python package**
56-
57-
4a. Download a release of the ``natcap.invest`` python package.
58-
59-
* `Releases on the python package index <https://pypi.org/project/natcap.invest/#files>`_
60-
61-
4b. Install the downloaded python package..
62-
63-
* ``win32.whl`` files are prebuilt binary distributions and can be
64-
installed via pip.
65-
See the `pip docs for installing a package from a wheel
66-
<https://pip.pypa.io/en/stable/user_guide/#installing-from-wheels>`_
67-
* ``.zip`` and ``.tar.gz`` files are source archives.
68-
See :ref:`installing` for details, including how to
69-
install specific development versions of ``natcap.invest``.
70-
71-
72-
.. _CreatingSamplePythonScripts:
73-
74-
==============================
75-
Creating Sample Python Scripts
76-
==============================
77-
78-
1. **Launch InVEST Model**
79-
80-
Once an InVEST model is selected for scripting,
81-
launch that model from the Windows Start menu. This example in this guide
82-
follows the NDR model.
44+
Once you have selected an InVEST model to script, launch the workbench and
45+
select the model from the list of available models. This guide will follow
46+
the Nutrient Delivery Ratio (NDR) model.
8347

8448
2. **Fill in InVEST Model Input Parameters**
8549

8650
Once the user interface loads, populate the inputs in the model likely to
8751
be used in the Python script. For testing purposes the default InVEST’s
88-
data is appropriate. However, if a user wishes to write a batch for several
89-
InVEST runs, it would be reasonable to populate the user interface with
90-
data for the first run.
52+
data is appropriate. However, if you wish to write a script to execute
53+
several InVEST model runs in sequence, it would be reasonable to populate
54+
the user interface with data for the first run in the sequence.
9155

92-
3. **Generate a sample Python Script from the User Interface**
56+
3. **Generate a Python Script from the User Interface**
9357

94-
Open the Development menu at the top of the user interface and select
95-
*"Save to python script..."* and save the file to a known location.
58+
In the model interface, select *"Save as..."* in the left-hand menu bar,
59+
*"Python script"* in the dialog box, and then save the file to a known location.
9660

97-
|2w7pilj.png|
61+
|workbench_save_as.png|
62+
|modal_save_as.png|
9863

99-
.. |2w7pilj.png| image:: https://bitbucket.org/repo/ag8qdk/images/3205488039-2w7pilj.png
64+
.. |workbench_save_as.png| image:: scripting/workbench_save_as.png
65+
.. |modal_save_as.png| image:: scripting/modal_save_as.png
10066

10167
4. **Execute the script in the InVEST Python Environment**
10268

103-
Launch a Windows PowerShell from the Start menu (type “powershell” in the
104-
search box), then invoke the Python interpreter on the InVEST Python
105-
script from that shell. In this example the Python interpreter is
106-
installed in ``C:\Python37\python.exe`` and the script was saved in
107-
``C:\Users\rpsharp\Desktop\ndr.py``, thus the command to invoke the
108-
interpreter is::
69+
Launch a shell of your choice and activate your InVEST environment you
70+
created earlier. We will use the Windows command prompt ``cmd.exe`` for an
71+
example, but the same commands should work on Powershell, bash and zsh. If
72+
you created an environment called ``invest-env``, you would activate it with
73+
``conda`` like so::
10974

110-
> C:\Python37\python.exe C:\Users\rpsharp\Desktop\ndr.py
75+
> conda activate invest-env
11176

112-
|34ecba0.png|
77+
You will know your environment activated correctly when you see the
78+
environment name at the beginning of your shell prompt. For example::
11379

114-
.. |34ecba0.png| image:: https://bitbucket.org/repo/ag8qdk/images/2939811460-34ecba0.png
80+
(invest-env) C:\Users\demo >
81+
82+
Once the environment has been activated, we can run the python script we
83+
saved in the previous step. Suppose we're on Windows and the script was
84+
saved to ``C:\Users\demo\Desktop\ndr.py``, the command to run the script
85+
would be::
86+
87+
(invest-env) C:\Users\demo > python C:\Users\demo\Desktop\ndr.py
11588

11689
5. **Output Results**
11790

@@ -133,50 +106,68 @@ For reference, consider the following script generated by the Nutrient model wit
133106

134107
.. code-block:: python
135108
136-
"""
137-
This is a saved model run from natcap.invest.ndr.ndr.
138-
Generated: Mon 16 May 2016 03:52:59 PM
139-
InVEST version: 3.3.0
140-
"""
109+
# coding=UTF-8
110+
# -----------------------------------------------
111+
# Generated by InVEST 3.14.2 on Wed Oct 23 10:49:40 2024
112+
# Model: Nutrient Delivery Ratio
113+
114+
import logging
115+
import sys
141116
142117
import natcap.invest.ndr.ndr
118+
import natcap.invest.utils
119+
120+
LOGGER = logging.getLogger(__name__)
121+
root_logger = logging.getLogger()
122+
123+
handler = logging.StreamHandler(sys.stdout)
124+
formatter = logging.Formatter(
125+
fmt=natcap.invest.utils.LOG_FMT,
126+
datefmt='%m/%d/%Y %H:%M:%S ')
127+
handler.setFormatter(formatter)
128+
logging.basicConfig(level=logging.INFO, handlers=[handler])
143129
144130
args = {
145-
u'k_param': u'2',
146-
u'runoff_proxy_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\precip',
147-
u'subsurface_critical_length_n': u'150',
148-
u'subsurface_critical_length_p': u'150',
149-
u'subsurface_eff_n': u'0.8',
150-
u'subsurface_eff_p': u'0.8',
151-
u'threshold_flow_accumulation': u'1000',
152-
u'biophysical_table_uri': u'C:\InVEST_3.3.0_x86\WP_Nutrient_Retention\Input\water_biophysical_table.csv',
153-
u'calc_n': True,
154-
u'calc_p': True,
155-
u'suffix': '',
156-
u'dem_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\dem',
157-
u'lulc_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\landuse_90',
158-
u'watersheds_uri': u'C:\InVEST_3.3.0_x86\Base_Data\Freshwater\watersheds.shp',
159-
u'workspace_dir': u'C:\InVEST_3.3.0_x86\ndr_workspace',
131+
'biophysical_table_path': 'C:\\Users\demo\invest-sample-data\\NDR\\biophysical_table_gura.csv',
132+
'calc_n': True,
133+
'calc_p': True,
134+
'dem_path': 'C:\\Users\demo\invest-sample-data\\NDR\\DEM_gura.tif',
135+
'k_param': '2',
136+
'lulc_path': 'C:\\Users\demo\invest-sample-data\\NDR\land_use_gura.tif',
137+
'results_suffix': 'gura',
138+
'runoff_proxy_path': 'C:\\Users\demo\invest-sample-data\\NDR\precipitation_gura.tif',
139+
'subsurface_critical_length_n': '200',
140+
'subsurface_eff_n': '0.8',
141+
'threshold_flow_accumulation': '1000',
142+
'watersheds_path': 'C:\\Users\demo\invest-sample-data\\NDR\watershed_gura.shp',
143+
'workspace_dir': 'C:\\Users\demo\invest-sample-data\\NDR\workspace',
160144
}
161145
162146
if __name__ == '__main__':
163147
natcap.invest.ndr.ndr.execute(args)
164148
165-
Elements to note:
166-
167-
* *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.
168149
169-
|95zj7p.png|
150+
Elements to note:
170151

171-
.. |95zj7p.png| image:: https://bitbucket.org/repo/ag8qdk/images/22613179-95zj7p.png
152+
* *Parameter Python Dictionary*: Key elements include the ``'args'``
153+
dictionary. Note the similarities between the key values such as
154+
``'workspace_dir'`` and the equivalent "Workspace" input parameter in the
155+
user interface. Every key in the ``'args'`` dictionary has a corresponding
156+
reference in the user interface.
172157

173-
In the example below we’ll modify the script to execute the nutrient model for a parameter study of ``‘threshold_flow_accumulation’.``
158+
In the example below we’ll modify the script to execute the nutrient model
159+
for a parameter study of ``'threshold_flow_accumulation'``.
174160

175-
* *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
161+
* *Execution of the InVEST model*: The InVEST API invokes models with a
162+
consistent syntax where the module name that contains the InVEST model is
163+
listed first and is followed by a function called ‘execute’ that takes a
164+
single parameter called ``'args'``. This parameter is the dictionary of input
165+
parameters discussed above. In this example, the line ::
176166

177-
``natcap.invest.ndr.ndr.execute(args)``
167+
natcap.invest.ndr.ndr.execute(args)
178168

179-
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.
169+
executes the nutrient model end-to-end. If the user wishes to make batch
170+
calls to InVEST, this line will likely be placed inside a loop.
180171

181172
====================================================
182173
Example: Threshold Flow Accumulation Parameter Study
@@ -212,7 +203,7 @@ example, replace the last line in the UI generated Python script with:
212203
.. code-block:: python
213204
214205
import os
215-
landcover_dir = r'C:\User\Rich\Desktop\landcover_data'
206+
landcover_dir = r'C:\User\demo\Desktop\landcover_data'
216207
217208
if __name__ == '__main__':
218209
#Loop over all the filenames in the landcover dir
@@ -225,43 +216,31 @@ example, replace the last line in the UI generated Python script with:
225216
natcap.invest.ndr.ndr.execute(args)
226217
227218
This loop covers all the files located in
228-
``C:\User\Rich\Desktop\landcover_data``
229-
and updates the relevant ``lulc_uri`` key in the args dictionary to each
230-
of those files during execution as well as making a useful suffix so output
231-
files can be distinguished from each other.
219+
``C:\User\demo\Desktop\landcover_data`` and updates the relevant ``lulc_uri``
220+
key in the args dictionary to each of those files during execution as well as
221+
making a useful suffix so output files can be distinguished from each other.
232222

233223
============================================
234224
Example: Saving model log messages to a file
235225
============================================
236226

237-
There are many cases where you may want or need to capture all of the log
238-
messages generated by the model. When we run models through the InVEST user
239-
interface application, the UI captures all of this logging and saves it to a
240-
logfile. We can replicate this behavior through the python logging package,
241-
by adding the following code just after the ``import`` statements in the
242-
example script.
243-
227+
When you save a model run to a python script, InVEST will automatically include
228+
code to write all logging to your console while it executes. But sometimes,
229+
it's useful to save log messages from the model to a file. This can be done by
230+
adding a few lines of code to the script, just after the existing logging
231+
code:
244232

245233
.. code-block:: python
246234
247-
import logging
248-
import pygeoprocessing
249-
250-
# Write all NDR log messages to logfile.txt
251-
MODEL_LOGGER = logging.getLogger('natcap.invest.ndr')
252-
handler = logging.FileHandler('logfile.txt')
253-
MODEL_LOGGER.addHandler(handler)
254-
255-
# log pygeoprocessing messages to the same logfile
256-
PYGEO_LOGGER = logging.getLogger('pygeoprocessing')
257-
PYGEO_LOGGER.addHandler(handler)
235+
file_handler = logging.FileHandler('logfile.txt')
236+
root_logger.addHandler(file_handler)
258237
259-
This will capture all logging generated by the ``ndr`` model and by
260-
``pygeoprocessing``, writing all messages to ``logfile.txt``. While
238+
This will capture all logging generated by any python package that executes
239+
while running the ``ndr`` model writing all messages to ``logfile.txt``. While
261240
this is a common use case, the ``logging`` package provides functionality
262241
for many more complex logging features. For more
263242
advanced use of the python logging module, refer to the Python project's
264-
`Logging Cookbook <https://docs.python.org/2/howto/logging-cookbook.html>`_
243+
`Logging Cookbook <https://docs.python.org/3/howto/logging-cookbook.html>`_
265244

266245
=====================================
267246
Example: Enabling Parallel Processing
@@ -306,7 +285,8 @@ Using the parameter study example, this might look like:
306285
Internationalization
307286
====================
308287

309-
If you use the InVEST python API to access model names, ``MODEL_SPEC``s, or validation messages, you can translate those strings using ``gettext``:
288+
If you use the InVEST python API to access model names, ``MODEL_SPEC`` s, or
289+
validation messages, you can translate those strings using ``gettext``:
310290

311291
.. code-block:: python
312292
316 KB
Loading
166 KB
Loading

src/natcap/invest/validation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,7 @@ def get_validated_dataframe(
642642
patterns.append(f'{groups[0]}(.+){groups[2]}')
643643
else:
644644
# for regular column names, use the exact name as the pattern
645-
patterns.append(column.replace('(', '\(').replace(')', '\)'))
645+
patterns.append(column.replace('(', r'\(').replace(')', r'\)'))
646646

647647
# select only the columns that match a pattern
648648
df = df[[col for col in df.columns if any(

0 commit comments

Comments
 (0)