terraproof 0.0.0-stage → 0.4.0

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,232 @@
1
+ #!/usr/bin/env python3
2
+ """Generate a deterministic preview for a bundled scientific figure style."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import math
8
+ import sys
9
+ from typing import Any
10
+
11
+ from _common import CliError, emit_json, positive_float
12
+
13
+
14
+ def build_preview(style_name: str, palette_name: str) -> tuple[Any, dict[str, Any]]:
15
+ """Create a deterministic multi-panel preview and palette audit."""
16
+ try:
17
+ import matplotlib as mpl
18
+ import matplotlib.pyplot as plt
19
+ except ImportError as exc:
20
+ raise CliError(
21
+ "Matplotlib is required for previews; "
22
+ "run with --with 'matplotlib==3.11.1'"
23
+ ) from exc
24
+ from palette_audit import audit_palette
25
+ from style_presets import available_palettes, style_context
26
+
27
+ palettes = available_palettes()
28
+ if palette_name not in palettes:
29
+ raise CliError(
30
+ f"unknown palette {palette_name!r}; "
31
+ f"available: {', '.join(sorted(palettes))}"
32
+ )
33
+ colors = palettes[palette_name]
34
+ if len(colors) < 3:
35
+ raise CliError("preview palette must contain at least three colors")
36
+ audit = audit_palette(
37
+ colors,
38
+ background="#FFFFFF",
39
+ role="graphical",
40
+ name=palette_name,
41
+ )
42
+
43
+ with style_context(style_name, palette_name=palette_name):
44
+ fig, axes = plt.subplots(
45
+ 2,
46
+ 2,
47
+ figsize=(7.0, 5.2),
48
+ layout="constrained",
49
+ )
50
+ x_values = [index / 10.0 for index in range(41)]
51
+ line_styles = ["-", "--", "-.", ":"]
52
+ markers = ["o", "s", "^", "D"]
53
+ for index in range(4):
54
+ values = [
55
+ math.sin(value + index * 0.45) + index * 0.35
56
+ for value in x_values
57
+ ]
58
+ axes[0, 0].plot(
59
+ x_values,
60
+ values,
61
+ color=colors[index % len(colors)],
62
+ linestyle=line_styles[index],
63
+ marker=markers[index],
64
+ markevery=8,
65
+ label=f"Series {index + 1}",
66
+ )
67
+ axes[0, 0].axhline(0, color="0.35", linewidth=0.7)
68
+ axes[0, 0].set(
69
+ xlabel="Time (hours)",
70
+ ylabel="Response (a.u.)",
71
+ title="Color plus redundant encoding",
72
+ )
73
+ axes[0, 0].legend(ncols=2)
74
+
75
+ categories = ["Control", "Low", "High"]
76
+ values = [0.0, 1.4, -0.8]
77
+ hatches = ["", "///", "xx"]
78
+ bars = axes[0, 1].bar(
79
+ categories,
80
+ values,
81
+ color=[colors[index % len(colors)] for index in range(3)],
82
+ edgecolor="black",
83
+ linewidth=0.7,
84
+ )
85
+ for bar, hatch in zip(bars, hatches):
86
+ bar.set_hatch(hatch)
87
+ axes[0, 1].axhline(0, color="black", linewidth=0.7)
88
+ axes[0, 1].set(
89
+ ylabel="Change from baseline (unit)",
90
+ title="Signed bars with visible zero",
91
+ )
92
+
93
+ matrix = [
94
+ [-2.0, -1.2, -0.4, 0.2, 1.0],
95
+ [-1.5, -0.8, float("nan"), 0.8, 1.7],
96
+ [-1.0, -0.2, 0.0, 1.1, 2.0],
97
+ ]
98
+ colormap = mpl.colormaps["RdBu_r"].with_extremes(bad="#777777")
99
+ image = axes[1, 0].imshow(
100
+ matrix,
101
+ cmap=colormap,
102
+ norm=mpl.colors.TwoSlopeNorm(vmin=-2, vcenter=0, vmax=2),
103
+ aspect="auto",
104
+ interpolation="nearest",
105
+ )
106
+ axes[1, 0].set(
107
+ xlabel="Sample",
108
+ ylabel="Feature",
109
+ title="Centered normalization; gray = missing",
110
+ )
111
+ colorbar = fig.colorbar(image, ax=axes[1, 0])
112
+ colorbar.set_label("Effect (unit)")
113
+
114
+ groups = [
115
+ [1.0, 1.2, 0.9, 1.1, 1.4, 0.8],
116
+ [1.4, 1.8, 1.6, 1.5, 2.0, 1.7],
117
+ [0.7, 0.9, 1.0, 0.6, 0.8, 1.1],
118
+ ]
119
+ for index, group in enumerate(groups):
120
+ offsets = [-0.08, -0.05, -0.02, 0.02, 0.05, 0.08]
121
+ axes[1, 1].scatter(
122
+ [index + offset for offset in offsets],
123
+ group,
124
+ color=colors[index % len(colors)],
125
+ edgecolor="black",
126
+ linewidth=0.4,
127
+ marker=markers[index],
128
+ zorder=2,
129
+ )
130
+ ordered = sorted(group)
131
+ median = (ordered[2] + ordered[3]) / 2
132
+ axes[1, 1].plot(
133
+ [index - 0.15, index + 0.15],
134
+ [median, median],
135
+ color="black",
136
+ linewidth=1.2,
137
+ )
138
+ axes[1, 1].set(
139
+ xticks=range(3),
140
+ xticklabels=categories,
141
+ ylabel="Observed value (unit)",
142
+ title="Raw observations with median",
143
+ )
144
+
145
+ for label, ax in zip("ABCD", axes.flat):
146
+ ax.text(
147
+ -0.12,
148
+ 1.06,
149
+ label,
150
+ transform=ax.transAxes,
151
+ fontweight="bold",
152
+ va="top",
153
+ )
154
+ fig.suptitle(f"Style preview: {style_name} / {palette_name}")
155
+ return fig, audit
156
+
157
+
158
+ def build_parser() -> argparse.ArgumentParser:
159
+ parser = argparse.ArgumentParser(
160
+ description=(
161
+ "Render a deterministic accessible-style preview with line, bar, "
162
+ "heatmap, missing-data, and raw-observation examples."
163
+ )
164
+ )
165
+ parser.add_argument("--output", required=True, help="output base path")
166
+ parser.add_argument(
167
+ "--style",
168
+ choices=("default", "nature", "science", "cell", "minimal", "presentation"),
169
+ default="default",
170
+ )
171
+ parser.add_argument("--palette", default="okabe_ito_on_white")
172
+ parser.add_argument(
173
+ "--formats", default="png,svg", help="comma-separated formats"
174
+ )
175
+ parser.add_argument("--dpi", type=positive_float, default=300.0)
176
+ parser.add_argument("--manifest", action="store_true")
177
+ parser.add_argument("--force", action="store_true")
178
+ return parser
179
+
180
+
181
+ def main(argv: list[str] | None = None) -> int:
182
+ parser = build_parser()
183
+ try:
184
+ args = parser.parse_args(argv)
185
+ from figure_export import export_figure
186
+
187
+ fig, audit = build_preview(args.style, args.palette)
188
+ try:
189
+ report = export_figure(
190
+ fig,
191
+ args.output,
192
+ formats=args.formats.split(","),
193
+ dpi=args.dpi,
194
+ overwrite=args.force,
195
+ provenance={
196
+ "purpose": "deterministic bundled-style preview",
197
+ "style": args.style,
198
+ "palette": args.palette,
199
+ "data": "synthetic values defined in style_preview.py",
200
+ "transformations": [
201
+ "analytical sine offsets",
202
+ "explicit TwoSlopeNorm(-2, 0, 2)",
203
+ "median of displayed raw observations",
204
+ ],
205
+ "palette_screen": {
206
+ "background_review_count": audit["contrast_screen"][
207
+ "review_count"
208
+ ],
209
+ "grayscale_review_count": audit["grayscale_screen"][
210
+ "review_count"
211
+ ],
212
+ },
213
+ },
214
+ write_manifest=args.manifest,
215
+ )
216
+ finally:
217
+ import matplotlib.pyplot as plt
218
+
219
+ plt.close(fig)
220
+ report["palette_audit"] = {
221
+ "contrast_screen": audit["contrast_screen"],
222
+ "grayscale_screen": audit["grayscale_screen"],
223
+ "notice": audit["notice"],
224
+ }
225
+ emit_json(report)
226
+ return 0
227
+ except CliError as exc:
228
+ parser.exit(2, f"error: {exc}\n")
229
+
230
+
231
+ if __name__ == "__main__":
232
+ sys.exit(main())
@@ -0,0 +1,95 @@
1
+ {
2
+ "name": "scientific-visualization",
3
+ "layer": "domain",
4
+ "domains": [
5
+ "data",
6
+ "design"
7
+ ],
8
+ "capabilities": [
9
+ "publication-figures",
10
+ "matplotlib",
11
+ "seaborn",
12
+ "colorblind-palettes",
13
+ "multi-panel-plots"
14
+ ],
15
+ "triggers": [
16
+ "plot",
17
+ "chart",
18
+ "figure",
19
+ "visualization",
20
+ "matplotlib",
21
+ "seaborn",
22
+ "publish figure",
23
+ "multi-panel",
24
+ "graphical abstract"
25
+ ],
26
+ "recommended": [
27
+ "verification"
28
+ ],
29
+ "requires": [],
30
+ "conflicts": [],
31
+ "explanation": "Generates publication-ready scientific figures with colorblind-safe palettes.",
32
+ "sections": [
33
+ {
34
+ "id": "non-negotiable-guardrails",
35
+ "title": "Non-negotiable guardrails",
36
+ "source": "SKILL.md#non-negotiable-guardrails"
37
+ },
38
+ {
39
+ "id": "workflow",
40
+ "title": "Workflow",
41
+ "source": "SKILL.md#workflow"
42
+ },
43
+ {
44
+ "id": "pinned-snapshot",
45
+ "title": "Pinned snapshot",
46
+ "source": "SKILL.md#pinned-snapshot"
47
+ },
48
+ {
49
+ "id": "bundled-clis",
50
+ "title": "Bundled CLIs",
51
+ "source": "SKILL.md#bundled-clis"
52
+ },
53
+ {
54
+ "id": "assets",
55
+ "title": "Assets",
56
+ "source": "SKILL.md#assets"
57
+ },
58
+ {
59
+ "id": "references",
60
+ "title": "References",
61
+ "source": "SKILL.md#references"
62
+ },
63
+ {
64
+ "id": "final-review-checklist",
65
+ "title": "Final review checklist",
66
+ "source": "SKILL.md#final-review-checklist"
67
+ },
68
+ {
69
+ "id": "color_palettes",
70
+ "title": "Color, Contrast, and Palette Selection",
71
+ "source": "references/color_palettes.md"
72
+ },
73
+ {
74
+ "id": "journal_requirements",
75
+ "title": "Publisher and Journal Figure Snapshots",
76
+ "source": "references/journal_requirements.md"
77
+ },
78
+ {
79
+ "id": "matplotlib_examples",
80
+ "title": "Current Matplotlib, Seaborn, and Plotly Patterns",
81
+ "source": "references/matplotlib_examples.md"
82
+ },
83
+ {
84
+ "id": "publication_guidelines",
85
+ "title": "Publication Figure Principles",
86
+ "source": "references/publication_guidelines.md"
87
+ },
88
+ {
89
+ "id": "sources",
90
+ "title": "Sources and Version Snapshot",
91
+ "source": "references/sources.md"
92
+ }
93
+ ],
94
+ "checks": []
95
+ }
@@ -0,0 +1,235 @@
1
+ ---
2
+ name: spectral-indices
3
+ description: Compute and interpret vegetation, water, and burn indices with explicit formulas, sensor band mappings, calibrated reflectance, masks, and numeric safeguards; use for NDVI, McFeeters NDWI, MNDWI, NBR or dNBR, EVI, and SAVI from Sentinel-2 or Landsat 8/9 imagery.
4
+ ---
5
+
6
+ # Spectral indices
7
+
8
+ ## Require calibrated, aligned inputs
9
+
10
+ For this skill's quantitative comparison workflows, use cloud/shadow-screened,
11
+ physical **surface reflectance**, not raw DN, RGB display values, QA codes, or a
12
+ mixture of TOA and surface reflectance. Decode scale and additive offset exactly
13
+ once using [satellite preprocessing](../satellite-preprocessing/SKILL.md). A
14
+ common multiplicative scale cancels in a normalized difference, but an additive
15
+ offset does not. EVI/SAVI constants also require physical reflectance units.
16
+
17
+ Verify CRS, complete affine transform, dimensions, extent and validity masks
18
+ before pairing pixels. Use the intersection of masks for all bands in the
19
+ formula. Resampling a coarse SWIR band to a finer grid does not create finer
20
+ information; document the chosen analysis grid and resampling. Resampling
21
+ reflectance before a nonlinear index is generally not equivalent to resampling the
22
+ computed index. Use
23
+ [raster processing](../raster-processing/SKILL.md) for I/O, masks and alignment,
24
+ [GDAL](../gdal/SKILL.md) for CLI workflows, and
25
+ [geomaster](../geomaster/SKILL.md) for broader interpretation context.
26
+ Shared rules: [engineering](../../instructions/engineering.md),
27
+ [simplicity](../../instructions/simplicity.md), [security](../../instructions/security.md).
28
+
29
+ ## Map spectral roles to the sensor
30
+
31
+ Use product band identifiers, not positions in an arbitrary raster stack.
32
+ The following mapping is for Sentinel-2 MSI and Landsat **8/9 OLI**, not older
33
+ Landsat sensors [S1, S2]:
34
+
35
+ | Spectral role | Sentinel-2 | Landsat 8/9 surface reflectance |
36
+ |---|---|---|
37
+ | Blue (`B`) | B02 | SR_B2 |
38
+ | Green (`G`) | B03 | SR_B3 |
39
+ | Red (`R`) | B04 | SR_B4 |
40
+ | Broad NIR (`N`) | B08 | SR_B5 (OLI NIR) |
41
+ | Narrow NIR alternative | B8A | No interchangeable extra NIR band |
42
+ | SWIR1 (`S1`) | B11 | SR_B6 |
43
+ | SWIR2 (`S2`) | B12 | SR_B7 |
44
+
45
+ Sentinel-2 B02/B03/B04/B08 have native **10 m** resolution; B8A/B11/B12 have
46
+ native **20 m** resolution [S1]. B08 and B8A have different spectral responses.
47
+ For Sentinel-2 formulas below, `N` defaults to B08; if using B8A to match a
48
+ coarser grid or a harmonized workflow, name that choice and do not mix it across
49
+ dates as if unchanged. Landsat 8/9 reflective bands here have **30 m** resolution
50
+ [S2]. Do not read `src.read(8)` to obtain B08 from a single-band B08 file:
51
+ Rasterio indices address file bands, not sensor band names.
52
+
53
+ ## NDVI: vegetation contrast
54
+
55
+ Use physical, masked red and NIR reflectance on the same grid [S3]:
56
+
57
+ ```text
58
+ NDVI = (N - R) / (N + R)
59
+ Sentinel-2: (B08 - B04) / (B08 + B04)
60
+ Landsat 8/9: (SR_B5 - SR_B4) / (SR_B5 + SR_B4)
61
+ ```
62
+
63
+ For nonnegative inputs with nonzero sum, NDVI lies in **[-1, 1]**. High values
64
+ indicate stronger NIR/red contrast, not a universal biomass or plant-health
65
+ measurement. NDVI can saturate in dense vegetation and responds to soil,
66
+ phenology, water, shadow and atmosphere. Do not apply universal vegetation-class
67
+ thresholds without local calibration. Negative corrected reflectances can yield
68
+ ratios outside the nominal interval; investigate rather than silently clipping.
69
+
70
+ ## NDWI (McFeeters) versus MNDWI: specify the water index
71
+
72
+ For open-water contrast, use one named definition and physical reflectance [S4]:
73
+
74
+ ```text
75
+ NDWI_McFeeters = (G - N) / (G + N)
76
+ MNDWI_Xu = (G - S1) / (G + S1)
77
+ ```
78
+
79
+ McFeeters NDWI uses Sentinel-2 B03/B08 or Landsat 8/9 SR_B3/SR_B5. MNDWI uses
80
+ Sentinel-2 B03/B11 or Landsat 8/9 SR_B3/SR_B6. These are **not** the NIR/SWIR
81
+ vegetation-moisture index also called NDWI (Gao). ESA SNAP names the McFeeters
82
+ operator `NDWI2`; always state the formula rather than trusting an operator name.
83
+
84
+ Both normalized differences lie in **[-1, 1]** for nonnegative inputs and nonzero
85
+ sum. MNDWI substitutes SWIR1 to reduce some built-up-land confusion, not to create
86
+ an infallible water mask. Turbid/shallow water, shadows, snow, mixed shore pixels
87
+ and urban surfaces still require validation. Select a local threshold using
88
+ reference data; do not present either continuous index as measured water depth.
89
+
90
+ ## NBR and dNBR: burn-sensitive contrast and change
91
+
92
+ Use masked, aligned NIR and **SWIR2**, not SWIR1 [S5]:
93
+
94
+ ```text
95
+ NBR = (N - S2) / (N + S2)
96
+ dNBR = NBR_prefire - NBR_postfire
97
+ Sentinel-2 NBR: (B08 - B12) / (B08 + B12)
98
+ Landsat 8/9 NBR: (SR_B5 - SR_B7) / (SR_B5 + SR_B7)
99
+ ```
100
+
101
+ For nonnegative reflectances with nonzero sum, NBR lies in **[-1, 1]**. The
102
+ unscaled dNBR difference can consequently span **[-2, 2]** (derived from the two
103
+ NBR bounds), so it must not be tested as though it were a single normalized index.
104
+ Record whether a delivered product is scaled; do not compare encoded integer
105
+ thresholds with unscaled floats.
106
+
107
+ Positive dNBR commonly indicates decreased NBR after fire, but seasonality,
108
+ moisture, harvest, land-cover change and cloud remnants also alter NBR. Match
109
+ prefire/postfire season and processing, retain both-date validity, and validate
110
+ burn severity with suitable reference observations [S6]. Do not invent universal
111
+ severity class breaks or treat an index change as causal proof of fire.
112
+
113
+ ## EVI and SAVI: additive constants require physical reflectance
114
+
115
+ Use blue/red/NIR surface reflectance for EVI; use red/NIR for SAVI. The standard
116
+ USGS coefficients and the USGS SAVI soil adjustment choice are [S7, S8]:
117
+
118
+ ```text
119
+ EVI = 2.5 * (N - R) / (N + 6 * R - 7.5 * B + 1)
120
+ SAVI = (1 + L) * (N - R) / (N + R + L), with L = 0.5
121
+ ```
122
+
123
+ Map `B`, `R`, `N` using the sensor table. Do not put raw DN or reflectance scaled
124
+ to integer storage into these formulas: the additive constants would be in the
125
+ wrong units. EVI mitigates some canopy-background/atmospheric effects but is not
126
+ a substitute for atmospheric correction and QA. Its blue term is sensitive to
127
+ residual atmospheric problems; USGS warns that Landsat 8/9 SR blue-band retrieval
128
+ can be unreliable for analysis [S9]. Make that caveat visible when using EVI.
129
+
130
+ EVI has no universal algebraic **[-1, 1]** bound: even nonnegative inputs can
131
+ produce a near-zero denominator and extreme values. USGS delivered EVI products
132
+ have a specified valid range, but that product contract is not a theorem about
133
+ every raw formula result [S7]. SAVI with `L = 0.5` is bounded by **[-1, 1]** when
134
+ both input reflectances are within **[0, 1]** (derived from its formula); negative
135
+ or above-unity corrected values invalidate that assumption. Keep exceptions
136
+ visible. Do not clip EVI/SAVI simply to pass an index-range checker.
137
+
138
+ ## Divide safely and write explicit nodata
139
+
140
+ Cast before arithmetic. A zero denominator is invalid, not index zero. Mask
141
+ nonfinite inputs and outputs. If near-zero denominators are excluded, select a
142
+ tolerance from measurement/precision requirements and report it; a universal
143
+ machine epsilon is not a scientific quality threshold.
144
+
145
+ ```python
146
+ import numpy as np
147
+
148
+ def safe_ratio(numerator, denominator, min_abs_denominator=0.0):
149
+ if min_abs_denominator < 0:
150
+ raise ValueError("Denominator tolerance must be nonnegative")
151
+ num = np.ma.asarray(numerator, dtype="float32").filled(np.nan)
152
+ den = np.ma.asarray(denominator, dtype="float32").filled(np.nan)
153
+ valid = np.isfinite(num) & np.isfinite(den)
154
+ valid &= np.abs(den) > min_abs_denominator
155
+ out = np.full(np.broadcast_shapes(num.shape, den.shape), np.nan, dtype="float32")
156
+ with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
157
+ np.divide(num, den, out=out, where=valid)
158
+ out[~np.isfinite(out)] = np.nan
159
+ return out
160
+ ```
161
+
162
+ Standalone NDVI read/write example for **already decoded** single-band
163
+ reflectance files with identity scale/offset (small rasters; use windows for
164
+ large scenes). The helper above can be used for other formulas:
165
+
166
+ ```python
167
+ import numpy as np
168
+ import rasterio
169
+
170
+ with rasterio.open("sr_red.tif") as red_src, rasterio.open("sr_nir.tif") as nir_src:
171
+ if red_src.crs is None or red_src.crs != nir_src.crs:
172
+ raise ValueError("Known, matching CRS required")
173
+ if red_src.transform != nir_src.transform or red_src.shape != nir_src.shape:
174
+ raise ValueError("Bands must share the complete grid")
175
+ for src in (red_src, nir_src):
176
+ if src.count != 1 or src.scales != (1.0,) or src.offsets != (0.0,):
177
+ raise ValueError("Expected decoded single-band reflectance")
178
+ r = red_src.read(1, masked=True).astype("float32").filled(np.nan)
179
+ n = nir_src.read(1, masked=True).astype("float32").filled(np.nan)
180
+ den = n + r
181
+ valid = np.isfinite(n) & np.isfinite(r) & (den != 0)
182
+ ndvi = np.full(r.shape, np.nan, dtype="float32")
183
+ with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
184
+ np.divide(n - r, den, out=ndvi, where=valid)
185
+ ndvi[~np.isfinite(ndvi)] = np.nan
186
+ with rasterio.open(
187
+ "ndvi.tif", "w", driver="GTiff", width=red_src.width,
188
+ height=red_src.height, count=1, dtype="float32", nodata=np.nan,
189
+ crs=red_src.crs, transform=red_src.transform,
190
+ ) as dst:
191
+ dst.write(ndvi, 1)
192
+ ```
193
+
194
+ Metadata identity alone cannot prove physical encoding; that is a prerequisite
195
+ from the preprocessing record. Preserve valid zero indices and keep masked
196
+ pixels nodata. Independently check known input pixels and formula values.
197
+
198
+ ## Verify with Terraproof
199
+
200
+ Use an installed Python core and real local data:
201
+
202
+ ```bash
203
+ python -m terraproof check sr_red.tif sr_nir.tif --expect reflectance
204
+ python -m terraproof check ndvi.tif --expect index --format md --lang en --out ndvi-report.md
205
+ python -m terraproof check nbr_prefire.tif nbr_postfire.tif --expect index
206
+ python -m terraproof check dnbr.tif
207
+ ```
208
+
209
+ `rs.reflectance_range` is sampled plausibility, not proof of decoded SR.
210
+ `rs.index_range` tests a nominal normalized-index interval; it is useful for
211
+ NDVI/NDWI/MNDWI/NBR under the stated assumptions, **not a general validator for
212
+ dNBR or EVI**. The last command intentionally omits `--expect index` for dNBR.
213
+ Inspect out-of-range results rather than altering data to satisfy a checker.
214
+
215
+ `raster.nodata_declared`, `raster.grid_alignment`, `crs.defined` and
216
+ `crs.consistent` provide metadata checks. Grid alignment does not establish
217
+ identical shape/extent or actual co-registration. GeoTIFF inputs may also receive
218
+ the heuristic `raster.cog_layout` check.
219
+
220
+ Formula choice, correct band roles, exact-once calibration, cloud masking,
221
+ denominator policy, scientific interpretation, and burn/water/vegetation
222
+ threshold validity are **not checked automatically yet**. A plausible wrong-band
223
+ index can pass. See [verification](../verification/SKILL.md).
224
+
225
+ ## Sources
226
+
227
+ - [S1 — ESA Sentinel-2 mission](https://sentiwiki.copernicus.eu/web/s2-mission): spectral-band identities and native 10 m/20 m resolutions.
228
+ - [S2 — USGS Landsat band designations](https://www.usgs.gov/landsat-missions/landsat-8): OLI blue 2, green 3, red 4, NIR 5, SWIR1 6, SWIR2 7 and 30 m reflective resolution; [Landsat 9](https://www.usgs.gov/landsat-missions/landsat-9) has the corresponding OLI bands.
229
+ - [S3 — USGS NDVI](https://www.usgs.gov/landsat-missions/landsat-normalized-difference-vegetation-index): formula, Landsat 8/9 bands and delivered range. Normalized-difference bounds here follow algebraically for nonnegative inputs.
230
+ - [S4 — ESA SNAP McFeeters NDWI2 specification](https://raw.githubusercontent.com/senbox-org/optical-toolbox/master/opttbx-radiometric-indices-ui/src/main/resources/eu/esa/opt/radiometry/docs/ndwi2/Ndwi2AlgorithmSpecification.html) and [MNDWI specification](https://raw.githubusercontent.com/senbox-org/optical-toolbox/master/opttbx-radiometric-indices-ui/src/main/resources/eu/esa/opt/radiometry/docs/mndwi/MndwiAlgorithmSpecification.html): green/NIR versus green/middle-IR formulas with unit factors. No upstream text or code is vendored.
231
+ - [S5 — USGS NBR](https://www.usgs.gov/landsat-missions/landsat-normalized-burn-ratio): formula and Landsat 8/9 bands 5 and 7 (SWIR2).
232
+ - [S6 — USGS Burn Severity glossary](https://burnseverity.cr.usgs.gov/glossary): dNBR prefire-minus-postfire definition; [MTBS product descriptions](https://www.mtbs.gov/product-descriptions): seasonal/phenological scene matching.
233
+ - [S7 — USGS EVI](https://www.usgs.gov/landsat-missions/landsat-enhanced-vegetation-index): gain 2.5, red coefficient 6, blue coefficient 7.5, background constant 1 and delivered-product specifications.
234
+ - [S8 — USGS SAVI](https://www.usgs.gov/landsat-missions/landsat-soil-adjusted-vegetation-index): formula and L = 0.5; conditional bounds here are algebraic consequences, not universal physical limits.
235
+ - [S9 — USGS Collection 2 surface reflectance](https://www.usgs.gov/landsat-missions/landsat-collection-2-surface-reflectance): OLI coastal/blue-band aerosol-inversion caveat and potentially unreliable corrections.
@@ -0,0 +1,7 @@
1
+ # Attribution
2
+
3
+ Terraproof native — no upstream source.
4
+
5
+ Authored for Terraproof by Geova. License: MIT; see the [project license](../../LICENSE).
6
+ Primary technical references are listed in [SKILL.md](SKILL.md#sources).
7
+ No upstream skill text or code was copied or adapted.
@@ -0,0 +1,88 @@
1
+ {
2
+ "name": "spectral-indices",
3
+ "layer": "domain",
4
+ "domains": [
5
+ "geospatial"
6
+ ],
7
+ "capabilities": [
8
+ "spectral-index",
9
+ "vegetation-index",
10
+ "water-index",
11
+ "burn-index"
12
+ ],
13
+ "triggers": [
14
+ "spectral indices",
15
+ "vegetation index",
16
+ "water index",
17
+ "burn severity",
18
+ "ndvi",
19
+ "ndwi",
20
+ "mndwi",
21
+ "nbr",
22
+ "dnbr",
23
+ "evi",
24
+ "savi"
25
+ ],
26
+ "recommended": [
27
+ "satellite-preprocessing"
28
+ ],
29
+ "requires": [],
30
+ "conflicts": [],
31
+ "explanation": "Computes and interprets NDVI, NDWI/MNDWI, NBR/dNBR, EVI, and SAVI from calibrated, masked reflectance with safe numeric handling.",
32
+ "sections": [
33
+ {
34
+ "id": "require-calibrated-aligned-inputs",
35
+ "title": "Require calibrated, aligned inputs",
36
+ "source": "SKILL.md#require-calibrated-aligned-inputs"
37
+ },
38
+ {
39
+ "id": "map-spectral-roles-to-the-sensor",
40
+ "title": "Map spectral roles to the sensor",
41
+ "source": "SKILL.md#map-spectral-roles-to-the-sensor"
42
+ },
43
+ {
44
+ "id": "ndvi-vegetation-contrast",
45
+ "title": "NDVI: vegetation contrast",
46
+ "source": "SKILL.md#ndvi-vegetation-contrast"
47
+ },
48
+ {
49
+ "id": "ndwi-mcfeeters-versus-mndwi-specify-the-water-index",
50
+ "title": "NDWI (McFeeters) versus MNDWI: specify the water index",
51
+ "source": "SKILL.md#ndwi-mcfeeters-versus-mndwi-specify-the-water-index"
52
+ },
53
+ {
54
+ "id": "nbr-and-dnbr-burn-sensitive-contrast-and-change",
55
+ "title": "NBR and dNBR: burn-sensitive contrast and change",
56
+ "source": "SKILL.md#nbr-and-dnbr-burn-sensitive-contrast-and-change"
57
+ },
58
+ {
59
+ "id": "evi-and-savi-additive-constants-require-physical-reflectance",
60
+ "title": "EVI and SAVI: additive constants require physical reflectance",
61
+ "source": "SKILL.md#evi-and-savi-additive-constants-require-physical-reflectance"
62
+ },
63
+ {
64
+ "id": "divide-safely-and-write-explicit-nodata",
65
+ "title": "Divide safely and write explicit nodata",
66
+ "source": "SKILL.md#divide-safely-and-write-explicit-nodata"
67
+ },
68
+ {
69
+ "id": "verify-with-terraproof",
70
+ "title": "Verify with Terraproof",
71
+ "source": "SKILL.md#verify-with-terraproof"
72
+ },
73
+ {
74
+ "id": "sources",
75
+ "title": "Sources",
76
+ "source": "SKILL.md#sources"
77
+ }
78
+ ],
79
+ "checks": [
80
+ "rs.reflectance_range",
81
+ "rs.index_range",
82
+ "raster.nodata_declared",
83
+ "raster.grid_alignment",
84
+ "crs.defined",
85
+ "crs.consistent",
86
+ "raster.cog_layout"
87
+ ]
88
+ }