redlem-force 0.13.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,399 @@
1
+ Metadata-Version: 2.4
2
+ Name: redlem-force
3
+ Version: 0.13.1
4
+ Summary: Extract DLEM forcing data (URMA met + PRISM/URMA precip) for reservoir geometries from Google Earth Engine.
5
+ Author: Thomas Ott
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: earthengine-api
11
+ Requires-Dist: polars>=1.0
12
+ Requires-Dist: shapely>=2.0
13
+ Requires-Dist: pyproj
14
+ Requires-Dist: numpy
15
+ Requires-Dist: requests
16
+ Requires-Dist: geopandas
17
+ Requires-Dist: pandas
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest; extra == "test"
20
+ Provides-Extra: quota
21
+ Requires-Dist: google-cloud-monitoring; extra == "quota"
22
+ Provides-Extra: plot
23
+ Requires-Dist: matplotlib>=3.7; extra == "plot"
24
+ Requires-Dist: contextily; extra == "plot"
25
+ Dynamic: license-file
26
+
27
+ # redlem-force
28
+
29
+ Extract DLEM forcing data from Google Earth Engine for reservoir geometries.
30
+ Cell selection returns GeoDataFrames; extraction returns a pandas DataFrame.
31
+ Nothing is written to disk by the package — saving is up to you (the
32
+ scripts in `scripts/` show one way).
33
+
34
+ 1. **`extract_urma`** — forcing data (pandas DataFrame) for one day or a
35
+ period, one reservoir or many, from one table holding each reservoir's
36
+ URMA cells and PRISM cells. The original
37
+ reservoir polygons are not used: they are only needed to select the
38
+ cells.
39
+ 2. **URMA cell selection** — native reservoir polygon → the URMA grid cells
40
+ used for the met variables (with or without the water mask):
41
+ - `select_urma_cells(gdf, ...)` — GeoDataFrame (or a .shp / .gpkg path)
42
+ in, GeoDataFrame out: all original columns plus `N_CELLS`, `ELEV_M`
43
+ and `WATER_MASK`; geometry = the selected cells. Also accepts a polars
44
+ DataFrame. Computed locally on the URMA grid (below).
45
+ 3. **PRISM cell selection** — `select_prism_cells(path, ...)`: native
46
+ polygon → the PRISM 800 m cells used for precip (no water mask). Candidates
47
+ are the cells sharing area with the polygon (edge/corner contact does
48
+ not count); cells are taken by overlap, largest first, until their total
49
+ area reaches the polygon's area — ceil(area / cell area) cells, over by
50
+ less than one cell. A reservoir smaller than one cell gets the cell it
51
+ overlaps most. Stored as polygons only (one square for a single cell),
52
+ like the URMA cells, and sent to Earth Engine as those polygons. Same
53
+ format as `select_urma_cells`: GeoDataFrame in, GeoDataFrame out with
54
+ the original columns plus `N_CELLS`. Needed for precip.
55
+ 4. **Cell maps** — `plot_cells(path, id_col=..., ids=[...], ...)`: one
56
+ map per reservoir from the ORIGINAL polygon — the polygon, its URMA
57
+ cells and its PRISM 800 m cells (same rules as above), over Esri World
58
+ Imagery, with a legend and a km scale
59
+ bar. Needs `pip install matplotlib contextily` (or the `plot` extra).
60
+ See *Cell maps* below.
61
+
62
+ All Earth Engine work runs as local requests on the high-volume endpoint in a
63
+ worker pool; nothing uses `ee.batch.Export`.
64
+
65
+ ## Use without installing (while iterating)
66
+
67
+ Put `src/` on the import path at the top of a script, then import normally.
68
+ Edits under `src/redlem_force/` take effect on the next run:
69
+
70
+ ```python
71
+ import sys
72
+ sys.path.insert(0, '/path/to/redlem-force/src')
73
+ import redlem_force
74
+ ```
75
+
76
+ The scripts in `scripts/` already do this relative to their own location.
77
+ `print(redlem_force.__file__)` shows which copy is imported. If an installed
78
+ copy exists it would shadow the source folder: `pip uninstall redlem-force`.
79
+
80
+ ## Install
81
+
82
+ ```bash
83
+ pip install /path/to/redlem-force # regular install
84
+ pip install -e /path/to/redlem-force # editable, for development
85
+ pip install -e '/path/to/redlem-force[test]' # plus pytest
86
+ ```
87
+
88
+ or build a wheel to share: `pip wheel --no-deps /path/to/redlem-force`, then
89
+ `pip install redlem_force-0.13.1-py3-none-any.whl`.
90
+
91
+ Requires an authenticated Earth Engine account (`earthengine authenticate`).
92
+
93
+ ## Cell selection
94
+
95
+ `select_urma_cells` and `select_prism_cells` take the same arguments
96
+ (`select_urma_cells` adds `water_mask_col`) and return the same kind of
97
+ result:
98
+
99
+ ```python
100
+ gdf = gpd.read_file('owen_master_v1.gpkg') # or a database read
101
+ cfg = redlem_force.RunConfig(project='nasa-revap')
102
+ urma = redlem_force.select_urma_cells(gdf, id_col='OWEN_ID', config=cfg)
103
+ prism = redlem_force.select_prism_cells(gdf, id_col='OWEN_ID', config=cfg)
104
+ ```
105
+
106
+ Each is a GeoDataFrame: every original column plus the columns below, with
107
+ geometry = the selected cells (union of the pixel squares) in the input CRS.
108
+ A .shp / .gpkg path works in place of the GeoDataFrame (`layer=` for a
109
+ multi-layer GeoPackage). Nothing is written; `scripts/run_urma_cells.py` and
110
+ `scripts/run_prism_cells.py` save the results (GeoPackage, plus a parquet of
111
+ the URMA attributes).
112
+
113
+ | column | meaning |
114
+ |---|---|
115
+ | `N_CELLS` | number of selected cells (URMA and PRISM) |
116
+ | `ELEV_M` | URMA only: mean elevation (m) of the selected URMA cells |
117
+ | `WATER_MASK` | URMA only: 1 = cells selected with the water-mask rule, 0 = overlap/elevation rule |
118
+
119
+ The water-mask flag is max(water mask of the intersecting cells) == 1
120
+ unless `water_mask_col` names an existing 0/1 column. A reservoir flagged as
121
+ water with no water cells falls back to the overlap/elevation rule and gets
122
+ `WATER_MASK = 0` (logged). Reservoirs with no cells keep their row with null
123
+ geometry and `ELEV_M`. `sample=200` runs a random trial.
124
+ `scripts/run_urma_cells.py` wraps this with a CONFIG block.
125
+
126
+ ## Cell maps
127
+
128
+ ```python
129
+ redlem_force.plot_cells('owen_master_v1.gpkg', id_col='OWEN_ID',
130
+ ids=['BORGIS_146', 'BORGIS_64'], title_col=None,
131
+ out_dir='figs', dpi=300,
132
+ config=redlem_force.RunConfig(project='nasa-revap'))
133
+ ```
134
+
135
+ - Web Mercator map (the imagery's own projection, so it is not
136
+ resampled; conformal, so shapes are true locally). Cell edges are
137
+ densified before reprojection. URMA cells appear tilted by the Lambert
138
+ grid's convergence (about 10° near Lahontan); PRISM cells, a lon/lat
139
+ grid, are not tilted.
140
+ - The scale bar uses Web Mercator's scale factor at the reservoir.
141
+ - `basemap='esri'` needs internet; if the tiles cannot be fetched, the map
142
+ is drawn on white (warning). `basemap=None` draws on white with a
143
+ colour-blind-checked palette.
144
+ - Earth Engine: the two grids and the URMA elevation / water-mask arrays,
145
+ once per Python session (reused across calls).
146
+ - `scripts/plot_reservoir_cells.py` wraps this with a CONFIG block.
147
+
148
+ ## Extraction input: one table of cells
149
+
150
+ `extract_urma` takes ONE table — a polars DataFrame or a
151
+ geopandas GeoDataFrame — with one row per reservoir. No reservoir polygon:
152
+
153
+ | column (default name) | used for | notes |
154
+ |---|---|---|
155
+ | ID (`id_col`) | joining | cast to text; unique, non-null |
156
+ | `urma_cells` | URMA cells → met variables (+ URMA precip fallback) | from `select_urma_cells`; null = no cells → reservoir excluded (listed in the log / summary) |
157
+ | `prism_cells` | PRISM 800 m cells → PRISM 800 m / 4 km precip | from `select_prism_cells`; required when `precip=True` |
158
+
159
+ Column names are set with `urma_cells_col` and `prism_cells_col`.
160
+ **geopandas:** geometry columns that are
161
+ GeoSeries carry their own CRS, and the two may differ. A column that is
162
+ not a GeoSeries — e.g. the second geometry column of a `gpd.read_postgis`
163
+ read — may hold WKB bytes, hex WKB / EWKB text (as PostGIS returns it),
164
+ WKT text or shapely objects; pass its CRS (`urma_crs` / `prism_crs`).
165
+ **polars:** geometry as WKB bytes, hex WKB / EWKB or WKT text; `urma_crs`
166
+ is required, `prism_crs` defaults to `urma_crs`.
167
+
168
+ ## Examples
169
+
170
+ Run scripts under `if __name__ == '__main__':` — the worker pool needs it on
171
+ macOS and Windows.
172
+
173
+ ```python
174
+ import logging
175
+ import geopandas as gpd
176
+ import redlem_force
177
+
178
+ logging.basicConfig(level=logging.INFO)
179
+
180
+ if __name__ == '__main__':
181
+ cfg = redlem_force.RunConfig(project='nasa-revap', n_workers=20)
182
+
183
+ gdf = gpd.read_file('owen_master_v1.gpkg')
184
+
185
+ # 1. URMA and PRISM cells (GeoDataFrames)
186
+ urma = redlem_force.select_urma_cells(gdf, id_col='OWEN_ID', config=cfg)
187
+ prism = redlem_force.select_prism_cells(gdf, id_col='OWEN_ID', config=cfg)
188
+
189
+ # 2. One table with both cell geometries
190
+ table = urma[['OWEN_ID', 'geometry']].rename_geometry('urma_cells')
191
+ p = prism.set_index('OWEN_ID').geometry
192
+ table['prism_cells'] = gpd.GeoSeries(
193
+ p.reindex(table['OWEN_ID']).values, index=table.index, crs=p.crs)
194
+
195
+ # 4. Forcing data -> pandas DataFrame (one row per reservoir and day)
196
+ df = redlem_force.extract_urma(table, id_col='OWEN_ID',
197
+ start='2020-07-01', end='2020-07-31',
198
+ config=cfg)
199
+
200
+ # long periods: one call per year (or month), save each as you like
201
+ for year in range(1980, 2027):
202
+ df = redlem_force.extract_urma(table, id_col='OWEN_ID',
203
+ start=f'{year}-01-01',
204
+ end=f'{year}-12-31', config=cfg)
205
+ df.to_parquet(f'forcing_{year}.parquet')
206
+ ```
207
+
208
+ `extract_urma` holds its result in memory: all ~44,750 reservoirs are about
209
+ 1.4 million rows per month of dates, so call it per year or month for long
210
+ periods.
211
+
212
+ Pass `precip=False` for URMA met only: no precip requests are made, the
213
+ `pr` / `pr_source` columns are left out, and no PRISM cells are needed
214
+ (`prism_cells_col=None`).
215
+
216
+ `RunConfig(days_per_request=5)` (default) stacks 5 consecutive dates into
217
+ one request per source.
218
+
219
+ `dates` accepts one date or a list (`'YYYY-MM-DD'`, `'YYYYMMDD'`,
220
+ `datetime.date`). `start` / `end` are both inclusive.
221
+
222
+ ## Output columns
223
+
224
+ | column | source |
225
+ |---|---|
226
+ | ID | your ID column (text) |
227
+ | `date` | `'YYYYMMDD'` text |
228
+ | `pr` | Daily Precipitation, mm — PRISM 800 m `ppt`, mean over the reservoir's PRISM 800 m cells; fallback PRISM 4 km `ppt`, then URMA `PCP` (see below) |
229
+ | `tmax` | Daily Maximum Temperature, degC — URMA `TMAX`, mean |
230
+ | `tmin` | Daily Minimum Temperature, degC — URMA `TMIN`, mean |
231
+ | `vpd` | Daily Vapor Pressure Deficit, kPa — derived `vpd`, mean |
232
+ | `vs2m` | Daily 2 m wind speed, m/s — derived from URMA `WIND`, mean |
233
+ | `srad` | Daily Solar Radiation, W/m² — URMA `SRAD_TCDC`, mean |
234
+ | `etr` | Daily Alfalfa Reference ET, mm/day — URMA `ETr`, mean |
235
+ | `eto` | Daily Grass Reference ET, mm/day — URMA `ETo`, mean |
236
+ | `th` | Daily Wind Direction, deg — URMA `WDIR`, **median** |
237
+ | `sph` | Daily Specific Humidity, kg/kg — URMA `SPFH`, mean |
238
+ | `pres` | Daily Atmospheric Pressure, Pa — URMA `PRES`, mean |
239
+
240
+ | `pr_source` | `prism800`, `prism4k` or `urma` |
241
+ | `urma_status` | URMA image `status`: `permanent`, `provisional`, or `unknown` |
242
+ | `processed_date` | date the rows were produced, `'YYYY-MM-DD'` text, local date of the machine running the extraction |
243
+
244
+ A pandas DataFrame: numbers as float64 (missing = NaN), text as text
245
+ (`object` in pandas 2, `str` in pandas 3).
246
+ URMA variables are reduced over exactly the selected URMA cells (unweighted,
247
+ native grid). Names and units follow the DLEM variable config.
248
+
249
+ Met variables and the `vs2m` / `vpd` derivation are unchanged from
250
+ `urma_download_v2.py`. The reduction is not: URMA is reduced on its own
251
+ pixel grid, unweighted (no `scale=1000` sampling, which let edge samples
252
+ fall in neighbouring pixels):
253
+
254
+ over the selected URMA cell polygon, i.e. exactly the pixels whose centre
255
+ is inside it. A single cell is sent as its square too: the square holds
256
+ only its own pixel centre. (Earlier versions sent single cells as a point
257
+ at the pixel centre; it gave the same pixel and no measured speed gain.)
258
+
259
+ Note vs the old archive: `urma_elev_mean` and `lat_mean` are no longer in
260
+ the forcing output (elevation and latitude come from elsewhere; the URMA
261
+ cells file still has `ELEV_M`).
262
+
263
+ ## Quota check
264
+
265
+ Before extracting, `extract_urma` prints the project's
266
+ remaining monthly Earth Engine compute quota and the run's estimated cost:
267
+
268
+ QUOTA: estimated 0.15 EECU-h for 44,749 reservoir-days (0.012 EECU-s each);
269
+ 985.2 of 1,000 EECU-h left this month -> OK
270
+
271
+ The estimate is reservoir-days × `RunConfig.eecu_s_per_reservoir_day`
272
+ (default 0.012; measured 2026-10-15 with URMA met + PRISM precip and
273
+ 5-day blocks: ~0.0102). If the
274
+ estimate exceeds the remaining quota (× `quota_fraction`), the run stops
275
+ with `QuotaExceededError` before any data request. If the quota cannot be
276
+ read, it prints `QUOTA: quota and estimate unavailable ...` and continues.
277
+ No per-request
278
+ tracking: usage from earlier runs is already in the remaining quota Google
279
+ reports (with some reporting delay).
280
+
281
+ Reading the quota needs `pip install google-cloud-monitoring` (or the
282
+ `[quota]` extra) and `gcloud auth application-default login`.
283
+ `redlem_force.quota_status('nasa-revap')` returns the numbers directly.
284
+ `RunConfig(check_quota=False)` turns the check off.
285
+
286
+ ## How it works
287
+
288
+ **Precip, per reservoir and day** (first source with a value):
289
+
290
+ 1. PRISM 800 m `ppt` — plain (unweighted) mean of the reservoir's PRISM
291
+ 800 m cells, on the 800 m grid;
292
+ 2. PRISM 4 km `ppt` — over the **same 800 m cells**, on the 800 m grid
293
+ (each 800 m cell takes the 4 km pixel it lies in);
294
+ 3. URMA `PCP` — over the reservoir's URMA cell polygon, on
295
+ the URMA grid.
296
+
297
+ Only cell polygons are sent to Earth Engine, never the native polygons.
298
+ This replaced the area-weighted mean over the native polygon (redlem-force
299
+ <= 0.5): on 5,000 reservoirs x 3 days, 27% of values differed by more than
300
+ 0.01 mm (mean |difference| 0.04 mm, max 3.5 mm), and the precip requests ran
301
+ ~5x faster (benchmark on 5,000 reservoirs, 2026-10-13). Every collection is matched by
302
+ date label (`system:index`), never `filterDate`: the 4 km images are stamped
303
+ 12:00 UTC the day before their label.
304
+
305
+ **Latitude:** area centroid if it is inside the polygon, otherwise the pole
306
+ of inaccessibility of the largest part (computed in EPSG:5070 for geographic
307
+ input). Checked inside for every polygon; the run stops if one is not.
308
+
309
+ **Invalid geometry** is repaired with `shapely.make_valid` (polygon parts
310
+ kept) and logged.
311
+
312
+ **Grids — one source.** All grid information comes from one reference
313
+ image per source (`config.GRID_REFERENCE`, `redlem_force.grids`):
314
+
315
+ - URMA: the first URMA daily image of 2026 (`20260101`), band TMAX —
316
+ "NWS CONUS" Lambert conformal conic, 2,539.703 m pixels. The first image
317
+ of every year 2015–2026 has the same grid, and `rtma_elev` /
318
+ `rtma_water_mask` sit on the same lattice. Its WKT names a WGS 84 datum
319
+ but projects on a 6,371,200 m sphere (`semi_major` / `semi_minor`
320
+ parameters). Earth Engine uses the sphere; pyproj on its own ignores
321
+ those parameters and uses WGS 84 — up to 8 km (2–3 pixels) off.
322
+ `grid_cells.local_crs()` rebuilds the projection on the sphere, which
323
+ matched Earth Engine to 0.000 m on 40 test points (2026-10-15).
324
+ - Every run checks this: five pixel centres are converted to lon/lat
325
+ locally and back by Earth Engine, and the run stops if they move by more
326
+ than 1/1000 of a pixel.
327
+ - PRISM 800 m: the first image of its collection, band ppt.
328
+
329
+ Local work (cell squares, cell counts, centroids) uses the grid's CRS and
330
+ affine transform; Earth Engine reductions use the same image's projection.
331
+
332
+ **URMA cell selection** (local, same logic as `urma_cells.py`):
333
+ candidate cells are the URMA cells the polygon intersects (sharing area);
334
+ each cell's elevation and water mask are the `rtma_elev` /
335
+ `rtma_water_mask` pixel values of that cell, read once per run as arrays on
336
+ the URMA grid (6 requests). Water-mask reservoirs keep the candidates whose
337
+ water mask is 1; others keep candidates with overlap ≥ median, then
338
+ elevation ≤ median. If a water-mask reservoir has no water cells it falls
339
+ back to the overlap/elevation rule (`cell_method = water_mask_fallback`).
340
+ The flag comes from a Boolean column, or the rule max(water mask of the
341
+ candidates) == 1. Cell output columns: ID, `cell_geometry` (WKB,
342
+ EPSG:4326), `n_cells`, `n_touching`, `wm_value`, `cell_method`,
343
+ `cell_elev_m`.
344
+
345
+ **Parallel work:** jobs = blocks of `days_per_request` dates × reservoir
346
+ chunks (`features_per_request` each), run on `n_workers` processes. All
347
+ days of a block are bands of one image, so one request per source covers
348
+ the block. A day with no URMA image is reported and skipped (the rest of the
349
+ block is kept). Rate-limit (429) and
350
+ transient errors are retried with exponential backoff. "User memory limit
351
+ exceeded" is not retried: lower `features_per_request` or raise `tile_scale`.
352
+
353
+ ## Checks done on Earth Engine (check scripts since removed)
354
+
355
+ - PRISM 800 m grid: identical on 549 dates, 1981–2026.
356
+ - URMA grid: all 17,089 daily images 1980-01-01 to 2026-10-14 on the same
357
+ pixel lattice as the 2026 reference image (same projection, pixel size,
358
+ origin whole pixels apart), with every band extraction reads; no dates
359
+ missing in that range.
360
+ - URMA cells: on 2,000 sampled reservoirs, Earth Engine's unweighted pixel
361
+ count over each cell polygon equals `n_cells` for all 2,000; `ELEV_M`
362
+ vs the previous cells file: median difference 0 m, 95th percentile 0 m,
363
+ max 81 m.
364
+ - Stacked days, PRISM pixels and precip values (v0.6 validation): passed.
365
+ - PRISM cells, current rule (largest overlap), 2,000 sampled reservoirs:
366
+ Earth Engine's pixel count equals the selected cells for 1,998, fewer
367
+ for 2, more for none; stacking 5 days vs 1 day identical (max diff
368
+ 8.9e-16). 20200715: all 1,173
369
+ single-cell reservoirs get exactly their assigned pixel's precip (max
370
+ |diff| 0; 573 of them with rain > 0), both with single cells sent as
371
+ points (earlier) and as their squares (current).
372
+
373
+ ## Not yet verified
374
+
375
+ - The `features_per_request` (1000) default is a guess; it needs a
376
+ benchmark. Extraction chunks are also capped by
377
+ `max_request_bytes` (4 MB of geometry): a full-set run with 1000
378
+ reservoirs per request hit Earth Engine's 10,485,760-byte request limit
379
+ on 6 of 45 chunks. Requests that still exceed it are split automatically.
380
+ - `days_per_request` beyond 5 is not benchmarked.
381
+ - `plot_cells` with Esri imagery has only been rendered with a stand-in
382
+ image (the imagery server is not reachable from where it was written);
383
+ the layout, cells, scale bar and legend were checked.
384
+ - Medians in the overlap/elevation rule are numpy medians; urma_cells.py
385
+ used Earth Engine's percentile reducer, which may treat ties / even
386
+ counts differently.
387
+
388
+ ## Tests
389
+
390
+ `pytest tests/` covers dates, geometry parsing/repair, internal point and
391
+ output assembly, cell-result parsing, request splitting, the file-based
392
+ cell workflows, PRISM cell selection, the per-(reservoir, day) precip
393
+ fallback, day blocks, cell maps (no imagery) and an end-to-end run with Earth Engine replaced (no
394
+ Earth Engine).
395
+
396
+ Scripts: `scripts/run_urma_cells.py` and `scripts/run_prism_cells.py` run
397
+ cell selection on a file; `scripts/example_extract_forcing.py` runs the
398
+ forcing extraction; `scripts/plot_reservoir_cells.py` makes cell maps.
399
+