terraproof 0.0.0-stage → 0.4.1

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.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/bin/terraproof.js +4 -0
  4. package/dist/router/apply.js +147 -0
  5. package/dist/router/classify.js +111 -0
  6. package/dist/router/explain.js +9 -0
  7. package/dist/router/index.js +272 -0
  8. package/dist/router/resolve.js +239 -0
  9. package/dist/router/score.js +60 -0
  10. package/dist/router/types.js +1 -0
  11. package/dist/router/validate.js +81 -0
  12. package/instructions/engineering.md +14 -0
  13. package/instructions/security.md +14 -0
  14. package/instructions/simplicity.md +13 -0
  15. package/package.json +65 -4
  16. package/routing/DOMAIN_ROUTING.md +161 -0
  17. package/routing/ROUTER_DESIGN.md +173 -0
  18. package/routing/SKILL_MANIFEST.md +86 -0
  19. package/routing/checks.json +121 -0
  20. package/routing/collections.json +47 -0
  21. package/routing/registry.json +2211 -0
  22. package/routing/rules.json +64 -0
  23. package/skills/accuracy-assessment/SKILL.md +213 -0
  24. package/skills/accuracy-assessment/UPSTREAM.md +7 -0
  25. package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
  26. package/skills/accuracy-assessment/skill.json +103 -0
  27. package/skills/brainstorming/SKILL.md +250 -0
  28. package/skills/brainstorming/UPSTREAM.md +29 -0
  29. package/skills/brainstorming/scripts/frame-template.html +213 -0
  30. package/skills/brainstorming/scripts/helper.js +167 -0
  31. package/skills/brainstorming/scripts/server.cjs +723 -0
  32. package/skills/brainstorming/scripts/start-server.sh +209 -0
  33. package/skills/brainstorming/scripts/stop-server.sh +120 -0
  34. package/skills/brainstorming/skill.json +73 -0
  35. package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  36. package/skills/brainstorming/visual-companion.md +299 -0
  37. package/skills/crs-and-units/SKILL.md +200 -0
  38. package/skills/crs-and-units/UPSTREAM.md +7 -0
  39. package/skills/crs-and-units/skill.json +74 -0
  40. package/skills/design-postgis-tables/SKILL.md +494 -0
  41. package/skills/design-postgis-tables/UPSTREAM.md +21 -0
  42. package/skills/design-postgis-tables/skill.json +90 -0
  43. package/skills/gdal/SKILL.md +125 -0
  44. package/skills/gdal/UPSTREAM.md +22 -0
  45. package/skills/gdal/references/gdal-recipes.md +103 -0
  46. package/skills/gdal/skill.json +66 -0
  47. package/skills/geomaster/README.md +105 -0
  48. package/skills/geomaster/SKILL.md +366 -0
  49. package/skills/geomaster/UPSTREAM.md +21 -0
  50. package/skills/geomaster/references/advanced-gis.md +376 -0
  51. package/skills/geomaster/references/big-data.md +363 -0
  52. package/skills/geomaster/references/code-examples.md +531 -0
  53. package/skills/geomaster/references/coordinate-systems.md +364 -0
  54. package/skills/geomaster/references/core-libraries.md +273 -0
  55. package/skills/geomaster/references/data-sources.md +330 -0
  56. package/skills/geomaster/references/gis-software.md +369 -0
  57. package/skills/geomaster/references/industry-applications.md +420 -0
  58. package/skills/geomaster/references/machine-learning.md +462 -0
  59. package/skills/geomaster/references/programming-languages.md +456 -0
  60. package/skills/geomaster/references/remote-sensing.md +370 -0
  61. package/skills/geomaster/references/scientific-domains.md +416 -0
  62. package/skills/geomaster/references/specialized-topics.md +428 -0
  63. package/skills/geomaster/references/troubleshooting.md +439 -0
  64. package/skills/geomaster/skill.json +157 -0
  65. package/skills/geopandas/SKILL.md +250 -0
  66. package/skills/geopandas/UPSTREAM.md +22 -0
  67. package/skills/geopandas/references/crs-management.md +231 -0
  68. package/skills/geopandas/references/data-io.md +323 -0
  69. package/skills/geopandas/references/data-structures.md +207 -0
  70. package/skills/geopandas/references/geometric-operations.md +262 -0
  71. package/skills/geopandas/references/spatial-analysis.md +294 -0
  72. package/skills/geopandas/references/visualization.md +230 -0
  73. package/skills/geopandas/scripts/_common.py +605 -0
  74. package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
  75. package/skills/geopandas/scripts/export_plan.py +305 -0
  76. package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
  77. package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
  78. package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
  79. package/skills/geopandas/scripts/vector_inventory.py +140 -0
  80. package/skills/geopandas/skill.json +116 -0
  81. package/skills/geoparquet-validation/SKILL.md +125 -0
  82. package/skills/geoparquet-validation/UPSTREAM.md +24 -0
  83. package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
  84. package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
  85. package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
  86. package/skills/geoparquet-validation/skill.json +71 -0
  87. package/skills/geospatial-data-discovery/SKILL.md +49 -0
  88. package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
  89. package/skills/geospatial-data-discovery/skill.json +51 -0
  90. package/skills/geospatial-frontend/SKILL.md +86 -0
  91. package/skills/geospatial-frontend/UPSTREAM.md +23 -0
  92. package/skills/geospatial-frontend/references/design-system.md +283 -0
  93. package/skills/geospatial-frontend/references/user-preferences.md +96 -0
  94. package/skills/geospatial-frontend/skill.json +87 -0
  95. package/skills/geozarr/SKILL.md +244 -0
  96. package/skills/geozarr/UPSTREAM.md +21 -0
  97. package/skills/geozarr/skill.json +97 -0
  98. package/skills/networkx/SKILL.md +440 -0
  99. package/skills/networkx/UPSTREAM.md +22 -0
  100. package/skills/networkx/references/algorithms.md +384 -0
  101. package/skills/networkx/references/generators.md +385 -0
  102. package/skills/networkx/references/graph-basics.md +284 -0
  103. package/skills/networkx/references/io.md +457 -0
  104. package/skills/networkx/references/visualization.md +531 -0
  105. package/skills/networkx/skill.json +93 -0
  106. package/skills/raster-processing/SKILL.md +222 -0
  107. package/skills/raster-processing/UPSTREAM.md +7 -0
  108. package/skills/raster-processing/skill.json +81 -0
  109. package/skills/sar-basics/SKILL.md +202 -0
  110. package/skills/sar-basics/UPSTREAM.md +7 -0
  111. package/skills/sar-basics/references/calibration-lut.md +98 -0
  112. package/skills/sar-basics/skill.json +97 -0
  113. package/skills/satellite-preprocessing/SKILL.md +241 -0
  114. package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
  115. package/skills/satellite-preprocessing/skill.json +84 -0
  116. package/skills/scientific-visualization/SKILL.md +285 -0
  117. package/skills/scientific-visualization/UPSTREAM.md +25 -0
  118. package/skills/scientific-visualization/assets/color_palettes.py +263 -0
  119. package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
  120. package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
  121. package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
  122. package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
  123. package/skills/scientific-visualization/references/color_palettes.md +227 -0
  124. package/skills/scientific-visualization/references/journal_requirements.md +169 -0
  125. package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
  126. package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
  127. package/skills/scientific-visualization/references/sources.md +76 -0
  128. package/skills/scientific-visualization/scripts/_common.py +136 -0
  129. package/skills/scientific-visualization/scripts/export_plan.py +493 -0
  130. package/skills/scientific-visualization/scripts/figure_export.py +642 -0
  131. package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
  132. package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
  133. package/skills/scientific-visualization/scripts/style_presets.py +501 -0
  134. package/skills/scientific-visualization/scripts/style_preview.py +232 -0
  135. package/skills/scientific-visualization/skill.json +95 -0
  136. package/skills/spectral-indices/SKILL.md +235 -0
  137. package/skills/spectral-indices/UPSTREAM.md +7 -0
  138. package/skills/spectral-indices/skill.json +88 -0
  139. package/skills/stac-and-cloud-access/SKILL.md +209 -0
  140. package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
  141. package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
  142. package/skills/stac-and-cloud-access/skill.json +98 -0
  143. package/skills/statistical-analysis/SKILL.md +446 -0
  144. package/skills/statistical-analysis/UPSTREAM.md +24 -0
  145. package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
  146. package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
  147. package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
  148. package/skills/statistical-analysis/references/reporting_standards.md +482 -0
  149. package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
  150. package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
  151. package/skills/statistical-analysis/skill.json +127 -0
  152. package/skills/systematic-debugging/SKILL.md +283 -0
  153. package/skills/systematic-debugging/UPSTREAM.md +28 -0
  154. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  155. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  156. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  157. package/skills/systematic-debugging/find-polluter.sh +72 -0
  158. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  159. package/skills/systematic-debugging/skill.json +88 -0
  160. package/skills/time-series-and-change/SKILL.md +217 -0
  161. package/skills/time-series-and-change/UPSTREAM.md +7 -0
  162. package/skills/time-series-and-change/references/change-methods.md +42 -0
  163. package/skills/time-series-and-change/skill.json +116 -0
  164. package/skills/vector-quality/SKILL.md +204 -0
  165. package/skills/vector-quality/UPSTREAM.md +7 -0
  166. package/skills/vector-quality/skill.json +82 -0
  167. package/skills/verification/SKILL.md +120 -0
  168. package/skills/verification/UPSTREAM.md +31 -0
  169. package/skills/verification/skill.json +67 -0
  170. package/skills/writing-plans/SKILL.md +171 -0
  171. package/skills/writing-plans/UPSTREAM.md +23 -0
  172. package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  173. package/skills/writing-plans/skill.json +80 -0
  174. package/sources/SOURCES.md +374 -0
  175. package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
  176. package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
  177. package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
  178. package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
  179. package/third_party/superpowers/LICENSE +21 -0
  180. package/third_party/superpowers/NOTICE.md +17 -0
  181. package/third_party/timescale-pg-aiguide/LICENSE +176 -0
  182. package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
