@@ -20,98 +20,71 @@ InVEST models from the command-line.
20
20
Setting up your Python environment
21
21
==================================
22
22
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::
24
25
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
27
27
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 ``.
28
31
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.
30
35
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 :
35
37
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
+ =======================
38
41
39
- > pip install <packagename>
42
+ 1. ** Launch InVEST Workbench and Open the Selected Model **
40
43
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.
83
47
84
48
2. **Fill in InVEST Model Input Parameters **
85
49
86
50
Once the user interface loads, populate the inputs in the model likely to
87
51
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 .
91
55
92
- 3. **Generate a sample Python Script from the User Interface **
56
+ 3. **Generate a Python Script from the User Interface **
93
57
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.
96
60
97
- |2w7pilj.png |
61
+ |workbench_save_as.png |
62
+ |modal_save_as.png |
98
63
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
100
66
101
67
4. **Execute the script in the InVEST Python Environment **
102
68
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::
109
74
110
- > C:\Python37\python.exe C:\Users\rpsharp\Desktop\ndr.py
75
+ > conda activate invest-env
111
76
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::
113
79
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
115
88
116
89
5. **Output Results **
117
90
@@ -133,50 +106,68 @@ For reference, consider the following script generated by the Nutrient model wit
133
106
134
107
.. code-block :: python
135
108
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
141
116
142
117
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])
143
129
144
130
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\n dr_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' ,
160
144
}
161
145
162
146
if __name__ == ' __main__' :
163
147
natcap.invest.ndr.ndr.execute(args)
164
148
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.
168
149
169
- | 95zj7p.png |
150
+ Elements to note:
170
151
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.
172
157
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' ``.
174
160
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 ::
176
166
177
- `` natcap.invest.ndr.ndr.execute(args) ``
167
+ natcap.invest.ndr.ndr.execute(args)
178
168
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.
180
171
181
172
====================================================
182
173
Example: Threshold Flow Accumulation Parameter Study
@@ -212,7 +203,7 @@ example, replace the last line in the UI generated Python script with:
212
203
.. code-block :: python
213
204
214
205
import os
215
- landcover_dir = r ' C:\U ser\R ich \D esktop\l andcover_data'
206
+ landcover_dir = r ' C:\U ser\d emo \D esktop\l andcover_data'
216
207
217
208
if __name__ == ' __main__' :
218
209
# 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:
225
216
natcap.invest.ndr.ndr.execute(args)
226
217
227
218
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.
232
222
233
223
============================================
234
224
Example: Saving model log messages to a file
235
225
============================================
236
226
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:
244
232
245
233
.. code-block :: python
246
234
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)
258
237
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
261
240
this is a common use case, the ``logging `` package provides functionality
262
241
for many more complex logging features. For more
263
242
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 >`_
265
244
266
245
=====================================
267
246
Example: Enabling Parallel Processing
@@ -306,7 +285,8 @@ Using the parameter study example, this might look like:
306
285
Internationalization
307
286
====================
308
287
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 ``:
310
290
311
291
.. code-block :: python
312
292
0 commit comments