arrayprobe 0.1.0__py3-none-any.whl

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 (189) hide show
  1. arrayprobe/__init__.py +219 -0
  2. arrayprobe/__main__.py +19 -0
  3. arrayprobe/_v314_lazy.py +48 -0
  4. arrayprobe/ai_ready.py +212 -0
  5. arrayprobe/attributed_export.py +1333 -0
  6. arrayprobe/authordefaults.py +267 -0
  7. arrayprobe/cli.py +3510 -0
  8. arrayprobe/combine.py +12 -0
  9. arrayprobe/compare.py +950 -0
  10. arrayprobe/config.py +1239 -0
  11. arrayprobe/constants.py +12 -0
  12. arrayprobe/count_closure.py +204 -0
  13. arrayprobe/diagnostic_views.py +769 -0
  14. arrayprobe/diode_report.py +265 -0
  15. arrayprobe/driver/__init__.py +5 -0
  16. arrayprobe/driver/_load_record.py +331 -0
  17. arrayprobe/driver/preflight_inputs.py +250 -0
  18. arrayprobe/driver/reprocess.py +553 -0
  19. arrayprobe/driver/run_flight.py +8166 -0
  20. arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
  21. arrayprobe/dropsize.py +519 -0
  22. arrayprobe/friendly.py +206 -0
  23. arrayprobe/geometry/__init__.py +77 -0
  24. arrayprobe/geometry/min_rectangle.py +92 -0
  25. arrayprobe/intarr.py +12 -0
  26. arrayprobe/intarr_analysis.py +16 -0
  27. arrayprobe/intarr_plots.py +12 -0
  28. arrayprobe/inventory.py +129 -0
  29. arrayprobe/jit_kernels.py +344 -0
  30. arrayprobe/lwc.py +44 -0
  31. arrayprobe/masks.py +349 -0
  32. arrayprobe/matio.py +410 -0
  33. arrayprobe/matlab_compat.py +13 -0
  34. arrayprobe/ncio.py +26 -0
  35. arrayprobe/particle.py +55 -0
  36. arrayprobe/particle_perimeter.py +12 -0
  37. arrayprobe/products.py +78 -0
  38. arrayprobe/profiles.py +179 -0
  39. arrayprobe/provenance.py +21 -0
  40. arrayprobe/py.typed +11 -0
  41. arrayprobe/readers/__init__.py +9 -0
  42. arrayprobe/readers/dmt.py +603 -0
  43. arrayprobe/readers/mask_csv.py +12 -0
  44. arrayprobe/readers/pms.py +12 -0
  45. arrayprobe/readers/sea.py +433 -0
  46. arrayprobe/readers/tasinfo.py +12 -0
  47. arrayprobe/regimes.py +507 -0
  48. arrayprobe/render.py +728 -0
  49. arrayprobe/reproduce_report.py +149 -0
  50. arrayprobe/review_agreement.py +135 -0
  51. arrayprobe/review_sampling.py +327 -0
  52. arrayprobe/run_page.py +624 -0
  53. arrayprobe/sample_area.py +12 -0
  54. arrayprobe/selector.py +206 -0
  55. arrayprobe/sizing.py +151 -0
  56. arrayprobe/time_convert.py +12 -0
  57. arrayprobe/timing_closure.py +141 -0
  58. arrayprobe/tools/__init__.py +27 -0
  59. arrayprobe/tools/make_demo_flight.py +1089 -0
  60. arrayprobe/tools/make_tas_file.py +760 -0
  61. arrayprobe/tools/probe_comparison.py +569 -0
  62. arrayprobe/tools/synthetic_truth.py +698 -0
  63. arrayprobe/tools/tas_sources.py +705 -0
  64. arrayprobe/triage_context.py +488 -0
  65. arrayprobe/triage_server.py +5215 -0
  66. arrayprobe/tune/__init__.py +15 -0
  67. arrayprobe/tune/diodes.py +400 -0
  68. arrayprobe/tune/distributions.py +300 -0
  69. arrayprobe/tune/sample.py +243 -0
  70. arrayprobe/tune/score.py +230 -0
  71. arrayprobe/tune/settings.py +354 -0
  72. arrayprobe/validate_by_condition.py +208 -0
  73. arrayprobe/validation_report.py +166 -0
  74. arrayprobe-0.1.0.dist-info/METADATA +260 -0
  75. arrayprobe-0.1.0.dist-info/RECORD +189 -0
  76. arrayprobe-0.1.0.dist-info/WHEEL +5 -0
  77. arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
  78. arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
  79. arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
  80. arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
  81. arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
  82. arrayprobe_soda2/__init__.py +131 -0
  83. arrayprobe_soda2/angles.py +143 -0
  84. arrayprobe_soda2/aspect_ratio.py +541 -0
  85. arrayprobe_soda2/backfill.py +100 -0
  86. arrayprobe_soda2/binary_dof.py +181 -0
  87. arrayprobe_soda2/buildindex.py +113 -0
  88. arrayprobe_soda2/decompress_dmt.py +285 -0
  89. arrayprobe_soda2/enhancement_hooks.py +275 -0
  90. arrayprobe_soda2/export_ascii.py +732 -0
  91. arrayprobe_soda2/export_ncdf.py +683 -0
  92. arrayprobe_soda2/export_ncdf_raf.py +396 -0
  93. arrayprobe_soda2/fillholes.py +161 -0
  94. arrayprobe_soda2/find_radius.py +105 -0
  95. arrayprobe_soda2/findsize.py +407 -0
  96. arrayprobe_soda2/fit_poisson.py +170 -0
  97. arrayprobe_soda2/fix2dimage.py +63 -0
  98. arrayprobe_soda2/fixraking.py +162 -0
  99. arrayprobe_soda2/fixstuckbits.py +146 -0
  100. arrayprobe_soda2/hvps4_read_frame.py +121 -0
  101. arrayprobe_soda2/jit_kernels.py +152 -0
  102. arrayprobe_soda2/label_blobs.py +177 -0
  103. arrayprobe_soda2/min_circle_fast.py +320 -0
  104. arrayprobe_soda2/particlesort.py +703 -0
  105. arrayprobe_soda2/pbp_writer.py +558 -0
  106. arrayprobe_soda2/poisson_spot_correct.py +183 -0
  107. arrayprobe_soda2/princomp.py +107 -0
  108. arrayprobe_soda2/probespecs.py +361 -0
  109. arrayprobe_soda2/process_2d.py +1364 -0
  110. arrayprobe_soda2/process_2d_parallel.py +626 -0
  111. arrayprobe_soda2/process_hk.py +512 -0
  112. arrayprobe_soda2/processbuffer_2dc.py +155 -0
  113. arrayprobe_soda2/processbuffer_cip.py +213 -0
  114. arrayprobe_soda2/processbuffer_f2dc.py +139 -0
  115. arrayprobe_soda2/processbuffer_spec.py +441 -0
  116. arrayprobe_soda2/processbuffer_tail.py +350 -0
  117. arrayprobe_soda2/pth_readers.py +245 -0
  118. arrayprobe_soda2/py.typed +11 -0
  119. arrayprobe_soda2/read2dbuffer.py +371 -0
  120. arrayprobe_soda2/reject.py +246 -0
  121. arrayprobe_soda2/reprocess_pbp.py +156 -0
  122. arrayprobe_soda2/sample_area.py +264 -0
  123. arrayprobe_soda2/save_writer.py +480 -0
  124. arrayprobe_soda2/sea.py +324 -0
  125. arrayprobe_soda2/spec_absolutepointers.py +109 -0
  126. arrayprobe_soda2/spec_decompress.py +203 -0
  127. arrayprobe_soda2/spec_index.py +476 -0
  128. arrayprobe_soda2/spec_read_frame.py +286 -0
  129. arrayprobe_soda2/spec_read_hk.py +301 -0
  130. arrayprobe_soda2/spec_readint.py +127 -0
  131. arrayprobe_soda2/timeconv.py +77 -0
  132. arrayprobe_soda2/update_op.py +101 -0
  133. arrayprobe_uiops/__init__.py +45 -0
  134. arrayprobe_uiops/combine.py +192 -0
  135. arrayprobe_uiops/combine_fork.py +359 -0
  136. arrayprobe_uiops/constants.py +830 -0
  137. arrayprobe_uiops/decode_naming.py +113 -0
  138. arrayprobe_uiops/diode_mask.py +250 -0
  139. arrayprobe_uiops/engine_absence.py +41 -0
  140. arrayprobe_uiops/export_oap.py +325 -0
  141. arrayprobe_uiops/geometry_core.py +366 -0
  142. arrayprobe_uiops/habit.py +749 -0
  143. arrayprobe_uiops/habit_core.py +248 -0
  144. arrayprobe_uiops/hollow_size_rule.py +376 -0
  145. arrayprobe_uiops/imgproc.py +2081 -0
  146. arrayprobe_uiops/imgproc_core.py +275 -0
  147. arrayprobe_uiops/intarr.py +167 -0
  148. arrayprobe_uiops/intarr_analysis.py +569 -0
  149. arrayprobe_uiops/intarr_plots.py +119 -0
  150. arrayprobe_uiops/jit_kernels.py +430 -0
  151. arrayprobe_uiops/lwc.py +70 -0
  152. arrayprobe_uiops/matlab_compat.py +860 -0
  153. arrayprobe_uiops/measure.py +346 -0
  154. arrayprobe_uiops/min_circle.py +204 -0
  155. arrayprobe_uiops/min_ellipse.py +161 -0
  156. arrayprobe_uiops/min_rectangle.py +200 -0
  157. arrayprobe_uiops/ncar_2dc_timing.py +100 -0
  158. arrayprobe_uiops/ncio.py +810 -0
  159. arrayprobe_uiops/oap_read.py +228 -0
  160. arrayprobe_uiops/particle.py +51 -0
  161. arrayprobe_uiops/particle_perimeter.py +94 -0
  162. arrayprobe_uiops/particle_physics.py +199 -0
  163. arrayprobe_uiops/pecan_params.py +134 -0
  164. arrayprobe_uiops/probe_cases.py +298 -0
  165. arrayprobe_uiops/product_sanity.py +337 -0
  166. arrayprobe_uiops/profile.py +71 -0
  167. arrayprobe_uiops/profiles.py +756 -0
  168. arrayprobe_uiops/provenance.py +804 -0
  169. arrayprobe_uiops/py.typed +11 -0
  170. arrayprobe_uiops/qc.py +169 -0
  171. arrayprobe_uiops/readers/__init__.py +8 -0
  172. arrayprobe_uiops/readers/mask_csv.py +74 -0
  173. arrayprobe_uiops/readers/pms.py +239 -0
  174. arrayprobe_uiops/readers/tasinfo.py +57 -0
  175. arrayprobe_uiops/rect_ellipse.py +129 -0
  176. arrayprobe_uiops/register_image_assisted.py +25 -0
  177. arrayprobe_uiops/reject.py +501 -0
  178. arrayprobe_uiops/reject_core.py +220 -0
  179. arrayprobe_uiops/sample_area.py +93 -0
  180. arrayprobe_uiops/sizedist.py +1923 -0
  181. arrayprobe_uiops/sizedist_core.py +814 -0
  182. arrayprobe_uiops/sizedist_tables.py +642 -0
  183. arrayprobe_uiops/spec.py +1094 -0
  184. arrayprobe_uiops/spec_core.py +703 -0
  185. arrayprobe_uiops/stray_pixel.py +103 -0
  186. arrayprobe_uiops/tas.py +191 -0
  187. arrayprobe_uiops/time_convert.py +41 -0
  188. uiops/__init__.py +402 -0
  189. uiops/py.typed +11 -0