@@ -0,0 +1,416 @@
1
+ # Scientific Domain Applications
2
+
3
+ Geospatial applications across scientific disciplines: marine, atmospheric, hydrology, and more.
4
+
5
+ ## Marine & Coastal GIS
6
+
7
+ ### Coastal Vulnerability Assessment
8
+
9
+ ```python
10
+ import geopandas as gpd
11
+ import rasterio
12
+ import numpy as np
13
+
14
+ def coastal_vulnerability_index(dem_path, shoreline_path, output_path):
15
+ """Calculate coastal vulnerability index."""
16
+
17
+ # 1. Load elevation
18
+ with rasterio.open(dem_path) as src:
19
+ dem = src.read(1)
20
+ transform = src.transform
21
+
22
+ # 2. Distance to shoreline
23
+ shoreline = gpd.read_file(shoreline_path)
24
+ # ... calculate distance raster ...
25
+
26
+ # 3. Vulnerability criteria (0-1 scale)
27
+ elevation_vuln = 1 - np.clip(dem / 10, 0, 1) # Lower = more vulnerable
28
+ slope_vuln = 1 - np.clip(slope / 10, 0, 1)
29
+
30
+ # 4. Weighted overlay
31
+ weights = {
32
+ 'elevation': 0.3,
33
+ 'slope': 0.2,
34
+ 'distance_to_shore': 0.2,
35
+ 'wave_height': 0.2,
36
+ 'sea_level_trend': 0.1
37
+ }
38
+
39
+ cvi = sum(vuln * w for vuln, w in zip(
40
+ [elevation_vuln, slope_vuln, distance_vuln, wave_vuln, slr_vuln],
41
+ weights.values()
42
+ ))
43
+
44
+ return cvi
45
+ ```
46
+
47
+ ### Marine Habitat Mapping
48
+
49
+ ```python
50
+ # Benthic habitat classification
51
+ def classify_benthic_habitat(bathymetry, backscatter, derived_layers):
52
+ """
53
+ Classify benthic habitat using:
54
+ - Bathymetry (depth)
55
+ - Backscatter intensity
56
+ - Derived terrain features
57
+ """
58
+
59
+ # 1. Extract features
60
+ features = {
61
+ 'depth': bathymetry,
62
+ 'backscatter': backscatter,
63
+ 'slope': calculate_slope(bathymetry),
64
+ 'rugosity': calculate_rugosity(bathymetry),
65
+ 'curvature': calculate_curvature(bathymetry)
66
+ }
67
+
68
+ # 2. Classification rules
69
+ habitat_classes = {}
70
+
71
+ # Coral reef: shallow, high rugosity, moderate backscatter
72
+ coral_mask = (
73
+ (features['depth'] > -30) &
74
+ (features['depth'] < -5) &
75
+ (features['rugosity'] > 2) &
76
+ (features['backscatter'] > -15)
77
+ )
78
+ habitat_classes[coral_mask] = 1 # Coral
79
+
80
+ # Seagrass: very shallow, low backscatter
81
+ seagrass_mask = (
82
+ (features['depth'] > -15) &
83
+ (features['depth'] < -2) &
84
+ (features['backscatter'] < -20)
85
+ )
86
+ habitat_classes[seagrass_mask] = 2 # Seagrass
87
+
88
+ # Sandy bottom: low rugosity
89
+ sand_mask = (
90
+ (features['rugosity'] < 1.5) &
91
+ (features['slope'] < 5)
92
+ )
93
+ habitat_classes[sand_mask] = 3 # Sand
94
+
95
+ return habitat_classes
96
+ ```
97
+
98
+ ## Atmospheric Science
99
+
100
+ ### Weather Data Processing
101
+
102
+ ```python
103
+ import xarray as xr
104
+ import rioxarray
105
+
106
+ # Open NetCDF weather data
107
+ ds = xr.open_dataset('era5_data.nc')
108
+
109
+ # Select variable and time
110
+ temperature = ds.t2m # 2m temperature
111
+ precipitation = ds.tp # Total precipitation
112
+
113
+ # Spatial subsetting
114
+ roi = ds.sel(latitude=slice(20, 30), longitude=slice(65, 75))
115
+
116
+ # Temporal aggregation
117
+ monthly = roi.resample(time='1M').mean()
118
+ daily = roi.resample(time='1D').sum()
119
+
120
+ # Export to GeoTIFF
121
+ temperature.rio.to_raster('temperature.tif')
122
+
123
+ # Calculate climate indices
124
+ def calculate_spi(precip, scale=3):
125
+ """Standardized Precipitation Index."""
126
+ # Fit gamma distribution
127
+ from scipy import stats
128
+ # ... SPI calculation ...
129
+ return spi
130
+ ```
131
+
132
+ ### Air Quality Analysis
133
+
134
+ ```python
135
+ # PM2.5 interpolation
136
+ def interpolate_pm25(sensor_gdf, grid_resolution=1000):
137
+ """
138
+ Interpolate PM2.5 from sensor network.
139
+ Uses IDW or Kriging.
140
+ """
141
+ from pykrige.ok import OrdinaryKriging
142
+ import numpy as np
143
+
144
+ # Extract coordinates and values
145
+ lon = sensor_gdf.geometry.x.values
146
+ lat = sensor_gdf.geometry.y.values
147
+ values = sensor_gdf['PM25'].values
148
+
149
+ # Create grid
150
+ grid_lon = np.arange(lon.min(), lon.max(), grid_resolution)
151
+ grid_lat = np.arange(lat.min(), lat.max(), grid_resolution)
152
+
153
+ # Ordinary Kriging
154
+ OK = OrdinaryKriging(lon, lat, values,
155
+ variogram_model='exponential',
156
+ verbose=False,
157
+ enable_plotting=False)
158
+
159
+ # Interpolate
160
+ z, ss = OK.execute('grid', grid_lon, grid_lat)
161
+
162
+ return z, grid_lon, grid_lat
163
+ ```
164
+
165
+ ## Hydrology
166
+
167
+ ### Watershed Delineation
168
+
169
+ ```python
170
+ import rasterio
171
+ import numpy as np
172
+ from scipy import ndimage
173
+
174
+ def delineate_watershed(dem_path, outlet_point):
175
+ """
176
+ Delineate watershed from DEM and outlet point.
177
+ """
178
+
179
+ # 1. Load DEM
180
+ with rasterio.open(dem_path) as src:
181
+ dem = src.read(1)
182
+ transform = src.transform
183
+
184
+ # 2. Fill sinks
185
+ filled = fill_sinks(dem)
186
+
187
+ # 3. Calculate flow direction (D8 method)
188
+ flow_dir = calculate_flow_direction_d8(filled)
189
+
190
+ # 4. Calculate flow accumulation
191
+ flow_acc = calculate_flow_accumulation(flow_dir)
192
+
193
+ # 5. Delineate watershed
194
+ # Convert outlet point to raster coordinates
195
+ row, col = ~transform * (outlet_point.x, outlet_point.y)
196
+ row, col = int(row), int(col)
197
+
198
+ # Trace upstream
199
+ watershed = trace_upstream(flow_dir, row, col)
200
+
201
+ return watershed, flow_acc, flow_dir
202
+
203
+ def calculate_flow_direction_d8(dem):
204
+ """D8 flow direction algorithm."""
205
+ # Encode direction as powers of 2
206
+ # 32 64 128
207
+ # 16 0 1
208
+ # 8 4 2
209
+
210
+ rows, cols = dem.shape
211
+ flow_dir = np.zeros_like(dem, dtype=np.uint8)
212
+
213
+ directions = [
214
+ (-1, 0, 64), (-1, 1, 128), (0, 1, 1), (1, 1, 2),
215
+ (1, 0, 4), (1, -1, 8), (0, -1, 16), (-1, -1, 32)
216
+ ]
217
+
218
+ for i in range(1, rows - 1):
219
+ for j in range(1, cols - 1):
220
+ max_drop = -np.inf
221
+ steepest_dir = 0
222
+
223
+ for di, dj, code in directions:
224
+ ni, nj = i + di, j + dj
225
+ drop = dem[i, j] - dem[ni, nj]
226
+
227
+ if drop > max_drop and drop > 0:
228
+ max_drop = drop
229
+ steepest_dir = code
230
+
231
+ flow_dir[i, j] = steepest_dir
232
+
233
+ return flow_dir
234
+ ```
235
+
236
+ ### Flood Inundation Modeling
237
+
238
+ ```python
239
+ def flood_inundation(dem, flood_level, roughness=0.03):
240
+ """
241
+ Simple flood inundation modeling.
242
+ """
243
+
244
+ # 1. Identify flooded cells
245
+ flooded_mask = dem < flood_level
246
+
247
+ # 2. Calculate flood depth
248
+ flood_depth = np.where(flood_mask, flood_level - dem, 0)
249
+
250
+ # 3. Remove isolated pixels (connected components)
251
+ labeled, num_features = ndimage.label(flooded_mask)
252
+
253
+ # Keep only large components (lakes, not pixels)
254
+ component_sizes = np.bincount(labeled.ravel())
255
+ large_components = component_sizes > 100 # Threshold
256
+
257
+ mask_indices = large_components[labeled]
258
+ final_flooded = flooded_mask & mask_indices
259
+
260
+ # 4. Flood extent area
261
+ cell_area = 30 * 30 # Assuming 30m resolution
262
+ flooded_area = np.sum(final_flooded) * cell_area
263
+
264
+ return flood_depth, final_flooded, flooded_area
265
+ ```
266
+
267
+ ## Agriculture
268
+
269
+ ### Crop Condition Monitoring
270
+
271
+ ```python
272
+ def crop_condition_indices(ndvi_time_series):
273
+ """
274
+ Monitor crop condition using NDVI time series.
275
+ """
276
+
277
+ # 1. Calculate growing season metrics
278
+ max_ndvi = np.max(ndvi_time_series)
279
+ time_to_peak = np.argmax(ndvi_time_series)
280
+
281
+ # 2. Compare to historical baseline
282
+ baseline_max = 0.8 # From historical data
283
+ condition = (max_ndvi / baseline_max) * 100
284
+
285
+ # 3. Classify condition
286
+ if condition > 90:
287
+ status = "Excellent"
288
+ elif condition > 75:
289
+ status = "Good"
290
+ elif condition > 60:
291
+ status = "Fair"
292
+ else:
293
+ status = "Poor"
294
+
295
+ # 4. Estimate yield (simplified)
296
+ yield_potential = condition * 0.5 # tonnes/ha
297
+
298
+ return {
299
+ 'condition': condition,
300
+ 'status': status,
301
+ 'yield_potential': yield_potential
302
+ }
303
+ ```
304
+
305
+ ### Precision Agriculture
306
+
307
+ ```python
308
+ def prescription_map(soil_data, yield_data, nutrient_data):
309
+ """
310
+ Generate variable rate prescription map.
311
+ """
312
+
313
+ # 1. Grid analysis
314
+ # Divide field into management zones
315
+ from sklearn.cluster import KMeans
316
+
317
+ features = np.column_stack([
318
+ soil_data['organic_matter'],
319
+ soil_data['ph'],
320
+ yield_data['yield_t'],
321
+ nutrient_data['nitrogen']
322
+ ])
323
+
324
+ # Cluster into 3-4 zones
325
+ kmeans = KMeans(n_clusters=3, random_state=42)
326
+ zones = kmeans.fit_predict(features)
327
+
328
+ # 2. Prescription rates per zone
329
+ prescriptions = {}
330
+ for zone_id in range(3):
331
+ zone_mask = zones == zone_id
332
+ avg_yield = np.mean(yield_data['yield_t'][zone_mask])
333
+
334
+ # Higher yield areas = higher nutrient requirement
335
+ nitrogen_rate = avg_yield * 0.02 # kg N per kg yield
336
+ prescriptions[zone_id] = {
337
+ 'nitrogen': nitrogen_rate,
338
+ 'phosphorus': nitrogen_rate * 0.3,
339
+ 'potassium': nitrogen_rate * 0.4
340
+ }
341
+
342
+ return zones, prescriptions
343
+ ```
344
+
345
+ ## Forestry
346
+
347
+ ### Forest Inventory Analysis
348
+
349
+ ```python
350
+ def estimate_biomass_from_lidar(chm_path, plot_data):
351
+ """
352
+ Estimate above-ground biomass from LiDAR CHM.
353
+ """
354
+
355
+ # 1. Load Canopy Height Model
356
+ with rasterio.open(chm_path) as src:
357
+ chm = src.read(1)
358
+
359
+ # 2. Extract metrics per plot
360
+ metrics = {}
361
+ for plot_id, geom in plot_data.geometry.items():
362
+ # Extract CHM values for plot
363
+ # ... (mask and extract)
364
+
365
+ plot_metrics = {
366
+ 'height_max': np.max(plot_chm),
367
+ 'height_mean': np.mean(plot_chm),
368
+ 'height_std': np.std(plot_chm),
369
+ 'height_p95': np.percentile(plot_chm, 95),
370
+ 'canopy_cover': np.sum(plot_chm > 2) / plot_chm.size
371
+ }
372
+
373
+ # 3. Allometric equation for biomass
374
+ # Biomass = a * (height^b) * (cover^c)
375
+ biomass = 0.2 * (plot_metrics['height_mean'] ** 1.5) * \
376
+ (plot_metrics['canopy_cover'] ** 0.8)
377
+
378
+ metrics[plot_id] = {
379
+ **plot_metrics,
380
+ 'biomass_tonnes': biomass
381
+ }
382
+
383
+ return metrics
384
+ ```
385
+
386
+ ### Deforestation Detection
387
+
388
+ ```python
389
+ def detect_deforestation(image1_path, image2_path, threshold=0.3):
390
+ """
391
+ Detect deforestation between two dates.
392
+ """
393
+
394
+ # 1. Load NDVI images
395
+ with rasterio.open(image1_path) as src:
396
+ ndvi1 = src.read(1)
397
+ with rasterio.open(image2_path) as src:
398
+ ndvi2 = src.read(1)
399
+
400
+ # 2. Calculate NDVI difference
401
+ ndvi_diff = ndvi2 - ndvi1
402
+
403
+ # 3. Detect deforestation (significant NDVI decrease)
404
+ deforestation = ndvi_diff < -threshold
405
+
406
+ # 4. Remove small patches
407
+ deforestation_cleaned = remove_small_objects(deforestation, min_size=100)
408
+
409
+ # 5. Calculate area
410
+ pixel_area = 900 # m2 (30m resolution)
411
+ deforested_area = np.sum(deforestation_cleaned) * pixel_area
412
+
413
+ return deforestation_cleaned, deforested_area
414
+ ```
415
+
416
+ For more domain-specific examples, see [code-examples.md](code-examples.md).