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,642 @@
1
+ #!/usr/bin/env python3
2
+ """Safe Matplotlib export helpers with explicit, auditable settings.
3
+
4
+ This module does not certify journal compliance. Publisher profiles are dated
5
+ planning snapshots and must be confirmed against the target journal.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import importlib.metadata
12
+ import json
13
+ import math
14
+ import os
15
+ import sys
16
+ import tempfile
17
+ from pathlib import Path
18
+ from typing import Any, Iterable
19
+
20
+ from _common import CliError, checked_output_file, emit_json, positive_float
21
+
22
+ SCHEMA_VERSION = "1.0"
23
+ SUPPORTED_FORMATS = {
24
+ "pdf",
25
+ "svg",
26
+ "eps",
27
+ "ps",
28
+ "png",
29
+ "tiff",
30
+ "jpeg",
31
+ "webp",
32
+ }
33
+ FORMAT_ALIASES = {"jpg": "jpeg", "tif": "tiff"}
34
+ VECTOR_FORMATS = {"pdf", "svg", "eps", "ps"}
35
+ RASTER_FORMATS = {"png", "tiff", "jpeg", "webp"}
36
+ METADATA_FORMATS = {"pdf", "svg", "png", "eps", "ps"}
37
+ MAX_FORMATS = 8
38
+
39
+
40
+ def _normalize_formats(formats: Iterable[str]) -> list[str]:
41
+ normalized: list[str] = []
42
+ for item in formats:
43
+ for value in item.split(","):
44
+ raw_name = value.strip().lower().lstrip(".")
45
+ name = FORMAT_ALIASES.get(raw_name, raw_name)
46
+ if not name:
47
+ continue
48
+ if name not in SUPPORTED_FORMATS:
49
+ raise CliError(
50
+ f"unsupported format {name!r}; "
51
+ f"available: {', '.join(sorted(SUPPORTED_FORMATS))}"
52
+ )
53
+ if name not in normalized:
54
+ normalized.append(name)
55
+ if not normalized:
56
+ raise CliError("at least one output format is required")
57
+ if len(normalized) > MAX_FORMATS:
58
+ raise CliError(f"at most {MAX_FORMATS} output formats are allowed")
59
+ return normalized
60
+
61
+
62
+ def _base_output_path(value: str | os.PathLike[str]) -> Path:
63
+ path = Path(value).expanduser()
64
+ if path.suffix.lower().lstrip(".") in SUPPORTED_FORMATS | set(FORMAT_ALIASES):
65
+ path = path.with_suffix("")
66
+ if not path.name:
67
+ raise CliError("output must include a base filename")
68
+ return path
69
+
70
+
71
+ def _font_rc(font_mode: str) -> dict[str, Any]:
72
+ if font_mode == "current":
73
+ return {}
74
+ if font_mode == "truetype":
75
+ return {
76
+ "pdf.fonttype": 42,
77
+ "ps.fonttype": 42,
78
+ # Editable SVG text; unlike PDF Type 42, this is not embedded.
79
+ "svg.fonttype": "none",
80
+ }
81
+ if font_mode == "paths":
82
+ return {
83
+ "pdf.fonttype": 3,
84
+ "ps.fonttype": 3,
85
+ "svg.fonttype": "path",
86
+ }
87
+ raise CliError("font_mode must be 'truetype', 'paths', or 'current'")
88
+
89
+
90
+ def _package_version(distribution: str) -> str | None:
91
+ try:
92
+ return importlib.metadata.version(distribution)
93
+ except importlib.metadata.PackageNotFoundError:
94
+ return None
95
+
96
+
97
+ def _atomic_savefig(
98
+ fig: Any,
99
+ destination: Path,
100
+ *,
101
+ format_name: str,
102
+ save_kwargs: dict[str, Any],
103
+ overwrite: bool,
104
+ ) -> None:
105
+ destination = checked_output_file(destination, force=overwrite)
106
+ descriptor, temporary_name = tempfile.mkstemp(
107
+ prefix=f".{destination.stem}.",
108
+ suffix=f".{format_name}",
109
+ dir=destination.parent,
110
+ )
111
+ os.close(descriptor)
112
+ temporary = Path(temporary_name)
113
+ try:
114
+ # Matplotlib expects to create the target on some backends.
115
+ temporary.unlink()
116
+ fig.savefig(temporary, format=format_name, **save_kwargs)
117
+ if not temporary.exists() or temporary.stat().st_size == 0:
118
+ raise CliError(f"Matplotlib produced no data for {destination}")
119
+ if destination.exists() and not overwrite:
120
+ raise CliError(f"refusing to overwrite existing output: {destination}")
121
+ os.replace(temporary, destination)
122
+ except CliError:
123
+ raise
124
+ except Exception as exc:
125
+ raise CliError(
126
+ f"failed to export {destination.name} as {format_name}: {exc}"
127
+ ) from exc
128
+ finally:
129
+ try:
130
+ temporary.unlink()
131
+ except FileNotFoundError:
132
+ pass
133
+
134
+
135
+ def _validate_provenance(provenance: dict[str, Any] | None) -> dict[str, Any]:
136
+ if provenance is None:
137
+ return {}
138
+ if not isinstance(provenance, dict):
139
+ raise CliError("provenance must be a dictionary")
140
+ try:
141
+ encoded = json.dumps(provenance, sort_keys=True).encode("utf-8")
142
+ except (TypeError, ValueError) as exc:
143
+ raise CliError(f"provenance must be JSON serializable: {exc}") from exc
144
+ if len(encoded) > 1_000_000:
145
+ raise CliError("provenance metadata is limited to 1,000,000 bytes")
146
+ return provenance
147
+
148
+
149
+ def export_figure(
150
+ fig: Any,
151
+ filename: str | os.PathLike[str],
152
+ *,
153
+ formats: Iterable[str] = ("pdf", "png"),
154
+ dpi: float = 300,
155
+ transparent: bool = False,
156
+ bbox_inches: str | None = None,
157
+ pad_inches: float = 0.1,
158
+ facecolor: str = "white",
159
+ edgecolor: str = "none",
160
+ font_mode: str = "truetype",
161
+ overwrite: bool = False,
162
+ mkdir: bool = False,
163
+ metadata: dict[str, Any] | None = None,
164
+ provenance: dict[str, Any] | None = None,
165
+ write_manifest: bool = False,
166
+ savefig_kwargs: dict[str, Any] | None = None,
167
+ ) -> dict[str, Any]:
168
+ """Export a Matplotlib figure atomically with explicit format settings.
169
+
170
+ ``dpi`` is passed to vector backends too because it controls rasterized
171
+ artists and embedded raster images. ``bbox_inches=None`` preserves the
172
+ figure's physical page dimensions; use ``"tight"`` only when that change is
173
+ intentional.
174
+ """
175
+ if not (float(dpi) > 0 and math.isfinite(float(dpi))):
176
+ raise CliError("dpi must be finite and greater than zero")
177
+ if not (float(pad_inches) >= 0 and math.isfinite(float(pad_inches))):
178
+ raise CliError("pad_inches must be finite and non-negative")
179
+ normalized_formats = _normalize_formats(formats)
180
+ base = _base_output_path(filename)
181
+ parent = base.parent
182
+ if mkdir:
183
+ parent.mkdir(parents=True, exist_ok=True)
184
+ if not parent.exists() or not parent.is_dir():
185
+ raise CliError(f"output parent directory does not exist: {parent}")
186
+ if parent.is_symlink():
187
+ raise CliError(f"output parent must not be a symlink: {parent}")
188
+ for format_name in normalized_formats:
189
+ checked_output_file(
190
+ parent / f"{base.name}.{format_name}",
191
+ force=overwrite,
192
+ )
193
+ if write_manifest:
194
+ checked_output_file(
195
+ parent / f"{base.name}.export.json",
196
+ force=overwrite,
197
+ )
198
+
199
+ try:
200
+ import matplotlib as mpl
201
+ except ImportError as exc:
202
+ raise CliError(
203
+ "Matplotlib is required for figure export; "
204
+ "run with --with 'matplotlib==3.11.1'"
205
+ ) from exc
206
+
207
+ provenance_document = _validate_provenance(provenance)
208
+ user_metadata = dict(metadata or {})
209
+ creator = user_metadata.setdefault(
210
+ "Creator",
211
+ f"scientific-visualization figure_export.py; Matplotlib {mpl.__version__}",
212
+ )
213
+ if not isinstance(creator, str):
214
+ raise CliError("metadata Creator must be a string")
215
+ extra_kwargs = dict(savefig_kwargs or {})
216
+ if "format" in extra_kwargs:
217
+ raise CliError("savefig_kwargs must not override format")
218
+ protected = {
219
+ "dpi",
220
+ "transparent",
221
+ "bbox_inches",
222
+ "pad_inches",
223
+ "facecolor",
224
+ "edgecolor",
225
+ "metadata",
226
+ }
227
+ overlap = protected.intersection(extra_kwargs)
228
+ if overlap:
229
+ raise CliError(
230
+ "savefig_kwargs must not override explicit settings: "
231
+ + ", ".join(sorted(overlap))
232
+ )
233
+
234
+ figure_size = [float(value) for value in fig.get_size_inches()]
235
+ outputs: list[dict[str, Any]] = []
236
+ warnings_list: list[str] = []
237
+ export_rc = _font_rc(font_mode)
238
+ if bbox_inches is None:
239
+ # Prevent a user's global savefig.bbox="tight" from changing page size.
240
+ export_rc["savefig.bbox"] = None
241
+ with mpl.rc_context(export_rc):
242
+ for format_name in normalized_formats:
243
+ destination = parent / f"{base.name}.{format_name}"
244
+ checked_output_file(destination, force=overwrite)
245
+ if format_name in {"eps", "ps"}:
246
+ format_metadata = {"Creator": user_metadata["Creator"]}
247
+ elif format_name in METADATA_FORMATS:
248
+ format_metadata = user_metadata
249
+ else:
250
+ format_metadata = None
251
+ if user_metadata and format_name not in METADATA_FORMATS:
252
+ warnings_list.append(
253
+ f"{format_name}: Matplotlib does not support savefig metadata "
254
+ "for this format; metadata remains in the optional manifest."
255
+ )
256
+ save_kwargs: dict[str, Any] = {
257
+ "dpi": float(dpi),
258
+ "transparent": transparent,
259
+ "bbox_inches": bbox_inches,
260
+ "pad_inches": float(pad_inches),
261
+ "facecolor": "none" if transparent else facecolor,
262
+ "edgecolor": "none" if transparent else edgecolor,
263
+ **extra_kwargs,
264
+ }
265
+ if format_metadata is not None:
266
+ save_kwargs["metadata"] = format_metadata
267
+ if format_name == "tiff":
268
+ save_kwargs["pil_kwargs"] = {"compression": "tiff_lzw"}
269
+
270
+ _atomic_savefig(
271
+ fig,
272
+ destination,
273
+ format_name=format_name,
274
+ save_kwargs=save_kwargs,
275
+ overwrite=overwrite,
276
+ )
277
+ outputs.append(
278
+ {
279
+ "path": str(destination.resolve()),
280
+ "format": format_name,
281
+ "kind": (
282
+ "vector-container"
283
+ if format_name in VECTOR_FORMATS
284
+ else "raster"
285
+ ),
286
+ "size_bytes": destination.stat().st_size,
287
+ }
288
+ )
289
+
290
+ report: dict[str, Any] = {
291
+ "schema_version": SCHEMA_VERSION,
292
+ "outputs": outputs,
293
+ "settings": {
294
+ "formats": normalized_formats,
295
+ "dpi": float(dpi),
296
+ "transparent": transparent,
297
+ "bbox_inches": bbox_inches,
298
+ "pad_inches": float(pad_inches),
299
+ "facecolor": facecolor,
300
+ "font_mode": font_mode,
301
+ "figure_size_inches": figure_size,
302
+ },
303
+ "versions": {
304
+ "matplotlib": mpl.__version__,
305
+ "pillow": _package_version("Pillow"),
306
+ },
307
+ "provenance": provenance_document,
308
+ "warnings": sorted(set(warnings_list)),
309
+ "notice": (
310
+ "Export completed with explicit settings. This report does not "
311
+ "establish visual, accessibility, scientific-integrity, or "
312
+ "journal-submission compliance."
313
+ ),
314
+ }
315
+
316
+ if write_manifest:
317
+ manifest_path = parent / f"{base.name}.export.json"
318
+ emit_json(report, output=manifest_path, force=overwrite)
319
+ report["manifest"] = str(manifest_path.resolve())
320
+ return report
321
+
322
+
323
+ def save_publication_figure(
324
+ fig: Any,
325
+ filename: str | os.PathLike[str],
326
+ formats: Iterable[str] = ("pdf", "png"),
327
+ dpi: float = 300,
328
+ transparent: bool = False,
329
+ bbox_inches: str | None = None,
330
+ pad_inches: float = 0.1,
331
+ facecolor: str = "white",
332
+ *,
333
+ overwrite: bool = False,
334
+ provenance: dict[str, Any] | None = None,
335
+ write_manifest: bool = False,
336
+ **kwargs: Any,
337
+ ) -> list[Path]:
338
+ """Compatibility wrapper returning saved paths.
339
+
340
+ Unlike the previous implementation, this function refuses implicit
341
+ overwrite, does not silently swallow export errors, does not cap vector
342
+ DPI, and preserves figure dimensions unless ``bbox_inches="tight"`` is
343
+ requested.
344
+ """
345
+ report = export_figure(
346
+ fig,
347
+ filename,
348
+ formats=formats,
349
+ dpi=dpi,
350
+ transparent=transparent,
351
+ bbox_inches=bbox_inches,
352
+ pad_inches=pad_inches,
353
+ facecolor=facecolor,
354
+ overwrite=overwrite,
355
+ provenance=provenance,
356
+ write_manifest=write_manifest,
357
+ savefig_kwargs=kwargs,
358
+ )
359
+ return [Path(item["path"]) for item in report["outputs"]]
360
+
361
+
362
+ def _load_profiles() -> dict[str, Any]:
363
+ profile_path = Path(__file__).resolve().parents[1] / "assets" / "publisher_profiles.json"
364
+ try:
365
+ document = json.loads(profile_path.read_text(encoding="utf-8"))
366
+ except (OSError, json.JSONDecodeError) as exc:
367
+ raise CliError(f"cannot load publisher profiles: {exc}") from exc
368
+ if not isinstance(document.get("profiles"), dict):
369
+ raise CliError("publisher profile asset is malformed")
370
+ return document
371
+
372
+
373
+ def check_figure_size(
374
+ fig: Any,
375
+ journal: str = "nature",
376
+ *,
377
+ tolerance_mm: float = 1.0,
378
+ ) -> dict[str, Any]:
379
+ """Compare figure dimensions with a dated profile without claiming compliance."""
380
+ if not (tolerance_mm >= 0 and math.isfinite(tolerance_mm)):
381
+ raise CliError("tolerance_mm must be finite and non-negative")
382
+ document = _load_profiles()
383
+ try:
384
+ profile = document["profiles"][journal]
385
+ except KeyError as exc:
386
+ raise CliError(
387
+ f"unknown profile {journal!r}; "
388
+ f"available: {', '.join(sorted(document['profiles']))}"
389
+ ) from exc
390
+ width_inches, height_inches = (float(value) for value in fig.get_size_inches())
391
+ width_mm = width_inches * 25.4
392
+ height_mm = height_inches * 25.4
393
+ candidates = {
394
+ name: float(value)
395
+ for name, value in (profile.get("widths_mm") or {}).items()
396
+ }
397
+ nearest_name = None
398
+ nearest_width = None
399
+ difference = None
400
+ if candidates:
401
+ nearest_name, nearest_width = min(
402
+ candidates.items(), key=lambda item: abs(width_mm - item[1])
403
+ )
404
+ difference = abs(width_mm - nearest_width)
405
+ max_height = profile.get("max_height_mm")
406
+ return {
407
+ "schema_version": SCHEMA_VERSION,
408
+ "profile": journal,
409
+ "profile_label": profile["label"],
410
+ "profile_scope": profile["scope"],
411
+ "profile_accessed": document["accessed"],
412
+ "figure": {
413
+ "width_inches": width_inches,
414
+ "height_inches": height_inches,
415
+ "width_mm": width_mm,
416
+ "height_mm": height_mm,
417
+ },
418
+ "nearest_profile_width": {
419
+ "name": nearest_name,
420
+ "width_mm": nearest_width,
421
+ "difference_mm": difference,
422
+ "matches_tolerance": (
423
+ difference is not None and difference <= tolerance_mm
424
+ ),
425
+ },
426
+ "height_screen": {
427
+ "maximum_mm": max_height,
428
+ "within_snapshot": (
429
+ None if max_height is None else height_mm <= float(max_height)
430
+ ),
431
+ },
432
+ "notice": (
433
+ "A dimensional match to this dated snapshot is not a journal "
434
+ "compliance determination."
435
+ ),
436
+ }
437
+
438
+
439
+ def save_for_journal(
440
+ fig: Any,
441
+ filename: str | os.PathLike[str],
442
+ journal: str,
443
+ figure_type: str = "combination",
444
+ *,
445
+ confirm_profile: bool = False,
446
+ format_name: str | None = None,
447
+ dpi: float | None = None,
448
+ overwrite: bool = False,
449
+ ) -> list[Path]:
450
+ """Use a dated profile only after explicit caller confirmation.
451
+
452
+ This compatibility helper intentionally requires ``confirm_profile=True``.
453
+ Prefer ``export_plan.py`` and ``export_figure`` for an auditable workflow.
454
+ """
455
+ if not confirm_profile:
456
+ raise CliError(
457
+ "publisher rules are date-sensitive; run export_plan.py, verify the "
458
+ "target journal, then pass confirm_profile=True if this snapshot is "
459
+ "appropriate"
460
+ )
461
+ document = _load_profiles()
462
+ try:
463
+ profile = document["profiles"][journal]
464
+ except KeyError as exc:
465
+ raise CliError(f"unknown publisher profile: {journal!r}") from exc
466
+ profile_formats = profile.get("formats") or {}
467
+ allowed = profile_formats.get(figure_type) or []
468
+ selected = (
469
+ _normalize_formats([format_name])[0]
470
+ if format_name is not None
471
+ else next((name for name in allowed if name in SUPPORTED_FORMATS), None)
472
+ )
473
+ if selected is None:
474
+ raise CliError(
475
+ f"profile {journal!r} has no directly exportable {figure_type!r} "
476
+ "format; choose settings manually"
477
+ )
478
+ if selected not in allowed:
479
+ raise CliError(
480
+ f"format {selected!r} is not recorded for {journal} "
481
+ f"{figure_type}; recorded formats: {', '.join(allowed)}"
482
+ )
483
+ if dpi is None:
484
+ raise CliError(
485
+ "provide an explicit dpi after reviewing embedded raster content; "
486
+ "the compatibility helper does not choose one automatically"
487
+ )
488
+ dpi_profile = (profile.get("raster_dpi") or {}).get(figure_type) or {}
489
+ if dpi_profile.get("min") is not None and dpi < float(dpi_profile["min"]):
490
+ raise CliError(f"dpi is below the profile snapshot minimum: {dpi_profile}")
491
+ if (
492
+ dpi_profile.get("min_exclusive") is not None
493
+ and dpi <= float(dpi_profile["min_exclusive"])
494
+ ):
495
+ raise CliError(
496
+ f"dpi does not exceed the profile snapshot threshold: {dpi_profile}"
497
+ )
498
+ if dpi_profile.get("max") is not None and dpi > float(dpi_profile["max"]):
499
+ raise CliError(f"dpi is above the profile snapshot maximum: {dpi_profile}")
500
+ return save_publication_figure(
501
+ fig,
502
+ filename,
503
+ formats=[selected],
504
+ dpi=dpi,
505
+ overwrite=overwrite,
506
+ provenance={
507
+ "publisher_profile": journal,
508
+ "profile_accessed": document["accessed"],
509
+ "profile_scope": profile["scope"],
510
+ "caller_confirmed_snapshot": True,
511
+ },
512
+ write_manifest=True,
513
+ )
514
+
515
+
516
+ def verify_font_embedding(pdf_path: str | os.PathLike[str]) -> dict[str, Any]:
517
+ """Return a conservative PDF font-resource report using the metadata tool."""
518
+ try:
519
+ from image_metadata import inspect_file
520
+ except ImportError as exc:
521
+ raise CliError(f"cannot import image_metadata.py: {exc}") from exc
522
+ report = inspect_file(pdf_path)
523
+ if report["metadata"]["format"] != "PDF":
524
+ raise CliError("font embedding inspection requires a PDF input")
525
+ return {
526
+ "path": report["input"]["path"],
527
+ "font_resources": report["metadata"].get("font_resources"),
528
+ "notice": (
529
+ "Inspection covers declared first-page font resources only; "
530
+ "publisher preflight may apply additional checks."
531
+ ),
532
+ }
533
+
534
+
535
+ def _demo_figure() -> Any:
536
+ try:
537
+ import matplotlib.pyplot as plt
538
+ except ImportError as exc:
539
+ raise CliError(
540
+ "Matplotlib is required for --demo; "
541
+ "run with --with 'matplotlib==3.11.1'"
542
+ ) from exc
543
+ x_values = [index / 20.0 for index in range(121)]
544
+ first = [math.sin(value) for value in x_values]
545
+ second = [math.cos(value) for value in x_values]
546
+ fig, ax = plt.subplots(figsize=(3.5, 2.5), layout="constrained")
547
+ ax.plot(x_values, first, label="sin(x)", marker="o", markevery=20)
548
+ ax.plot(
549
+ x_values,
550
+ second,
551
+ label="cos(x)",
552
+ linestyle="--",
553
+ marker="s",
554
+ markevery=20,
555
+ )
556
+ ax.axhline(0, color="0.35", linewidth=0.7)
557
+ ax.set(xlabel="Angle (radians)", ylabel="Amplitude (unitless)")
558
+ ax.legend()
559
+ return fig
560
+
561
+
562
+ def build_parser() -> argparse.ArgumentParser:
563
+ parser = argparse.ArgumentParser(
564
+ description=(
565
+ "Render a deterministic Matplotlib export smoke-test. Programmatic "
566
+ "helpers in this module support explicit, safe figure export."
567
+ )
568
+ )
569
+ parser.add_argument(
570
+ "--demo",
571
+ metavar="BASE_PATH",
572
+ help="render a deterministic demo to this base path",
573
+ )
574
+ parser.add_argument(
575
+ "--formats",
576
+ default="pdf,png",
577
+ help="comma-separated formats (default: pdf,png)",
578
+ )
579
+ parser.add_argument("--dpi", type=positive_float, default=300.0)
580
+ parser.add_argument(
581
+ "--font-mode",
582
+ choices=("truetype", "paths", "current"),
583
+ default="truetype",
584
+ )
585
+ parser.add_argument("--transparent", action="store_true")
586
+ parser.add_argument(
587
+ "--tight",
588
+ action="store_true",
589
+ help="use bbox_inches='tight' (changes physical page dimensions)",
590
+ )
591
+ parser.add_argument("--manifest", action="store_true")
592
+ parser.add_argument("--force", action="store_true")
593
+ parser.add_argument(
594
+ "--style",
595
+ choices=("default", "nature", "science", "cell", "minimal", "presentation"),
596
+ default="default",
597
+ )
598
+ parser.add_argument("--palette", default="okabe_ito_on_white")
599
+ return parser
600
+
601
+
602
+ def main(argv: list[str] | None = None) -> int:
603
+ parser = build_parser()
604
+ try:
605
+ args = parser.parse_args(argv)
606
+ if not args.demo:
607
+ parser.error("--demo BASE_PATH is required")
608
+ try:
609
+ from style_presets import style_context
610
+ except ImportError as exc:
611
+ raise CliError(f"cannot import style_presets.py: {exc}") from exc
612
+ with style_context(args.style, palette_name=args.palette):
613
+ fig = _demo_figure()
614
+ try:
615
+ report = export_figure(
616
+ fig,
617
+ args.demo,
618
+ formats=args.formats.split(","),
619
+ dpi=args.dpi,
620
+ transparent=args.transparent,
621
+ bbox_inches="tight" if args.tight else None,
622
+ font_mode=args.font_mode,
623
+ overwrite=args.force,
624
+ provenance={
625
+ "purpose": "deterministic export smoke test",
626
+ "raw_data": "analytical sin/cos values generated in code",
627
+ "transformations": ["none"],
628
+ },
629
+ write_manifest=args.manifest,
630
+ )
631
+ finally:
632
+ import matplotlib.pyplot as plt
633
+
634
+ plt.close(fig)
635
+ emit_json(report)
636
+ return 0
637
+ except CliError as exc:
638
+ parser.exit(2, f"error: {exc}\n")
639
+
640
+
641
+ if __name__ == "__main__":
642
+ sys.exit(main())