@@ -0,0 +1,553 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """``arrayprobe reprocess <product> --preset NAME`` -- re-run a product's stage from its own stamp.
3
+
4
+ SODA-2's "Load Settings" (reprocessing from a saved options structure) is the model;
5
+ this project's ``.call`` sidecar (``run_flight.py``'s
6
+ ``write_stamp``/``read_stamp``) already records how an S3 or S4 output was made. This closes the
7
+ loop: read the product's stamp, re-run the one stage that wrote it under exactly that
8
+ configuration, from the input the driver's own naming convention puts beside it, and report
9
+ whether the fresh output is identical to the product.
10
+
11
+ **Exactly as recorded, or refused.** The stamp is parsed only to *propose* a configuration
12
+ (engine, profile, the twelfth ``sizeDist`` argument, the diode mask, the aircraft file's name).
13
+ The proposal is then accepted only if ``run_flight``'s own label function, run under it, writes
14
+ the recorded stamp **character for character** -- the same equality test ``output_state`` makes
15
+ on every resume. So a profile whose thresholds moved since the stamp was written, a v3.5 call
16
+ switch that changed, an engine the stamp does not name, or a parse this module got wrong all end
17
+ in a refusal naming both strings, never in a run under a neighbouring configuration. The stage's
18
+ *input* is held to the same rule: an S4 reprocess needs a proc file whose own stamp matches
19
+ (``stage4``'s check, unchanged, with no ``accept_unstamped`` override); an S3 reprocess needs a
20
+ decoded image whose stamp is the one ``image_call_label`` would write. There is deliberately no
21
+ ``--accept-unstamped`` here: an input of unknown configuration cannot be re-run "as recorded".
22
+
23
+ **What the stamp does not record, and what is asked for instead** (measured from
24
+ ``config_label``/``sd_call_label``, 2026-09-14, not inferred):
25
+
26
+ * **the campaign preset** (probe, channel, project, ``d_choice``, ``sa_method``, pressure,
27
+ temperature). No stamp carries it, so ``--preset`` is **required** -- never defaulted, the same
28
+ rule ``arrayprobe run`` applies to ``[run].preset``. A wrong preset either fails the naming check
29
+ (a channel that does not match the product's name) or shows up in the diff (``project`` is a
30
+ written attribute; pressure and temperature reach the sd variables).
31
+ * **the aircraft TAS file's path** -- only its basename is stamped. S4 never reads the file, so the
32
+ basename is enough to regenerate the label; S3 does read it, so ``--tas-file`` is required there
33
+ and its basename must equal the stamped one.
34
+ * **a TAS source chain's sources** (``tas_chain=`` / ``tas_series=`` name the tier and the
35
+ registered source, never a path), so the chain is not resolved again. What S3 and S4 consume is
36
+ the series the chain wrote, ``<stem>.tas_<tier>.cdf`` beside the product, and that file is the
37
+ input a chain product's reprocess reads -- for S3 in place of ``--tas-file``. Its own record of
38
+ the chain and policy that wrote it must agree with the stamp; a missing file is refused by name.
39
+ * **the raw file** -- so S2 (decode) cannot be re-run from a stamp, and is refused rather than
40
+ guessed at. Nor is S4c (combine): its stamp records the engine and the borrowed-combine opt-in
41
+ but not the flight date or summary time the call needs.
42
+
43
+ **Which products.** ``proc.*.nc`` (S3, both engines; ``.diodecorrected.nc`` under v3.1.4 through
44
+ ``stage3_corrected``) and ``sd.*.nc`` (S4, both engines).
45
+
46
+ **Identical means** every dimension, variable (name, order, type, dimensions, attributes, stored
47
+ bytes with masking and scaling off) and global attribute agrees, and the fresh ``.call`` text
48
+ equals the product's, with two exceptions, both the ones the existing byte-comparison tests make:
49
+ ``Creation Time`` / ``Creation_Time`` is skipped (non-deterministic), and the
50
+ path-valued ``Image Source`` / ``Data Source`` / ``Data_Source`` are compared by **basename**
51
+ rather than skipped, because the fresh run necessarily reads from a different directory string
52
+ than the original may have, while a run that read the *wrong* file must still fail
53
+ (basenames are enough to tell files apart).
54
+
55
+ The driver is loaded as a **private copy per call**, never the shared ``sys.modules["run_flight"]``
56
+ that ``arrayprobe run`` and the tests bind to, so setting its globals from a stamp cannot leak into
57
+ anything else in the process, and every reprocess starts from the driver's module defaults rather
58
+ than whatever the last run left behind (``scripts/make_demo_reference.py``'s ``_load_tool_module``
59
+ records the incident that made this the rule).
60
+ """
61
+ from __future__ import annotations
62
+
63
+ import argparse
64
+ import contextlib
65
+ import importlib.util
66
+ import itertools
67
+ import os
68
+ import re
69
+ import shutil
70
+ import sys
71
+ import tempfile
72
+ from dataclasses import dataclass, field
73
+ from pathlib import Path
74
+
75
+ import numpy as np
76
+
77
+ _TOOLS = Path(__file__).resolve().parent
78
+
79
+ #: Skipped outright: written from the clock, so it differs on every run.
80
+ VOLATILE_ATTRS = frozenset({"Creation Time", "Creation_Time"})
81
+
82
+ #: Compared by basename: a path the stage wrote from its own input argument.
83
+ PATH_ATTRS = frozenset({"Image Source", "Data Source", "Data_Source"})
84
+
85
+ #: A stamp's optional leading engine key. v3.5 stamps have carried it since 2026-09-13; v3.1.4
86
+ #: stamps since 2026-09-15. A stamp without it is v3.1.4, as
87
+ #: ``run_flight._stamps_equivalent`` reads it.
88
+ _ENGINE_KEY = re.compile(r"engine=(\S+) ")
89
+
90
+
91
+ class ReprocessRefused(ValueError):
92
+ """The product cannot be re-run exactly as recorded; the message says why."""
93
+
94
+
95
+ # Kept as a name for the pre-2026-09-14 callers and tests.
96
+ StampFormatError = ReprocessRefused
97
+
98
+
99
+ @dataclass
100
+ class ReprocessResult:
101
+ """What a reprocess found. ``differences`` is empty exactly when the fresh output is identical
102
+ to the product under the rule in the module docstring."""
103
+
104
+ product: Path
105
+ stage: str
106
+ engine: str
107
+ stamp: str
108
+ differences: list[str] = field(default_factory=list)
109
+
110
+ @property
111
+ def identical(self) -> bool:
112
+ """True when the fresh output matched the product with no recorded difference."""
113
+ return not self.differences
114
+
115
+
116
+ # --------------------------------------------------------------------------- the driver
117
+
118
+ _copies = itertools.count()
119
+
120
+
121
+ @contextlib.contextmanager
122
+ def _private_driver(log=None):
123
+ """A fresh, private copy of ``scripts/run_flight.py`` at its module defaults.
124
+
125
+ Registered in ``sys.modules`` under a private name only while it runs (a dataclass resolves its
126
+ module there) and removed afterwards."""
127
+ name = f"_reprocess_run_flight_{next(_copies)}"
128
+ origin = importlib.util.find_spec("arrayprobe.driver.run_flight").origin
129
+ spec = importlib.util.spec_from_file_location(name, origin)
130
+ assert spec is not None and spec.loader is not None
131
+ module = importlib.util.module_from_spec(spec)
132
+ sys.modules[name] = module
133
+ try:
134
+ spec.loader.exec_module(module)
135
+ module.log = log if log is not None else (lambda *a, **kw: None)
136
+ yield module
137
+ finally:
138
+ sys.modules.pop(name, None)
139
+
140
+
141
+ # --------------------------------------------------------------------------- the stamp
142
+
143
+ def parse_stamp(text: str, stage: str) -> dict:
144
+ """Propose the configuration a ``.call`` stamp names. A *proposal* only: :func:`reprocess`
145
+ accepts it solely if ``run_flight`` regenerates ``text`` from it exactly.
146
+
147
+ ``stage`` is ``"S3"`` (a proc stamp, ``proc_call_label``) or ``"S4"`` (an sd stamp,
148
+ ``sd_call_label``). Raises :class:`ReprocessRefused` naming the field it could not find."""
149
+ from arrayprobe_uiops import provenance
150
+
151
+ text = text.strip()
152
+ key = _ENGINE_KEY.match(text)
153
+ engine = key[1] if key else "3.1.4"
154
+ # Each key's value runs to the start of the next key (provenance's reader, shared with every
155
+ # other stamp consumer), so a value never swallows the keys written after it.
156
+ parsed = provenance.parse(text)
157
+ fields = dict(parsed.fields) if parsed.format == "driver" else {}
158
+ # Neither engine= nor port_validation= (R4) is part of the stage's own key order:
159
+ # an sd stamp now reads ``engine=3.1.4 port_validation=on iat_file=...``.
160
+ keys = [k for k in fields if k not in ("engine", "port_validation")]
161
+ iat_file = None
162
+ if stage == "S4":
163
+ if not keys or keys[0] != "iat_file" or keys[1:2] != ["profile"]:
164
+ raise ReprocessRefused(f"not an sd stamp (no leading iat_file=...): {text!r}")
165
+ iat_file = None if fields["iat_file"] == "<none>" else fields["iat_file"]
166
+ elif keys[:1] == ["iat_file"]:
167
+ raise ReprocessRefused(f"an sd stamp where a proc stamp was expected: {text!r}")
168
+ profile, shadow = fields.get("profile"), fields.get("shadow_diode")
169
+ if not profile or not shadow:
170
+ raise ReprocessRefused(f"stamp names no profile= / shadow_diode=: {text!r}")
171
+ # A TAS chain names itself as tas_chain= (a profile that reads an aircraft file) or, in an sd
172
+ # stamp, as tas_series=; tas_series=probe_hk:... is a different mechanism (the CIP borrowing
173
+ # the 2D-S's airspeed), not a chain.
174
+ chain = fields.get("tas_chain")
175
+ series = fields.get("tas_series")
176
+ if chain is None and series is not None and not series.startswith("probe_hk:"):
177
+ chain = series
178
+ policy = fields.get("tas_policy", fields.get("tas_series_policy"))
179
+ return {
180
+ "engine": engine,
181
+ "port_validation": fields.get("port_validation") == "on",
182
+ "iat_file": iat_file,
183
+ "profile_name": profile,
184
+ "shadow_diode": None if shadow == "none" else [int(x) for x in shadow.split(",")],
185
+ "tas_file_name": fields.get("tas_file"),
186
+ "tas_chain": chain,
187
+ "tas_policy": policy[1:-1] if policy and policy[0] == "(" and policy[-1] == ")" else policy,
188
+ "tas_grid": fields.get("tas_grid"),
189
+ # The stray-pixel rule: a v3.5 stamp names stray_pixel=on:<params> or stray_pixel=off; a
190
+ # v3.5 stamp written before the correction carries no key and was made uncorrected (None
191
+ # here, regenerated as off). Only the on/off switch is restored; the parameters are the
192
+ # driver's own, so a stamp recording other parameters fails the regeneration check.
193
+ "stray_pixel": fields.get("stray_pixel"),
194
+ # The NCAR 2DC timing conversion, the same way: a v3.5 probetype-0 stamp names
195
+ # ncar_2dc_timing=on:fix2dimage or ncar_2dc_timing=off; no key reads as off.
196
+ "ncar_2dc_timing": fields.get("ncar_2dc_timing"),
197
+ }
198
+
199
+
200
+ def parse_sd_stamp(text: str) -> dict:
201
+ """:func:`parse_stamp` for an S4 stamp (the pre-2026-09-14 name, kept)."""
202
+ return parse_stamp(text, "S4")
203
+
204
+
205
+ def stage_of(product: Path) -> str:
206
+ """``"S3"`` for ``proc.*``, ``"S4"`` for ``sd.*``; anything else is refused by name."""
207
+ if product.name.startswith("proc."):
208
+ return "S3"
209
+ if product.name.startswith("sd."):
210
+ return "S4"
211
+ raise ReprocessRefused(
212
+ f"{product.name}: only a proc.* (S3) or sd.* (S4) product can be reprocessed from its "
213
+ "stamp -- an S2 stamp does not record the raw file, and an S4c stamp does not record the "
214
+ "flight date or summary time its call needs")
215
+
216
+
217
+ def proc_path_for(sd_path: Path) -> Path:
218
+ """The proc file an sd file's own name says sits beside it (``run_flight.sd_path``'s
219
+ convention, read in the other direction)."""
220
+ if not sd_path.name.startswith("sd."):
221
+ raise ReprocessRefused(f"{sd_path.name} does not start with 'sd.'")
222
+ return sd_path.with_name("proc." + sd_path.name.removeprefix("sd."))
223
+
224
+
225
+ # --------------------------------------------------------------------------- the diff
226
+
227
+ def _attr_equal(a, b) -> bool:
228
+ if isinstance(a, str) or isinstance(b, str):
229
+ return isinstance(a, str) and isinstance(b, str) and a == b
230
+ aa, bb = np.asarray(a), np.asarray(b)
231
+ return aa.dtype == bb.dtype and aa.shape == bb.shape and aa.tobytes() == bb.tobytes()
232
+
233
+
234
+ def _basename(value) -> str:
235
+ return os.path.basename(str(value).replace("\\", "/"))
236
+
237
+
238
+ def _diff_attrs(where: str, a, b, out: list[str]) -> None:
239
+ names_a, names_b = list(a.ncattrs()), list(b.ncattrs())
240
+ if names_a != names_b:
241
+ out.append(f"{where}: attribute names/order differ: {names_a} vs {names_b}")
242
+ return
243
+ for key in names_a:
244
+ if key in VOLATILE_ATTRS:
245
+ continue
246
+ va, vb = a.getncattr(key), b.getncattr(key)
247
+ if key in PATH_ATTRS:
248
+ if _basename(va) != _basename(vb):
249
+ out.append(f"{where}@{key}: input basename differs: {va!r} vs {vb!r}")
250
+ elif not _attr_equal(va, vb):
251
+ out.append(f"{where}@{key}: {va!r} vs {vb!r}")
252
+
253
+
254
+ def _diff_group(where: str, a, b, out: list[str]) -> None:
255
+ dims_a = [(n, len(d), d.isunlimited()) for n, d in a.dimensions.items()]
256
+ dims_b = [(n, len(d), d.isunlimited()) for n, d in b.dimensions.items()]
257
+ if dims_a != dims_b:
258
+ out.append(f"{where}: dimensions differ: {dims_a} vs {dims_b}")
259
+ _diff_attrs(where or "<global>", a, b, out)
260
+ vars_a, vars_b = list(a.variables), list(b.variables)
261
+ if vars_a != vars_b:
262
+ out.append(f"{where}: variable names/order differ: "
263
+ f"only fresh {sorted(set(vars_a) - set(vars_b))}, "
264
+ f"only product {sorted(set(vars_b) - set(vars_a))}")
265
+ for name in (n for n in vars_a if n in b.variables):
266
+ va, vb = a.variables[name], b.variables[name]
267
+ label = f"{where}/{name}"
268
+ if va.dtype != vb.dtype or va.dimensions != vb.dimensions or va.shape != vb.shape:
269
+ out.append(f"{label}: definition differs: {va.dtype} {va.dimensions} {va.shape} vs "
270
+ f"{vb.dtype} {vb.dimensions} {vb.shape}")
271
+ continue
272
+ _diff_attrs(label, va, vb, out)
273
+ va.set_auto_maskandscale(False)
274
+ vb.set_auto_maskandscale(False)
275
+ ra = np.ascontiguousarray(va[...])
276
+ rb = np.ascontiguousarray(vb[...])
277
+ if ra.tobytes() != rb.tobytes():
278
+ n = int(np.count_nonzero(ra != rb)) if ra.shape == rb.shape else -1
279
+ out.append(f"{label}: stored values differ ({n} element(s))")
280
+ groups_a, groups_b = list(a.groups), list(b.groups)
281
+ if groups_a != groups_b:
282
+ out.append(f"{where}: groups differ: {groups_a} vs {groups_b}")
283
+ for g in (g for g in groups_a if g in b.groups):
284
+ _diff_group(f"{where}/{g}", a.groups[g], b.groups[g], out)
285
+
286
+
287
+ def content_differences(fresh: Path, product: Path) -> list[str]:
288
+ """Every way ``fresh`` differs from ``product`` under the module docstring's rule; ``[]`` when
289
+ identical. The file format is compared too (NETCDF3_CLASSIC is part of the output contract)."""
290
+ import netCDF4
291
+
292
+ out: list[str] = []
293
+ with netCDF4.Dataset(str(fresh)) as a, netCDF4.Dataset(str(product)) as b:
294
+ if a.data_model != b.data_model:
295
+ out.append(f"file format differs: {a.data_model} vs {b.data_model}")
296
+ _diff_group("", a, b, out)
297
+ return out
298
+
299
+
300
+ # --------------------------------------------------------------------------- reprocess
301
+
302
+ def reprocess(product, *, preset: str, tas_file=None, log=None) -> ReprocessResult:
303
+ """Re-run the stage that wrote ``product`` under its recorded configuration and diff.
304
+
305
+ Raises :class:`ReprocessRefused` (or ``run_flight.UnverifiableProvenance`` from the stage's
306
+ own input check) when the product cannot be re-run exactly as recorded."""
307
+ product = Path(product).resolve()
308
+ stage = stage_of(product)
309
+ if not product.is_file():
310
+ raise ReprocessRefused(f"{product} is not a file")
311
+
312
+ with _private_driver(log) as drv:
313
+ stamp = drv.read_stamp(product)
314
+ if stamp is None:
315
+ raise ReprocessRefused(
316
+ f"{product.name} has no .call sidecar; with no recorded configuration there is "
317
+ "nothing to reprocess it from")
318
+ cfg = parse_stamp(stamp, stage)
319
+
320
+ if preset not in drv.PRESETS:
321
+ raise ReprocessRefused(f"unknown preset {preset!r}; the driver knows "
322
+ f"{', '.join(sorted(drv.PRESETS))}")
323
+ drv.use_preset(preset)
324
+ drv.ENGINE = cfg["engine"]
325
+ # A stamp that records port_validation=on is regenerated with it on, so the comparison
326
+ # below sees the token and the fresh product carries it; a stamp from before R4 has none.
327
+ drv.PORT_VALIDATION = cfg["port_validation"]
328
+ # The stray-pixel switch is part of the recorded configuration (ON by default for engine
329
+ # 3.5 since 2026-10-03), so it is restored from the stamp rather than left at the private
330
+ # driver's import-time False, which refused every default v3.5 product.
331
+ drv.STRAY_PIXEL = (cfg["engine"] == "3.5" and cfg["stray_pixel"] is not None
332
+ and cfg["stray_pixel"].startswith("on"))
333
+ # The NCAR 2DC timing switch (ON by default for engine 3.5 2DC/2DP since 2026-10-07),
334
+ # restored from the stamp for the same reason.
335
+ drv.NCAR_2DC_TIMING = (cfg["engine"] == "3.5" and cfg["ncar_2dc_timing"] is not None
336
+ and cfg["ncar_2dc_timing"].startswith("on"))
337
+
338
+ from arrayprobe.profiles import PROFILES
339
+ if cfg["profile_name"] not in PROFILES:
340
+ raise ReprocessRefused(
341
+ f"the stamp names profile {cfg['profile_name']!r}, which is not registered in "
342
+ "this process (a register_profile() variant has to be imported first)")
343
+ drv.PROFILE = PROFILES[cfg["profile_name"]]
344
+
345
+ raw_stem = product.name.split(".")[1]
346
+ chain_file = None
347
+ if cfg["tas_chain"] is not None:
348
+ chain_file = _restore_chain(drv, product, raw_stem, cfg)
349
+ if tas_file is None and stage == "S3" and cfg["tas_file_name"] is not None:
350
+ # The chain's own output is the aircraft file S3 read; it sits beside the
351
+ # product by the driver's naming convention, so it need not be named.
352
+ tas_file = chain_file
353
+
354
+ stamped_tas = cfg["tas_file_name"]
355
+ if stage == "S3" and stamped_tas is not None:
356
+ if tas_file is None:
357
+ raise ReprocessRefused(
358
+ f"{product.name} was framed with aircraft file {stamped_tas} (stamped by "
359
+ "name only); S3 reads it, so pass --tas-file")
360
+ tas_path = Path(tas_file).resolve()
361
+ if tas_path.name != stamped_tas:
362
+ raise ReprocessRefused(f"--tas-file {tas_path.name} is not the stamped "
363
+ f"{stamped_tas}")
364
+ if not tas_path.is_file():
365
+ raise ReprocessRefused(f"--tas-file {tas_path} does not exist")
366
+ drv.TAS_FILE = str(tas_path)
367
+ elif tas_file is not None:
368
+ why = ("no aircraft file is stamped" if stamped_tas is None
369
+ else "S4 never reads the aircraft file")
370
+ raise ReprocessRefused(f"--tas-file given, but {why} for {product.name}; drop it "
371
+ "rather than carry an input the run ignores")
372
+ else:
373
+ # S4: the file is never read; only its stamped name enters the label.
374
+ drv.TAS_FILE = stamped_tas
375
+
376
+ shadow = cfg["shadow_diode"]
377
+ if stage == "S4":
378
+ want = drv.sd_call_label(cfg["iat_file"], shadow_diode=shadow)
379
+ else:
380
+ want = drv.proc_call_label(shadow_diode=shadow)
381
+ if not drv._stamps_equivalent(stamp, want):
382
+ raise ReprocessRefused(
383
+ f"{product.name} cannot be re-run as recorded: under the configuration its stamp "
384
+ f"names, this driver would stamp\n {want}\nbut the product records\n {stamp}")
385
+
386
+ expected = (drv.sd_path if stage == "S4" else drv.proc_path)(
387
+ raw_stem, product.parent, shadow)
388
+ if expected.name != product.name:
389
+ raise ReprocessRefused(
390
+ f"under preset {preset} this product would be named {expected.name}, not "
391
+ f"{product.name} -- the preset's channel or the diode mask does not match")
392
+
393
+ with tempfile.TemporaryDirectory(prefix="reprocess_") as tmp:
394
+ out_dir = Path(tmp)
395
+ try:
396
+ if stage == "S4":
397
+ fresh = _rerun_s4(drv, product, raw_stem, out_dir, cfg)
398
+ else:
399
+ fresh = _rerun_s3(drv, product, raw_stem, out_dir, shadow)
400
+ except drv.UnverifiableProvenance as exc:
401
+ # The stage's own input check (stage4's proc-stamp test), unchanged.
402
+ raise ReprocessRefused(str(exc)) from exc
403
+ differences = content_differences(fresh, product)
404
+ fresh_stamp = drv.read_stamp(fresh)
405
+ if fresh_stamp is None or not drv._stamps_equivalent(stamp, fresh_stamp):
406
+ differences.append(f".call: fresh {fresh_stamp!r} vs product {stamp!r}")
407
+ return ReprocessResult(product, stage, cfg["engine"], stamp, differences)
408
+
409
+
410
+ def _restore_chain(drv, product: Path, raw_stem: str, cfg) -> Path:
411
+ """Put the TAS chain a product was made under back into the private driver, from the chain's
412
+ own output file beside the product (``<stem>.tas_<tier>.cdf``, the name ``run_flight`` gives
413
+ it). Returns that file's path.
414
+
415
+ The chain is not re-resolved: its sources (a merge or aircraft file) are recorded by name
416
+ only, never by path. What S3 and S4 consume is the series the chain wrote -- S3 reads that
417
+ file as its aircraft file, S4 sizes on the same ``Time``/``TAS`` values -- so re-running either
418
+ stage needs that file and nothing upstream of it. The file's own record of which chain and
419
+ policy wrote it must agree with the stamp, or the run is refused."""
420
+ import netCDF4
421
+
422
+ from arrayprobe.tools import make_tas_file, tas_sources
423
+
424
+ chain = cfg["tas_chain"]
425
+ tier, _, source = chain.partition(":")
426
+ if tier not in tas_sources.TIERS or not source:
427
+ raise ReprocessRefused(f"the stamp names TAS chain {chain!r}, which is not "
428
+ f"<tier>:<source> with a tier in {tas_sources.TIERS}")
429
+ path = product.parent / f"{raw_stem}.tas_{tier}.cdf"
430
+ if cfg["tas_file_name"] is not None and cfg["tas_file_name"] != path.name:
431
+ raise ReprocessRefused(
432
+ f"the stamp names aircraft file {cfg['tas_file_name']} and TAS chain {chain}, whose "
433
+ f"output the driver writes as {path.name}; they disagree")
434
+ if not path.is_file():
435
+ raise ReprocessRefused(
436
+ f"{product.name} was sized on TAS chain {chain}, and re-running it needs "
437
+ f"{path.name} (the series that chain wrote) beside it. The chain cannot be resolved "
438
+ "again here: its sources are recorded by name only, not by path")
439
+ try:
440
+ policy = (make_tas_file.TasPolicy.parse(cfg["tas_policy"]) if cfg["tas_policy"]
441
+ else make_tas_file.TasPolicy())
442
+ except (KeyError, ValueError) as exc:
443
+ raise ReprocessRefused(f"the stamp's TAS policy {cfg['tas_policy']!r} does not parse: "
444
+ f"{exc}") from exc
445
+ with netCDF4.Dataset(str(path)) as ds:
446
+ attrs = {k: ds.getncattr(k) for k in ds.ncattrs()}
447
+ t_var, v_var = (ds.variables[make_tas_file.TIME_VARIABLE],
448
+ ds.variables[make_tas_file.TAS_VARIABLE])
449
+ t_var.set_auto_maskandscale(False)
450
+ v_var.set_auto_maskandscale(False)
451
+ time = np.asarray(t_var[:], dtype=np.float64)
452
+ tas = np.asarray(v_var[:], dtype=np.float64)
453
+ for attr, want in (("tas_chain_used", chain), ("tas_policy", policy.token())):
454
+ got = attrs.get(attr)
455
+ if got != want:
456
+ raise ReprocessRefused(f"{path.name} records {attr}={got!r}, but "
457
+ f"{product.name}'s stamp names {want!r}")
458
+ drv.TAS_POLICY = policy
459
+ drv.TAS_GRID = cfg["tas_grid"] or "probe"
460
+ drv.TAS_CHAIN = tas_sources.ChainResult(
461
+ mode=str(attrs.get("tas_chain_mode", tier)), tier=tier, source=source, path=str(path),
462
+ time=time, tas=tas, policy=policy, steps=[], substituted=[], lines=[], provenance=attrs)
463
+ return path
464
+
465
+
466
+ def _rerun_s4(drv, product: Path, raw_stem: str, out_dir: Path, cfg) -> Path:
467
+ proc = drv.proc_path(raw_stem, product.parent, cfg["shadow_diode"])
468
+ tas_csv = product.parent / f"{raw_stem}.tas.csv"
469
+ for need, what in ((proc, "the proc file S4 reads"), (tas_csv, "S2's TAS sidecar")):
470
+ if not need.is_file():
471
+ raise ReprocessRefused(f"{product.name} needs {need.name} ({what}) beside it")
472
+ # stage4 reads the TAS sidecar from its own output directory.
473
+ shutil.copy2(tas_csv, out_dir / tas_csv.name)
474
+ # The TAS QC sidecar (<sd>.tasqc.json) is not part of the diff and lands in the discarded
475
+ # temporary directory, but building it opens the aircraft file, which the stamp names by
476
+ # basename only -- so every v3.5 re-run printed "S4 TAS QC record not written: cannot read
477
+ # <name>", a warning about a file the product never needed (cold-user walk, 2026-09-26).
478
+ # This is a private copy of the driver, so the override ends with it. Engine 3.5 also
479
+ # writes the record INTO the sd file, so the re-run carries the record the user's
480
+ # run wrote beside the product rather than none -- otherwise every v3.5 re-run differed from
481
+ # its original by exactly those attributes.
482
+ from arrayprobe.tools import tas_sources
483
+ recorded = tas_sources.read_qc_sidecar(product)
484
+ drv._tas_qc_record = lambda *_a, **_k: recorded
485
+ fresh = drv.stage4(proc, raw_stem, out_dir, iat_file=cfg["iat_file"],
486
+ shadow_diode=cfg["shadow_diode"], accept_unstamped=False)
487
+ if not fresh.is_file():
488
+ raise ReprocessRefused(f"S4 wrote no {fresh.name}")
489
+ return fresh
490
+
491
+
492
+ def _rerun_s3(drv, product: Path, raw_stem: str, out_dir: Path, shadow) -> Path:
493
+ image = drv.image_path(raw_stem, product.parent)
494
+ if not image.is_file():
495
+ raise ReprocessRefused(f"{product.name} needs {image.name} (the decoded image S3 reads) "
496
+ "beside it")
497
+ image_want = drv.image_call_label()
498
+ image_got = drv.read_stamp(image)
499
+ # The raw-input inventory keys S2 appends describe the input, not the configuration
500
+ # (run_flight._strip_inventory, the driver's own rule).
501
+ if image_got is None or drv._strip_inventory(image_got) != image_want:
502
+ raise ReprocessRefused(
503
+ f"{image.name} is {'unstamped' if image_got is None else f'stamped {image_got!r}'}, "
504
+ f"but S3 under this configuration reads an image stamped {image_want!r}")
505
+ if shadow:
506
+ fresh = drv.stage3_corrected(image, out_dir, accept_unstamped=False)
507
+ if fresh is None:
508
+ raise ReprocessRefused(f"no registered diode override for {raw_stem}")
509
+ else:
510
+ fresh = drv.stage3(image, out_dir, chunks=1, accept_unstamped=False)
511
+ if not fresh.is_file():
512
+ raise ReprocessRefused(f"S3 wrote no {fresh.name}")
513
+ return fresh
514
+
515
+
516
+ # --------------------------------------------------------------------------- command line
517
+
518
+ def run(args: argparse.Namespace) -> int:
519
+ """``arrayprobe reprocess``'s handler body (the argument surface is ``arrayprobe.cli``'s, the
520
+ one place it is declared). 0 identical, 1 differs, 2 refused -- the meanings ``arrayprobe
521
+ compare`` gives 0/1/2."""
522
+ from arrayprobe import __version__
523
+
524
+ def log(msg: str) -> None:
525
+ print(f" {msg}", file=sys.stderr, flush=True)
526
+
527
+ try:
528
+ result = reprocess(args.product, preset=args.preset, tas_file=args.tas_file, log=log)
529
+ except ReprocessRefused as exc:
530
+ print(f"reprocess: REFUSED -- {exc}", file=sys.stderr)
531
+ return 2
532
+ print(f"product : {result.product}")
533
+ print(f"stage : {result.stage}, UIOPS {result.engine} engine, arrayprobe {__version__}")
534
+ print(f"stamp : {result.stamp}")
535
+ if result.identical:
536
+ print("result : IDENTICAL (every dimension, variable and attribute; Creation Time "
537
+ "skipped, source paths compared by basename)")
538
+ return 0
539
+ print(f"result : DIFFERS in {len(result.differences)} place(s)")
540
+ for line in result.differences:
541
+ print(f" {line}")
542
+ return 1
543
+
544
+
545
+ def main(argv=None) -> int:
546
+ """A shim onto ``arrayprobe reprocess``: one
547
+ argument surface, so the script and the subcommand cannot drift apart."""
548
+ from arrayprobe.cli import main as cli_main
549
+ return cli_main(["reprocess", *(sys.argv[1:] if argv is None else argv)])
550
+
551
+
552
+ if __name__ == "__main__":
553
+ raise SystemExit(main())