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
arrayprobe/cli.py ADDED
@@ -0,0 +1,3510 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """``arrayprobe`` -- the command-line front door.
3
+
4
+ Each subcommand is an argparse wrapper around one already-validated
5
+ function -- this module adds no new pipeline logic, only argument parsing
6
+ and dispatch:
7
+
8
+ ``run``
9
+ One line: a configuration file -> the whole chain of the engine the file names
10
+ (``[run].engine``, 3.1.4 or 3.5), via :mod:`arrayprobe.driver.run_flight`; every choice --
11
+ engine, profile, campaign preset -- is named in the file (:mod:`arrayprobe.config`).
12
+ ``reprocess``
13
+ A proc/sd product -> the same stage re-run exactly as its ``.call`` stamp records, and a
14
+ verdict on whether the fresh file is identical (:mod:`arrayprobe.driver.reprocess`).
15
+ Refuses unless the driver regenerates the recorded stamp exactly.
16
+ ``read-binary``
17
+ A raw OAP file -> a decoded netCDF, via one of the four raw-format
18
+ readers (:mod:`arrayprobe.readers.spec`/``dmt``/``pms``/``sea``).
19
+ ``imgproc``
20
+ A decoded image file -> a per-particle proc file
21
+ (:func:`arrayprobe.imgproc.imgproc_sm`).
22
+ ``sizedist``
23
+ A proc file -> a one-second size-distribution file
24
+ (:func:`arrayprobe.sizedist.run`). Reads the TAS/time arrays from a
25
+ ``.tas.csv`` sidecar via :func:`arrayprobe.readers.tasinfo.load_tas_info`.
26
+ ``combine``
27
+ Several ``sd`` files from one flight -> the single stitched product
28
+ (:func:`arrayprobe.combine.combine_sizedist`).
29
+
30
+ **The per-stage subcommands stay explicit-argument, on purpose.** Each one
31
+ takes every fidelity-sensitive parameter (``profile``, ``tree``, ``d_choice``,
32
+ ``sa_method``, ...) as a required argument, never a default -- matching the
33
+ same "no default silently picks a side" rule :mod:`arrayprobe.profiles`
34
+ states for :class:`~arrayprobe.profiles.FidelityProfile`. A general front door
35
+ must never default a fidelity choice; getting one of these wrong is exactly
36
+ the failure mode this module refuses to make easy.
37
+
38
+ ``run`` is the same rule applied to a *file* instead of a command line: it
39
+ drives :mod:`arrayprobe.driver.run_flight` (the batch driver -- probe,
40
+ orientation and every fidelity-sensitive constant fixed in one place, on
41
+ purpose, so a wrong value can't silently produce a plausible answer) but
42
+ every choice still has to be *named*, this time in the config file rather
43
+ than as flags. :mod:`arrayprobe.config` bounds what a file may do to
44
+ selection only -- it cannot set a threshold, only choose
45
+ among documented profiles and presets -- so this is not a loosening of the
46
+ explicit-argument rule above, it is the rule's file-shaped form.
47
+
48
+ ``intarr-threshold``
49
+ A per-particle file -> the inter-arrival threshold file ``sizeDist``
50
+ reads as its optional twelfth argument
51
+ (:mod:`arrayprobe.intarr_analysis`). The rest of the same MATLAB script
52
+ is reachable opt-in, every flag default OFF: ``--plot`` (B8's axis
53
+ reproduced unless ``--fix-b8``), ``--mat-workspace`` and
54
+ ``--extra-thresholds-json``.
55
+ ``compare``
56
+ Two output files -> a join-then-diff report by tolerance class
57
+ (:mod:`arrayprobe.compare`). The handler is below, and there is one of it.
58
+ A second copy would be a
59
+ second place for the acceptance rule
60
+ to drift.
61
+ ``gallery``
62
+ A flight's particles -> a directory of rendered images with index pages
63
+ (:mod:`arrayprobe.render`). Visualisation changes no computed number, so
64
+ it is core rather than an enhancement -- the same reason
65
+ :mod:`arrayprobe.triage_server` is.
66
+ ``triage``
67
+ Starts the review server (:mod:`arrayprobe.triage_server`).
68
+
69
+ That module's own ``main`` says it is deliberately **not** a console
70
+ script, because it needs a decoded directory to point at and a bare
71
+ command "makes it look like a command that works anywhere". That
72
+ objection is answered rather than overruled: ``--decoded-dir`` is
73
+ **required** here, with no default, so the subcommand cannot be run
74
+ somewhere it would silently find nothing. ``python -m
75
+ arrayprobe.triage_server`` keeps its ``../_decoded`` default and is
76
+ unchanged.
77
+ ``validate``
78
+ Diagnostic checks on files the pipeline already wrote. Nothing here
79
+ computes a pipeline number or writes one; every check reads output and
80
+ reports a comparison. Added 2026-09-10 so the checks the literature asks
81
+ for are reachable from the front door rather than only from a script in
82
+ ``scripts/`` that a new user has no reason to find -- the same argument
83
+ that put ``read-binary`` here rather than leaving it an import.
84
+
85
+ ``validate timing-closure``
86
+ (:mod:`arrayprobe.timing_closure`, McFarquhar et al. 2017 p. 11.20). It
87
+ **reports and does not verdict**: no published tolerance exists for how
88
+ closely the probe's particle clock and its housekeeping clock should
89
+ agree, so the exit status is 0 on any successful comparison. A check
90
+ that invented a threshold would be worse than no check, because the
91
+ threshold would then be cited.
92
+ ``view``
93
+ Diagnostic views of the port's own outputs (:mod:`arrayprobe.diagnostic_views`):
94
+ ``view strip`` draws whole image records with their particles in place, coloured by
95
+ reject code or habit; ``view second`` sets one second of two ``sd`` files side by side,
96
+ bin by bin, and lists the particles behind the differing cells. Visualisation only, so
97
+ core, like ``gallery``.
98
+ """
99
+
100
+ from __future__ import annotations
101
+
102
+ import argparse
103
+ import logging
104
+ import os
105
+ import re
106
+ import sys
107
+ from pathlib import Path
108
+ from typing import Any
109
+
110
+ import numpy as np
111
+
112
+ from . import __version__, provenance
113
+ from . import combine as combine_module
114
+ from . import compare as compare_module
115
+ from . import render as render_module
116
+ from . import timing_closure as timing_closure_module
117
+ from . import triage_server as triage_module
118
+ from . import validate_by_condition as by_condition_module
119
+ from ._v314_lazy import ABSENT_MESSAGE as _V314_ABSENT_MESSAGE
120
+ from ._v314_lazy import engine_present as _v314_engine_present
121
+ from ._v314_lazy import lazy_module as _lazy_module
122
+ from .matlab_compat import MatlabIndexError
123
+ from .profiles import profile as lookup_profile
124
+ from .readers import dmt, pms, sea
125
+ from .readers.tasinfo import load_tas_info
126
+
127
+ # v3.1.4 engine modules are absent from the public distribution: load on first use.
128
+ imgproc_module = _lazy_module("arrayprobe.imgproc")
129
+ sizedist_module = _lazy_module("arrayprobe.sizedist")
130
+ spec = _lazy_module("arrayprobe.readers.spec")
131
+
132
+ __all__ = ["build_parser", "main"]
133
+
134
+ _FORMATS = {"spec": spec, "dmt": dmt, "pms": pms, "sea": sea}
135
+
136
+ _RUN_FLIGHT_MODULE = "run_flight"
137
+
138
+
139
+ def _load_reprocess():
140
+ """``arrayprobe.driver.reprocess``, also bound in ``sys.modules`` as
141
+ ``_arrayprobe_cli_reprocess`` so repeated calls share one object. It loads its OWN private
142
+ copy of the driver per call, so it never touches the shared ``run_flight`` module the tests
143
+ and ``run`` bind to."""
144
+ import importlib
145
+ name = "_arrayprobe_cli_reprocess"
146
+ mod = sys.modules.get(name)
147
+ if mod is not None:
148
+ return mod
149
+ mod = importlib.import_module("arrayprobe.driver.reprocess")
150
+ return sys.modules.setdefault(name, mod)
151
+
152
+
153
+ def _load_run_flight():
154
+ """The batch driver, ``arrayprobe.driver.run_flight``, as the one module object bound to
155
+ ``sys.modules["run_flight"]``.
156
+
157
+ The tests and the ``scripts/run_flight.py`` shim (a source checkout only) bind the driver
158
+ under that name, so when it is already
159
+ loaded this command returns that object and shares its ``PROFILE`` and ``ENGINE`` globals;
160
+ otherwise it imports the package module and binds it there, so exactly one object answers
161
+ to the name. The driver ships inside the package, so an installed wheel or sdist reaches it
162
+ with no ``scripts/`` directory present.
163
+ """
164
+ import importlib
165
+ mod = sys.modules.get(_RUN_FLIGHT_MODULE)
166
+ if mod is not None:
167
+ return mod
168
+ mod = importlib.import_module("arrayprobe.driver.run_flight")
169
+ return sys.modules.setdefault(_RUN_FLIGHT_MODULE, mod)
170
+
171
+
172
+ def _profile_names() -> list[str]:
173
+ """Every fidelity profile name the CLI accepts: the shipped ones and any a fork registered."""
174
+ from .profiles import PROFILES
175
+ return sorted(PROFILES)
176
+
177
+
178
+ def _check_read_binary(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
179
+ """``--profile`` is required with ``--format spec`` and refused with the other formats.
180
+
181
+ argparse cannot express a requirement that depends on another option's value, so it is
182
+ enforced here, through ``parser.error`` -- the same usage line and exit status 2 as any
183
+ other missing argument -- and the message lists the names a user can give.
184
+ """
185
+ names = ", ".join(_profile_names())
186
+ if args.format == "spec" and not args.profile:
187
+ parser.error(f"read-binary --format spec needs --profile (no default); one of: {names}")
188
+ if args.format != "spec" and args.profile:
189
+ parser.error(f"read-binary --format {args.format} takes no --profile: only the SPEC "
190
+ f"reader reads one, and a profile given here would be ignored")
191
+ if args.profile and args.profile not in _profile_names():
192
+ parser.error(f"unknown --profile {args.profile!r}; one of: {names}")
193
+ if args.format != "spec" and args.channels is not None:
194
+ parser.error(f"read-binary --format {args.format} takes no --channels: only the SPEC "
195
+ f"reader splits H and V, and a channel given here would be ignored")
196
+ if args.format == "spec" and args.channels is None:
197
+ args.channels = "HV"
198
+
199
+
200
+ def _offered_engines() -> tuple[str, ...]:
201
+ """The ``--engine`` values a per-stage command offers: ``3.1.4`` only where it is installed.
202
+
203
+ A distribution without the v3.1.4 engine offers ``3.5`` alone, so its ``--help`` never
204
+ advertises an engine it cannot run (engine-exposure Option 2, author 2026-10-15).
205
+ """
206
+ return ("3.1.4", "3.5") if _v314_engine_present() else ("3.5",)
207
+
208
+
209
+ def _engine_value(text: str) -> str:
210
+ """``type=`` for every ``--engine``: accepts the offered values and ``3.1.4`` by name.
211
+
212
+ ``3.1.4`` is accepted even where absent so that :func:`main` prints ``ABSENT_MESSAGE``
213
+ and exits 2, instead of argparse's bare "invalid choice". Anything else is refused here.
214
+ """
215
+ if text in _offered_engines() or text == "3.1.4":
216
+ return text
217
+ raise argparse.ArgumentTypeError(
218
+ f"invalid choice: {text!r} (choose from {', '.join(_offered_engines())})")
219
+
220
+
221
+ def _engine_metavar() -> str:
222
+ return "{" + ",".join(_offered_engines()) + "}"
223
+
224
+
225
+ def _stage_engine_help() -> str:
226
+ if _v314_engine_present():
227
+ return ("which UIOPS engine this stage runs: 3.1.4 (the validation engine) or 3.5. "
228
+ "Required, with no default, so no run silently picks a side; recorded in the "
229
+ ".call stamp. A top-level --uiops-version naming the other engine is refused, "
230
+ "never overridden.")
231
+ return ("which UIOOPS engine this stage runs: 3.5. Required, with no default, so no run "
232
+ "silently picks a side; recorded in the .call stamp.")
233
+
234
+
235
+ def _add_stage_engine(p: argparse.ArgumentParser) -> None:
236
+ """``--engine`` for read-binary, sizedist and combine (review item 2, 2026-09-26).
237
+
238
+ Required, as the batch driver's ``--engine`` is: omitting it exits 2.
239
+ """
240
+ p.add_argument("--engine", required=True, type=_engine_value, metavar=_engine_metavar(),
241
+ help=_stage_engine_help())
242
+
243
+
244
+ def _stage_engine(args: argparse.Namespace) -> str:
245
+ """The engine a per-stage command runs: its required ``--engine``."""
246
+ return str(args.engine)
247
+
248
+
249
+ def _add_read_binary(sub: argparse._SubParsersAction) -> None:
250
+ p = sub.add_parser(
251
+ "read-binary",
252
+ help="decode a raw OAP file into netCDF",
253
+ description="Dispatches to one of the four raw-format readers by "
254
+ "--format, explicitly -- never inferred from the file "
255
+ "name or extension, since a wrong guess would silently "
256
+ "decode a file as the wrong format. These are the "
257
+ "readers of the v3.1.4 validation engine, which this distribution does "
258
+ "not include; the dmt, pms "
259
+ "and sea readers are the same code under v3.5, whose "
260
+ "MATLAB is byte-identical. To process data on the default "
261
+ "engine, use `arrayprobe run <config.toml>`.",
262
+ )
263
+ p.add_argument("infile", help="raw binary file")
264
+ # The help below is wrong for pms and sea (see _read_binary_outputs); it is left as is
265
+ # because docs/13-cli-reference.md is generated from it, and the page and the
266
+ # help change together (python docs/_build/clidoc.py).
267
+ p.add_argument("outfile", help="output path: spec writes <outfile>.H.cdf / <outfile>.V.cdf, "
268
+ "pms <outfile>.2dc.cdf / .f2dc.cdf / .2dp.cdf, sea "
269
+ "<outfile>.CIP.cdf / .2DC.cdf; dmt writes exactly this path")
270
+ p.add_argument("--format", required=True, choices=sorted(_FORMATS),
271
+ help="raw format family: spec (2D-S/HVPS), dmt (CIP/PIP), "
272
+ "pms (2DC/2DP/Fast2DC), sea")
273
+ p.add_argument("--profile",
274
+ help="fidelity profile name, required with --format spec and refused with "
275
+ "the other formats, whose readers take none. No default: the "
276
+ "profile selects the SPEC decoder's record-buffer guard, on which the "
277
+ "MATLAB sources differ. One of: "
278
+ + ", ".join(_profile_names()))
279
+ p.add_argument("--channels", default=None, choices=("HV", "H", "V"),
280
+ help="which SPEC channel(s) to write (spec only, "
281
+ "default HV; refused with the other formats)")
282
+ _add_stage_engine(p)
283
+ p.set_defaults(func=_run_read_binary)
284
+
285
+
286
+ def _stamp(outputs, *, engine: str, stage: str, profile: str | None,
287
+ extra: dict[str, str] | None = None) -> None:
288
+ """Record what wrote each path in ``outputs`` that actually exists.
289
+
290
+ **Why every writer here calls this** (2026-09-18). Before it, the only stamp writer
291
+ in the whole pipeline was the batch driver's ``write_stamp``, called after each of
292
+ the driver's stages. Every other caller -- including these shipped subcommands, which the
293
+ documentation offers as the way to run one stage -- produced a product with nothing beside
294
+ it saying what had made it. Provenance was a property of one driver's happy path rather
295
+ than of the product, so the repository documented a way to make exactly what the driver
296
+ refuses. A stamp written here is not as complete as the driver's (it records this verb's
297
+ arguments, not a campaign preset), and ``reprocess`` will still refuse to re-run from it,
298
+ which is correct: it says what it knows and nothing it does not.
299
+
300
+ A path that does not exist is skipped rather than stamped -- an orphan stamp would assert
301
+ a product that is not there, which is the one failure state :func:`provenance.state`
302
+ exists to name.
303
+ """
304
+ fields = {"writer": "arrayprobe-cli"}
305
+ fields.update(extra or {})
306
+ for out in outputs:
307
+ path = Path(out)
308
+ if path.exists():
309
+ provenance.write(path, engine=engine, profile=profile, stage=stage,
310
+ extra=dict(fields))
311
+
312
+
313
+ def _read_binary_outputs(args: argparse.Namespace) -> list[Path]:
314
+ """Which files ``read-binary`` actually wrote.
315
+
316
+ SPEC writes ``<outfile>.H.cdf`` / ``<outfile>.V.cdf`` per ``--channels``, PMS
317
+ ``<outfile>.2dc.cdf`` / ``.f2dc.cdf`` / ``.2dp.cdf`` and SEA ``<outfile>.CIP.cdf`` /
318
+ ``.2DC.cdf`` (each reader's own docstring); DMT writes ``outfile`` verbatim -- stated once
319
+ here so the stamp lands on the product and not on a path nobody created. Until 2026-09-26
320
+ PMS and SEA were listed as ``outfile`` verbatim: the command printed ``wrote <outfile>``, a
321
+ file that never existed, and their real products were left unstamped.
322
+ """
323
+ out = Path(args.outfile)
324
+ suffixes = {"spec": [f"{c}.cdf" for c in (args.channels or "HV")],
325
+ "pms": ["2dc.cdf", "f2dc.cdf", "2dp.cdf"],
326
+ "sea": ["CIP.cdf", "2DC.cdf"]}.get(args.format)
327
+ if suffixes is None:
328
+ return [out]
329
+ return [out.with_name(f"{out.name}.{s}") for s in suffixes]
330
+
331
+
332
+ def _run_read_binary(args: argparse.Namespace) -> int:
333
+ engine = _stage_engine(args)
334
+ if engine == "3.5" and args.format == "spec":
335
+ print("arrayprobe read-binary --engine 3.5 --format spec: not wired here. "
336
+ "arrayprobe_uiops.spec.read_binary_spec_v35 requires `software` (the Software "
337
+ "attribute upstream reads from a cwd-relative version.txt) and the flight's "
338
+ "TAS series, each a choice this command's flags do not carry and none of them "
339
+ "defaultable. Run the v3.5 chain through `arrayprobe run <config>` with "
340
+ "[run].engine = \"3.5\". The dmt, pms and sea readers do run on 3.5 here.",
341
+ file=sys.stderr)
342
+ return 2
343
+ if not Path(args.infile).is_file():
344
+ # Before any reader runs: SPEC creates its .H/.V.cdf files first and then raised
345
+ # FileNotFoundError, leaving two empty products behind a traceback.
346
+ print(f"arrayprobe read-binary: not a file: {args.infile}", file=sys.stderr)
347
+ return 2
348
+ try:
349
+ if args.format == "spec":
350
+ if not args.profile:
351
+ # main() refuses this before dispatch; kept for a caller that builds args itself.
352
+ raise SystemExit("--format spec needs --profile "
353
+ "(no default -- see FidelityProfile)")
354
+ counts = spec.read_binary_SPEC(
355
+ args.infile, args.outfile,
356
+ profile=lookup_profile(args.profile), channels=args.channels or "HV",
357
+ )
358
+ elif args.format == "dmt":
359
+ counts = (dmt.read_binary_DMT(args.infile, args.outfile),)
360
+ elif args.format == "pms":
361
+ counts = pms.read_binary_PMS(args.infile, args.outfile)
362
+ else:
363
+ n_cip, _n_weird, n_2dc = sea.read_binary_SEA(args.infile, args.outfile)
364
+ counts = (n_cip, n_2dc)
365
+ except (ValueError, sea.SeaUndefinedVariableError, MatlabIndexError) as exc:
366
+ # The readers' own refusals (DecompressionError, a missing </OAP> terminator, the
367
+ # MATLAB error a SEA reader raises where read_binary_SEA.m dies, ...) --
368
+ # usually a --format that does not match the file. One line, not a traceback.
369
+ print(f"arrayprobe read-binary --format {args.format}: {args.infile} did not decode: "
370
+ f"{exc}. Check that --format matches the file", file=sys.stderr)
371
+ return 1
372
+ written = [p for p in _read_binary_outputs(args) if p.exists()]
373
+ print(f"wrote {', '.join(str(p) for p in written)} (records: "
374
+ f"{', '.join(str(int(n)) for n in counts)})")
375
+ # These readers are `arrayprobe`'s, so engine=3.1.4 is a statement about the code that ran,
376
+ # not a claim that no other release shares it: uiops.CATALOGUE marks read_binary_DMT/PMS/SEA
377
+ # SHARED (the MATLAB is byte-identical between v3.1.4 and v3.5, so one translation serves
378
+ # both) and read_binary_SPEC OVERRIDDEN. `catalogue=` carries that distinction into the
379
+ # stamp rather than letting `engine=` overstate it.
380
+ # Under --engine 3.5 only the SHARED readers reach this line (SPEC is refused above), so
381
+ # engine=3.5 names the same translation, whose MATLAB the catalogue measures byte-identical.
382
+ catalogue = "overridden" if args.format == "spec" else "shared"
383
+ _stamp(_read_binary_outputs(args), engine=engine, stage="S2",
384
+ profile=args.profile,
385
+ extra={"format": args.format, "catalogue": catalogue, "raw": Path(args.infile).name,
386
+ **({"channels": args.channels or "HV"} if args.format == "spec" else {})})
387
+ if not any(counts):
388
+ # A SEA or PMS reader handed a file of another format finds no record it recognises
389
+ # and writes empty products, exit 0, with nothing to say it read nothing.
390
+ print(f"arrayprobe read-binary: no records decoded from {args.infile} -- is "
391
+ f"--format {args.format} right for this file?", file=sys.stderr)
392
+ return 1
393
+ return 0
394
+
395
+
396
+ def _add_imgproc(sub: argparse._SubParsersAction) -> None:
397
+ p = sub.add_parser(
398
+ "imgproc",
399
+ help="frame particles out of a decoded image file (imgProc_sm) on the v3.1.4 "
400
+ "validation engine, which this distribution does not include; use "
401
+ "`arrayprobe run`",
402
+ description="Frame particles out of a decoded image file (imgProc_sm) on the "
403
+ "v3.1.4 validation engine, which this distribution does not include. To "
404
+ "process data on the default engine, v3.5, use `arrayprobe run "
405
+ "<config.toml>`; to run a "
406
+ "single stage there, use [run].stages in the config.",
407
+ )
408
+ p.add_argument("infile")
409
+ p.add_argument("outfile")
410
+ p.add_argument("probename")
411
+ p.add_argument("n", type=int, help="chunk index, 1-based (n=1 for a "
412
+ "whole-file run)")
413
+ p.add_argument("every", type=int, help="records per chunk (nEvery; the "
414
+ "whole file's record count for "
415
+ "a whole-file run)")
416
+ p.add_argument("projectname")
417
+ p.add_argument("--profile", required=True,
418
+ help="fidelity profile name -- no default")
419
+ p.add_argument("--engine", required=True, type=_engine_value, metavar=_engine_metavar(),
420
+ help="which UIOOPS engine frames the particles; required, no default, and "
421
+ "recorded in the .call stamp. "
422
+ + ("3.1.4 is the validation engine and runs here; "
423
+ if _v314_engine_present() else
424
+ "3.1.4, the validation engine this command runs, is not in this "
425
+ "distribution; ")
426
+ + "3.5 is refused with the reason, because its image processing "
427
+ "needs choices this command's flags do not carry. For 3.5 use "
428
+ "`arrayprobe run` with [run].engine = \"3.5\".")
429
+ p.add_argument("--i-rect-ellipse", type=int, default=0, choices=(0, 1))
430
+ p.add_argument("--i-calc-all-diode-stats", type=int, default=0,
431
+ choices=(0, 1))
432
+ p.add_argument("--tas-file", default=None,
433
+ help="aircraft TAS file (only if the profile's "
434
+ "time_in_seconds_from_tas is set)")
435
+ p.set_defaults(func=_run_imgproc)
436
+
437
+
438
+ #: What ``imgProc_sm`` needs under v3.5 that this subcommand's flag surface does not carry.
439
+ #: Each is a fidelity decision with no defensible default (``arrayprobe_uiops.imgproc:489-510``
440
+ #: makes all four keyword-only and required for the same reason), so the verb refuses rather
441
+ #: than inventing them -- the module docstring's "a general front door must never default a
442
+ #: fidelity choice", applied to the engine that has more of them.
443
+ _V35_IMGPROC_UNCARRIED = ("iNewHabit", "reject_config", "tas_time/tas", "software")
444
+
445
+
446
+ def _v35_stage_route(stage: str, name: str) -> str:
447
+ """The v3.5 route for one stage: `arrayprobe run` with that stage selected."""
448
+ return (f"To run {name} on v3.5, use `arrayprobe run <config.toml>` with "
449
+ f'[run].engine = "3.5" and [run].stages = "{stage}" (or "234" for the whole chain); '
450
+ f"examples/configs/cip_uiops/cip_run.toml is a template.")
451
+
452
+
453
+ #: The stage each per-stage verb runs, for the refusal a distribution without the engine prints.
454
+ _STAGE_VERB_ROUTES = {"imgproc": ("3", "image processing"),
455
+ "sizedist": ("4", "the size distribution")}
456
+
457
+
458
+ def _absent_engine_refusal(command: str | None) -> str:
459
+ """What a per-stage verb prints where the engine it runs is absent: the shared absence
460
+ message, plus, for a verb that is one stage, the working route (`arrayprobe run` with that
461
+ stage), so the refusal never leaves the user without a command that works. Names no
462
+ engine version beyond v3.5, as the rest of a distribution without the engine does."""
463
+ route = _STAGE_VERB_ROUTES.get(command or "")
464
+ if route is None:
465
+ return _V314_ABSENT_MESSAGE
466
+ return _V314_ABSENT_MESSAGE + " " + _v35_stage_route(*route)
467
+
468
+
469
+ def _run_imgproc(args: argparse.Namespace) -> int:
470
+ import uiops # local, matching every other uiops use here (`:1525`, `:1587`)
471
+
472
+ engine = uiops.engine(args.engine)
473
+ if engine.version == "3.5":
474
+ print(f"arrayprobe imgproc --engine 3.5: not wired here. "
475
+ f"{engine.dotted('imgproc')}.imgproc_sm_v35 requires "
476
+ f"{', '.join(_V35_IMGPROC_UNCARRIED)}, each of them a fidelity choice this "
477
+ f"subcommand's flags do not carry and none of them defaultable -- inventing one "
478
+ f"would silently pick a side. "
479
+ + _v35_stage_route("3", "image processing"),
480
+ file=sys.stderr)
481
+ return 2
482
+ try:
483
+ chosen = lookup_profile(args.profile)
484
+ except KeyError as exc:
485
+ print(f"arrayprobe imgproc: {exc.args[0]}", file=sys.stderr)
486
+ return 2
487
+ # The library's own rule (imgproc.py): the TAS file is needed only when the profile builds
488
+ # Time_in_seconds from it AND the probe reads it (probetype 2); a PIP or CIP run under the same
489
+ # profile needs none. Checking the profile alone refused the documented PECAN PIP tour.
490
+ needs_tas = (chosen.time_in_seconds_from_tas
491
+ and imgproc_module.imgproc_config(args.probename).needs_tas_file)
492
+ if needs_tas and args.tas_file is None:
493
+ # Checked here so the refusal names the flag; the library's own ValueError names its
494
+ # keyword (`tas_file=`), which a command-line user cannot type.
495
+ print(f"arrayprobe imgproc: --profile {args.profile} builds Time_in_seconds from the "
496
+ f"aircraft TAS file (imgProc_sm.m:183-185); pass --tas-file", file=sys.stderr)
497
+ return 2
498
+ written = imgproc_module.imgproc_sm(
499
+ args.infile, args.outfile, args.probename, args.n, args.every,
500
+ args.projectname,
501
+ profile=lookup_profile(args.profile),
502
+ iRectEllipse=args.i_rect_ellipse,
503
+ iCalcAllDiodeStats=args.i_calc_all_diode_stats,
504
+ tas_file=args.tas_file,
505
+ )
506
+ print(f"wrote {written} particles to {args.outfile}")
507
+ _stamp([args.outfile], engine=args.engine, stage="S3", profile=args.profile,
508
+ extra={"probe": args.probename, "n": str(args.n), "every": str(args.every),
509
+ "iRectEllipse": str(args.i_rect_ellipse),
510
+ "iCalcAllDiodeStats": str(args.i_calc_all_diode_stats),
511
+ "tas_file": Path(args.tas_file).name if args.tas_file else "<none>"})
512
+ return 0
513
+
514
+
515
+ def _add_sizedist(sub: argparse._SubParsersAction) -> None:
516
+ p = sub.add_parser(
517
+ "sizedist",
518
+ help="compute one-second size distributions from a proc file (sizeDist) on the "
519
+ "v3.1.4 validation engine, which this distribution does not include; use "
520
+ "`arrayprobe run`",
521
+ description="Compute one-second size distributions from a proc file (sizeDist) on "
522
+ "the v3.1.4 validation engine, which this distribution does not include. "
523
+ "To process data on the default engine, v3.5, use `arrayprobe run "
524
+ "<config.toml>`; to run a "
525
+ "single stage there, use [run].stages in the config.",
526
+ )
527
+ p.add_argument("infile", help="proc file (imgproc's output)")
528
+ p.add_argument("outfile")
529
+ p.add_argument("--tas-csv", required=True,
530
+ help="the .tas.csv sidecar written alongside the "
531
+ "decoded image file (read-binary --format spec)")
532
+ p.add_argument("probename")
533
+ p.add_argument("d_choice", type=int)
534
+ p.add_argument("sa_method", type=int)
535
+ p.add_argument("pres", type=float, help="pressure, Pa, applied uniformly")
536
+ p.add_argument("temp", type=float, help="temperature, C, applied uniformly")
537
+ p.add_argument("projectname")
538
+ p.add_argument("ddate", help="'YYYYMMDD HHMMSS'")
539
+ p.add_argument("--iat-file", default=None,
540
+ help="inter-arrival threshold file (sizeDist's optional "
541
+ "twelfth argument). Passing nothing is NOT the same "
542
+ "as passing a name that does not exist -- see "
543
+ "sizedist.run's own docstring.")
544
+ p.add_argument("--tree", required=True, choices=("stock", "production"),
545
+ help="which sizeDist.m lineage's project/probe switch and "
546
+ "reject thresholds to use -- no default, the two "
547
+ "disagree on whether the 2D-S applies shattering "
548
+ "identification at all. NOTE: this selects those "
549
+ "TABLES, not the whole lineage's control flow, which "
550
+ "is the production one throughout. See README's "
551
+ "'Known gaps' for the two measured places that "
552
+ "matters.")
553
+ _add_stage_engine(p)
554
+ p.set_defaults(func=_run_sizedist)
555
+
556
+
557
+ def _run_sizedist(args: argparse.Namespace) -> int:
558
+ import numpy as np
559
+
560
+ if _stage_engine(args) == "3.5":
561
+ print("arrayprobe sizedist --engine 3.5: not wired here. v3.5's sizeDist takes three "
562
+ "output switches and no --tree (one source tree), each a fidelity choice this "
563
+ "command's flags do not carry. "
564
+ + _v35_stage_route("4", "the size distribution"), file=sys.stderr)
565
+ return 2
566
+
567
+ timehhmmss, tas = load_tas_info(args.tas_csv)
568
+ varargin = (args.iat_file,) if args.iat_file else ()
569
+ sizedist_module.run(
570
+ args.infile, args.outfile, tas, np.floor(timehhmmss), args.probename,
571
+ args.d_choice, args.sa_method,
572
+ np.full_like(tas, args.pres), np.full_like(tas, args.temp),
573
+ args.projectname, args.ddate, *varargin,
574
+ tree=args.tree,
575
+ )
576
+ print(f"wrote {args.outfile}")
577
+ _stamp([args.outfile], engine="3.1.4", stage="S4", profile=None,
578
+ extra={"probe": args.probename, "tree": args.tree,
579
+ "d_choice": str(args.d_choice), "sa_method": str(args.sa_method),
580
+ "iat_file": Path(args.iat_file).name if args.iat_file else "<none>",
581
+ "proc": Path(args.infile).name})
582
+ return 0
583
+
584
+
585
+ def _add_combine(sub: argparse._SubParsersAction) -> None:
586
+ p = sub.add_parser(
587
+ "combine",
588
+ help="stitch a flight's sd files into one product (combine_sizedist)",
589
+ )
590
+ p.add_argument("sd_files", nargs="+",
591
+ help="sd files, IN ORDER (see combine_sizedist's own "
592
+ "docstring -- order is a contract, not a convenience)")
593
+ p.add_argument("outfile")
594
+ p.add_argument("--flight-date", required=True, help="'YYYYMMDD', full year")
595
+ p.add_argument("--summary-time", required=True,
596
+ help="'YY_MM_DD_HH_MM_SS', the campaign summary file's own "
597
+ "basename")
598
+ _add_stage_engine(p)
599
+ p.add_argument("--borrowed-combine", action="store_true",
600
+ help="with --engine 3.5 only, and required there: opt in to a campaign "
601
+ "fork's combine_sizedist over v3.5 sd files. No stock UIOOPS release "
602
+ "ships a combine step, so on 3.5 it is borrowed and off by default.")
603
+ p.set_defaults(func=_run_combine)
604
+
605
+
606
+ def _run_combine(args: argparse.Namespace) -> int:
607
+ engine = _stage_engine(args)
608
+ if engine == "3.5":
609
+ if not args.borrowed_combine:
610
+ print("arrayprobe combine --engine 3.5 needs --borrowed-combine: no stock UIOPS "
611
+ "release ships a combine step, so on v3.5 a campaign fork's is borrowed, "
612
+ "opt-in and off by default. Nothing was written.", file=sys.stderr)
613
+ return 2
614
+ import uiops # local, as in _run_imgproc
615
+
616
+ uiops.engine("3.5").get("combine", "combine_sizedist")(
617
+ args.sd_files, args.outfile,
618
+ flight_date=args.flight_date, summary_time=args.summary_time,
619
+ borrowed_combine=True,
620
+ )
621
+ elif args.borrowed_combine:
622
+ print("arrayprobe combine: --borrowed-combine applies to --engine 3.5 only; on 3.1.4 "
623
+ "the fork's combine is the port's own.", file=sys.stderr)
624
+ return 2
625
+ else:
626
+ combine_module.combine_sizedist(
627
+ args.sd_files, args.outfile,
628
+ flight_date=args.flight_date, summary_time=args.summary_time,
629
+ )
630
+ print(f"wrote {args.outfile}")
631
+ # combine_sizedist.m is FORK_ONLY (uiops.CATALOGUE): it exists in no stock UIOOPS release,
632
+ # so the engine named here is the port that ran, arrayprobe's.
633
+ extra = {"flight_date": args.flight_date, "summary_time": args.summary_time,
634
+ "inputs": ",".join(Path(p).name for p in args.sd_files),
635
+ "catalogue": "fork-only"}
636
+ if engine == "3.5":
637
+ extra["borrowed_combine"] = "1"
638
+ _stamp([args.outfile], engine=engine, stage="S4c", profile=None, extra=extra)
639
+ return 0
640
+
641
+
642
+ def _add_intarr(sub: argparse._SubParsersAction) -> None:
643
+ p = sub.add_parser(
644
+ "intarr-threshold",
645
+ help="per-particle inter-arrival thresholds (IntArrAnalysis_time)",
646
+ description="Fit each population of inter-arrival times and write the threshold file "
647
+ "sizeDist accepts as its optional twelfth argument. NOTE: the "
648
+ "production call behind the archived products this port is validated "
649
+ "against passed a threshold file that does not exist, so nothing in them "
650
+ "depends on this stage.",
651
+ )
652
+ p.add_argument("proc_file", help="a per-particle file (proc.*.nc) or a combined one")
653
+ p.add_argument("outfile", help="threshold .cdf for sizeDist's optional twelfth argument")
654
+ p.add_argument("--probe", required=True, help="probe name, e.g. 2DS")
655
+ p.add_argument("--flight-date", required=True, help="'YYYYMMDD', full year")
656
+ p.add_argument("--blocks", type=int, default=5,
657
+ help="number of populations to split the file into (the source's fileNum); "
658
+ "the block size is derived from it exactly as IntArrAnalysis_time does")
659
+ p.add_argument("--extra-thresholds-json", default=None,
660
+ help="opt-in: write the two thresholds the source computes but never writes "
661
+ "(threshold, threshold_ww) to this JSON sidecar, never a netCDF file "
662
+ "(arrayprobe.intarr_analysis.write_extra_thresholds_sidecar)")
663
+ p.add_argument("--plot", default=None,
664
+ help="opt-in: render IntArrAnalysis_time.m's contour figure "
665
+ "(arrayprobe.intarr_plots.plot_intarr_contour) to this image path "
666
+ "(matplotlib; requires the scipy/matplotlib extras)")
667
+ p.add_argument("--fix-b8", action="store_true",
668
+ help="with --plot: use the corrected time axis instead of reproducing "
669
+ "the original's NaN gaps before 10:00:00 (a defect in the original "
670
+ "time axis)")
671
+ p.add_argument("--mat-workspace", default=None,
672
+ help="opt-in: write IntArrAnalysis_time.m's :331 workspace dump "
673
+ "(arrayprobe.intarr_analysis.write_mat_workspace) to this .mat path "
674
+ "(requires the scipy extra)")
675
+ p.set_defaults(func=_run_intarr)
676
+
677
+
678
+ def _run_intarr(args: argparse.Namespace) -> int:
679
+ import netCDF4
680
+
681
+ from . import intarr_analysis
682
+
683
+ try:
684
+ with netCDF4.Dataset(args.proc_file) as d:
685
+ times = np.asarray(d.variables["Time"][:], dtype=float).reshape(-1)
686
+ seconds = np.asarray(d.variables["Time_in_seconds"][:], dtype=float).reshape(-1)
687
+ # Read only when an opt-in output needs them, so the default call
688
+ # touches exactly the variables it always did.
689
+ need_extras = args.plot or args.mat_workspace
690
+ dates = (np.asarray(d.variables["Date"][:], dtype=float).reshape(-1)
691
+ if need_extras else None)
692
+ dmax = (np.asarray(d.variables["image_diam_minR"][:], dtype=float).reshape(-1)
693
+ if args.mat_workspace else None)
694
+ except FileNotFoundError:
695
+ raise # main()'s handler prints "arrayprobe intarr-threshold: No such file ..."
696
+ except OSError as exc:
697
+ print(f"arrayprobe intarr-threshold: {args.proc_file} is not a readable netCDF "
698
+ f"file: {exc}", file=sys.stderr)
699
+ return 2
700
+ except KeyError as exc:
701
+ print(f"arrayprobe intarr-threshold: {args.proc_file} has no variable {exc}; pass "
702
+ f"the proc file the image-processing stage wrote", file=sys.stderr)
703
+ return 2
704
+ arr = intarr_analysis.inter_arrival(seconds)
705
+ result = intarr_analysis.analyse(arr, times, n_blocks=args.blocks)
706
+ intarr_analysis.write_threshold_file(
707
+ args.outfile, times, result["threshold_ak"],
708
+ probename=args.probe, flight_date=args.flight_date,
709
+ data_source=os.path.basename(args.proc_file),
710
+ population_size=result["population_size"],
711
+ )
712
+ print(f"wrote {args.outfile} "
713
+ f"({result['block_starts'].size} population(s) of {result['population_size']})")
714
+
715
+ if args.extra_thresholds_json:
716
+ intarr_analysis.write_extra_thresholds_sidecar(
717
+ args.extra_thresholds_json, times, result["threshold"], result["threshold_ww"],
718
+ threshold_ak=result["threshold_ak"])
719
+ print(f"wrote {args.extra_thresholds_json}")
720
+
721
+ if args.plot:
722
+ import matplotlib.pyplot as plt
723
+
724
+ from . import intarr_plots
725
+ fig, _ax = intarr_plots.plot_intarr_contour(
726
+ arr, times, dates, result["threshold"], result["threshold_ww"],
727
+ result["threshold_ak"], population_size=result["population_size"],
728
+ date_string=args.flight_date, fix_b8=args.fix_b8)
729
+ fig.savefig(args.plot)
730
+ plt.close(fig)
731
+ print(f"wrote {args.plot}")
732
+
733
+ if args.mat_workspace:
734
+ intarr_analysis.write_mat_workspace(
735
+ args.mat_workspace, timehhmmss=times, date=dates, time_in_seconds=seconds,
736
+ dmax=dmax, probe_name=args.probe, date_string=args.flight_date,
737
+ infile=os.path.basename(args.proc_file), n_blocks=args.blocks)
738
+ print(f"wrote {args.mat_workspace}")
739
+
740
+ return 0
741
+
742
+
743
+ def _compare(args) -> int:
744
+ """``arrayprobe compare`` -- the comparison handler.
745
+
746
+ Moved verbatim on 2026-09-10 rather than reimplemented, so there
747
+ is one copy. Two copies of an acceptance rule is two places for it to
748
+ drift, and this particular rule is one the tool's own comments call out as
749
+ easy to get wrong.
750
+ """
751
+ # The console on Windows defaults to cp1252 and would raise on any
752
+ # non-ASCII byte the report contains. Done here rather than at import so
753
+ # importing the CLI never has a side effect on someone else's stdout.
754
+ try:
755
+ # `type: ignore` because sys.stdout is only TextIO to mypy, and
756
+ # `reconfigure` is TextIOWrapper-only -- which is exactly why
757
+ # this is wrapped in a try at all.
758
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
759
+ except (AttributeError, ValueError): # pragma: no cover -- odd stdout
760
+ pass
761
+
762
+ if args.classes:
763
+ for key, tc in compare_module.CLASSES.items():
764
+ proc = sorted(n for n, c in compare_module.PROC_CLASSES.items()
765
+ if c == key)
766
+ sd = sorted(n for n, c in compare_module.SD_CLASSES.items()
767
+ if c == key)
768
+ print(f"{key} {tc.name} "
769
+ f"({'asserts' if tc.asserts else 'informational'})")
770
+ print(f" {tc.rule}")
771
+ print(f" proc-file variables: {', '.join(proc) if proc else '-'}")
772
+ print(f" sizeDist variables : {', '.join(sd) if sd else '-'}")
773
+ print()
774
+ return 0
775
+
776
+ for path in (args.left, args.right):
777
+ if not os.path.isfile(path):
778
+ print(f"not a file: {path}", file=sys.stderr)
779
+ return 2
780
+
781
+ # The kind is read out of the file's dimensions, never out of its name --
782
+ # the S2 rule that a filename is not evidence. Only these refusals sit in
783
+ # the try: reading each file's kind opens it (the right-hand one included),
784
+ # so a file that is not netCDF, or two files of different kinds, is one line
785
+ # and exit 2. An error raised inside the comparison itself propagates with
786
+ # its traceback, so an internal defect is never reported as bad input.
787
+ try:
788
+ kind = compare_module.file_kind(args.left)
789
+ kind_right = compare_module.file_kind(args.right)
790
+ if kind != kind_right:
791
+ raise ValueError(f"cannot compare a {kind} file against a {kind_right} file: "
792
+ f"{args.left} vs {args.right}")
793
+ except ValueError as exc:
794
+ print(exc, file=sys.stderr)
795
+ return 2
796
+ except OSError as exc:
797
+ # netCDF4 raises OSError (errno -51) for a file that is not netCDF; the
798
+ # isfile check above has already ruled out a missing path.
799
+ print(f"arrayprobe compare: not a readable netCDF file: {exc}", file=sys.stderr)
800
+ return 2
801
+ # A file whose header opens but whose variable data does not (a corrupt
802
+ # netCDF4/HDF5 chunk) fails only here: netCDF4 raises RuntimeError ("NetCDF:
803
+ # HDF error") for a failed variable read, OSError only for a failed open.
804
+ # Either is bad input: one line and exit 2. A ValueError from inside the
805
+ # comparison is an internal defect and keeps its traceback, and so do the two
806
+ # RuntimeError subclasses that only a defect raises. (A truncated netCDF4 file
807
+ # never gets this far: HDF5 refuses it at open, above.)
808
+ try:
809
+ report = compare_module.compare_files(args.left, args.right)
810
+ except (NotImplementedError, RecursionError):
811
+ raise
812
+ except (OSError, RuntimeError) as exc:
813
+ print(f"arrayprobe compare: not a readable netCDF file: {exc}", file=sys.stderr)
814
+ return 2
815
+ print(f"kind : {kind} file\n")
816
+
817
+ # Acceptance is ALWAYS computed over the whole file, before any --var
818
+ # filtering. Otherwise `--var image_auto_reject` -- a class E variable that
819
+ # never asserts -- reports ACCEPTED: True while forty other variables went
820
+ # unexamined, which is the precise kind of report this exists to stop
821
+ # anyone writing.
822
+ accepted = report.accepted(min_join=args.min_join)
823
+
824
+ wanted = None
825
+ if args.var:
826
+ wanted = set(args.var)
827
+ unknown = wanted - {v.name for v in report.variables}
828
+ if unknown:
829
+ print(f"no such variable(s): {', '.join(sorted(unknown))}",
830
+ file=sys.stderr)
831
+ return 2
832
+ report.variables = [v for v in report.variables if v.name in wanted]
833
+
834
+ print(compare_module.format_report(
835
+ report, verbose=args.verbose or bool(args.var), accepted=accepted))
836
+ if wanted:
837
+ print(f"\n (the table above is filtered to "
838
+ f"{len(wanted)} variable(s); "
839
+ "the verdict above it is for the WHOLE file)")
840
+ return 0 if accepted else 1
841
+
842
+
843
+ def _add_compare(sub: argparse._SubParsersAction) -> None:
844
+ p = sub.add_parser(
845
+ "compare",
846
+ help="join two output files on particle identity, then diff by "
847
+ "tolerance class",
848
+ description="Read the join block first, always. A value difference "
849
+ "reported against a bad join is an artefact of the "
850
+ "alignment, not a finding, and the two are "
851
+ "indistinguishable once you are looking at a column of "
852
+ "numbers. Exit status is 0 when the comparison is "
853
+ "ACCEPTED (>=--min-join join, no failure in an asserting "
854
+ "tolerance class, no unclassified variable, no duplicate "
855
+ "join keys) and 1 otherwise, so it can gate a run without "
856
+ "anyone reading the output; 2 is a usage or file error.",
857
+ )
858
+ p.add_argument("left", nargs="?", help="the file under test (usually ours)")
859
+ p.add_argument("right", nargs="?", help="the reference file")
860
+ p.add_argument("-v", "--verbose", action="store_true",
861
+ help="list bit-exact variables too, not only the differing ones")
862
+ p.add_argument("--var", action="append", default=None, metavar="NAME",
863
+ help="restrict the value comparison to these variables "
864
+ "(repeatable); the join is always computed in full")
865
+ p.add_argument("--classes", action="store_true",
866
+ help="print the tolerance classes and what each one means, "
867
+ "then exit")
868
+ p.add_argument("--min-join", type=float, default=0.999,
869
+ help="join fraction required for acceptance (default 0.999)")
870
+ p.set_defaults(func=_compare)
871
+
872
+
873
+ def _gallery(args) -> int:
874
+ """``arrayprobe gallery`` -- render one flight's particle gallery to disk.
875
+
876
+ Moved 2026-09-10, script kept as a shim. Same reasoning as ``compare``:
877
+ the rendering engine was always in the package, but nothing in
878
+ ``arrayprobe --help`` said the package could render a flight at all.
879
+ """
880
+ import json
881
+ import time
882
+
883
+ import netCDF4
884
+
885
+ from arrayprobe_uiops.decode_naming import decode_path
886
+
887
+ # The decode is named from the proc file's own stamp (engine and reader together),
888
+ # never from which file exists; no stamp reads as v3.1.4, as the triage server does.
889
+ proc_path = os.path.join(args.decoded_dir, f"proc.{args.flight}.nc")
890
+ if not os.path.exists(proc_path):
891
+ print(f"missing input: {proc_path}; --decoded-dir {args.decoded_dir} must hold the "
892
+ f"decoded proc.{args.flight}.nc (pass the folder the decode wrote)",
893
+ file=sys.stderr)
894
+ return 2
895
+ try:
896
+ image_path = str(decode_path(proc_path, assume_engine="3.1.4"))
897
+ except ValueError as exc:
898
+ print(f"--flight must be <stem>.<channel>: {exc}", file=sys.stderr)
899
+ return 2
900
+ if not os.path.exists(image_path):
901
+ print(f"missing input: {image_path}", file=sys.stderr)
902
+ return 2
903
+
904
+ verdict_path = os.path.join(args.decoded_dir, "triage_verdicts",
905
+ f"{args.flight}.json")
906
+ verdicts = {}
907
+ if os.path.exists(verdict_path):
908
+ with open(verdict_path, encoding="utf-8") as fh:
909
+ verdicts = json.load(fh)
910
+ print(f"verdicts: {len(verdicts)} human labels from "
911
+ f"{verdict_path if verdicts else '(none on disk)'}", flush=True)
912
+
913
+ out_dir = os.path.join(args.out, args.flight)
914
+ started = time.time()
915
+
916
+ def progress(done, total, counts):
917
+ rate = done / max(time.time() - started, 1e-9)
918
+ left = (total - done) / rate if rate else 0
919
+ print(f" {done}/{total} ({100 * done / total:.1f}%) "
920
+ f"{rate:.0f}/s eta {left / 60:.1f} min {counts}", flush=True)
921
+
922
+ with netCDF4.Dataset(image_path) as image_ds:
923
+ with netCDF4.Dataset(proc_path) as proc_ds:
924
+ counts = render_module.render_flight_to_disk(
925
+ image_ds, proc_ds, out_dir, verdicts=verdicts,
926
+ classes=tuple(args.classes), scale=args.scale,
927
+ crop=not args.no_crop, limit=args.limit, progress=progress)
928
+
929
+ print(f"done in {(time.time() - started) / 60:.1f} min: {counts}", flush=True)
930
+ if not args.no_index:
931
+ pages = render_module.write_flight_index(out_dir, title=args.flight)
932
+ print(f"wrote {len(pages)} index pages; "
933
+ f"open {os.path.join(out_dir, 'index.html')}", flush=True)
934
+ return 0
935
+
936
+
937
+ def _inventory(args: argparse.Namespace) -> int:
938
+ from arrayprobe import inventory as inventory_module
939
+ if not Path(args.dir).exists():
940
+ print(f"arrayprobe inventory: {args.dir}: no such file or directory", file=sys.stderr)
941
+ return 2
942
+ rows = inventory_module.inventory(args.dir, fmt=args.format)
943
+ jpath, cpath = inventory_module.write_inventory(rows, args.out)
944
+ flagged = sum(1 for r in rows if r.get("empty") or r.get("truncated"))
945
+ print(f"{len(rows)} raw files, {flagged} flagged empty or truncated; "
946
+ f"wrote {jpath} and {cpath}")
947
+ return 0
948
+
949
+
950
+ def _add_inventory(sub: argparse._SubParsersAction) -> None:
951
+ p = sub.add_parser(
952
+ "inventory",
953
+ help="list raw files with size, SHA-256 and empty/truncated flags (JSON + CSV)",
954
+ description="Reads raw bytes only; writes <out>.json and <out>.csv, one row per "
955
+ "file. Computes no product and changes nothing.",
956
+ )
957
+ p.add_argument("dir", help="directory of raw files (or one file)")
958
+ p.add_argument("--out", required=True,
959
+ help="output stem; writes <stem>.json and <stem>.csv")
960
+ p.add_argument("--format", default=None, choices=["spec", "dmt", "pms_2d"],
961
+ help="record format for every file (default: guessed per file)")
962
+ p.set_defaults(func=_inventory)
963
+
964
+
965
+ def _check_counts(args: argparse.Namespace) -> int:
966
+ """Reconcile an sd product's binned counts with its proc file, second by second.
967
+
968
+ Read only. Exit 0 when every second's residual is within ``--tolerance``
969
+ (default 0, exact), 1 otherwise. The probe's own housekeeping total is not
970
+ written by any reader this package ships, so that line reads "not available".
971
+ """
972
+ import json
973
+
974
+ from arrayprobe.count_closure import NOT_AVAILABLE, count_closure
975
+ r = count_closure(args.sd, args.proc)
976
+ tol = float(args.tolerance)
977
+ differing = 0
978
+ for t, b, a, d in zip(r["time"], r["binned_per_second"], r["accepted_per_second"],
979
+ r["residual_per_second"], strict=True):
980
+ if abs(float(d)) > tol:
981
+ differing += 1
982
+ print(f"{t:g} binned={float(b):g} accepted={int(a)} residual={float(d):+g}")
983
+ for e in r["excluded"]:
984
+ print(f"excluded particle {e['index'] + 1} at {e['time']:g}: {e['cause']}")
985
+ if differing == 0:
986
+ print(f"closure: exact ({r['total_accepted']} accepted of {r['total_in_proc']} "
987
+ f"particles, {r['total_binned']:g} binned)")
988
+ else:
989
+ print(f"closure: {differing} seconds differ (residual {r['residual']:+g})")
990
+ probe = r["probe_reported"]
991
+ print(f"probe_reported: {NOT_AVAILABLE if probe is None else probe}")
992
+ if args.out:
993
+ payload = {k: (v.tolist() if hasattr(v, "tolist") else v) for k, v in r.items()}
994
+ payload["differing_seconds"] = differing
995
+ payload["tolerance"] = tol
996
+ with open(args.out, "w", encoding="utf-8") as fh:
997
+ json.dump(payload, fh, indent=2)
998
+ print(f"wrote {args.out}")
999
+ return 0 if differing == 0 else 1
1000
+
1001
+
1002
+ def _add_check_counts(sub: argparse._SubParsersAction) -> None:
1003
+ p = sub.add_parser(
1004
+ "check-counts",
1005
+ help="reconcile a size-distribution file's binned counts with its particle file, "
1006
+ "second by second, naming the cause of every excluded particle",
1007
+ description="Reads the sd and proc files only and writes nothing but --out. "
1008
+ "Prints every second whose binned count differs from the accepted "
1009
+ "particle count, each excluded particle with its cause, a closure "
1010
+ "line and the probe's own reported total (not available until a "
1011
+ "reader writes it). Exit 0 when closure is exact, 1 otherwise.",
1012
+ )
1013
+ p.add_argument("sd", help="size-distribution netCDF (its .call sidecar beside it)")
1014
+ p.add_argument("proc", help="the per-particle netCDF the sd file was made from")
1015
+ p.add_argument("--out", default=None, help="write the full reconciliation as JSON")
1016
+ p.add_argument("--tolerance", default=0.0, type=float,
1017
+ help="largest per-second residual still counted as closed (default 0)")
1018
+ p.set_defaults(func=_check_counts)
1019
+
1020
+
1021
+ def _add_gallery(sub: argparse._SubParsersAction) -> None:
1022
+ p = sub.add_parser(
1023
+ "gallery",
1024
+ help="render a whole flight's particles to disk, with index pages",
1025
+ description="Visualisation only -- it reads a decoded file and its "
1026
+ "proc file and writes images; it computes nothing and "
1027
+ "changes nothing.",
1028
+ )
1029
+ p.add_argument("--decoded-dir", required=True,
1030
+ help="directory holding <flight>.cdf and proc.<flight>.nc")
1031
+ p.add_argument("--flight", required=True,
1032
+ help="flight stem including the channel, e.g. "
1033
+ "base170817073523.H")
1034
+ p.add_argument("--out", required=True,
1035
+ help="output root; a <flight>/ subdirectory is created "
1036
+ "under it")
1037
+ p.add_argument("--classes", nargs="+", default=["accepted"],
1038
+ choices=render_module.PARTICLE_CLASSES,
1039
+ help="which classes to write (default: accepted only, which "
1040
+ "keeps a large flight's gallery a manageable size)")
1041
+ p.add_argument("--scale", type=int, default=3, help="pixel scale (default 3)")
1042
+ p.add_argument("--no-crop", action="store_true",
1043
+ help="keep the full diode-search window instead of cropping "
1044
+ "to the particle. The window can vastly exceed the "
1045
+ "shadow right after a record reset, which is why "
1046
+ "cropping is the default")
1047
+ p.add_argument("--limit", type=int, default=None,
1048
+ help="stop after N particles")
1049
+ p.add_argument("--no-index", action="store_true",
1050
+ help="skip the index pages")
1051
+ p.set_defaults(func=_gallery)
1052
+
1053
+
1054
+ def _triage(args) -> int:
1055
+ # `Path.resolve()`, not `os.path.abspath`: `run` is annotated for a Path
1056
+ # and, on Windows, only resolve() expands an 8.3 short path -- so abspath
1057
+ # would hand the server a directory string that differs from the one every
1058
+ # other part of the tool prints and stores verdicts under.
1059
+ queue = Path(args.queue_file) if args.queue_file else None
1060
+ if not Path(args.decoded_dir).is_dir():
1061
+ print(f"arrayprobe triage: --decoded-dir {args.decoded_dir} is not a directory; "
1062
+ "point it at the folder holding the decoded proc.*.nc files", file=sys.stderr)
1063
+ return 2
1064
+ triage_module.run(Path(args.decoded_dir).resolve(), args.port, queue, args.reviewer,
1065
+ accept_unstamped=args.accept_unstamped,
1066
+ met_dir=Path(args.met_dir) if args.met_dir else None,
1067
+ state_file=Path(args.state_file) if args.state_file else None,
1068
+ state_var=args.state_var,
1069
+ run_root=Path(args.run_root).resolve() if args.run_root else None)
1070
+ return 0
1071
+
1072
+
1073
+ _STAMP = re.compile(r"(\d{6})(\d{6})\.([HV])[._]")
1074
+
1075
+
1076
+ def _add_diode_masks(sub: argparse._SubParsersAction) -> None:
1077
+ p = sub.add_parser(
1078
+ "diode-masks",
1079
+ help="find the stuck diodes in first-pass proc files (find_shadow_diodes.m) "
1080
+ "and show the per-diode occupancy beside them",
1081
+ description="Runs masks.find_shadow_diodes -- a field-campaign fork's "
1082
+ "find_shadow_diodes.m, bug for bug -- on each --proc, writing "
1083
+ "the diode.<date><time>.<or>[empty].mat MATLAB writes (an upstream defect: an "
1084
+ "empty result is named ...<or>empty.mat, which the second pass "
1085
+ "never loads) and nothing else. Beside it, prints bin_stats and, "
1086
+ "when --image is given, diode_report's occupancy and SPEC's "
1087
+ "noisy-diode flags. The mask reaches a second pass only when "
1088
+ "the diodes are declared in [run].diode_masks AND the run is "
1089
+ "given --diode-corrected.",
1090
+ )
1091
+ p.add_argument("--proc", action="append", required=True, type=Path,
1092
+ help="a first-pass proc file; repeat for several")
1093
+ p.add_argument("--image", action="append", type=Path, default=None,
1094
+ help="the decoded image .cdf for the matching --proc, in the "
1095
+ "same order; enables the occupancy / SPEC view")
1096
+ p.add_argument("--date", help="'YYMMDD'; default: parsed from the proc name")
1097
+ p.add_argument("--time", help="'HHMMSS'; default: parsed from the proc name")
1098
+ p.add_argument("--orientation", choices=("H", "V"),
1099
+ help="default: parsed from the proc name")
1100
+ p.add_argument("--out-dir", type=Path, default=None,
1101
+ help="where the .mat goes; default the proc's own directory "
1102
+ "(MATLAB's `path`, which it both reads from and saves to)")
1103
+ p.add_argument("--no-write", action="store_true",
1104
+ help="report only; write no .mat")
1105
+ p.add_argument("--profile", default=None, metavar="NAME",
1106
+ help=("the v3.1.4 fidelity profile, when the proc file's stamp names none "
1107
+ "(it decides whether bin_stats counts lit or shadowed slices)"
1108
+ if _v314_engine_present() else
1109
+ "the fidelity profile, when the proc file's stamp names none "
1110
+ "(it decides whether bin_stats counts lit or shadowed slices)"))
1111
+ p.add_argument("--probe", default=None, metavar="NAME",
1112
+ help="the probe whose image_slice_offset enters S for a shadow count")
1113
+ p.set_defaults(func=_run_diode_masks)
1114
+
1115
+
1116
+ def _run_diode_masks(args: argparse.Namespace) -> int:
1117
+ from . import diode_report
1118
+ from . import masks as masks_module
1119
+ from .tune import diodes as tune_diodes
1120
+
1121
+ images = args.image or []
1122
+ if images and len(images) != len(args.proc):
1123
+ print("arrayprobe diode-masks: give one --image per --proc, or none",
1124
+ file=sys.stderr)
1125
+ return 2
1126
+ status = 0
1127
+ for i, proc in enumerate(args.proc):
1128
+ stamp = _STAMP.search(proc.name)
1129
+ date = args.date or (stamp.group(1) if stamp else None)
1130
+ time_ = args.time or (stamp.group(2) if stamp else None)
1131
+ orientation = args.orientation or (stamp.group(3) if stamp else None)
1132
+ if not (date and time_ and orientation):
1133
+ print(f"arrayprobe diode-masks: cannot read <date><time>.<H|V> from "
1134
+ f"{proc.name}; pass --date, --time and --orientation", file=sys.stderr)
1135
+ return 2
1136
+ out_dir = args.out_dir or proc.parent
1137
+ print(f"== {proc} (date {date}, time {time_}, orientation {orientation})")
1138
+ # Polarity is read exactly as `tune diodes` reads it (one helper, no second copy).
1139
+ try:
1140
+ conv = tune_diodes.counting_convention(proc, args.profile)
1141
+ find_kw: dict = {}
1142
+ if conv["shadowed"]:
1143
+ bs, _ = tune_diodes._read(proc)
1144
+ offset, _src = tune_diodes.slice_offset(bs.size, args.probe)
1145
+ total = tune_diodes.position_slice_total(proc, offset)
1146
+ if total is None:
1147
+ raise tune_diodes.DiodeReportError(
1148
+ f"{proc.name}: a shadow count needs the proc file's position "
1149
+ "to compute S")
1150
+ find_kw = {"counts": "shadowed", "slice_total": int(total)}
1151
+ except (ValueError, KeyError, OSError) as exc:
1152
+ print(f"arrayprobe diode-masks: {exc}", file=sys.stderr)
1153
+ return 2
1154
+ try:
1155
+ found = masks_module.find_shadow_diodes(
1156
+ date, time_, orientation, path=str(out_dir) + "/", infile=proc,
1157
+ write=not args.no_write, **find_kw)
1158
+ except masks_module.ShadowDiodeSearchError as exc:
1159
+ print(f" find_shadow_diodes: {exc}")
1160
+ status = 1
1161
+ continue
1162
+ a = found.bin_stats.astype(float)
1163
+ kind = ("shadowed-slice count per diode, converted to lit"
1164
+ if conv["shadowed"] else "lit-slice count per diode")
1165
+ print(f" bin_stats ({kind}): {a.size} diodes, "
1166
+ f"mean {a.mean():.1f}, min {a.min():.0f} (diode {int(a.argmin()) + 1}), "
1167
+ f"max {a.max():.0f} (diode {int(a.argmax()) + 1})")
1168
+ if found.ill_diode.size:
1169
+ print(f" over 1.2 x mean (masked in flight, replaced): "
1170
+ f"{found.ill_diode.astype(int).tolist()}")
1171
+ rule = "0.80 x mean" if found.branch == "mean" else "0.80 x max"
1172
+ print(f" find_shadow_diodes: stuck = below {rule} = {found.threshold:g}")
1173
+ print(f" shadow_diode (1-based): {found.shadow_diode.astype(int).tolist()}")
1174
+ if found.written is not None:
1175
+ note = (" <- F2: this name is never loaded; an empty mask is inert"
1176
+ if not found.shadow_diode.size else "")
1177
+ print(f" wrote {found.written}{note}")
1178
+ if images:
1179
+ report = diode_report.report_from_files(images[i], proc)
1180
+ flagged, threshold, mean_count = diode_report.flag_noisy_diodes(report)
1181
+ print(" diode_report: " + report.summary().replace("\n", "\n "))
1182
+ print(f" SPEC noisy-diode test (report only): threshold {threshold:.2f} "
1183
+ f"images over mean {mean_count:.2f}; flagged (1-based): "
1184
+ f"{(flagged + 1).tolist()}")
1185
+ return status
1186
+
1187
+
1188
+ def _add_triage(sub: argparse._SubParsersAction) -> None:
1189
+ p = sub.add_parser(
1190
+ "triage",
1191
+ help="start the particle review and labelling server",
1192
+ description="Manual labelling and visualisation. It writes verdicts "
1193
+ "to <decoded-dir>/triage_verdicts/ and changes no "
1194
+ "computed number. --decoded-dir is required, as it is "
1195
+ "for `python -m arrayprobe.triage_server`.",
1196
+ )
1197
+ p.add_argument("--decoded-dir", required=True,
1198
+ help="directory containing proc.*.H.nc files and their decodes "
1199
+ + ("(*.H.nc from v3.5, *.H.cdf from v3.1.4)"
1200
+ if _v314_engine_present() else "(*.H.nc)"))
1201
+ p.add_argument("--port", type=int, default=8765)
1202
+ p.add_argument("--queue-file", default=None,
1203
+ help="JSON file of named curated particle lists for a "
1204
+ "specific review pass")
1205
+ # Required to save a label, but not `required=True` at startup: refusing to
1206
+ # start would stop a read-only viewer another agent is demoing, so the server
1207
+ # starts and refuses every save with HTTP 400 instead. Not defaulted from
1208
+ # the OS username either -- that would attribute a label to someone who
1209
+ # never said it was theirs, which is worse than recording nothing.
1210
+ p.add_argument("--reviewer", default=os.environ.get(triage_module.REVIEWER_ENV),
1211
+ help="who is labelling; REQUIRED to save labels and recorded "
1212
+ f"with every verdict (or set {triage_module.REVIEWER_ENV}). "
1213
+ "With neither, the server starts but refuses every save "
1214
+ "(HTTP 400) -- the id is never guessed")
1215
+ p.add_argument("--met-dir", default=None,
1216
+ help="folder of ARM AAF merged files (enaaafmergedF1.c1.*.nc); the particle "
1217
+ "page then shows the air temperature at the particle's record time")
1218
+ p.add_argument("--state-file", default=None,
1219
+ help="netCDF state-variable file for the air temperature (any names: the "
1220
+ "temperature is chosen by units and standard_name/long_name, and a "
1221
+ "file with several candidates is refused, listing them). Takes precedence "
1222
+ "over --met-dir. With neither, the index page asks for the file")
1223
+ p.add_argument("--state-var", default=None,
1224
+ help="the temperature variable in --state-file (default: chosen by content)")
1225
+ p.add_argument("--accept-unstamped", action="store_true",
1226
+ help="index products whose provenance is unrecorded. WITHOUT this flag they "
1227
+ "are refused and listed by name on the index page under 'Refused: no "
1228
+ "provenance' -- never silently dropped. Labels attached to a product of "
1229
+ "unknown configuration cannot be traced afterwards. Pass this when you "
1230
+ "know what you are looking at and the stamp is simply absent.")
1231
+ p.add_argument("--run-root", default=None,
1232
+ help="folder whose _runs/ the Run page lists at /runs (default: the output "
1233
+ "folder of the first run launched from /run)")
1234
+ p.set_defaults(func=_triage)
1235
+
1236
+
1237
+ def _triage_recheck(args) -> int:
1238
+ from .review_agreement import recheck_queue
1239
+ data = recheck_queue(Path(args.decoded_dir), args.flight, Path(args.out),
1240
+ fraction=args.fraction, seed=args.seed)
1241
+ about = data["_about"]
1242
+ name = next(k for k in data if not k.startswith("_"))
1243
+ print(f"wrote {args.out}: queue {name}, {about['drawn']} of "
1244
+ f"{about['of_human_labelled']} human-labelled particles (seed {args.seed})")
1245
+ print(f"review it blind: arrayprobe triage --decoded-dir {args.decoded_dir} "
1246
+ f"--queue-file {args.out}")
1247
+ return 0
1248
+
1249
+
1250
+ def _triage_agreement(args) -> int:
1251
+ from .review_agreement import agreement
1252
+ r = agreement(Path(args.decoded_dir), args.flight)
1253
+ if r.n == 0:
1254
+ print(f"{args.flight}: no particle has both a first and a re-check human label yet")
1255
+ return 0
1256
+ kappa = "undefined (one label throughout)" if r.kappa is None else f"{r.kappa:.2f}"
1257
+ print(f"{args.flight}: {r.n} re-checked particles; observed agreement {r.observed:.2f}, "
1258
+ f"chance {r.expected:.2f}, Cohen's kappa {kappa}")
1259
+ width = max(len(x) for x in r.labels)
1260
+ print(" " * (width + 2) + " ".join(f"{x:>{width}}" for x in r.labels) + " (re-check)")
1261
+ for a in r.labels:
1262
+ print(f"{a:>{width}} " + " ".join(f"{r.confusion[a][b]:>{width}}" for b in r.labels))
1263
+ return 0
1264
+
1265
+
1266
+ def _add_triage_agreement(sub: argparse._SubParsersAction) -> None:
1267
+ p = sub.add_parser(
1268
+ "triage-recheck",
1269
+ help="write a blind re-check queue of particles a person already labelled",
1270
+ description="Draws a seeded random fraction of one flight's human labels into a "
1271
+ "queue file whose name starts 'recheck-'. The triage server stores its "
1272
+ "verdicts separately (triage_verdicts/<flight>.recheck.json) and hides "
1273
+ "the first label, so the second is blind. Changes no computed number.",
1274
+ )
1275
+ p.add_argument("--decoded-dir", required=True, help="the directory the triage server uses")
1276
+ p.add_argument("--flight", required=True, help="flight name as the triage server shows it")
1277
+ p.add_argument("--out", required=True, help="queue file to write (JSON)")
1278
+ p.add_argument("--fraction", type=float, default=0.2,
1279
+ help="share of the human-labelled particles to re-show (default 0.2)")
1280
+ p.add_argument("--seed", type=int, default=0, help="random seed, recorded in the file")
1281
+ p.set_defaults(func=_triage_recheck)
1282
+ q = sub.add_parser(
1283
+ "triage-agreement",
1284
+ help="report label agreement (Cohen's kappa) between first and re-check labels",
1285
+ description="Pairs each re-checked particle's first human label with its re-check "
1286
+ "label and prints the observed and chance agreement, Cohen's kappa and "
1287
+ "the confusion matrix.",
1288
+ )
1289
+ q.add_argument("--decoded-dir", required=True, help="the directory the triage server uses")
1290
+ q.add_argument("--flight", required=True, help="flight name as the triage server shows it")
1291
+ q.set_defaults(func=_triage_agreement)
1292
+
1293
+
1294
+ def _add_provenance(sub: argparse._SubParsersAction) -> None:
1295
+ p = sub.add_parser(
1296
+ "provenance",
1297
+ help="what wrote these products, read from their .call sidecars",
1298
+ description="Per file: the engine, profile and stage its stamp records, the stamp's "
1299
+ "format, its link count, and its state -- stamped, unstamped, orphan-stamp "
1300
+ "(a sidecar whose product is gone), in-flight, legacy-json or unparseable. "
1301
+ "A directory expands to every .nc/.cdf in it plus every orphan sidecar. "
1302
+ "Nothing here infers an engine from a date, a filename or a neighbouring "
1303
+ "file: a product whose stamp does not name one is reported as unrecorded, "
1304
+ "which is the true answer. The git revision printed at the end is THIS "
1305
+ "CHECKOUT's, not the product's -- no stamp records the revision that wrote "
1306
+ "it.",
1307
+ )
1308
+ p.add_argument("paths", nargs="+", type=Path, help="products or directories")
1309
+ p.add_argument("--require", action="store_true",
1310
+ help="exit 1 unless every path is 'stamped' -- the form a script wants, and "
1311
+ "the form that makes 'all clear' mean something")
1312
+ p.set_defaults(func=_run_provenance)
1313
+
1314
+
1315
+ def _run_provenance(args: argparse.Namespace) -> int:
1316
+ # A path with neither a file nor a sidecar behind it is a typo, not an unstamped product:
1317
+ # reported as one, a mistyped path printed a table row and exited 0.
1318
+ missing = [str(p) for p in args.paths
1319
+ if not p.exists() and not Path(str(p) + provenance.CALL_SUFFIX).exists()]
1320
+ if missing:
1321
+ print(f"arrayprobe provenance: not found (no file, directory or .call sidecar): "
1322
+ f"{', '.join(missing)}", file=sys.stderr)
1323
+ return 2
1324
+ text, code = provenance.report(args.paths, require=args.require)
1325
+ print(text)
1326
+ return code
1327
+
1328
+
1329
+ def _attributed(args) -> int:
1330
+ """``arrayprobe attributed`` -- the self-describing sibling of a faithful product.
1331
+
1332
+ Delegates to :func:`arrayprobe.attributed_export.main` rather than reimplementing the
1333
+ flag surface, the same way :func:`_make_demo_flight` does, so the subcommand and
1334
+ ``python -m arrayprobe.attributed_export`` cannot drift into accepting different
1335
+ arguments. The module form stays supported and is what ``docs/developer/ATTRIBUTED_EXPORT.md``
1336
+ cites; this is the way in for someone who installed the package and never reads it.
1337
+ """
1338
+ from arrayprobe import attributed_export
1339
+
1340
+ if getattr(args, "layout", "dimensions") == "particles":
1341
+ # Opt-in: one row per particle from a proc file, straight to Parquet; the default
1342
+ # path below is unchanged. The two flags of the default path have no meaning here
1343
+ # and are refused rather than parsed and dropped.
1344
+ if args.accept_unstamped or args.enhancements:
1345
+ print("arrayprobe attributed: --accept-unstamped and --enhancements apply to "
1346
+ "--layout dimensions only; drop them for --layout particles",
1347
+ file=sys.stderr)
1348
+ return 2
1349
+ try:
1350
+ written = attributed_export.export_parquet(args.source, args.out,
1351
+ layout="particles")
1352
+ except (ValueError, ImportError, OSError,
1353
+ attributed_export.AttributedExportError) as exc:
1354
+ print(f"arrayprobe attributed: {exc}", file=sys.stderr)
1355
+ return 2
1356
+ print(f"wrote {written}")
1357
+ return 0
1358
+ argv = [str(args.source)]
1359
+ if args.out is not None:
1360
+ argv.append(str(args.out))
1361
+ if args.accept_unstamped:
1362
+ argv.append("--accept-unstamped")
1363
+ if args.enhancements:
1364
+ argv += ["--enhancements", args.enhancements]
1365
+ return attributed_export.main(argv)
1366
+
1367
+
1368
+ def _add_attributed(sub: argparse._SubParsersAction) -> None:
1369
+ p = sub.add_parser(
1370
+ "attributed",
1371
+ help="write the self-describing sibling of a faithful product",
1372
+ description="Writes a SECOND file beside a faithful product, carrying the same "
1373
+ "values plus the whole .call sidecar and a sourced unit on every "
1374
+ "variable, so a recipient can answer 'where did this number come "
1375
+ "from' from one file. The faithful product is opened READ-ONLY and "
1376
+ "never modified -- it is the byte-comparison artefact and carries no "
1377
+ "attributes because the MATLAB combine step writes none. Every unit "
1378
+ "is quoted from the MATLAB line that writes it; a product shape with "
1379
+ "no sourced unit table is refused by name rather than exported with "
1380
+ "a guess. Design: docs/developer/ATTRIBUTED_EXPORT.md.",
1381
+ )
1382
+ p.add_argument("source", help="the faithful product (its .call sidecar is read too)")
1383
+ p.add_argument("out", nargs="?", default=None,
1384
+ help="output path (default: <source>.attributed.nc)")
1385
+ p.add_argument("--accept-unstamped", action="store_true",
1386
+ help="export a product with no .call sidecar; the file then RECORDS "
1387
+ "that its provenance is not established, rather than staying "
1388
+ "silent about the gap")
1389
+ p.add_argument("--enhancements", default="",
1390
+ help="comma-separated names of enhancements the producing chain "
1391
+ "applied; empty (the default) means none, which is the port's "
1392
+ "own case by construction")
1393
+ p.add_argument("--layout", choices=("dimensions", "particles"), default="dimensions",
1394
+ help="'dimensions' (the default, unchanged) writes the attributed netCDF4 "
1395
+ "sibling; 'particles' instead reads a proc (per-particle) file and "
1396
+ "writes one Parquet table, one row per particle (default "
1397
+ "<source>.particles.parquet); needs the [parquet] extra")
1398
+ p.set_defaults(func=_attributed)
1399
+
1400
+
1401
+ def _make_demo_flight(args) -> int:
1402
+ """``arrayprobe make-demo-flight`` -- the quickstart input, no data needed.
1403
+
1404
+ Delegates to :mod:`arrayprobe.tools.make_demo_flight`'s own ``main`` rather
1405
+ than reimplementing the flag surface, so the tool and the subcommand cannot
1406
+ drift into accepting different arguments.
1407
+ """
1408
+ from arrayprobe.tools import make_demo_flight
1409
+
1410
+ argv = [str(args.path), "--seconds", str(args.seconds),
1411
+ "--tas-mps", str(args.tas_mps)]
1412
+ if args.dense:
1413
+ argv.append("--dense")
1414
+ if getattr(args, "distinct_counters", False):
1415
+ argv.append("--distinct-counters")
1416
+ if getattr(args, "with_config", False):
1417
+ argv.append("--with-config")
1418
+ return make_demo_flight.main(argv)
1419
+
1420
+
1421
+ def _add_make_demo_flight(sub: argparse._SubParsersAction) -> None:
1422
+ p = sub.add_parser(
1423
+ "make-demo-flight",
1424
+ help="write a synthetic raw .2DS file (no campaign data required)",
1425
+ description="Builds a raw SPEC-shaped .2DS recording from nothing -- "
1426
+ "the quickstart input, so the pipeline can be exercised "
1427
+ "without any archived data or Octave. Synthetic, not "
1428
+ "validated science: it proves the chain runs and writes "
1429
+ "valid files, and is not a stand-in for the oracle-backed "
1430
+ "validation the fidelity claims rest on. Name the output "
1431
+ "base<YYMMDDhhmmss>.2DS if you intend to reach the combine "
1432
+ "stage, which reads the flight date from the stem. "
1433
+ "WITHOUT --dense the flight is deliberately sparse: its one "
1434
+ "particle per second has an arbitrary inter-arrival time, so "
1435
+ "sizeDist rejects every particle as sub-6 us and the combined "
1436
+ "product is all fill value. Pass --dense for a run that yields "
1437
+ "a real size distribution.",
1438
+ )
1439
+ p.add_argument("path", help="output path, e.g. base160101000000.2DS")
1440
+ p.add_argument("--seconds", type=int, default=5,
1441
+ help="number of one-second records to write (default: 5)")
1442
+ p.add_argument("--tas-mps", type=float, default=130.0,
1443
+ help="synthetic true airspeed in m/s (default: 130.0)")
1444
+ # Exposed on the subcommand by the 2026-09-16 usability audit (2.3): the tool
1445
+ # has had this
1446
+ # flag since 2026-09-13, but `arrayprobe make-demo-flight --help` did not forward
1447
+ # it, so the only demo a CLI-only user could reach produced a 68 MB all-NaN
1448
+ # product, and the one that yields a plottable PSD was undiscoverable.
1449
+ p.add_argument("--dense", action="store_true",
1450
+ help="write the DENSE demo instead: many particles per second with "
1451
+ "realistic inter-arrival gaps, so the size distribution comes "
1452
+ "out populated. This is the demo to run first.")
1453
+ p.add_argument("--distinct-counters", action="store_true",
1454
+ help="give each image packet its own particle counter (default: "
1455
+ "the constant 7), so SODA-2's spec_index keeps every "
1456
+ "particle; changes the written bytes")
1457
+ p.add_argument("--with-config", action="store_true",
1458
+ help="also create the output folder if needed and write a "
1459
+ "ready-to-run run.toml beside the flight, so `arrayprobe run "
1460
+ "<folder>/run.toml <flight> --yes` works from a plain "
1461
+ "pip install, without the repository's examples/ folder")
1462
+ p.set_defaults(func=_make_demo_flight)
1463
+
1464
+
1465
+ def _make_tas_file(args) -> int:
1466
+ """``arrayprobe make-tas-file`` -- write the aircraft file the v3.5 engine requires.
1467
+
1468
+ Delegates to :mod:`arrayprobe.tools.make_tas_file`'s own ``main``, the same way
1469
+ ``make-demo-flight`` does, so the tool and the subcommand cannot accept different
1470
+ arguments.
1471
+ """
1472
+ from arrayprobe.tools import make_tas_file
1473
+
1474
+ argv = [str(args.path)]
1475
+ if args.from_tas_csv is not None:
1476
+ argv += ["--from-tas-csv", str(args.from_tas_csv)]
1477
+ if args.constant_tas is not None:
1478
+ argv += ["--constant-tas", str(args.constant_tas)]
1479
+ if args.start_hhmmss is not None:
1480
+ argv += ["--start-hhmmss", str(args.start_hhmmss)]
1481
+ if args.seconds is not None:
1482
+ argv += ["--seconds", str(args.seconds)]
1483
+ if args.second_rule is not None:
1484
+ argv += ["--second-rule", str(args.second_rule)]
1485
+ if args.neighbour is not None:
1486
+ argv += ["--neighbour", str(args.neighbour)]
1487
+ if args.on_unsettled is not None:
1488
+ argv += ["--on-unsettled", str(args.on_unsettled)]
1489
+ for flag in ("from_merge", "from_aircraft", "chain", "date", "probe_csv", "cutoff_mps",
1490
+ "default_mps", "soda2_pth"):
1491
+ if getattr(args, flag) is not None:
1492
+ argv += [f"--{flag.replace('_', '-')}", str(getattr(args, flag))]
1493
+ for d in args.search or ():
1494
+ argv += ["--search", str(d)]
1495
+ return make_tas_file.main(argv)
1496
+
1497
+
1498
+ def _add_make_tas_file(sub: argparse._SubParsersAction) -> None:
1499
+ p = sub.add_parser(
1500
+ "make-tas-file",
1501
+ help="write the aircraft TAS file the v3.5 engine requires",
1502
+ description="Writes the aircraft file stock imgProc_sm.m reads as varargin{1}: a "
1503
+ "netCDF file with two 1-D f8 variables, `Time` (HHMMSS, e.g. 60638 for "
1504
+ "06:06:38) and `TAS` (m/s); the image-processing stage reads those "
1505
+ "exact names. The v3.5 engine -- the package default -- refuses "
1506
+ "to run without one. Build it from the .tas.csv sidecar the decode "
1507
+ "already wrote, or state a constant speed explicitly.",
1508
+ )
1509
+ p.add_argument("path", help="output path, e.g. aircraft_160906.cdf")
1510
+ p.add_argument("--from-tas-csv", default=None,
1511
+ help="the <stem>.tas.csv the decode wrote (columns: timehhmmss, tas)")
1512
+ p.add_argument("--constant-tas", type=float, default=None,
1513
+ help="flat series at this speed, NOT a measurement "
1514
+ "(needs --start-hhmmss and --seconds)")
1515
+ p.add_argument("--start-hhmmss", type=float, default=None,
1516
+ help="first sample's time as HHMMSS")
1517
+ p.add_argument("--seconds", type=int, default=None,
1518
+ help="number of 1-Hz samples for --constant-tas")
1519
+ p.add_argument("--second-rule", choices=("round", "floor"), default=None,
1520
+ help="fractional HHMMSS to whole seconds; default round (this package's choice)")
1521
+ p.add_argument("--neighbour", choices=("adjacent", "nearest-present"), default=None,
1522
+ help="the neighbouring second the duplicate-second rule compares against; "
1523
+ "default adjacent (this package's choice)")
1524
+ p.add_argument("--on-unsettled", choices=("default", "refuse"), default=None,
1525
+ help="a duplicated second the duplicate-second rule cannot settle; default: "
1526
+ "it takes --default-mps (this package's choice)")
1527
+ p.add_argument("--from-merge", default=None,
1528
+ help="a campaign merge file, e.g. mrg1_<platform>_<yyyymmdd>_R*.nc")
1529
+ p.add_argument("--from-aircraft", default=None,
1530
+ help="another registered aircraft file, e.g. ARM enaaafmergedF1.c1.*.nc")
1531
+ p.add_argument("--chain", choices=("auto", "merge", "aircraft", "probe"), default=None,
1532
+ help="resolve the source through the fallback chain "
1533
+ "(merge -> aircraft -> probe)")
1534
+ p.add_argument("--date", default=None, help="--chain: the flight date YYYYMMDD")
1535
+ p.add_argument("--search", action="append", default=None,
1536
+ help="--chain: a directory holding merge/aircraft files (repeatable)")
1537
+ p.add_argument("--probe-csv", default=None, help="--chain: the decode's <stem>.tas.csv")
1538
+ p.add_argument("--cutoff-mps", type=float, default=None,
1539
+ help="TAS above this takes --default-mps; default 300 (this package's choice)")
1540
+ p.add_argument("--default-mps", type=float, default=None,
1541
+ help="the fall-back value; default 170, UIOOPS's own fall-back airspeed")
1542
+ p.add_argument("--soda2-pth", default=None,
1543
+ help="also write the series as a SODA-2 op.pth ASCII file")
1544
+ p.set_defaults(func=_make_tas_file)
1545
+
1546
+
1547
+ def _tas_from_nasa_ames(args) -> int:
1548
+ """``arrayprobe tas-from-nasa-ames`` -- a MEASURED 1 Hz TAS series for the SEA/CIP chain.
1549
+
1550
+ Delegates to :mod:`arrayprobe.tools.nasa_ames_tas`'s own ``main``, the same way
1551
+ ``make-tas-file`` does, so the tool and the subcommand cannot accept different arguments.
1552
+ """
1553
+ try:
1554
+ import importlib
1555
+
1556
+ nasa_ames_tas = importlib.import_module("arrayprobe.tools.nasa_ames_tas")
1557
+ except ImportError:
1558
+ print("arrayprobe tas-from-nasa-ames is not available in this release: it needs "
1559
+ "arrayprobe.tools.nasa_ames_tas, which this distribution does not ship. "
1560
+ "Use `make-tas-file` with a TAS series of your own.", file=sys.stderr)
1561
+ return 2
1562
+
1563
+ argv = [str(args.path), "--out", str(args.out),
1564
+ "--flight-date", str(args.flight_date)]
1565
+ if args.drop_missing:
1566
+ argv.append("--drop-missing")
1567
+ if getattr(args, "variable", None):
1568
+ argv += ["--variable", args.variable]
1569
+ if getattr(args, "round_seconds", False):
1570
+ argv.append("--round-seconds")
1571
+ if getattr(args, "assume_units", "as-declared") != "as-declared":
1572
+ argv += ["--assume-units", args.assume_units]
1573
+ return nasa_ames_tas.main(argv)
1574
+
1575
+
1576
+ def _add_tas_from_nasa_ames(sub: argparse._SubParsersAction) -> None:
1577
+ p = sub.add_parser(
1578
+ "tas-from-nasa-ames",
1579
+ help="convert a NASA-Ames 1001 true-air-speed file into the .tas.csv sidecar",
1580
+ description="Reads a NASA-Ames 1001 aircraft true-air-speed file (plain or .gz) and "
1581
+ "writes the .tas.csv sidecar arrayprobe.readers.tasinfo.load_tas_info "
1582
+ "reads, which `make-tas-file --from-tas-csv` then turns into the aircraft "
1583
+ "netCDF the v3.5 engine requires. This is the SEA/CIP chain's route to a "
1584
+ "MEASURED TAS: `make-tas-file --constant-tas` fabricates one and says so, "
1585
+ "and nothing on that chain writes a sidecar of its own.",
1586
+ )
1587
+ p.add_argument("path", help="the NASA-Ames 1001 file, e.g. <stem>.SODA2_TAS.1Hz.gz")
1588
+ p.add_argument("--out", required=True, help="the .tas.csv to write")
1589
+ p.add_argument("--flight-date", required=True, metavar="YYYY-MM-DD",
1590
+ help="the flight this series is for; must equal the file's own DATE")
1591
+ p.add_argument("--drop-missing", action="store_true",
1592
+ help="leave out rows carrying the file's missing-value code instead of "
1593
+ "refusing")
1594
+ p.add_argument("--variable", default=None, metavar="SUBSTRING",
1595
+ help="name which true-air-speed variable to use, when the file declares "
1596
+ "more than one (UND's own .basic.1Hz declares two). The reader still "
1597
+ "refuses to choose on its own; this is how an operator chooses, and "
1598
+ "the full name of the column used is reported")
1599
+ p.add_argument("--assume-units", default="as-declared", choices=("as-declared", "knots"),
1600
+ help="declare the column's REAL units when they contradict the file's "
1601
+ "header; 'knots' multiplies by 0.514444 and reports it")
1602
+ p.add_argument("--round-seconds", action="store_true",
1603
+ help="attribute each sample to its nearest whole second, for a file whose "
1604
+ "1 Hz grid is offset from the integer second (UND's .basic.1Hz sits "
1605
+ "0.21 s off on the 2016 flights). The shift is reported")
1606
+ p.set_defaults(func=_tas_from_nasa_ames)
1607
+
1608
+
1609
+ def _run(args: argparse.Namespace) -> int:
1610
+ """``arrayprobe run`` -- one line: a configuration file names the
1611
+ engine and the campaign, and this builds the batch driver's (``arrayprobe.driver.run_flight``)
1612
+ argv from it and calls its unmodified ``main()``. No pipeline logic here."""
1613
+ import glob as glob_module
1614
+
1615
+ from .config import ConfigError, load_config
1616
+ try:
1617
+ cfg = load_config(args.config)
1618
+ except FileNotFoundError:
1619
+ print(f"arrayprobe run: config file {args.config} does not exist; pass the path of a "
1620
+ f"run configuration (a starting point: examples/start_here/run.toml)",
1621
+ file=sys.stderr)
1622
+ return 2
1623
+ except ConfigError as exc:
1624
+ print(f"arrayprobe run: {exc}", file=sys.stderr)
1625
+ return 2
1626
+ run = cfg.run
1627
+ if run.get("engine") == "3.1.4" and not _v314_engine_present():
1628
+ print(f"arrayprobe run: {args.config} names [run].engine = \"3.1.4\". "
1629
+ + _V314_ABSENT_MESSAGE, file=sys.stderr)
1630
+ return 2
1631
+ if run.get("engine") == "soda2":
1632
+ # Before the preset check: a SODA-2 config has no campaign preset to be missing.
1633
+ print(f"arrayprobe run: {args.config} names [run].engine = \"soda2\", which is not a "
1634
+ f"UIOPS engine and does not run through the UIOPS batch driver; use "
1635
+ f"`arrayprobe soda2 run {args.config}`", file=sys.stderr)
1636
+ return 2
1637
+ missing = [k for k in ("engine", "preset") if k not in run]
1638
+ if missing:
1639
+ print(f"arrayprobe run: {args.config} has no [run].{' / [run].'.join(missing)}; "
1640
+ f"the engine and the campaign preset are chosen by name in the file, never assumed",
1641
+ file=sys.stderr)
1642
+ return 2
1643
+ if args.uiops_version != "3.1.4" and args.uiops_version != run["engine"]:
1644
+ print(f"arrayprobe run: --uiops-version {args.uiops_version} disagrees with "
1645
+ f"[run].engine = {run['engine']!r} in {args.config}", file=sys.stderr)
1646
+ return 2
1647
+ base = Path(args.config).resolve().parent
1648
+ raw_globs = run.get("raw", [])
1649
+ assert isinstance(raw_globs, list), "config.py validates [run].raw as a list"
1650
+ raws = [str(p) for p in args.raw] or sorted(
1651
+ str(p) for pattern in raw_globs for p in glob_module.glob(str(base / str(pattern))))
1652
+ if not raws:
1653
+ print(f"arrayprobe run: no raw files -- give them on the command line or as [run].raw "
1654
+ f"globs relative to {base}", file=sys.stderr)
1655
+ return 2
1656
+ run_flight = _load_run_flight()
1657
+ preset = run_flight.PRESETS.get(str(run["preset"]))
1658
+ if "probe" in run and preset is not None and preset.probe != run["probe"]:
1659
+ # A SEA file carries several probes; the preset fixes which one the run follows, so a
1660
+ # [run].probe that names another would be silently ignored if it were not refused.
1661
+ matching = sorted(p.name for p in run_flight.PRESETS.values()
1662
+ if p.probe == run["probe"])
1663
+ print(f"arrayprobe run: [run].probe = {run['probe']!r} but preset "
1664
+ f"{preset.name!r} processes the {preset.probe}; "
1665
+ + (f"presets for the {run['probe']}: {', '.join(matching)}" if matching
1666
+ else f"no shipped preset processes the {run['probe']!r}"),
1667
+ file=sys.stderr)
1668
+ return 2
1669
+ tas_from_probe: list[str] = []
1670
+ probe_tas_globs = run.get("tas_from_probe", []) or []
1671
+ assert isinstance(probe_tas_globs, list), "config.py validates [run].tas_from_probe as a list"
1672
+ for pattern in probe_tas_globs:
1673
+ hits = sorted(glob_module.glob(str(base / str(pattern))))
1674
+ if not hits:
1675
+ print(f"arrayprobe run: [run].tas_from_probe entry {pattern!r} matches no file "
1676
+ f"(relative to {base}); nothing was run", file=sys.stderr)
1677
+ return 2
1678
+ tas_from_probe += hits
1679
+ argv = [*raws, "--config", str(args.config), "--preset", str(run["preset"])]
1680
+ for hk in tas_from_probe:
1681
+ # Another probe's airspeed record on the same aircraft, for a CIP or PIP whose own
1682
+ # decode writes none; run_flight refuses it on a probe that writes its own.
1683
+ argv += ["--tas-from-probe", hk]
1684
+ if "presets" in run:
1685
+ argv += ["--presets", str((base / str(run["presets"])).resolve())]
1686
+ if "probe_case" in run:
1687
+ argv += ["--probe-case", str(run["probe_case"])]
1688
+ if "probe_case_module" in run:
1689
+ argv += ["--probe-case-module", str(run["probe_case_module"])]
1690
+ # No [run].out: the output goes beside the config, at <config dir>/output, rather than
1691
+ # falling to the driver's own default (../_decoded from the current directory).
1692
+ argv += ["--out", str((base / str(run.get("out", "output"))).resolve())]
1693
+ if "stages" in run:
1694
+ argv += ["--stages", str(run["stages"])]
1695
+ if "tas_file" in run:
1696
+ # Relative to the config, like `out`; run_flight refuses it under a
1697
+ # profile that never reads it and requires it under one that does.
1698
+ argv += ["--tas-file", str((base / str(run["tas_file"])).resolve())]
1699
+ argv += ["--engine", str(run["engine"])]
1700
+ if getattr(args, "port_validation", False):
1701
+ # R4. Forwarded, never added from the engine: the refusal (v3.1.4 without
1702
+ # the flag, or the flag under any other engine) lives in run_flight.main, so
1703
+ # `arrayprobe run` and a direct batch-driver invocation cannot disagree.
1704
+ argv.append("--port-validation")
1705
+ if cfg.borrowed_combine:
1706
+ argv.append("--borrowed-combine")
1707
+ if args.dry_run:
1708
+ argv.append("--dry-run")
1709
+ if getattr(args, "yes", False):
1710
+ # Forwarded rather than answered here: the gate, the panel and the refusal all
1711
+ # live in one place (run_flight.confirm_or_declare), so `arrayprobe run` and a direct
1712
+ # batch-driver invocation cannot come to different conclusions about the same
1713
+ # configuration. A config that declares [thresholds] is never gated at all.
1714
+ argv.append("--yes")
1715
+ for flag in ("jobs", "s2_jobs", "chunks", "enh_jobs"):
1716
+ argv += [f"--{flag.replace('_', '-')}", str(getattr(args, flag))]
1717
+ if getattr(args, "jit", False):
1718
+ argv.append("--jit")
1719
+ if getattr(args, "enhancements", False):
1720
+ # Forwarded, never decided here: the flag only says *whether* to apply, and
1721
+ # which modules, the resolution, the appliers and the refusals all live on the
1722
+ # batch-driver side (`apply_enhancements_to_run`) behind its guarded import --
1723
+ # so this module still references nothing in arrayprobe_enhancements, which is what
1724
+ # tests/test_no_enhancement_coupling.py sweeps this package's source for.
1725
+ argv.append("--enhancements")
1726
+ for flag in _RUN_OVERRIDES:
1727
+ # Forwarded, never decided here: each refusal these overrides answer lives in
1728
+ # tools/run_flight.py and names the flag, so `arrayprobe run` must accept every one
1729
+ # (tests/test_run_accepts_refusal_flags.py). Per-run decisions, flag-only, default off.
1730
+ if getattr(args, flag.replace("-", "_"), False):
1731
+ argv.append(f"--{flag}")
1732
+ for flag in _RUN_VALUE_OVERRIDES:
1733
+ # Same rule, for run_flight options that take a value: default None, so nothing is
1734
+ # forwarded unless the user names it, and run_flight's own default stands.
1735
+ value = getattr(args, flag.replace("-", "_"), None)
1736
+ if value is not None:
1737
+ argv.extend([f"--{flag}", value])
1738
+ return run_flight.main(argv)
1739
+
1740
+
1741
+ #: run_flight's refusal overrides that `arrayprobe run` forwards, each opt-in and default off.
1742
+ _RUN_OVERRIDES = {
1743
+ "accept-preset-mismatch": "run a raw file whose extension names a different probe than "
1744
+ "the preset (a renamed file); recorded as "
1745
+ "accept_preset_mismatch=on in the .call stamps",
1746
+ "accept-unstamped": "accept an input product with no .call stamp instead of refusing it",
1747
+ "accept-flagged": "process a raw file the input inventory flags as empty instead of "
1748
+ "refusing it; the decode .call records the inventory flags "
1749
+ "(inventory_empty=1), not the override",
1750
+ "accept-implausible": "accept a size distribution the plausibility gate refuses; the "
1751
+ "override is recorded in the .call stamps",
1752
+ "allow-mixed-config": "allow inputs stamped with differing configurations to be combined",
1753
+ "libm-pow": "engine 3.1.4 only: compute S4's massBL power with libm's pow, as MATLAB "
1754
+ "does; stamped libm_pow=on into the sd .call",
1755
+ }
1756
+
1757
+ #: run_flight options that take a value and that its messages tell the user to pass; forwarded
1758
+ #: only when given (default None), so run_flight's own default applies otherwise.
1759
+ #: flag -> (choices or None, help).
1760
+ _RUN_VALUE_OVERRIDES = {
1761
+ "tas-grid": (("probe", "regular"), "the time vector the size-distribution stage gets under "
1762
+ "a TAS source; run_flight's default when not given"),
1763
+ "tas-ratio": (("off", "on"), "v3.5 only: write tasRatio from an aircraft airspeed source "
1764
+ "(changes the product); run_flight's default (off) when not given"),
1765
+ "iat-file": (None, "sizeDist's twelfth argument, the inter-arrival threshold file; "
1766
+ "run_flight's default (a threshold file that does not exist, so the per-probe "
1767
+ "default threshold applies) when not given"),
1768
+ }
1769
+
1770
+
1771
+ def _add_run(sub: argparse._SubParsersAction) -> None:
1772
+ p = sub.add_parser(
1773
+ "run",
1774
+ help="the one line: run a whole flight from one configuration file "
1775
+ "(the [run] table in the file drives it)",
1776
+ description="One line of code to run and one file to configure. "
1777
+ "Every choice -- engine, fidelity profile, campaign preset, "
1778
+ "output directory, which stages -- is named in the file "
1779
+ "(arrayprobe.config); nothing here is assumed. Without "
1780
+ "[run].out, output goes to an 'output' folder beside the "
1781
+ "config file. Runs the batch driver "
1782
+ "(arrayprobe.driver.run_flight) with every setting read from "
1783
+ "[run] -- no new pipeline logic.",
1784
+ )
1785
+ p.add_argument("config", type=Path, help="a run configuration TOML (arrayprobe.config)")
1786
+ p.add_argument("raw", nargs="*", type=Path,
1787
+ help="raw files; wins over [run].raw in the file")
1788
+ p.add_argument("--dry-run", action="store_true", help="preflight only, decode nothing")
1789
+ p.add_argument("--yes", "-y", action="store_true",
1790
+ help="accept the configuration this prints without being asked. A "
1791
+ "config that declares [thresholds] needs no confirmation and ignores "
1792
+ "this; one that declares none is confirmed before the run starts, and "
1793
+ "where stdin is not a terminal (a detached run, CI) it refuses to start "
1794
+ "without this flag rather than blocking on a prompt nobody can answer.")
1795
+ p.add_argument("--jobs", type=int, default=1, metavar="N",
1796
+ help="process N raw files at once, one worker process each (default 1). "
1797
+ "Helps a flight recorded as many files; outputs are the same as a "
1798
+ "one-at-a-time run.")
1799
+ p.add_argument("--enh-jobs", type=int, default=1, metavar="N",
1800
+ help="run the out-of-focus correction across N worker processes when "
1801
+ "--enhancements applies it (default 1). Separate from --jobs, which "
1802
+ "spreads raw files: the corrections run after every file is done. "
1803
+ "The written files are the same for any N.")
1804
+ p.add_argument("--s2-jobs", type=int, default=1, metavar="N",
1805
+ help="decode one raw file across N worker processes (default 1). Helps a "
1806
+ "flight recorded as one large file, where --jobs has nothing to "
1807
+ "spread; the decoded file is byte-identical to a one-process decode. "
1808
+ "2D-S/HVPS (SPEC) files only: where the engine or format has no "
1809
+ "parallel decoder the run refuses the flag rather than ignore it.")
1810
+ p.add_argument("--chunks", type=int, default=1, metavar="N",
1811
+ help="split each file's image processing (particle framing) into N "
1812
+ "record ranges run in parallel and merged (default 1); the merged "
1813
+ "file is byte-identical to an unsplit run. Independent of --jobs, "
1814
+ "which spreads files rather than one file's records.")
1815
+ p.add_argument("--jit", action="store_true",
1816
+ help="speed only, default off: the image-processing stage's hot kernels "
1817
+ "through numba "
1818
+ "(arrayprobe.jit_kernels); the proc file is byte-identical, "
1819
+ "which the test suite checks")
1820
+ # Parsed either way, so a stale script gets run_flight's refusal (which names the reason)
1821
+ # rather than argparse's unknown-flag error; listed in --help only with the engine present.
1822
+ p.add_argument("--port-validation", action="store_true",
1823
+ help=("forwarded to the batch driver: required when [run].engine is 3.1.4 "
1824
+ "and refused under any other engine. The v3.1.4 engine is "
1825
+ "the ORACLES-validation anchor only; this flag declares the run port "
1826
+ "validation and stamps port_validation=on into every .call it writes, "
1827
+ "marking the output not for quoting. Changes no computed byte. "
1828
+ "Where the v3.1.4 engine is not installed, the run exits 2 saying so.")
1829
+ if _v314_engine_present() else argparse.SUPPRESS)
1830
+ p.add_argument("--enhancements", action="store_true",
1831
+ help="default off: after the stages finish, apply the corrections this "
1832
+ "config's [enhancements] table names to the products the run wrote, "
1833
+ "each into its own <stem>.enh.<stage>.nc with an `enhancements=` "
1834
+ "fragment in its .call. Off, the run is byte-identical to one "
1835
+ "without the flag; the port's own outputs are never overwritten "
1836
+ "either way. Needs `pip install arrayprobe-uiops-enhancements`.")
1837
+ for flag, why in _RUN_OVERRIDES.items():
1838
+ p.add_argument(f"--{flag}", action="store_true",
1839
+ help=(argparse.SUPPRESS
1840
+ if flag == "libm-pow" and not _v314_engine_present()
1841
+ else f"default off, forwarded to the batch driver: {why}"))
1842
+ for flag, (choices, why) in _RUN_VALUE_OVERRIDES.items():
1843
+ p.add_argument(f"--{flag}", choices=choices, default=None,
1844
+ help=f"forwarded to the batch driver only when given: {why}")
1845
+ p.set_defaults(func=_run)
1846
+
1847
+
1848
+ def _reprocess(args: argparse.Namespace) -> int:
1849
+ """``arrayprobe reprocess`` -- the body is ``scripts/reprocess.py``'s ``run``; the engine comes
1850
+ from the product's own stamp, so a top-level ``--uiops-version`` that disagrees is refused
1851
+ rather than silently overridden (the rule ``run`` applies to ``[run].engine``).
1852
+
1853
+ **The stamp is now read before anything runs, and an absent one refuses** (since
1854
+ 2026-09-18). Until then this function read the sidecar itself with
1855
+ ``stamp.startswith("engine=3.5 ")``, under which a missing sidecar, a lane script's JSON
1856
+ sidecar and a truncated sidecar all answered ``"3.1.4"`` -- and the whole check was skipped
1857
+ unless the user had passed ``--uiops-version``, which is its default. So the common case
1858
+ was: no check, and a wrong answer available if there had been one.
1859
+ :func:`arrayprobe.provenance.engine_of` answers ``None`` by raising instead.
1860
+ """
1861
+ tool = _load_reprocess()
1862
+ try:
1863
+ stamped = provenance.engine_of(args.product)
1864
+ except (provenance.Unstamped, provenance.EngineUnrecorded) as exc:
1865
+ print(f"arrayprobe reprocess: {exc}", file=sys.stderr)
1866
+ print(f"Nothing was run. `arrayprobe provenance {args.product}` shows the state; there "
1867
+ f"is no --accept-unstamped here, on purpose: a product of unknown configuration "
1868
+ f"cannot be re-run 'exactly as recorded'.", file=sys.stderr)
1869
+ return 2
1870
+ if args.uiops_version != "3.1.4" and args.uiops_version != stamped:
1871
+ print(f"arrayprobe reprocess: --uiops-version {args.uiops_version} disagrees with the "
1872
+ f"UIOPS {stamped} engine {args.product.name}'s stamp records", file=sys.stderr)
1873
+ return 2
1874
+ return tool.run(args)
1875
+
1876
+
1877
+ def _add_reprocess(sub: argparse._SubParsersAction) -> None:
1878
+ p = sub.add_parser(
1879
+ "reprocess",
1880
+ help="re-run the stage that wrote a proc/sd product, exactly as its .call stamp "
1881
+ "records, and report whether the result is identical",
1882
+ description="Reads the product's .call sidecar, re-runs the one stage that wrote it "
1883
+ "(image processing for proc.*, size distribution for sd.*; either engine, "
1884
+ "from the stamp) under exactly that "
1885
+ "configuration, from the input beside it, and diffs the fresh file against "
1886
+ "the product. Refuses -- exit 2, nothing run -- unless the batch driver's "
1887
+ "own label function regenerates the recorded stamp character for character, "
1888
+ "and unless the stage's input carries the matching stamp. Exit 0 identical "
1889
+ "(Creation Time skipped, source paths compared by basename), 1 differs. The "
1890
+ "fresh file is written to a temporary directory and discarded; the product "
1891
+ "is never modified. Decode and combine products are refused: their stamps do "
1892
+ "not record the raw file or the combine call.",
1893
+ )
1894
+ p.add_argument("product", type=Path,
1895
+ help="a proc.*.nc (image processing) or sd.*.nc (size distribution) file "
1896
+ "with its .call sidecar beside it")
1897
+ p.add_argument("--preset", required=True,
1898
+ help="the campaign preset the product was run under (the batch driver's "
1899
+ "PRESETS). REQUIRED: no stamp records the preset, so it is named, never "
1900
+ "assumed")
1901
+ p.add_argument("--tas-file", type=Path, default=None,
1902
+ help="the aircraft TAS file, for a proc.* product whose stamp names one (the "
1903
+ "stamp records its basename only, which must match). Not needed for a "
1904
+ "product made under a TAS source chain: the chain's own "
1905
+ "<stem>.tas_<tier>.cdf beside it is read instead")
1906
+ p.set_defaults(func=_reprocess)
1907
+
1908
+
1909
+ def _soda2_enhancement_table(cfg, protective_mode: str | None = None) -> dict:
1910
+ """The SODA-2 correction registry as the ``.pbp.call`` sidecar and ``soda2 enhancements``
1911
+ report it. The port never imports ``arrayprobe_soda2_enhancements`` unguarded: the
1912
+ package is optional, and its absence is a recorded state, not an error. Now
1913
+ the corrections are **applied**: ``_soda2_run`` wraps the driver in the
1914
+ package's ``registry.apply``, which substitutes each routable resolved-ON correction at
1915
+ an ``arrayprobe_soda2.enhancement_hooks`` point and fills ``applied``/``skipped``/
1916
+ ``hook_points`` here from its record.
1917
+
1918
+ ``protective_mode`` is ``None`` (no command-line flag: the config's ``[enhancements]
1919
+ protective = true/false`` selects ``"on"``/``"off"``, and its absence ``"auto"``), ``"auto"``
1920
+ (resolve ``registry.protective_set`` for this run's probe), ``"on"`` (every
1921
+ :data:`registry.PROTECTIVE` name, ignoring ``registry.LINEAGE_PROBES``) or ``"off"``
1922
+ (none). This is A14's SODA-2 equivalent of the UIOOPS batch driver's ``--protective``.
1923
+ An explicit ``[enhancements] <name> = false`` in the config still wins over a protective
1924
+ default, exactly as :func:`registry.resolve` states.
1925
+
1926
+ Registration is an import-time side effect of each correction module, so every module of
1927
+ the package is imported before the registry is read -- importing ``registry`` alone
1928
+ leaves ``REGISTRY`` empty (measured 2026-09-14). ``requested`` is the file's own
1929
+ ``[enhancements]`` table, kept even when the package is absent so an opt-out the file
1930
+ states is never lost from the record. Raises the registry's ``UnknownEnhancement`` for a
1931
+ name the package does not ship."""
1932
+ requested = dict(sorted((getattr(cfg, "enhancements", None) or {}).items()))
1933
+ if protective_mode is None:
1934
+ # No --protective on the command line: the config's `[enhancements] protective = …`
1935
+ # decides, as in the UIOOPS batch driver (`run_flight.py`'s PROTECTIVE_MODE); the
1936
+ # command line wins when given.
1937
+ declared = requested.get("protective")
1938
+ protective_mode = "auto" if declared is None else ("on" if declared else "off")
1939
+ import importlib
1940
+ import pkgutil
1941
+ try:
1942
+ import arrayprobe_soda2_enhancements as soda2_enh
1943
+ from arrayprobe_soda2_enhancements import registry as soda2_registry
1944
+ except ImportError:
1945
+ return {"package": "not installed", "requested": requested, "resolved": {},
1946
+ "applied": [], "skipped": {}, "protective_mode": protective_mode,
1947
+ "protective_set": []}
1948
+ # Outside the guard on purpose: a correction module that fails to import in an INSTALLED
1949
+ # package is a real error, not "package not installed".
1950
+ for mod in pkgutil.iter_modules(soda2_enh.__path__):
1951
+ if mod.name != "registry" and not mod.name.startswith("_"):
1952
+ importlib.import_module(f"arrayprobe_soda2_enhancements.{mod.name}")
1953
+ probe = str((getattr(cfg, "soda2", None) or {}).get("probetype", ""))
1954
+ if protective_mode == "off":
1955
+ protective: frozenset[str] = frozenset()
1956
+ elif protective_mode == "on":
1957
+ protective = soda2_registry.PROTECTIVE
1958
+ else:
1959
+ protective = soda2_registry.protective_set(probe=probe)
1960
+ try:
1961
+ resolved = soda2_registry.resolve_from_config(cfg, protective=protective)
1962
+ except soda2_registry.UnknownEnhancement as exc:
1963
+ from .config import ConfigError
1964
+ raise ConfigError(str(exc.args[0]) if exc.args else str(exc)) from exc
1965
+ return {
1966
+ "package": "installed",
1967
+ "requested": requested,
1968
+ "resolved": dict(sorted(resolved.items())),
1969
+ "reachability": {n: s.reachability for n, s in sorted(soda2_registry.REGISTRY.items())},
1970
+ "protective_mode": protective_mode,
1971
+ "protective_set": sorted(protective),
1972
+ # Filled by `_soda2_run` from `registry.apply`'s record: the driver
1973
+ # adapter applies every resolved-ON correction it can route.
1974
+ "applied": [],
1975
+ "skipped": {},
1976
+ }
1977
+
1978
+
1979
+ def _soda2_versions() -> dict[str, str]:
1980
+ from importlib import metadata
1981
+ out: dict[str, str] = {}
1982
+ for dist in ("arrayprobe", "arrayprobe-soda2-enhancements"):
1983
+ try:
1984
+ out[dist] = metadata.version(dist)
1985
+ except metadata.PackageNotFoundError:
1986
+ out[dist] = "not installed"
1987
+ return out
1988
+
1989
+
1990
+ def _soda2_jsonable(v):
1991
+ """One resolved ``op`` value as JSON: arrays as lists, NumPy scalars as their Python value.
1992
+ The NumPy dtype is recorded separately (``op_dtypes``), because in SODA-2 it is part of
1993
+ what the run computed -- e.g. a FLOAT vs DOUBLE ``op.rate`` sets ``activetime``'s dtype
1994
+ (``process_2d.py``, S6-e) -- and ``str()`` of an ``np.int16`` would record ``"0"``, a
1995
+ string, where the driver saw an INT16."""
1996
+ if isinstance(v, np.ndarray):
1997
+ return v.tolist()
1998
+ if isinstance(v, np.generic):
1999
+ return v.item()
2000
+ if isinstance(v, (list, tuple)):
2001
+ return [_soda2_jsonable(x) for x in v]
2002
+ return v
2003
+
2004
+
2005
+ def _soda2_run(args: argparse.Namespace) -> int:
2006
+ """``arrayprobe soda2 run <config> [--out DIR]``: ``load_config`` -> ``op = [soda2]`` ->
2007
+ the enhancement table (resolved when the optional package is installed, and then applied
2008
+ through its ``registry.apply`` around the driver call) -> ``soda2_process_2d(op)`` ->
2009
+ ``<stem>.pbp.call`` beside the outputs, where
2010
+ ``<stem>`` is the PBP files' own (``soda2_filename.pro``: ``<date>_<hhmmss>_<shortname>
2011
+ [_<probeid>]``), so two windows written to one directory never share a sidecar. The
2012
+ sidecar is deterministic (no timestamp): two runs of one config are byte-identical.
2013
+
2014
+ Exit 2 for a config this command cannot run; exit 1 when the driver returns no data
2015
+ (``soda2_process_2d.pro:430-433`` / ``:576``, the IDL ``return`` with no output) -- no
2016
+ sidecar is written then, and any PBP file the driver opened is left as S6-f leaves it."""
2017
+ import json
2018
+
2019
+ from arrayprobe_soda2.pbp_writer import pbp_filename, soda2_stamp_profile
2020
+ from arrayprobe_soda2.process_2d import (
2021
+ REPORT_EVERY_BUFFERS,
2022
+ soda2_process_2d,
2023
+ )
2024
+ from arrayprobe_soda2.process_2d_parallel import Soda2ParallelRefused
2025
+
2026
+ from .config import ConfigError, load_config
2027
+ try:
2028
+ cfg = load_config(args.config)
2029
+ except (ConfigError, FileNotFoundError) as exc:
2030
+ print(f"arrayprobe soda2 run: {exc}", file=sys.stderr)
2031
+ return 2
2032
+ if cfg.run.get("engine", "soda2") != "soda2":
2033
+ print(f"arrayprobe soda2 run: {args.config} names [run].engine = "
2034
+ f"{cfg.run['engine']!r}; this command runs the SODA-2 engine only", file=sys.stderr)
2035
+ return 2
2036
+ if not cfg.soda2:
2037
+ print(f"arrayprobe soda2 run: {args.config} has no [soda2] table (the driver's op "
2038
+ f"fields)", file=sys.stderr)
2039
+ return 2
2040
+ # [outputs] selections the SODA-2 engine has not built yet are refused by name, never
2041
+ # ignored; an all-false [outputs] runs exactly as a file without the section. [arm] is read
2042
+ # only by an ARM output, so it is refused while that output is unbuilt. Built:
2043
+ # `faithful_attributed` (the run's `<stem>.nc` and its attributed sibling) and
2044
+ # `analysis_ready` (how that attributed file is stored).
2045
+ built = {"faithful_attributed", "analysis_ready", "enhanced_attributed"}
2046
+ unbuilt = sorted(k for k, v in cfg.outputs.items() if v is not False and k not in built)
2047
+ if unbuilt:
2048
+ print(f"arrayprobe soda2 run: {args.config}: [outputs] {unbuilt} not yet implemented "
2049
+ f"for engine soda2; set them false or remove them", file=sys.stderr)
2050
+ return 2
2051
+ if cfg.arm:
2052
+ print(f"arrayprobe soda2 run: {args.config}: [arm] is read only by the ARM output, "
2053
+ f"not yet implemented for engine soda2; remove [arm]", file=sys.stderr)
2054
+ return 2
2055
+ protective_mode = getattr(args, "protective", None)
2056
+ try:
2057
+ enh = _soda2_enhancement_table(cfg, protective_mode=protective_mode)
2058
+ except ConfigError as exc:
2059
+ print(f"arrayprobe soda2 run: {args.config}: {exc}", file=sys.stderr)
2060
+ return 2
2061
+ # `[outputs] enhanced_attributed = true` makes the run two passes: the faithful pass below
2062
+ # runs with the protective corrections OFF and no [enhancements] (today's file names), and
2063
+ # a corrected pass after it carries the resolved set under `<stem>.enh.*`. A run without
2064
+ # that selection is one pass, exactly as before.
2065
+ two_pass = cfg.outputs.get("enhanced_attributed") is True
2066
+ enh_corrected = enh
2067
+ if two_pass:
2068
+ enh = {"package": enh["package"], "pass": "faithful", "requested": {}, "resolved": {},
2069
+ "applied": [], "skipped": {}, "protective_mode": "off", "protective_set": []}
2070
+ op = dict(cfg.soda2)
2071
+ if args.out is not None:
2072
+ op["outdir"] = str(Path(args.out).resolve()) + os.sep
2073
+ if op.get("outdir"):
2074
+ # Before the driver runs, not only after it returns: with particlefile = 1 the driver
2075
+ # opens the per-particle CSV itself partway through, and a directory that did not yet
2076
+ # exist failed there with FileNotFoundError (the "--out trap" the SODA-2 example READMEs
2077
+ # told users to work around with mkdir).
2078
+ Path(str(op["outdir"])).mkdir(parents=True, exist_ok=True)
2079
+ apply = None
2080
+ if enh["package"] == "installed":
2081
+ try:
2082
+ # Sentinel-then-conditional-import: `apply` is `None` above so the
2083
+ # name always exists whether or not the optional package is
2084
+ # installed, and TheCliNeverImportsTheSoda2PackageUnguarded (see
2085
+ # tests/test_cli_soda2.py) depends on this exact
2086
+ # try/except ImportError shape -- restructure the guard and that
2087
+ # AST sweep stops seeing it as guarded. mypy has no way to type an
2088
+ # import that may or may not rebind a name to a different type
2089
+ # than its sentinel; the code itself is correct, so this is a
2090
+ # scoped ignore rather than a rewrite.
2091
+ from arrayprobe_soda2_enhancements.registry import ( # type: ignore[no-redef,assignment]
2092
+ apply,
2093
+ )
2094
+ except ImportError: # keeps TheCliNeverImportsTheSoda2PackageUnguarded green
2095
+ apply = None
2096
+ if apply is None and not two_pass and enh.get("requested"):
2097
+ # The one-pass path says what the two-pass path says when the config asks for
2098
+ # [enhancements] the optional package cannot supply, rather than running silently.
2099
+ print("ENHANCED skipped: no correction applies to this run (the optional SODA-2 "
2100
+ "enhancements package is not installed); no <stem>.enh.* written",
2101
+ file=sys.stderr)
2102
+ # `--jobs`/`--chunks` are resource knobs: they reach the driver as call
2103
+ # arguments and are NOT written into `op`, so the `.pbp.call` sidecar's `op`
2104
+ # record stays the IDL struct and two runs at different `--jobs` produce the
2105
+ # same sidecar -- which is the honest record, because they produce the same
2106
+ # numbers (tests/test_soda2_parallel.py).
2107
+ jobs, chunks = int(getattr(args, "jobs", 1) or 1), int(getattr(args, "chunks", 0) or 0)
2108
+ # `--jit` is the same kind of knob, and is ORed with `[run].jit` rather than
2109
+ # overriding it: the flag can only turn the kernel ON, so a config that asks
2110
+ # for it cannot be silently switched off by a command line that omits it.
2111
+ # It is likewise not written into `op` -- it moves no written byte.
2112
+ jit = bool(getattr(args, "jit", False)) or bool(cfg.run.get("jit", False))
2113
+ # In-file provenance: SODA-2 has no fidelity profile, so the name a run is made under is its
2114
+ # config file's -- written as `.pbp.nc`'s `arrayprobe_profile`, never into `op`.
2115
+ stamp = soda2_stamp_profile(args.config)
2116
+ try:
2117
+ if apply is not None and not two_pass:
2118
+ with apply(enh["resolved"]) as applied_record:
2119
+ d = soda2_process_2d(op, report_every=REPORT_EVERY_BUFFERS,
2120
+ jobs=jobs, chunks=chunks, jit=jit,
2121
+ stamp_profile=stamp)
2122
+ enh["applied"] = applied_record["applied"]
2123
+ enh["skipped"] = applied_record["skipped"]
2124
+ enh["hook_points"] = applied_record["hook_points"]
2125
+ else:
2126
+ d = soda2_process_2d(op, report_every=REPORT_EVERY_BUFFERS,
2127
+ jobs=jobs, chunks=chunks, jit=jit,
2128
+ stamp_profile=stamp)
2129
+ except Soda2ParallelRefused as exc:
2130
+ print(f"arrayprobe soda2 run: {exc}", file=sys.stderr)
2131
+ return 2
2132
+ if d is None:
2133
+ print(f"arrayprobe soda2 run: soda2_process_2d returned no data for {args.config} "
2134
+ f"(no buffers in [starttime, stoptime], soda2_process_2d.pro:430-433/:576); "
2135
+ f"no .pbp.call written", file=sys.stderr)
2136
+ return 1
2137
+ outdir = str(d.op.get("outdir") or (str(Path(args.config).resolve().parent) + os.sep))
2138
+ Path(outdir).mkdir(parents=True, exist_ok=True)
2139
+ sidecar = Path(pbp_filename(d.op, str(d.op["shortname"]), extension=".pbp.call",
2140
+ outdir=outdir))
2141
+ # The probe the run decoded, named at the top level beside `engine` so a reader of the
2142
+ # sidecar sees `format=RAF probetype=F2DC_v2 subformat=3` without walking `op`; the values
2143
+ # are `op`'s own after `update_op`, so the two cannot disagree.
2144
+ record = _soda2_record(d, args.config, enh,
2145
+ {"pbp_csv": d.pbp_csv_path, "pbp_ncdf": d.pbp_ncdf_path})
2146
+ sidecar.write_text(json.dumps(record, indent=1, sort_keys=True) + "\n", encoding="utf-8")
2147
+ print(f"wrote {sidecar}")
2148
+ if cfg.outputs.get("faithful_attributed") is True:
2149
+ # After the sidecar: the attributed export reads `<stem>.pbp.call` as the run record.
2150
+ _soda2_write_attributed(d, outdir,
2151
+ analysis_ready=cfg.outputs.get("analysis_ready") is not False)
2152
+ if two_pass:
2153
+ return _soda2_corrected_pass(
2154
+ op, enh_corrected, apply, config_path=args.config, outdir=outdir,
2155
+ jobs=jobs, chunks=chunks, jit=jit, stamp=stamp,
2156
+ analysis_ready=cfg.outputs.get("analysis_ready") is not False)
2157
+ return 0
2158
+
2159
+
2160
+ def _soda2_record(d, config_path, enh: dict, outputs: dict) -> dict:
2161
+ """The ``.pbp.call`` record of one SODA-2 pass (the same shape for both passes)."""
2162
+ return {
2163
+ "engine": "soda2",
2164
+ "probe": {k: _soda2_jsonable(d.op.get(k)) for k in ("format", "probetype", "subformat")},
2165
+ "config_path": str(Path(config_path).resolve()),
2166
+ "op": {k: _soda2_jsonable(v) for k, v in d.op.items()},
2167
+ "op_dtypes": {k: str(np.asarray(v).dtype) for k, v in d.op.items()
2168
+ if isinstance(v, (np.ndarray, np.generic))},
2169
+ "enhancements": enh,
2170
+ "versions": _soda2_versions(),
2171
+ "outputs": outputs,
2172
+ }
2173
+
2174
+
2175
+ def _soda2_corrected_pass(op: dict, enh: dict, apply, *, config_path, outdir: str, jobs: int,
2176
+ chunks: int, jit: bool, stamp, analysis_ready: bool) -> int:
2177
+ """The corrected pass of a two-pass ``[outputs] enhanced_attributed = true`` run.
2178
+
2179
+ Runs the driver again inside ``apply(...)`` with the resolved set (the protective
2180
+ corrections for the probe and any ``[enhancements]`` the config selects), with the same
2181
+ ``jobs``/``chunks``/``jit`` as the faithful pass. The driver writes into a private
2182
+ subdirectory of ``outdir``, and each file is then moved beside the faithful ones under
2183
+ ``<stem>.enh.<rest>``, so the faithful pass's files are never touched. Its record is
2184
+ ``<stem>.enh.pbp.call``, then ``<stem>.enh.nc`` and its attributed sibling.
2185
+
2186
+ When no correction applies (the optional package is not installed, or the resolved set is
2187
+ empty), the pass is skipped with a named line and no copy of the faithful files is
2188
+ written. Returns the run's exit code."""
2189
+ import json
2190
+
2191
+ from arrayprobe import attributed_export
2192
+ from arrayprobe_soda2.export_ncdf import write_run_psd
2193
+ from arrayprobe_soda2.pbp_writer import pbp_filename
2194
+ from arrayprobe_soda2.process_2d import REPORT_EVERY_BUFFERS, soda2_process_2d
2195
+
2196
+ on = sorted(n for n, v in (enh.get("resolved") or {}).items() if v)
2197
+ if apply is None or not on:
2198
+ why = ("the optional SODA-2 enhancements package is not installed" if apply is None
2199
+ else "the resolved set is empty for this probe and config")
2200
+ print(f"ENHANCED skipped: no correction applies to this run ({why}); "
2201
+ f"no <stem>.enh.* written")
2202
+ return 0
2203
+ work = Path(outdir) / ".enh_pass"
2204
+ work.mkdir(parents=True, exist_ok=True)
2205
+ op2 = dict(op)
2206
+ op2["outdir"] = str(work.resolve()) + os.sep
2207
+ enh = dict(enh, **{"pass": "corrected"})
2208
+ with apply(enh["resolved"]) as applied_record:
2209
+ d = soda2_process_2d(op2, report_every=REPORT_EVERY_BUFFERS, jobs=jobs, chunks=chunks,
2210
+ jit=jit, stamp_profile=stamp)
2211
+ enh["applied"] = applied_record["applied"]
2212
+ enh["skipped"] = applied_record["skipped"]
2213
+ enh["hook_points"] = applied_record["hook_points"]
2214
+ if d is None:
2215
+ print("arrayprobe soda2 run: the corrected pass returned no data; no <stem>.enh.* "
2216
+ "written", file=sys.stderr)
2217
+ return 1
2218
+ stem = Path(pbp_filename(d.op, str(d.op["shortname"]), extension="", outdir="")).name
2219
+
2220
+ def _move(path) -> str | None:
2221
+ if not path:
2222
+ return None
2223
+ src = Path(str(path))
2224
+ if not src.is_file():
2225
+ return str(path)
2226
+ rest = src.name[len(stem):] if src.name.startswith(stem) else "." + src.name
2227
+ dst = Path(outdir) / f"{stem}.enh{rest}"
2228
+ os.replace(src, dst)
2229
+ return str(dst)
2230
+
2231
+ outputs = {"pbp_csv": _move(d.pbp_csv_path), "pbp_ncdf": _move(d.pbp_ncdf_path)}
2232
+ sidecar = Path(outdir) / f"{stem}.enh.pbp.call"
2233
+ record = _soda2_record(d, config_path, enh, outputs)
2234
+ sidecar.write_text(json.dumps(record, indent=1, sort_keys=True) + "\n", encoding="utf-8")
2235
+ print(f"wrote {sidecar}")
2236
+ psd: Path | None
2237
+ try:
2238
+ psd = Path(str(_move(write_run_psd(d, outdir=str(work) + os.sep))))
2239
+ except Exception as exc: # noqa: BLE001 -- never lose the finished run to an extra file
2240
+ print(f"arrayprobe soda2 run: PSD <stem>.enh.nc skipped: {type(exc).__name__}: {exc}",
2241
+ file=sys.stderr)
2242
+ psd = None
2243
+ if psd is not None:
2244
+ print(f"wrote {psd}")
2245
+ try:
2246
+ written = attributed_export.export(psd, analysis_ready=analysis_ready)
2247
+ print(f"wrote {written}")
2248
+ except Exception as exc: # noqa: BLE001 -- the same rule
2249
+ print(f"arrayprobe soda2 run: ATTRIBUTED skipped for {psd.name}: "
2250
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
2251
+ for left in sorted(work.iterdir()):
2252
+ # the driver's other files (housekeeping and the like) take the same .enh. name
2253
+ if left.is_file():
2254
+ print(f"wrote {_move(left)}")
2255
+ try:
2256
+ work.rmdir() # only when empty: anything unexpected the driver left is kept
2257
+ except OSError:
2258
+ pass
2259
+ return 0
2260
+
2261
+
2262
+ def _soda2_write_attributed(d, outdir: str, *, analysis_ready: bool) -> Path | None:
2263
+ """``[outputs] faithful_attributed = true`` for a SODA-2 run: the run's size-distribution
2264
+ file ``<stem>.nc`` (:func:`arrayprobe_soda2.export_ncdf.write_run_psd` on the struct the
2265
+ driver returned) and its attributed sibling beside it, named by
2266
+ :func:`arrayprobe.attributed_export.default_output_path` exactly as the UIOOPS driver names
2267
+ its own.
2268
+
2269
+ A failure of either is logged by name and never fails the run, as in the UIOOPS driver's
2270
+ ``write_attributed``: the faithful PBP files and their ``.pbp.call`` are already written.
2271
+ Returns the attributed path, or ``None`` when it was not written."""
2272
+ from arrayprobe import attributed_export
2273
+ from arrayprobe_soda2.export_ncdf import write_run_psd
2274
+
2275
+ try:
2276
+ psd = Path(write_run_psd(d, outdir=outdir))
2277
+ except Exception as exc: # noqa: BLE001 -- never lose the finished run to an extra file
2278
+ print(f"arrayprobe soda2 run: PSD <stem>.nc skipped: {type(exc).__name__}: {exc}",
2279
+ file=sys.stderr)
2280
+ return None
2281
+ print(f"wrote {psd}")
2282
+ try:
2283
+ written = attributed_export.export(psd, analysis_ready=analysis_ready)
2284
+ except Exception as exc: # noqa: BLE001 -- the same rule
2285
+ print(f"arrayprobe soda2 run: ATTRIBUTED skipped for {psd.name}: "
2286
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
2287
+ return None
2288
+ print(f"wrote {written}")
2289
+ return written
2290
+
2291
+
2292
+ def _soda2_enhancements(args: argparse.Namespace) -> int:
2293
+ """``arrayprobe soda2 enhancements [config]``: the registry with reachability and, given
2294
+ a config, each correction's resolved state; or "package not installed"."""
2295
+ from .config import ConfigError, load_config
2296
+ cfg = None
2297
+ if args.config is not None:
2298
+ try:
2299
+ cfg = load_config(args.config)
2300
+ except (ConfigError, FileNotFoundError) as exc:
2301
+ print(f"arrayprobe soda2 enhancements: {exc}", file=sys.stderr)
2302
+ return 2
2303
+ try:
2304
+ table = _soda2_enhancement_table(cfg, protective_mode=getattr(args, "protective", None))
2305
+ except ConfigError as exc:
2306
+ print(f"arrayprobe soda2 enhancements: {args.config}: {exc}", file=sys.stderr)
2307
+ return 2
2308
+ if table["package"] == "not installed":
2309
+ print("arrayprobe_soda2_enhancements: package not installed "
2310
+ "(pip install arrayprobe-soda2-enhancements)")
2311
+ return 0
2312
+ try:
2313
+ from arrayprobe_soda2_enhancements._adapter import NOT_ROUTED
2314
+ except ImportError: # keeps TheCliNeverImportsTheSoda2PackageUnguarded green
2315
+ NOT_ROUTED = {}
2316
+ print(f"protective: mode={table['protective_mode']} "
2317
+ f"set={','.join(table['protective_set']) or '(none)'}")
2318
+ print(f"{'name':32s} {'reachability':12s} {'resolved':8s} applied")
2319
+ for name, reach in table["reachability"].items():
2320
+ on = table["resolved"].get(name, False)
2321
+ if not on:
2322
+ state = "-"
2323
+ elif name in NOT_ROUTED:
2324
+ state = f"no ({NOT_ROUTED[name]})"
2325
+ else:
2326
+ state = "yes"
2327
+ print(f"{name:32s} {reach:12s} {str(on):8s} {state}")
2328
+ return 0
2329
+
2330
+
2331
+ #: The two things a SODA-2 user needs before writing a config. Shown under
2332
+ #: `soda2 run --help`, and so on the generated CLI reference page. The GDL measurement behind
2333
+ #: the FLOAT claim: `help, fltarr(3)+{rate:1}.rate` is FLOAT, `...{rate:1.0d}...` DOUBLE.
2334
+ _SODA2_CONFIG_NOTE = """\
2335
+ The config file: [run] holds engine = "soda2" and, optionally, jit = true
2336
+ (the same switch as --jit, and the two are ORed); [soda2] holds the op
2337
+ fields, names unchanged from IDL; [enhancements] is optional. No [fidelity]
2338
+ table: the SODA-2 engine has one source tree and reads no UIOOPS profile, so
2339
+ naming one is refused. Raw file and output
2340
+ directory are [soda2].fn and [soda2].outdir (--out overrides outdir).
2341
+
2342
+ IDL types: TOML carries no IDL type, so every [soda2] number arrives as a
2343
+ Python int or float, where the IDL op held INT or FLOAT. A field left out
2344
+ takes soda2_update_op's default with IDL's own dtype. In IDL, activetime =
2345
+ fltarr(n) + op.rate is FLOAT unless op.rate is DOUBLE (1.0d). The driver
2346
+ reads a Python int rate as INT, so rate = 1 gives FLOAT as example_batch.pro's
2347
+ rate=1 does; a TOML float such as rate = 1.0 is DOUBLE. A nonzero FLOAT
2348
+ timeoffset is widened from FLOAT in IDL; to reproduce it, call the driver
2349
+ from Python with numpy.float32 values, e.g. op["timeoffset"] =
2350
+ numpy.float32(0.5):
2351
+ from arrayprobe_soda2.process_2d import soda2_process_2d
2352
+ """
2353
+
2354
+
2355
+ def _reproduce_report(args: argparse.Namespace) -> int:
2356
+ from arrayprobe.reproduce_report import render_markdown, write_report
2357
+
2358
+ rep = write_report(args.product, args.archived, out_md=args.out, out_json=args.json)
2359
+ if not args.out:
2360
+ print(render_markdown(rep), end="")
2361
+ return 0 if rep["identical"] else 1
2362
+
2363
+
2364
+ def _add_reproduce_report(sub: argparse._SubParsersAction) -> None:
2365
+ p = sub.add_parser(
2366
+ "reproduce-report",
2367
+ help="compare a product with an archived product, listing every differing cell",
2368
+ description="Read-only. Compares every variable the two netCDF files share, cell "
2369
+ "by cell, and reports cells compared, exact matches, max absolute and "
2370
+ "relative residual, every differing cell, and the engine and .call "
2371
+ "stamp of each file. Exits 0 when exact, 1 otherwise.",
2372
+ )
2373
+ p.add_argument("product", help="the product to check (netCDF)")
2374
+ p.add_argument("archived", help="the archived product (netCDF)")
2375
+ p.add_argument("--out", help="write the Markdown report here (default: stdout)")
2376
+ p.add_argument("--json", help="also write the report as JSON here")
2377
+ p.set_defaults(func=_reproduce_report)
2378
+
2379
+
2380
+ def _add_soda2(sub: argparse._SubParsersAction) -> None:
2381
+ import textwrap
2382
+
2383
+ # Filled here, not by argparse, because the raw formatter (kept for the epilog's code
2384
+ # line) would otherwise print the description as one unwrapped line.
2385
+ p = sub.add_parser(
2386
+ "soda2",
2387
+ help="the SODA-2 engine (arrayprobe_soda2, a faithful port of NCAR's IDL): "
2388
+ "run a config, or list its enhancements",
2389
+ description=textwrap.fill(
2390
+ "`soda2 run` reads [soda2] (the driver's op fields) from a config whose "
2391
+ "[run].engine is \"soda2\", runs soda2_process_2d and writes a deterministic "
2392
+ "<stem>.pbp.call sidecar beside the PBP outputs, <stem> being theirs. "
2393
+ "With the optional correction package installed, every resolved-ON "
2394
+ "correction the driver adapter can route is applied and the sidecar records "
2395
+ "which were applied and which skipped, with the reason. "
2396
+ "`soda2 enhancements` lists the optional correction package's "
2397
+ "registry. The UIOOPS version options do not apply to this engine, and `arrayprobe "
2398
+ "run` refuses a soda2 config with a pointer here. What a soda2 config may "
2399
+ "hold, and the IDL-type limit on op.rate: `soda2 run --help`.", width=76),
2400
+ formatter_class=argparse.RawDescriptionHelpFormatter,
2401
+ )
2402
+ verbs = p.add_subparsers(dest="verb", required=True)
2403
+ r = verbs.add_parser("run", help="run soda2_process_2d from a config file",
2404
+ description=textwrap.fill(
2405
+ "Run soda2_process_2d with op = the file's [soda2] table and "
2406
+ "write <stem>.pbp.call beside the PBP outputs. Exit 2 for a "
2407
+ "config it cannot run, 1 when the driver returns no data.",
2408
+ width=76),
2409
+ epilog=_SODA2_CONFIG_NOTE,
2410
+ formatter_class=argparse.RawDescriptionHelpFormatter)
2411
+ r.add_argument("config", type=Path, help="a run configuration TOML with a [soda2] table")
2412
+ r.add_argument("--out", type=Path, default=None,
2413
+ help="output directory; overrides [soda2].outdir")
2414
+ r.add_argument("--jobs", type=int, default=1, metavar="N",
2415
+ help="split soda2_process_2d's buffer loop across N processes "
2416
+ "(default 1, serial). Byte-identical to serial -- asserted by "
2417
+ "tests/test_soda2_parallel.py, not claimed here -- and refused "
2418
+ "by name where it would not be (op.stuckbits, "
2419
+ "op.activetimefrommissed, more than one raw file). It "
2420
+ "composes with the correction package: the enhancements are "
2421
+ "rebuilt by name inside each worker and the split stays "
2422
+ "byte-identical to serial with them ON "
2423
+ "(tests/test_soda2_parallel_enhancements.py), so --jobs is not "
2424
+ "a choice between fast and corrected. A resource "
2425
+ "knob, not a threshold: it is a flag and not a config key, "
2426
+ "because a config file may select a run's science and never "
2427
+ "describe it")
2428
+ r.add_argument("--chunks", type=int, default=0, metavar="N",
2429
+ help="how many contiguous buffer ranges --jobs splits the loop into "
2430
+ "(default 0 = 4 per job). More than one per job because a "
2431
+ "buffer's cost is its particle count, so equal buffer counts "
2432
+ "are not equal work. SODA-2 engine only, and read ONLY when "
2433
+ "--jobs > 1: with --jobs left at 1 this value is accepted and "
2434
+ "never looked at (process_2d.py's `if jobs > 1:` is its one "
2435
+ "reader), so it is a balance knob for the split and not a way "
2436
+ "to break one long run into resumable pieces")
2437
+ r.add_argument("--jit", action="store_true",
2438
+ help="SODA-2 engine only. Speed only, default off: route "
2439
+ "label_blobs's flood fill -- and fillholes' own call to it -- "
2440
+ "through numba (arrayprobe_soda2.jit_kernels; needs "
2441
+ "pip install \"arrayprobe[jit]\"). The PBP files are byte-identical to a "
2442
+ "run without it, asserted in "
2443
+ "tests/test_soda2_jit_product_identity.py (the written product, "
2444
+ "off against on) over tests/test_soda2_label_region_jit_identity.py "
2445
+ "(the kernel's own array) and not claimed here, so it is not "
2446
+ "written into op and the .pbp.call sidecar is "
2447
+ "the same either way. Measured 36.2x at the kernel. It installs "
2448
+ "no substitution (a --jit run leaves every enhancement_hooks "
2449
+ "point pristine, measured), so it composes with --jobs and "
2450
+ "--chunks at the engine level and the same module asserts that. "
2451
+ "With arrayprobe-soda2-enhancements installed, the two speedups "
2452
+ "and the corrections compose in one run. "
2453
+ "`[run].jit = true` in the config does "
2454
+ "the same thing; the two are ORed, so this flag can turn the "
2455
+ "kernel on and never off")
2456
+ r.add_argument("--protective", choices=("auto", "on", "off"), default=None,
2457
+ help="The protective-corrections rule applied to SODA-2: which of "
2458
+ "arrayprobe_soda2_enhancements.registry.PROTECTIVE (the corrections "
2459
+ "for data-destroying upstream defects) run by default. 'auto' (the "
2460
+ "default) resolves registry.protective_set for this config's "
2461
+ "[soda2].probetype; 'on' applies every PROTECTIVE name regardless of "
2462
+ "probe; 'off' applies none of them. Omitted, the config's "
2463
+ "[enhancements] protective = true/false decides (else 'auto'). "
2464
+ "An explicit "
2465
+ "[enhancements] <name> = false in the config still wins over a "
2466
+ "protective default. Recorded in the .pbp.call sidecar's "
2467
+ "enhancements.protective_mode/protective_set")
2468
+ r.set_defaults(func=_soda2_run)
2469
+ e = verbs.add_parser("enhancements",
2470
+ help="list the SODA-2 corrections (reachability; resolved state "
2471
+ "from a config if given)")
2472
+ e.add_argument("config", nargs="?", type=Path, default=None)
2473
+ e.add_argument("--protective", choices=("auto", "on", "off"), default=None,
2474
+ help="same meaning as `soda2 run --protective`")
2475
+ e.set_defaults(func=_soda2_enhancements)
2476
+
2477
+
2478
+ def _pct(a: float, b: float) -> str:
2479
+ return f"{100 * a / b:6.1f}%" if b else " nan%"
2480
+
2481
+
2482
+ def _validate_by_condition(args) -> int:
2483
+ """``arrayprobe validate by-condition`` -- formatting only.
2484
+
2485
+ Every number comes from :func:`arrayprobe.validate_by_condition.stratify`,
2486
+ which is where it moved on 2026-09-10 so that something could assert on it.
2487
+ This function decides column widths and nothing else.
2488
+ """
2489
+ try:
2490
+ ref = args.product or by_condition_module.find_product(
2491
+ args.combined, args.product_dir)
2492
+ except ValueError as e: # no --product-dir and no ARRAYPROBE_PRODUCT_DIR
2493
+ print(e, file=sys.stderr)
2494
+ return 2
2495
+ if not ref:
2496
+ print("no archived product found", file=sys.stderr)
2497
+ return 2
2498
+ if not os.path.isfile(args.combined):
2499
+ print(f"not a file: {args.combined}", file=sys.stderr)
2500
+ return 2
2501
+
2502
+ st = by_condition_module.stratify(
2503
+ args.combined, ref, args.window, args.drop_bins)
2504
+
2505
+ print(f"ours {os.path.basename(st.ours_path)}")
2506
+ print(f"ref {os.path.basename(st.ref_path)}")
2507
+ line = f"shared seconds {st.shared_seconds:,}"
2508
+ if args.window:
2509
+ line += f", in window {st.window_seconds:,}"
2510
+ print(line)
2511
+ print()
2512
+ print(f"{'condition':20s} {'secs':>6s} {'all: ours/ref':>20s} "
2513
+ f"{'ratio':>7s} {'used: ours/ref':>18s} {'ratio':>7s} "
2514
+ f"{'exact secs':>12s}")
2515
+ for b in (*st.bands, st.overall):
2516
+ print(f"{b.label:20s} {b.seconds:6,} "
2517
+ f"{b.all_ours:10,.0f}/{b.all_ref:<9,.0f} "
2518
+ f"{_pct(b.all_ours, b.all_ref)} "
2519
+ f"{b.used_ours:8,.0f}/{b.used_ref:<9,.0f} "
2520
+ f"{_pct(b.used_ours, b.used_ref)} "
2521
+ f"{b.exact_seconds:6,}/{b.seconds:<,}")
2522
+ return 0
2523
+
2524
+
2525
+ def _validate_timing_closure(args) -> int:
2526
+ for path in (args.decoded, args.proc):
2527
+ if not os.path.isfile(path):
2528
+ print(f"not a file: {path}", file=sys.stderr)
2529
+ return 1
2530
+ try:
2531
+ r = timing_closure_module.check_closure(
2532
+ args.decoded, args.proc, day_rollover_h=args.day_rollover_h)
2533
+ except ValueError as exc:
2534
+ print(exc, file=sys.stderr)
2535
+ return 1
2536
+ print(f"decoded file : {args.decoded} ({r.n_records} records)")
2537
+ print(f"proc file : {args.proc} ({r.n_particles} particles)")
2538
+ print(f"particle-clock span : {r.particle_clock_span_s:.3f} s")
2539
+ print(f"record-clock span : {r.record_clock_span_s:.3f} s")
2540
+ print(f"difference : {r.difference_s:+.3f} s")
2541
+ print(f"ratio (particle/record) : {r.ratio:.4f}")
2542
+ print()
2543
+ print("No published tolerance exists for this check "
2544
+ "(McFarquhar et al. 2017 states the check, not a number) -- "
2545
+ "this reports, it does not verdict.")
2546
+ return 0
2547
+
2548
+
2549
+ #: Why the PER-STAGE pipeline SUBCOMMANDS run the v3.1.4 engine and refuse ``3.5`` -- ``run`` is
2550
+ #: unaffected (it dispatches on ``[run].engine``, wired to both engines since 2026-09-13; see
2551
+ #: :func:`_refuse_unwired_engine`'s docstring). Each clause is a separate reason.
2552
+ _V35_PIPELINE_GAPS = (
2553
+ "`combine` wraps the v3.1.4 signature of the ORACLES fork's `combine_sizedist.m`; for v3.5 the "
2554
+ "same fork combine is BORROWED, opt-in and labelled (arrayprobe_uiops.combine), reached only "
2555
+ "through `arrayprobe run` with [run].engine = \"3.5\" and [combine].borrowed = true",
2556
+ "`read-binary`, `imgproc` and `sizedist` take v3.1.4's arguments (a profile, a tree); the v3.5 "
2557
+ "stage functions take the reject thresholds of a v3.5-flavoured profile -- STOCK_V35, or "
2558
+ "ORACLES_PRODUCTION_V35 for the ORACLES thresholds on the v3.5 engine -- plus v3.5-only "
2559
+ "switches, named whole as scripts/run_flight.py's V35_CALL and stamped in every .call; not "
2560
+ "exposed per stage here",
2561
+ "scripts/run_flight.py runs the v3.5 chain only when told --engine 3.5, which `arrayprobe run` "
2562
+ "passes from [run].engine; the per-stage subcommands never reach it",
2563
+ )
2564
+
2565
+
2566
+ #: The decision ``arrayprobe engines`` prints first: which engine for which job, and the command
2567
+ #: that runs it. Plain words for a first-time user; the per-module catalogue is behind
2568
+ #: ``--catalogue``.
2569
+ ENGINE_DECISION = (
2570
+ ("UIOPS v3.5 (the default)",
2571
+ "new data from any campaign and any probe",
2572
+ 'arrayprobe run <config.toml> with [run].engine = "3.5"'),
2573
+ ("SODA-2",
2574
+ "an independent second processing of the same raw file, to cross-check a UIOPS result",
2575
+ "arrayprobe soda2 run <config.toml>"),
2576
+ ("UIOPS v3.1.4",
2577
+ "only to reproduce an archived UIOPS product, such as the ORACLES 2D-S/HVPS record, "
2578
+ "or to check the port against one",
2579
+ 'arrayprobe run <config.toml> --port-validation with [run].engine = "3.1.4"'),
2580
+ )
2581
+
2582
+
2583
+ def _print_engine_decision() -> None:
2584
+ print("Which engine to use")
2585
+ for name, use, command in ENGINE_DECISION:
2586
+ if name == "UIOPS v3.1.4" and not _v314_engine_present():
2587
+ continue
2588
+ print(f" {name}")
2589
+ print(f" use for: {use}")
2590
+ print(f" run: {command}")
2591
+ print()
2592
+
2593
+
2594
+ def _engines(args: argparse.Namespace) -> int:
2595
+ """Print which engine to use for what, then what the chosen engine rests on.
2596
+
2597
+ With ``--catalogue`` (or ``--module``), also print which package implements
2598
+ each module for that UIOOPS version, and why. Imported inside the handler so
2599
+ the CLI's own import stays light and ``arrayprobe`` takes no module-level
2600
+ dependency on the selector.
2601
+ """
2602
+ import uiops
2603
+
2604
+ # `engines` describes rather than runs, so it defaults to the package
2605
+ # default (v3.5) and not to the pipeline's wired engine.
2606
+ engine = uiops.engine(args.engines_version)
2607
+ entries = uiops.CATALOGUE
2608
+ if args.module:
2609
+ unknown = [m for m in args.module if m not in entries]
2610
+ if unknown:
2611
+ print(f"no such module(s): {unknown}. Run with --catalogue for "
2612
+ f"the full list.", file=sys.stderr)
2613
+ return 2
2614
+ catalogue = bool(args.catalogue or args.module)
2615
+ if not args.module:
2616
+ _print_engine_decision()
2617
+ print(f"UIOPS {engine.version}"
2618
+ f"{' (the default)' if engine.is_default else ''}")
2619
+ print(f" validation: {engine.validation}")
2620
+ if not catalogue:
2621
+ print()
2622
+ print("Which package implements each module for this engine, and why: "
2623
+ "arrayprobe engines --catalogue")
2624
+ return 0
2625
+ print()
2626
+ names = args.module or sorted(n for n in entries if n)
2627
+ for name in names:
2628
+ print(f"{name}")
2629
+ print(f" {engine.provenance(name)}")
2630
+ if not args.module:
2631
+ print()
2632
+ print(f"{len(names)} modules. States: "
2633
+ f"overridden = v3.5 has its own translation; "
2634
+ f"shared = the MATLAB source is byte-identical, so one "
2635
+ f"translation serves both; "
2636
+ f"tooling = no MATLAB counterpart; "
2637
+ f"fork-only = the file is in no stock UIOPS release; "
2638
+ f"read-shared = the file changed but this region did not.")
2639
+ return 0
2640
+
2641
+
2642
+ def _add_engines(sub: argparse._SubParsersAction) -> None:
2643
+ p = sub.add_parser(
2644
+ "engines",
2645
+ help="which engine to use for what; --catalogue for the per-module detail",
2646
+ description=("Prints which engine to use for what: UIOPS v3.5 (the "
2647
+ "default) for new data, SODA-2 as an independent second "
2648
+ "processing, and UIOPS v3.1.4 only to reproduce an "
2649
+ "archived UIOPS product. Then states what the chosen "
2650
+ "engine's results rest on. --catalogue adds, per module, "
2651
+ "which package implements it for that UIOPS version and "
2652
+ "why: many MATLAB files are byte-identical between the "
2653
+ "two releases, so v3.5 often uses the v3.1.4 translation. "
2654
+ "Reads nothing and writes nothing."
2655
+ if _v314_engine_present() else
2656
+ "Prints which engine to use for what: UIOOPS v3.5 (the "
2657
+ "default) for new data and SODA-2 as an independent second "
2658
+ "processing. Then states what the chosen engine's results rest on. "
2659
+ "--catalogue adds, per module, which package implements it "
2660
+ "and why. Reads nothing and writes nothing."),
2661
+ )
2662
+ # Its own dest: `--uiops-version` also exists on the top-level parser,
2663
+ # and a subparser sharing the dest overwrites whatever was given before
2664
+ # the subcommand with its own default. Same flag to type, two stores.
2665
+ p.add_argument("--uiops-version", dest="engines_version",
2666
+ choices=list(uiops_versions()), default=None,
2667
+ help=("which UIOOPS engine to describe (default: the package "
2668
+ "default, v3.5)") if _v314_engine_present() else argparse.SUPPRESS)
2669
+ p.add_argument("--catalogue", action="store_true",
2670
+ help="also list every module and which package implements "
2671
+ "it for that engine, and why")
2672
+ p.add_argument("--module", action="append", metavar="NAME",
2673
+ help="describe only this module; repeatable")
2674
+ p.set_defaults(func=_engines)
2675
+
2676
+
2677
+ def uiops_versions() -> tuple[str, ...]:
2678
+ """The selectable UIOOPS versions, read from :mod:`uiops` rather than
2679
+ retyped -- a second list here would be one more thing to keep true."""
2680
+ import uiops
2681
+
2682
+ return uiops.VERSIONS
2683
+
2684
+
2685
+ def _tune_settings(args: argparse.Namespace) -> int:
2686
+ """Print :data:`arrayprobe.tune.settings.SETTINGS`, as text or JSON.
2687
+
2688
+ Read-only: runs nothing and writes nothing. With ``--probe-case`` each row also says whether
2689
+ it changes the output on that case (:meth:`~arrayprobe.tune.settings.Setting.effect`).
2690
+ """
2691
+ import json
2692
+
2693
+ from arrayprobe.tune import settings as tune_settings
2694
+
2695
+ case = args.probe_case
2696
+ effects: dict[str, Any] = {}
2697
+ if case is not None:
2698
+ from arrayprobe_uiops import probe_cases
2699
+
2700
+ try:
2701
+ effects = {s.name: s.effect(case, args.ia_thresh_type)
2702
+ for s in tune_settings.SETTINGS}
2703
+ except probe_cases.UnknownProbeCase as exc:
2704
+ print(f"arrayprobe tune settings: {exc}", file=sys.stderr)
2705
+ return 2
2706
+ if args.json:
2707
+ rows = []
2708
+ for s in tune_settings.SETTINGS:
2709
+ row: dict[str, Any] = {
2710
+ "name": s.name, "does": s.does, "default": s.default, "where": list(s.where),
2711
+ "engine_3_5": s.engine_35, "sources": [str(c) for c in s.cites]}
2712
+ if case is not None:
2713
+ eff = effects[s.name]
2714
+ row["effect"] = {"effective": eff.effective, "reason": eff.reason}
2715
+ rows.append(row)
2716
+ print(json.dumps({"engine": "3.5", "probe_case": case,
2717
+ "ia_thresh_type": args.ia_thresh_type, "settings": rows}, indent=2))
2718
+ return 0
2719
+ print("Settings a run on the default engine (UIOPS v3.5) can change.")
2720
+ if case is not None:
2721
+ print(f"Effect column: probe case {case!r}, iaThreshType {args.ia_thresh_type}.")
2722
+ print()
2723
+ for s in tune_settings.SETTINGS:
2724
+ print(s.name)
2725
+ print(f" what it does: {s.does}")
2726
+ print(f" default: {s.default}")
2727
+ print(f" where to set: {'; '.join(s.where)}")
2728
+ print(f" engine 3.5: {s.engine_35}")
2729
+ if case is not None:
2730
+ print(f" on {case}: {effects[s.name].reason}")
2731
+ print(f" source: {s.cites[0]}")
2732
+ print()
2733
+ print(f"{len(tune_settings.SETTINGS)} settings. Where: TOML = a key in the run file "
2734
+ "(`arrayprobe run run.toml`); CLI = a batch-driver (`arrayprobe run`) flag; "
2735
+ "probe case and "
2736
+ "profile = registered from Python. --json lists every source line.")
2737
+ return 0
2738
+
2739
+
2740
+ def _tune_sample(args: argparse.Namespace) -> int:
2741
+ """Draw the two review queues from one proc file and merge them into ``--queue-out``.
2742
+
2743
+ Reads three columns of the proc file and writes only the queue file
2744
+ (:mod:`arrayprobe.tune.sample`); the proc file and every product are left unchanged.
2745
+ """
2746
+ from arrayprobe.tune import sample
2747
+
2748
+ try:
2749
+ windows = sample.read_windows(args.windows)
2750
+ edges = (sample.check_edges(args.size_edges) if args.size_edges is not None
2751
+ else sample.SIZE_EDGES_MM)
2752
+ if args.per_bin < 1:
2753
+ raise ValueError("--per-bin must be at least 1")
2754
+ except ValueError as exc:
2755
+ print(f"arrayprobe tune sample: {exc}", file=sys.stderr)
2756
+ return 2
2757
+ if not args.proc.is_file():
2758
+ print(f"arrayprobe tune sample: no proc file at {args.proc}", file=sys.stderr)
2759
+ return 2
2760
+ flight = args.flight or sample.flight_from_proc_name(args.proc.name)
2761
+ t, diam, rej = sample.read_proc_columns(args.proc)
2762
+ try:
2763
+ queues, coverage = sample.build(
2764
+ args.proc.name, t, diam, rej, route=args.route, flight=flight, windows=windows,
2765
+ queue_stem=args.queue_stem, edges=edges, per_bin=args.per_bin, seed=args.seed)
2766
+ sample.write_queues(args.queue_out, queues, coverage)
2767
+ except ValueError as exc:
2768
+ print(f"arrayprobe tune sample: {exc}", file=sys.stderr)
2769
+ return 2
2770
+ for line in sample.summary_lines(coverage):
2771
+ print(line)
2772
+ print(f"wrote {args.queue_out} (open it with: arrayprobe triage --decoded-dir <dir> "
2773
+ f"--queue-file {args.queue_out})")
2774
+ return 0
2775
+
2776
+
2777
+ def _tune_distributions(args: argparse.Namespace) -> int:
2778
+ """Write the per-particle distributions inside the windows of one proc file to ``--out``.
2779
+
2780
+ Reads eight columns of the proc file (:mod:`arrayprobe.tune.distributions`) and writes only
2781
+ the JSON report; the proc file and every product are left unchanged.
2782
+ """
2783
+ import json
2784
+
2785
+ from arrayprobe.tune import distributions, sample
2786
+
2787
+ try:
2788
+ windows = sample.read_windows(args.windows)
2789
+ edges = (sample.check_edges(args.size_edges) if args.size_edges is not None
2790
+ else distributions.SIZE_EDGES_MM)
2791
+ marks = distributions.threshold_marks(args.probe_case, args.area_ratio_z)
2792
+ except (ValueError, KeyError) as exc:
2793
+ print(f"arrayprobe tune distributions: {exc}", file=sys.stderr)
2794
+ return 2
2795
+ if not args.proc.is_file():
2796
+ print(f"arrayprobe tune distributions: no proc file at {args.proc}", file=sys.stderr)
2797
+ return 2
2798
+ try:
2799
+ cols = distributions.read_proc_columns(args.proc)
2800
+ except ValueError as exc:
2801
+ print(f"arrayprobe tune distributions: {exc}", file=sys.stderr)
2802
+ return 2
2803
+ rep = distributions.report(cols, windows=windows, marks=marks, edges=edges,
2804
+ proc_name=args.proc.name)
2805
+ args.out.parent.mkdir(parents=True, exist_ok=True)
2806
+ args.out.write_text(json.dumps(rep, indent=1), encoding="utf-8")
2807
+ for line in distributions.summary_lines(rep):
2808
+ print(line)
2809
+ print(f"wrote {args.out}")
2810
+ return 0
2811
+
2812
+
2813
+ def _tune_score(args: argparse.Namespace) -> int:
2814
+ """Cross the reviewer's labels with each particle's reject code and size bin.
2815
+
2816
+ Reads the queue file and the triage verdict store (:mod:`arrayprobe.tune.score`) and
2817
+ writes only the JSON report, when ``--out`` is given; nothing else is changed.
2818
+ """
2819
+ import json
2820
+
2821
+ from arrayprobe.triage_server import VerdictStoreError, _load_queue_file
2822
+ from arrayprobe.tune import score
2823
+
2824
+ if not args.queue_file.is_file():
2825
+ print(f"arrayprobe tune score: no queue file at {args.queue_file}", file=sys.stderr)
2826
+ return 2
2827
+ if not args.decoded_dir.is_dir():
2828
+ print(f"arrayprobe tune score: no decoded directory at {args.decoded_dir}",
2829
+ file=sys.stderr)
2830
+ return 2
2831
+ pv = tuple(v.strip() for v in args.phase_verdicts.split(",") if v.strip())
2832
+ try:
2833
+ data = _load_queue_file(args.queue_file)
2834
+ rep = score.score_file(data, args.decoded_dir, pv)
2835
+ except (ValueError, VerdictStoreError) as exc:
2836
+ print(f"arrayprobe tune score: {exc}", file=sys.stderr)
2837
+ return 2
2838
+ if not rep["queues"]:
2839
+ print(f"arrayprobe tune score: no queue in {args.queue_file}", file=sys.stderr)
2840
+ return 2
2841
+ for line in score.summary_lines(rep):
2842
+ print(line)
2843
+ if args.out is not None:
2844
+ args.out.parent.mkdir(parents=True, exist_ok=True)
2845
+ args.out.write_text(json.dumps(rep, indent=1), encoding="utf-8")
2846
+ print(f"wrote {args.out}")
2847
+ return 0
2848
+
2849
+
2850
+ def _tune_diodes(args: argparse.Namespace) -> int:
2851
+ """Report stuck diodes in each proc file and print the run-file lines that mask them.
2852
+
2853
+ Reads ``bin_stats`` (and ``position`` for a shadow count) through
2854
+ :mod:`arrayprobe.tune.diodes`; the proc files and every product are left unchanged.
2855
+ """
2856
+ import json
2857
+ import re
2858
+
2859
+ from arrayprobe.tune import diodes
2860
+
2861
+ reports = []
2862
+ for proc in args.proc:
2863
+ if not proc.is_file():
2864
+ print(f"arrayprobe tune diodes: no proc file at {proc}", file=sys.stderr)
2865
+ return 2
2866
+ stem = args.stem
2867
+ if stem is None:
2868
+ hit = re.search(r"base\d{12}", proc.name)
2869
+ if hit is None:
2870
+ print(f"arrayprobe tune diodes: {proc.name} names no raw stem "
2871
+ "(base<12 digits>); pass --stem", file=sys.stderr)
2872
+ return 2
2873
+ stem = hit.group(0)
2874
+ try:
2875
+ rep = diodes.report(proc, profile=args.profile, probe=args.probe,
2876
+ jobs=args.jobs)
2877
+ except (ValueError, KeyError, OSError) as exc:
2878
+ print(f"arrayprobe tune diodes: {exc}", file=sys.stderr)
2879
+ return 2
2880
+ rep["stem"] = stem
2881
+ rep["toml"] = diodes.toml_line(stem, rep["flagged"])
2882
+ reports.append(rep)
2883
+ if args.json:
2884
+ print(json.dumps(reports if len(reports) > 1 else reports[0], indent=1))
2885
+ return 0
2886
+ for rep in reports:
2887
+ for line in diodes.summary_lines(rep):
2888
+ print(line)
2889
+ print(" run-file lines (apply with --diode-corrected):")
2890
+ for line in rep["toml"].splitlines():
2891
+ print(f" {line}")
2892
+ return 0
2893
+
2894
+
2895
+ def _add_tune(sub: argparse._SubParsersAction) -> None:
2896
+ p = sub.add_parser(
2897
+ "tune",
2898
+ help="what a user can change for the default engine, and whether it has any effect",
2899
+ description="Tuning a run on the default engine (UIOOPS v3.5). Nothing here runs the "
2900
+ "pipeline or changes a product; `sample` writes only a review queue file "
2901
+ "and `distributions` and `score` only a JSON report.",
2902
+ )
2903
+ verbs = p.add_subparsers(dest="verb", required=True)
2904
+ s = verbs.add_parser(
2905
+ "settings",
2906
+ help="list every setting: what it does, its default, where to set it",
2907
+ description="Lists every setting a run on the default engine (UIOOPS v3.5) can "
2908
+ "change: what it does, its default, where it is set (run file, "
2909
+ "run_flight.py flag, probe case, profile or preset), and whether "
2910
+ "engine 3.5 accepts it. Given a probe case, it also says whether each "
2911
+ "setting has any effect there: the shattering settings change nothing "
2912
+ "where the case's applyIntArrThresh is 0, or where the run's "
2913
+ "iaThreshType is 0 (engine 3.5's default without a threshold file). "
2914
+ "Each default is cited to "
2915
+ "the source line it was read from; the JSON form lists them all.",
2916
+ )
2917
+ s.add_argument("--probe-case", default=None, metavar="NAME",
2918
+ help="also say whether each setting has any effect on this registered "
2919
+ "probe case (v35-2ds-ladder-fix is always available)")
2920
+ s.add_argument("--ia-thresh-type", type=int, choices=(0, 1, 2, 3), default=0,
2921
+ help="the run's iaThreshType for the effect column (default 0, engine "
2922
+ "3.5's default without a threshold file; 2 is "
2923
+ "[shattering].ia_thresh_type = 2)")
2924
+ s.add_argument("--json", action="store_true",
2925
+ help="print the table as JSON, with every source line")
2926
+ s.set_defaults(func=_tune_settings)
2927
+
2928
+ m = verbs.add_parser(
2929
+ "sample",
2930
+ help="draw review queues from a proc file: particles inside time windows, per size bin",
2931
+ description="From one proc file, take the particles whose record header time (Time, "
2932
+ "HHMMSS) falls inside any window (seconds of day, both ends included) "
2933
+ "and whose image_diam_minR is at least the first size edge, and draw up "
2934
+ "to --per-bin of each size bin at random with a fixed seed. Two queues: "
2935
+ "the accepted image codes only (0HhuR), and every code. They are merged "
2936
+ "into --queue-out, the file `arrayprobe triage --queue-file` reads, with "
2937
+ "a coverage block per queue; other queues in that file are kept.",
2938
+ )
2939
+ m.add_argument("--proc", type=Path, required=True, help="the proc file to draw from")
2940
+ m.add_argument("--windows", required=True, metavar="W",
2941
+ help="time windows as lo-hi seconds of day ('47925-47959,51671-51797'), "
2942
+ "or a file of such pairs (one or more per line, # for comments)")
2943
+ m.add_argument("--queue-out", type=Path, required=True, metavar="Q",
2944
+ help="queue file to write, or to add the two queues to")
2945
+ m.add_argument("--route", default="unspecified", metavar="R",
2946
+ help="how the proc file was made, recorded in the coverage")
2947
+ m.add_argument("--flight", default=None,
2948
+ help="flight name the triage server knows the particles by (default: "
2949
+ "the proc file name without 'proc.' and '.nc')")
2950
+ m.add_argument("--queue-stem", default="sample",
2951
+ help="queue name prefix; the queues are <stem>-accepted-n<N>-s<seed> "
2952
+ "and <stem>-all-n<N>-s<seed> (default: sample)")
2953
+ m.add_argument("--size-edges", type=float, nargs="+", default=None, metavar="MM",
2954
+ help="size-bin edges in mm, increasing; the first is the size floor "
2955
+ "and 'inf' closes the last bin (default: 0.055 0.1 0.2 0.4 1.0 inf)")
2956
+ m.add_argument("--per-bin", type=int, default=40,
2957
+ help="particles drawn per size bin (default: 40)")
2958
+ m.add_argument("--seed", type=int, default=20260930,
2959
+ help="random seed; the same seed and inputs give the same queues "
2960
+ "(default: 20260930)")
2961
+ m.set_defaults(func=_tune_sample)
2962
+
2963
+ d = verbs.add_parser(
2964
+ "distributions",
2965
+ help="per-particle distributions inside time windows of a proc file, thresholds marked",
2966
+ description="From one proc file, for the particles whose record header time (Time, "
2967
+ "HHMMSS) falls inside any window (seconds of day, both ends included): "
2968
+ "particles per second, inter-arrival time, area ratio and axis ratio per "
2969
+ "size bin, the reject codes in words, habit codes and the hollow fraction. "
2970
+ "Each active threshold is marked where it cuts, with where its value was "
2971
+ "read from: the area-ratio cut, the image-stage aspect-ratio ceilings and, "
2972
+ "given --probe-case, the shattering threshold, with whether it has any "
2973
+ "effect on that case. Non-finite diameters get their own size bin. Writes "
2974
+ "only the JSON report.",
2975
+ )
2976
+ d.add_argument("--proc", type=Path, required=True, help="the proc file to read")
2977
+ d.add_argument("--windows", required=True, metavar="W",
2978
+ help="time windows as lo-hi seconds of day ('47925-47959,51671-51797'), "
2979
+ "or a file of such pairs (one or more per line, # for comments)")
2980
+ d.add_argument("--out", type=Path, required=True, metavar="REPORT",
2981
+ help="JSON report to write")
2982
+ d.add_argument("--probe-case", default=None, metavar="NAME",
2983
+ help="mark this registered probe case's shattering threshold and say "
2984
+ "whether its gate is on (v35-2ds-ladder-fix is always available)")
2985
+ d.add_argument("--area-ratio-z", type=float, default=None, metavar="Z",
2986
+ help="the area-ratio cut to mark: the value the run passes for this "
2987
+ "flag (default: v3.5's stock cut)")
2988
+ d.add_argument("--size-edges", type=float, nargs="+", default=None, metavar="MM",
2989
+ help="size-bin edges in mm, increasing; 'inf' closes the last bin "
2990
+ "(default: 0 0.055 0.1 0.2 0.4 1.0 inf)")
2991
+ d.set_defaults(func=_tune_distributions)
2992
+
2993
+ g = verbs.add_parser(
2994
+ "diodes",
2995
+ help="stuck diodes from a proc file's bin_stats, with the run-file lines that mask them",
2996
+ description="For each proc file, read bin_stats as lit counts (a shadow count is "
2997
+ "converted as S - shadow, S the particles' slice total from "
2998
+ "position) and apply the archived-product variant's stuck-diode rule "
2999
+ "(find_shadow_diodes.m:66-97): below 0.80 x max, or below 0.80 x mean when "
3000
+ "a diode reads above 1.2 x mean. The engine and profile come from the "
3001
+ "file's provenance; an unstamped file needs "
3002
+ "--profile. Prints a [masking.diodes] entry per file, applied by a run "
3003
+ "given --diode-corrected. Reads only.",
3004
+ )
3005
+ g.add_argument("--proc", type=Path, required=True, action="append",
3006
+ help="a proc file to read (repeatable)")
3007
+ g.add_argument("--profile", default=None, metavar="NAME",
3008
+ help=("the v3.1.4 fidelity profile, when the file's stamp names none"
3009
+ if _v314_engine_present() else
3010
+ "the fidelity profile, when the file's stamp names none"))
3011
+ g.add_argument("--probe", default=None, metavar="NAME",
3012
+ help="the probe whose image_slice_offset enters S (default: the offset "
3013
+ "every probe of the file's diode count shares)")
3014
+ g.add_argument("--stem", default=None, metavar="STEM",
3015
+ help="the raw stem the [masking.diodes] entry is keyed by (default: the "
3016
+ "base<12 digits> in the proc file's name)")
3017
+ g.add_argument("--json", action="store_true",
3018
+ help="print the full report as JSON instead of the summary")
3019
+ g.add_argument("--jobs", type=int, default=None, metavar="N",
3020
+ help="worker processes reading position for S (default: up to 8 above "
3021
+ "2 M particles, else 1; 1 forces a serial read). A parallel read that "
3022
+ "fails or stalls falls back to the serial one; S is identical either way")
3023
+ g.set_defaults(func=_tune_diodes)
3024
+
3025
+ c = verbs.add_parser(
3026
+ "score",
3027
+ help="the reviewer's labels per reject code and size bin: what each code rejected "
3028
+ "that was labelled real, and accepted that was labelled artifact",
3029
+ description="For each queue in --queue-file, join the verdicts and phases recorded "
3030
+ "in `arrayprobe triage` (the verdict store under --decoded-dir; a "
3031
+ "recheck- queue reads its own store) to the queue's particles, and count "
3032
+ "them per size bin and per reject code (the code each particle carried "
3033
+ "when the queue was drawn). For a rejecting code: how many it rejected "
3034
+ "that were labelled real; for an accepted code: how many it accepted that "
3035
+ "were labelled artifact. Per size bin, the ice fraction ice / (ice + "
3036
+ "drizzle) with a Wilson 95 % interval. Writes only the JSON report.",
3037
+ )
3038
+ c.add_argument("--queue-file", type=Path, required=True, metavar="Q",
3039
+ help="the queue file the labels were made from")
3040
+ c.add_argument("--decoded-dir", type=Path, required=True, metavar="D",
3041
+ help="the directory `arrayprobe triage --decoded-dir` was given; verdicts "
3042
+ "are read from its triage_verdicts/")
3043
+ c.add_argument("--out", type=Path, default=None, metavar="REPORT",
3044
+ help="JSON report to write (default: print the summary only)")
3045
+ c.add_argument("--phase-verdicts", default="real", metavar="V",
3046
+ help="comma-separated verdicts whose phase enters the ice fraction "
3047
+ "(default: real)")
3048
+ c.set_defaults(func=_tune_score)
3049
+
3050
+
3051
+ def _add_validate(sub: argparse._SubParsersAction) -> None:
3052
+ p = sub.add_parser(
3053
+ "validate",
3054
+ help="diagnostic checks on files the pipeline already wrote",
3055
+ description="Read-only checks. Nothing here computes or writes a "
3056
+ "pipeline number. Each check reports a comparison and "
3057
+ "returns 0 on success -- none of them issues a pass/fail "
3058
+ "verdict, because none of the sources they implement "
3059
+ "publishes a tolerance.",
3060
+ )
3061
+ checks = p.add_subparsers(dest="check", required=True)
3062
+ tc = checks.add_parser(
3063
+ "timing-closure",
3064
+ help="does the probe's particle clock agree with its housekeeping clock?",
3065
+ description="McFarquhar et al. (2017) ch. 11 p. 11.20. Compares the "
3066
+ "proc file's particle-clock time span against the decoded "
3067
+ "file's own record-clock span, which is measured by a "
3068
+ "different clock in the instrument. Probetype 2 (2D-S / "
3069
+ "HVPS) only -- see arrayprobe.timing_closure for why.",
3070
+ )
3071
+ tc.add_argument("decoded",
3072
+ help="the decoded file the proc file was framed from "
3073
+ "(.H.nc/.V.nc from engine 3.5, or an archived "
3074
+ ".H.cdf/.V.cdf); pairing them correctly is the "
3075
+ "caller's responsibility")
3076
+ tc.add_argument("proc", help="the proc (image-processing) file")
3077
+ tc.add_argument("--day-rollover-h", type=float, default=24.0,
3078
+ help="hours added once if the record span looks negative "
3079
+ "(a single midnight crossing); default 24.0")
3080
+ tc.set_defaults(func=_validate_timing_closure)
3081
+
3082
+ bc = checks.add_parser(
3083
+ "by-condition",
3084
+ help="per-second agreement against the archived product, split by "
3085
+ "how much cloud the probe was in",
3086
+ description="A single headline percentage can hide a whole regime. "
3087
+ "The band for each second is decided by the REFERENCE's "
3088
+ "own per-second particle total, never by ours -- using "
3089
+ "ours would make the stratification depend on the thing "
3090
+ "being tested.",
3091
+ )
3092
+ bc.add_argument("combined", help="our combined product")
3093
+ bc.add_argument("--product",
3094
+ help="the archived product; when omitted, found by date "
3095
+ "in --product-dir")
3096
+ bc.add_argument("--product-dir",
3097
+ default=by_condition_module.DEFAULT_PRODUCTS)
3098
+ bc.add_argument("--window", help="HHMMSS-HHMMSS, inclusive-exclusive, so a "
3099
+ "partially processed flight is compared "
3100
+ "only where its raw files are all present")
3101
+ bc.add_argument("--drop-bins", type=int, default=5,
3102
+ help="bins excluded from the 'used' columns (default 5)")
3103
+ bc.set_defaults(func=_validate_by_condition)
3104
+
3105
+
3106
+ def _view_strip(args) -> int:
3107
+ """``arrayprobe view strip`` -- :func:`arrayprobe.diagnostic_views.record_strip`, to a file."""
3108
+ import netCDF4
3109
+
3110
+ from . import diagnostic_views as views
3111
+
3112
+ with netCDF4.Dataset(args.image) as im, netCDF4.Dataset(args.proc) as pr:
3113
+ strip = views.record_strip(im, pr, args.record, args.n_records,
3114
+ colour_by=args.colour_by)
3115
+ out = Path(args.out)
3116
+ if out.suffix.lower() == ".png":
3117
+ out.write_bytes(views.record_strip_png(strip))
3118
+ else:
3119
+ title = f"{Path(args.image).name}: records {strip.records[0]}-{strip.records[-1]}"
3120
+ out.write_text(f"<!doctype html><meta charset='utf-8'><title>{title}</title>"
3121
+ + views.record_strip_html(strip, title=title), encoding="utf-8")
3122
+ print(f"records {strip.records[0]}-{strip.records[-1]}: {len(strip.particles)} "
3123
+ f"particle(s), {int(strip.boundary.sum())} boundary slice(s); wrote {out}",
3124
+ flush=True)
3125
+ return 0
3126
+
3127
+
3128
+ def _view_second(args) -> int:
3129
+ """``arrayprobe view second`` -- :func:`arrayprobe.diagnostic_views.compare_second`."""
3130
+ from . import diagnostic_views as views
3131
+
3132
+ cmp = views.compare_second(args.ours, args.theirs, args.second, variable=args.variable,
3133
+ proc=args.proc, diameter_var=args.diameter_var,
3134
+ rtol=args.rtol)
3135
+ print(cmp.summary(), flush=True)
3136
+ if args.out:
3137
+ Path(args.out).write_text(
3138
+ f"<!doctype html><meta charset='utf-8'><title>second {cmp.second:06d}</title>"
3139
+ + views.second_comparison_html(cmp, ours_label=Path(args.ours).name,
3140
+ theirs_label=Path(args.theirs).name),
3141
+ encoding="utf-8")
3142
+ print(f"wrote {args.out}", flush=True)
3143
+ return 0
3144
+
3145
+
3146
+ def _view_hollow(args: argparse.Namespace) -> int:
3147
+ import netCDF4
3148
+ import numpy as np
3149
+
3150
+ from . import diagnostic_views as views
3151
+
3152
+ if args.edges_um is not None:
3153
+ edges = [float(x) for x in args.edges_um.split(",") if x.strip()]
3154
+ else:
3155
+ with netCDF4.Dataset(args.edges_from) as d:
3156
+ d.set_auto_maskandscale(False)
3157
+ bmin = np.asarray(d.variables["Bin Minimum"][:], dtype=np.float64)
3158
+ bmax = np.asarray(d.variables["Bin Maximum"][:], dtype=np.float64)
3159
+ edges = list(np.concatenate([bmin, bmax[-1:]]) * 1000.0)
3160
+ kw = {} if args.min_fraction is None else {"min_fraction": args.min_fraction}
3161
+ print(views.hollow_share_text(views.hollow_share(args.proc, edges, **kw)), flush=True)
3162
+ return 0
3163
+
3164
+
3165
+ def _add_view(sub: argparse._SubParsersAction) -> None:
3166
+ p = sub.add_parser(
3167
+ "view",
3168
+ help="diagnostic views of files the pipeline already wrote",
3169
+ description="Visualisation only: each view reads the port's own outputs "
3170
+ "and computes no pipeline number (arrayprobe.diagnostic_views). "
3171
+ "The triage server serves the record strip at /strip/<flight>.",
3172
+ )
3173
+ views = p.add_subparsers(dest="view", required=True)
3174
+ s = views.add_parser(
3175
+ "strip",
3176
+ help="whole image records with their particles in place (HydroViewer's view)",
3177
+ description="Consecutive 1700-slice records stacked one above the next, "
3178
+ "boundary slices marked, each particle's shadow coloured by its "
3179
+ "reject code or habit, and every fifth particle ticked in red.",
3180
+ )
3181
+ s.add_argument("image", help=("the decoded image file (.H.nc from engine 3.5, "
3182
+ ".H.cdf from engine 3.1.4)"
3183
+ if _v314_engine_present() else
3184
+ "the decoded image file (.H.nc)"))
3185
+ s.add_argument("proc", help="the proc file framed from it")
3186
+ s.add_argument("--record", type=int, default=1, help="first record, 1-based (default 1)")
3187
+ s.add_argument("--n-records", type=int, default=6, help="records to show (default 6)")
3188
+ s.add_argument("--colour-by", choices=("reject", "habit"), default="reject")
3189
+ s.add_argument("--out", required=True,
3190
+ help="output file: .png for the image alone, anything else for an "
3191
+ "HTML page with the legend and particle table")
3192
+ s.set_defaults(func=_view_strip)
3193
+
3194
+ c = views.add_parser(
3195
+ "second",
3196
+ help="one second of two sd files bin by bin, with the particles behind the "
3197
+ "differing cells",
3198
+ description="For validation: the port's second beside the archive's. Exact "
3199
+ "comparison unless --rtol is given. The particle list is where to "
3200
+ "look, not what was counted: `count` also requires the reject "
3201
+ "codes, centre-in and time window to pass.",
3202
+ )
3203
+ c.add_argument("ours", help="our sd (or combined) file")
3204
+ c.add_argument("theirs", help="the file to compare against, e.g. the archived product")
3205
+ c.add_argument("--second", type=int, required=True, help="the second, as HHMMSS")
3206
+ c.add_argument("--variable", default="count", help="a (time, bin) variable (default count)")
3207
+ c.add_argument("--proc", default=None,
3208
+ help="the proc file behind OURS; lists the particles in differing bins")
3209
+ c.add_argument("--diameter-var", default="image_diam_minR",
3210
+ help="the proc variable particles are placed in bins by "
3211
+ "(default image_diam_minR); printed with every listing")
3212
+ c.add_argument("--rtol", type=float, default=0.0,
3213
+ help="relative tolerance; 0 (default) is an exact comparison")
3214
+ c.add_argument("--out", default=None, help="also write an HTML page here")
3215
+ c.set_defaults(func=_view_second)
3216
+
3217
+ h = views.add_parser(
3218
+ "hollow",
3219
+ help="how much of a between-engine difference hollow ('H') particles can make",
3220
+ description="Reads one UIOOPS v3.5 proc file. Per size bin: accepted particles, "
3221
+ "accepted 'H' (hollow, Poisson-spot) particles, their share, how many the "
3222
+ "Korolev size correction moves out of and into the bin, and the count "
3223
+ "with the correction undone. Ends with a verdict: whether hollow sizing "
3224
+ "can explain a difference between engines (SODA-2 does not divide) in "
3225
+ "this size range. Reads the file and writes nothing.",
3226
+ )
3227
+ h.add_argument("proc", help="the v3.5 proc file (proc.<stem>.<channel>.nc)")
3228
+ edges = h.add_mutually_exclusive_group(required=True)
3229
+ edges.add_argument("--edges-um", default=None,
3230
+ help="comma-separated bin edges in micrometres, e.g. 55,65,75,85,95,105,115")
3231
+ edges.add_argument("--edges-from", default=None,
3232
+ help="a size-distribution file whose Bin Minimum/Bin Maximum (mm) give "
3233
+ "the bins")
3234
+ h.add_argument("--min-fraction", type=float, default=None,
3235
+ help="verdict threshold as a fraction of the range's count (default 0.05)")
3236
+ h.set_defaults(func=_view_hollow)
3237
+
3238
+
3239
+ def _stage_commands_sentence() -> str:
3240
+ """What the per-stage commands run, true in the tree this file is installed in."""
3241
+ if _v314_engine_present():
3242
+ return ("The per-stage commands (read-binary, imgproc, sizedist, "
3243
+ "combine) run the validation engine, UIOPS v3.1.4, which "
3244
+ "reproduces archived UIOPS products such as the ORACLES "
3245
+ "2D-S/HVPS record; use them to check one stage against "
3246
+ "that record, not to process new data. ")
3247
+ return ("To run one stage at a time, use `arrayprobe run` with "
3248
+ "[run].stages. ")
3249
+
3250
+
3251
+ def _uiops_version_help() -> str:
3252
+ """Help for the top-level ``--uiops-version``, true in the tree this file is installed in."""
3253
+ if _v314_engine_present():
3254
+ return ("which UIOPS engine the per-stage commands run. They "
3255
+ "run 3.1.4, the validation engine, only; naming "
3256
+ "another version refuses with the reason and runs "
3257
+ "nothing. For the default engine (3.5) use "
3258
+ "`arrayprobe run` with [run].engine = \"3.5\".")
3259
+ return argparse.SUPPRESS
3260
+
3261
+
3262
+ _V314_ONLY_SUBCOMMANDS = ("read-binary", "imgproc", "sizedist")
3263
+
3264
+
3265
+ def build_parser() -> argparse.ArgumentParser:
3266
+ """The whole command surface: one subcommand per pipeline stage.
3267
+
3268
+ Separate from :func:`main` so the argument surface can be inspected and
3269
+ tested without running anything -- the fidelity-sensitive defaults are the
3270
+ part worth pinning, and the tests assert what is *required* rather than what
3271
+ a run produces.
3272
+
3273
+ **Every fidelity-sensitive argument is required, never defaulted**, and that
3274
+ is the CLI's one real design decision. A default profile, tree or
3275
+ ``d_choice`` would let someone process a campaign under a configuration
3276
+ nobody chose, and a wrong reject threshold applied that way changes every
3277
+ concentration without a warning. Convenience defaults belong in a
3278
+ config file the user writes, not in the front door.
3279
+ """
3280
+ p = argparse.ArgumentParser(
3281
+ prog="arrayprobe",
3282
+ description="Start with `arrayprobe make-demo-flight`, which writes a small "
3283
+ "synthetic raw file, then process a flight with `arrayprobe run "
3284
+ "<config.toml>`: it runs every stage on the engine the file names "
3285
+ "([run].engine, required; use \"3.5\", UIOOPS v3.5, for new data; "
3286
+ "examples/configs/ has configs). "
3287
+ + _stage_commands_sentence()
3288
+ + "`arrayprobe engines` says which engine does what.",
3289
+ )
3290
+ # `--version` matters more here than in most packages: the whole claim is
3291
+ # that specific numbers come out, so "which version produced this" is a
3292
+ # question a user has to be able to answer from the command that produced
3293
+ # it. The `.call` sidecar records the arguments; this records the code.
3294
+ p.add_argument("--version", action="version",
3295
+ version=f"arrayprobe {__version__} (UIOOPS "
3296
+ f"v{'3.1.4' if _v314_engine_present() else '3.5'} engine)")
3297
+ # Naming a version the pipeline cannot run must fail loudly. The
3298
+ # alternative -- accepting `3.5` and quietly running v3.1.4 -- is the
3299
+ # shape of failure this project keeps building checks against: an
3300
+ # explicit instruction silently not happening. Same reasoning as the
3301
+ # enhancements resolver, which raises rather than dropping a switched-on
3302
+ # enhancement that does not apply to the engine.
3303
+ p.add_argument("--uiops-version", default="3.1.4",
3304
+ help=_uiops_version_help())
3305
+ # Since 2026-09-15 the four library packages (``arrayprobe``,
3306
+ # ``arrayprobe_uiops``, ``arrayprobe_soda2``, ``uiops``) route their
3307
+ # progress/warning messages through ``logging`` and install only a
3308
+ # ``NullHandler`` on import, so a bare library import stays silent. This
3309
+ # console script is where a real handler belongs -- these flags control
3310
+ # its level; they do not touch this module's own ``print()`` output
3311
+ # (subcommand results, help text, error banners), which is unaffected by
3312
+ # either flag.
3313
+ verbosity = p.add_mutually_exclusive_group()
3314
+ verbosity.add_argument(
3315
+ "--quiet", action="store_true",
3316
+ help="suppress informational/warning library logging (errors still "
3317
+ "show); does not affect a subcommand's own print() output.")
3318
+ verbosity.add_argument(
3319
+ "--verbose", action="store_true",
3320
+ help="show DEBUG-level library logging in addition to the default "
3321
+ "INFO/WARNING messages.")
3322
+ sub = p.add_subparsers(dest="command", required=True)
3323
+ _add_run(sub)
3324
+ _add_reprocess(sub)
3325
+ if _v314_engine_present():
3326
+ _add_read_binary(sub)
3327
+ _add_imgproc(sub)
3328
+ _add_sizedist(sub)
3329
+ # combine runs on v3.5 too (--engine 3.5 --borrowed-combine, the user guide's per-stage line)
3330
+ _add_combine(sub)
3331
+ _add_compare(sub)
3332
+ _add_gallery(sub)
3333
+ _add_inventory(sub)
3334
+ _add_check_counts(sub)
3335
+ _add_triage(sub)
3336
+ _add_triage_agreement(sub)
3337
+ _add_provenance(sub)
3338
+ _add_diode_masks(sub)
3339
+ _add_validate(sub)
3340
+ _add_view(sub)
3341
+ _add_intarr(sub)
3342
+ _add_attributed(sub)
3343
+ _add_make_demo_flight(sub)
3344
+ _add_make_tas_file(sub)
3345
+ _add_tas_from_nasa_ames(sub)
3346
+ _add_engines(sub)
3347
+ _add_tune(sub)
3348
+ _add_soda2(sub)
3349
+ _add_reproduce_report(sub)
3350
+ return p
3351
+
3352
+
3353
+ #: Subcommands left out of ``arrayprobe --help``'s listing: maintainer and review-workflow tools
3354
+ #: Each still runs and keeps its own
3355
+ #: ``--help``, and :func:`build_parser` still registers it, so the CLI reference pages
3356
+ #: generated from the parser list it. Only :func:`main`'s top-level listing leaves it out.
3357
+ _UNLISTED_SUBCOMMANDS = ("check-counts", "triage-recheck", "triage-agreement", "attributed",
3358
+ "reproduce-report")
3359
+
3360
+
3361
+ def _hide_unlisted(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
3362
+ """``parser`` with :data:`_UNLISTED_SUBCOMMANDS` dropped from its help listing only."""
3363
+ for action in parser._actions: # noqa: SLF001
3364
+ if isinstance(action, argparse._SubParsersAction): # noqa: SLF001
3365
+ shown = [a for a in action._choices_actions # noqa: SLF001
3366
+ if a.dest not in _UNLISTED_SUBCOMMANDS]
3367
+ action._choices_actions = shown # noqa: SLF001
3368
+ action.metavar = "{" + ",".join(a.dest for a in shown) + "}"
3369
+ return parser
3370
+
3371
+
3372
+ #: The per-stage commands whose own ``--engine`` resolves through :func:`_stage_engine`.
3373
+ _STAGE_ENGINE_COMMANDS = ("read-binary", "sizedist", "combine")
3374
+
3375
+
3376
+ def _refuse_unwired_engine(args: argparse.Namespace) -> int | None:
3377
+ """``None`` to proceed, or an exit status if the named engine is not wired.
3378
+
3379
+ ``engines`` is exempt: it *describes* an engine rather than running one,
3380
+ and refusing to describe v3.5 would make the one command that explains
3381
+ the situation the one command that cannot mention it. ``run`` is exempt for a related but
3382
+ different reason (2026-09-13): it dispatches on ``[run].engine`` itself, through
3383
+ the batch driver's ``--engine``, so a v3.5 config file is not "an unwired engine" at all --
3384
+ without this exemption a user who also passed ``--uiops-version 3.5`` at the top level
3385
+ (redundantly agreeing with a v3.5 config) would be refused here, before ``_run`` even ran,
3386
+ by this function's OWN top-level call in :func:`main`.
3387
+ """
3388
+ # ``soda2`` is its own engine, not a UIOOPS version: ``--uiops-version``
3389
+ # has no bearing on it, so it is exempt like ``run``.
3390
+ # ``reprocess`` reads its engine from the product's stamp and checks a disagreeing
3391
+ # ``--uiops-version`` itself (``_reprocess``), as ``run`` does against ``[run].engine``.
3392
+ if getattr(args, "command", None) in ("engines", "run", "reprocess", "soda2", "tune"):
3393
+ return None
3394
+ wanted = getattr(args, "uiops_version", "3.1.4")
3395
+ # read-binary, sizedist and combine carry their own --engine (review item 2). Given, it
3396
+ # decides; a top-level --uiops-version naming the other engine is refused, as `run` refuses
3397
+ # one that disagrees with [run].engine. Omitted, the unchanged rule below applies.
3398
+ stage_engine = getattr(args, "engine", None)
3399
+ if getattr(args, "command", None) in _STAGE_ENGINE_COMMANDS and stage_engine is not None:
3400
+ if wanted in ("3.1.4", stage_engine):
3401
+ return None
3402
+ print(f"arrayprobe {args.command}: --uiops-version {wanted} disagrees with "
3403
+ f"--engine {stage_engine}; nothing was run.", file=sys.stderr)
3404
+ return 2
3405
+ if wanted == "3.1.4":
3406
+ return None
3407
+ reasons = "\n".join(f" - {why}" for why in _V35_PIPELINE_GAPS)
3408
+ print(
3409
+ f"arrayprobe: the per-stage commands cannot run UIOPS {wanted}.\n"
3410
+ f"They run the validation engine, UIOPS 3.1.4, which reproduces archived UIOPS "
3411
+ f"products (the ORACLES 2D-S/HVPS record); they are not the way to process new data.\n"
3412
+ f"To process data on UIOPS 3.5, the default engine, name it in a config file and run "
3413
+ f"that file:\n"
3414
+ f" [run]\n engine = \"3.5\"\n\n"
3415
+ f" arrayprobe run <config.toml>\n"
3416
+ f"examples/configs/ has configs to start from (examples/configs/cip_uiops/cip_run.toml "
3417
+ f"for a CIP).\n"
3418
+ f"Why the per-stage commands stop at 3.1.4:\n"
3419
+ f"{reasons}\n"
3420
+ f"Nothing was run. Use --uiops-version 3.1.4 to check a stage on the validation "
3421
+ f"engine; `arrayprobe engines --catalogue --uiops-version 3.5` lists the v3.5 "
3422
+ f"modules for calling from Python.",
3423
+ file=sys.stderr)
3424
+ return 2
3425
+
3426
+
3427
+ #: The four packages whose module logger the CLI configures a handler for
3428
+ #: ``arrayprobe_soda2`` and ``uiops`` carry no converted
3429
+ #: ``print()`` today (R6 counted zero in each), but are included so a future
3430
+ #: message in either reaches the same default visibility without a second
3431
+ #: place to remember to add it.
3432
+ _LIBRARY_LOGGER_NAMES = ("arrayprobe", "arrayprobe_uiops", "arrayprobe_soda2", "uiops")
3433
+
3434
+
3435
+ def _configure_logging(*, quiet: bool, verbose: bool) -> None:
3436
+ """Attach one ``stderr`` handler per library logger, for this process only.
3437
+
3438
+ Each package's ``__init__`` installs a ``NullHandler`` and nothing else
3439
+ (constraint: a plain ``import arrayprobe`` must never print), so without
3440
+ this call a converted message would be silently dropped -- worse
3441
+ than the ``print()`` it replaced. Default level is ``INFO``, which is
3442
+ where every message converted so far (``logging.warning``) already
3443
+ shows; ``--quiet`` raises it to ``ERROR`` (informational/warning messages
3444
+ are suppressed, an ``.error()`` call would still show); ``--verbose``
3445
+ lowers it to ``DEBUG``. This does not touch a worker subprocess spawned
3446
+ through ``ProcessPoolExecutor`` -- ``readers/spec.py``'s
3447
+ ``_report_part_progress`` configures its own handler for exactly that
3448
+ reason (see its module comment) and is unaffected by these flags, same
3449
+ as it was unaffected by anything before this change.
3450
+ """
3451
+ level = logging.DEBUG if verbose else (logging.ERROR if quiet else logging.INFO)
3452
+ handler = logging.StreamHandler(sys.stderr)
3453
+ handler.setFormatter(logging.Formatter("%(message)s"))
3454
+ for name in _LIBRARY_LOGGER_NAMES:
3455
+ logger = logging.getLogger(name)
3456
+ logger.setLevel(level)
3457
+ logger.addHandler(handler)
3458
+ logger.propagate = False
3459
+
3460
+
3461
+ def main(argv=None) -> int:
3462
+ """Entry point for the ``arrayprobe`` console script (see ``pyproject.toml``).
3463
+
3464
+ Returns a process exit status rather than raising, so a shell pipeline can
3465
+ branch on it; each subcommand's own handler returns 0 for success. ``argv``
3466
+ is accepted explicitly so tests drive the real parser instead of patching
3467
+ ``sys.argv``.
3468
+ """
3469
+ parser = _hide_unlisted(build_parser())
3470
+ if not _v314_engine_present():
3471
+ # The three v3.1.4-only stage commands are unregistered without the engine; a stale script
3472
+ # naming one gets the reason, not argparse's "invalid choice".
3473
+ tokens = list(sys.argv[1:] if argv is None else argv)
3474
+ i = 0
3475
+ while i < len(tokens):
3476
+ tok = str(tokens[i])
3477
+ if tok == "--uiops-version":
3478
+ i += 2
3479
+ continue
3480
+ if tok.startswith("-"):
3481
+ i += 1
3482
+ continue
3483
+ if tok in _V314_ONLY_SUBCOMMANDS:
3484
+ print(_absent_engine_refusal(tok), file=sys.stderr)
3485
+ return 2
3486
+ break
3487
+ args = parser.parse_args(argv)
3488
+ if getattr(args, "engine", None) == "3.1.4" and not _v314_engine_present():
3489
+ print(_absent_engine_refusal(getattr(args, "command", None)), file=sys.stderr)
3490
+ return 2
3491
+ if getattr(args, "command", None) == "read-binary":
3492
+ sub = next(a for a in parser._actions if isinstance(a, argparse._SubParsersAction))
3493
+ _check_read_binary(sub.choices["read-binary"], args)
3494
+ _configure_logging(quiet=args.quiet, verbose=args.verbose)
3495
+ refusal = _refuse_unwired_engine(args)
3496
+ if refusal is not None:
3497
+ return refusal
3498
+ try:
3499
+ return args.func(args)
3500
+ except FileNotFoundError as exc:
3501
+ # A missing input reaching the top of a subcommand is a mistyped path, not a bug: one
3502
+ # line naming it, exit 2, rather than the traceback imgproc, sizedist and combine
3503
+ # printed for it (cold-user walk, 2026-09-26).
3504
+ what = f"{exc.strerror}: {exc.filename}" if exc.filename else str(exc)
3505
+ print(f"arrayprobe {getattr(args, 'command', '')}: {what}", file=sys.stderr)
3506
+ return 2
3507
+
3508
+
3509
+ if __name__ == "__main__":
3510
+ sys.exit(main())