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/config.py ADDED
@@ -0,0 +1,1239 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """A run configuration file (TOML) -- selection only, never a silent default.
3
+
4
+ Decision #10 (2026-08-28): the loader lives in the core, but it can only *select* -- a named
5
+ ``FidelityProfile``, per-file diode masks, the explicit shattering-threshold argument, export
6
+ options, and opt-in enhancement switches that the core does not interpret. It cannot set a
7
+ threshold on the port; a fidelity-changing key outside ``[fidelity]`` is rejected at load time.
8
+ Design: ``enhancements_uiops/docs/config_file_design.md``.
9
+
10
+ **The no-raw-thresholds rule is lifted for exactly two fields (configurable thresholds):**
11
+ ``[thresholds].area_ratio_z`` and ``[thresholds].default_int_arr_thresh`` -- the S4 (``sizeDist``)
12
+ threshold pair that was found arriving unnamed for any project ``constants.sizedist_config``
13
+ does not recognise (measured: an unrecognised project under ``tree="production"`` gets ORACLES's
14
+ own tuned values with no record of why). Everywhere else the rule stands: a raw
15
+ ``rej_hollow``, ``max_edge_img_ar``, ``max_comp_img_ar``, ``spec_buffer_guard``, ``hvps_reader`` or
16
+ ``zero_image_particle_recovery`` anywhere in the file is still refused (:data:`_FORBIDDEN`), because
17
+ those remain scientific claims that belong in code with provenance
18
+ (:class:`~arrayprobe.profiles.FidelityProfile`).
19
+
20
+ ``[thresholds]`` may name a :data:`~arrayprobe.regimes.REGIMES` entry (``regime = "liquid-warm"``),
21
+ or give a raw value for either field, or both at once -- a regime for one field and a raw override
22
+ for the other is normal and expected. A raw value here is validated (``arrayprobe.regimes``) and
23
+ recorded in ``RunConfig`` tagged ``"user:<config path>"``, distinct from a regime's
24
+ ``"regime:<name>"`` tag and the historical hard-coded ``"stock"`` fallback -- three different
25
+ epistemic objects, and the ``.call`` sidecar and the startup print both keep them apart (see
26
+ ``scripts/run_flight.py``). **A value here is a property of one run, never of the package**: the
27
+ package's own registered regimes (:data:`arrayprobe.regimes.REGIMES`) are the only names a fork may
28
+ add to permanently, through :func:`arrayprobe.regimes.register_regime` -- the same shape as a
29
+ :class:`~arrayprobe.profiles.FidelityProfile`.
30
+
31
+ Every fidelity-sensitive key is **required** when its section is present, and the file's absence
32
+ changes nothing: callers that do not use a config keep passing the profile explicitly.
33
+
34
+ A fork's own registered profile (``register_profile()``) is selected the same way once its
35
+ registration is *reachable*: ``[fidelity].profile_module`` names a Python module to import before
36
+ the profile is resolved, so a fresh process -- including every ``--jobs``/``--chunks`` worker
37
+ ``run_flight.py`` re-execs, each a brand-new interpreter that has never run the fork's own
38
+ registration code -- can still find it by name. The module still only *selects*: importing it must
39
+ call ``register_profile()``, itself constrained to a fully-specified :class:`FidelityProfile`
40
+ exactly as if called directly, never described as data in this file.
41
+
42
+ ``[fidelity].authordefaults`` (minimal form) is the third way to reach a profile,
43
+ mutually exclusive with ``profile``: it names a separate, content-hashed TOML file
44
+ (:mod:`arrayprobe.authordefaults`) that states a base profile plus cited overrides for the six
45
+ :class:`~arrayprobe_uiops.reject_core.RejectConfig` thresholds only. The loader here still only
46
+ *selects* --
47
+ the generated profile is built and registered the same way a fork's own variant would be, this
48
+ file just supplies six of its field values instead of them being typed by hand. Absent, nothing
49
+ about this loader's behaviour changes.
50
+
51
+ Example::
52
+
53
+ [fidelity]
54
+ profile = "ORACLES_PRODUCTION"
55
+ # profile_module = "my_lab.profiles" # only if profile names something it registers
56
+
57
+ [shattering]
58
+ threshold_file = "2DS_intArrThreshold_MISSING.cdf" # explicit: the twelfth argument
59
+
60
+ [masking]
61
+ diodes = { base160910124240 = [95], base160910071623 = [77] }
62
+
63
+ [export]
64
+ format = "NETCDF3_CLASSIC"
65
+
66
+ [enhancements]
67
+ last_record_fix = true
68
+
69
+ [run]
70
+ engine = "3.1.4" # "3.5" for new data, "3.1.4" to reproduce an archived
71
+ # product (as this ORACLES example does), or "soda2"
72
+ preset = "ORACLES_2016_2DS_H" # a campaign chosen whole, by name (CampaignPreset)
73
+ raw = ["../raw/base1609*.2DS"] # relative to this file; command-line raw files win
74
+ out = "../_decoded"
75
+ stages = "234"
76
+ tas_file = "../aircraft/flightData_160906.cdf" # only if profile.time_in_seconds_from_tas
77
+ # probe = "CIP" # optional: must be the preset's probe, or the run is refused
78
+ # tas_from_probe = ["../2ds/base160906*.tas.csv"] # CIP/PIP only: another probe's airspeed
79
+
80
+ [combine]
81
+ borrowed = true # engine 3.5 only: stitch with the ORACLES fork's combine, labelled borrowed
82
+
83
+ [thresholds]
84
+ regime = "ice" # optional: one of arrayprobe.regimes.REGIMES
85
+ area_ratio_z = 0.35 # optional: raw override, allowed for this field only
86
+ default_int_arr_thresh = 5e-6 # optional: raw override, same lift
87
+ # tas_max = 140.0 # 2DP only (it assigns no tasMax): the probe's own value, m/s
88
+ # pecan_params = "pecan_spirals.csv" # PECAN CIP/PIP only: stands in for getPECANparams
89
+
90
+ [arm]
91
+ site_id = "ena" # required together: real, already-assigned ARM codes,
92
+ platform_id = "aaf2dsh" # never invented -- see _load_arm's own docstring
93
+ facility_id = "F1"
94
+ # data_level = "c1" # optional: defaults to arm_export.export()'s own "c1"
95
+
96
+ [tas]
97
+ source = "auto" # or "merge" / "aircraft" / "probe" (pinned)
98
+ search = ["../merge", "~/data/merge"] # relative to this file; ~ expanded
99
+ # cutoff_mps = 300.0 # optional: TasPolicy's cutoff (documented default 300 m/s)
100
+ # default_mps = 170.0 # optional: TasPolicy's fallback (documented default 170 m/s)
101
+
102
+ [time_offset] # engine 3.5 only; all three together, or the section omitted
103
+ seconds = -100 # whole seconds added to every particle time in sizeDist
104
+ evidence = "SPEC clock vs aircraft TAS cross-correlation" # how it was measured
105
+ tas_clock = "probe" # "probe" or "aircraft": which clock the time/TAS rows carry
106
+ """
107
+
108
+ from __future__ import annotations
109
+
110
+ import importlib
111
+ import math
112
+ import os
113
+ import tomllib
114
+ from collections.abc import Mapping
115
+ from dataclasses import dataclass, field
116
+ from pathlib import Path
117
+ from typing import Any
118
+
119
+ from . import profiles
120
+ from .authordefaults import AuthorDefaultsError, load_authordefaults, resolve_profile
121
+ from .profiles import FidelityProfile
122
+ from .regimes import ThresholdValidationError, resolve_thresholds
123
+ from .tools import tas_sources
124
+ from .tools.make_tas_file import TasPolicy
125
+
126
+ __all__ = ["RunConfig", "ConfigError", "PROFILES", "load_config"]
127
+
128
+ def _constant_spelling(name: str) -> str:
129
+ """``"stock-v3.5"`` -> ``"STOCK_V35"``: a profile's own module-level constant name.
130
+
131
+ One transform, not a table: ``profiles.py`` names every shipped profile twice
132
+ -- once as a hyphenated ``name`` field and once as the Python constant bound to
133
+ it -- and this is the rule relating them. ``tests/test_profile_registry.py``
134
+ asserts the two sides against each other (``getattr(profiles, alias)`` is the
135
+ object :data:`PROFILES` resolves that alias to), so the transform cannot quietly
136
+ stop matching how ``profiles.py`` actually spells a constant.
137
+ """
138
+ return name.upper().replace("-", "_").replace(".", "")
139
+
140
+
141
+ #: The CONSTANT-style spellings config files have always used, kept because
142
+ #: written config files name them -- a config file may say
143
+ #: ``profile = "ORACLES_PRODUCTION"``. They are aliases *of* the registry
144
+ #: entries, resolved through it rather than bound to the objects here: this
145
+ #: table used to hold the three profiles directly, which made it a second copy
146
+ #: of a registry, keyed differently, that nothing compared with the first.
147
+ #:
148
+ #: **Derived from** :data:`arrayprobe.profiles.SHIPPED` **since 2026-09-20**, and
149
+ #: that is a fix, not a tidy-up. The table was hand-written with the three
150
+ #: v3.1.4-era profiles in it, so ``STOCK_V35`` -- the spelling
151
+ #: ``profiles.py`` and every Python caller use -- was **not an accepted config
152
+ #: value**, while ``ORACLES_PRODUCTION`` was, in the same file. A cold-user
153
+ #: end-to-end walk in September 2026 found exactly that. The registry two
154
+ #: lines below was made derived in September for the same reason
155
+ #: and this table was left behind: a fifth profile added to ``profiles.py``
156
+ #: joined ``PROFILES`` automatically and silently missed its alias. It cannot now.
157
+ _ALIASES: dict[str, str] = {_constant_spelling(n): n for n in sorted(profiles.SHIPPED)}
158
+
159
+
160
+ class _SelectableProfiles(Mapping[str, FidelityProfile]):
161
+ """Every profile a config file may name: the aliases, and the registry.
162
+
163
+ Computed on access rather than snapshotted at import, so a profile a fork
164
+ registers with :func:`arrayprobe.profiles.register_profile` can be selected
165
+ by name from a config file without this module having heard of it. It stays
166
+ a *selection*: registering constructs the object in Python, where every
167
+ divergence is named; the file only picks one that already exists.
168
+ """
169
+
170
+ def _resolved(self) -> dict[str, FidelityProfile]:
171
+ table = {alias: profiles.PROFILES[target] for alias, target in _ALIASES.items()}
172
+ table.update(profiles.PROFILES)
173
+ return table
174
+
175
+ def __getitem__(self, key: str) -> FidelityProfile:
176
+ return self._resolved()[key]
177
+
178
+ def __iter__(self):
179
+ return iter(self._resolved())
180
+
181
+ def __len__(self) -> int:
182
+ return len(self._resolved())
183
+
184
+
185
+ PROFILES: Mapping[str, FidelityProfile] = _SelectableProfiles()
186
+
187
+ #: Keys that would change what the port computes if they were honoured outside a profile.
188
+ _FORBIDDEN = {"rej_hollow", "max_edge_img_ar", "max_comp_img_ar", "spec_buffer_guard",
189
+ "area_ratio", "z_threshold", "defaultIntArrThresh", "iat_threshold",
190
+ "zero_image_particle_recovery", "hvps_reader"}
191
+
192
+ _SECTIONS = {"fidelity", "shattering", "masking", "export", "enhancements", "combine", "run",
193
+ "soda2", "thresholds", "v35", "arm", "tas", "outputs", "time_offset"}
194
+
195
+ #: What ``[thresholds]`` may hold -- the two fields exempt from the no-raw-thresholds rule,
196
+ #: plus the regime selector. Nothing else: a raw ``area_ratio`` (the ``_FORBIDDEN`` spelling)
197
+ #: or any S3-level reject field is still refused there, same as everywhere else in the file.
198
+ _THRESHOLD_KEYS = {"regime", "area_ratio_z", "default_int_arr_thresh", "tas_max",
199
+ "pecan_params"}
200
+
201
+ #: What ``[combine]`` may hold: the one opt-in switch, and nothing else.
202
+ #:
203
+ #: Added 2026-09-20 after the cold-user walk measured a config carrying
204
+ #: ``[combine].totally_made_up_key`` running to ``ALL DONE``, exit 0, silently.
205
+ #: Every other table with a fixed key set
206
+ #: -- ``[run]``, ``[thresholds]``, ``[v35]`` -- already refuses an unknown key by
207
+ #: name; this one kept the remainder in :attr:`RunConfig.combine`, which no
208
+ #: consumer reads, so a typo'd ``borrowd = true`` was accepted, stored, and the
209
+ #: run stitched the way the file said it should not.
210
+ #:
211
+ #: ``tests/test_config_keys_are_consumed.py`` could not have caught it and says so
212
+ #: in its own LIMIT paragraph: it sweeps ``RunConfig`` *fields*, and the field
213
+ #: ``combine`` matches the unrelated ``arrayprobe_uiops.combine`` in a consumer's
214
+ #: source. A field-level sweep cannot see a key that never becomes a field.
215
+ _COMBINE_KEYS = {"borrowed"}
216
+
217
+ #: The keys the four remaining fixed-shape UIOOPS sections may hold -- the same refusal
218
+ #: ``[combine]`` got on 2026-09-20, extended 2026-09-26 after a cold-user walk measured
219
+ #: ``[masking.diode]`` (for ``diodes``), ``[export] formt = ...`` and ``[fidelity]
220
+ #: profle_module = ...`` all loading cleanly and being ignored: a typo'd mask section left
221
+ #: every diode unmasked while the file said otherwise.
222
+ _SECTION_KEYS = {
223
+ "fidelity": {"profile", "profile_module", "authordefaults"},
224
+ "shattering": {"threshold_file", "ia_thresh_type"},
225
+ "masking": {"diodes"},
226
+ "export": {"format"},
227
+ }
228
+
229
+ #: What ``[v35]`` may hold (iQC and iNewHabit configurable) --
230
+ #: ``arrayprobe_uiops.imgproc.imgproc_sm_v35``'s two required, no-MATLAB-default switches (its
231
+ #: own module docstring): which habit scheme (Holroyd vs. Schima et al. 2024) and whether
232
+ #: ``qc_image`` runs. Each is a documented state (0 or 1), never a raw threshold, so the
233
+ #: no-raw-thresholds rule does not apply here.
234
+ _V35_KEYS = {"iQC", "iNewHabit"}
235
+
236
+ #: What ``[arm]`` may hold -- the real ARM identifiers
237
+ #: ``arrayprobe_enhancements.arm_export.export()`` needs and its own docstring insists are
238
+ #: "never invented": ``site_id``/``platform_id``/``facility_id`` are required together, since a
239
+ #: two-of-three identifier is not a real ARM identifier either. ``data_level`` is optional --
240
+ #: ``export()``'s own default (``"c1"``) is a documented ARM data-level category
241
+ #: (DOE/SC-ARM-15-004 S5.1.3), not a site fact, so falling back to it is not a guess the way a
242
+ #: missing site/platform/facility id would be. This is a selection, not a description, exactly
243
+ #: like ``[v35]``: a config file supplies the user's own real, already-assigned ARM codes for
244
+ #: this deployment, it does not derive or compute one, so the no-raw-thresholds rule is not
245
+ #: being relaxed here.
246
+ _ARM_KEYS = {"site_id", "platform_id", "facility_id", "data_level"}
247
+ _ARM_REQUIRED_KEYS = ("site_id", "platform_id", "facility_id")
248
+
249
+ #: What ``[tas]`` may hold (merged-file airspeed for ORACLES, the non-ORACLES airspeed chain) --
250
+ #: the TAS source chain's own opt-in, config-file half of the requirement that the
251
+ #: user can select both in config so nothing is hard coded. ``source`` selects a
252
+ #: chain mode (:data:`arrayprobe.tools.tas_sources.MODES`: ``auto``, or one pinned tier);
253
+ #: ``search`` names the directories the chain's ``merge``/``aircraft`` tiers glob in (resolved
254
+ #: relative to this file); ``cutoff_mps``/``default_mps`` are
255
+ #: :class:`~arrayprobe.tools.make_tas_file.TasPolicy`'s pair, validated the same way that class
256
+ #: validates its own constructor arguments -- a config file selects a policy, it does not describe
257
+ #: one differently from how Python does.
258
+ _TAS_KEYS = {"source", "search", "cutoff_mps", "default_mps"}
259
+
260
+ #: What ``[time_offset]`` must hold -- engine 3.5's opt-in whole-second probe-clock offset
261
+ #: (``arrayprobe_uiops.sizedist.TimeOffset``), the file's spelling of ``run_flight.py``'s
262
+ #: ``--time-offset-s`` / ``--time-offset-evidence`` / ``--time-offset-tas-clock``. All three or
263
+ #: none: an offset without its evidence, or without saying which clock the TAS rows carry, is
264
+ #: refused by the engine, so it is refused here at load time too.
265
+ _TIME_OFFSET_KEYS = ("seconds", "evidence", "tas_clock")
266
+
267
+ #: What ``[outputs]`` may hold -- which of a run's
268
+ #: three artefacts it owes, selected from the file with an explicit opt-out. Only the
269
+ #: keys whose effect is built are accepted, so a file cannot name an output the driver would then
270
+ #: silently not write: ``faithful_attributed`` is ``--attributed``; ``enhanced_attributed`` is
271
+ #: ``--enhancements`` with stage ``c`` (the enhanced combined and its attributed export), refused
272
+ #: by the driver before any stage runs when the file names no enhancement to apply. ``arm =
273
+ #: "faithful"`` is an ARM-format copy of the port's own sd, which needs ``[arm]``; without it the
274
+ #: driver logs a named skip. ``analysis_ready`` (absent = true) writes OUTPUT 2 chunked and
275
+ #: compressed; ``false`` writes it plain. ``zarr`` (absent = false) adds an opt-in Zarr copy of
276
+ #: each attributed file the run wrote, refused by the driver when no attributed output is selected;
277
+ #: ``parquet`` (absent = false) does the same with a directory of Parquet files.
278
+ _OUTPUTS_KEYS = {"faithful_attributed", "enhanced_attributed", "arm", "analysis_ready", "zarr",
279
+ "parquet"}
280
+
281
+ #: ``[run]`` selects (which engine, which named campaign) and locates (raw
282
+ #: files, output directory, which stages) -- it never describes a threshold or
283
+ #: assembles a campaign field by field (the no-raw-thresholds rule; ``run_flight.CampaignPreset``'s
284
+ #: own docstring: "chosen whole, by name, and never assembled field by field").
285
+ #: ``tas_file`` locates an input file, as ``raw`` does; which profile reads it is
286
+ #: the profile's own field.
287
+ #:
288
+ #: ``probe`` names which probe the run follows. A SEA file holds several probes' streams, so a
289
+ #: config for one says which it means; the preset already fixes the probe, so this key selects by
290
+ #: agreeing with it and ``arrayprobe run`` refuses the run, by name, when the two disagree.
291
+ #: ``tas_from_probe`` locates input files as ``raw`` does: the ``<stem>.tas.csv`` airspeed files
292
+ #: another probe on the same aircraft wrote (a 2D-S), for a CIP or PIP whose own decode writes
293
+ #: none. Each entry is a path or glob relative to this file and must match at least one file.
294
+ #: ``presets`` is a TOML file of ``[[campaign]]`` tables (relative to this file) registered before
295
+ #: ``preset`` is read; ``probe_case`` and ``probe_case_module`` are ``run_flight``'s
296
+ #: ``--probe-case`` / ``--probe-case-module`` (engine 3.5): the registered probe case that fixes the
297
+ #: bin table, and the module whose import registers it. Each is forwarded only when set.
298
+ _RUN_KEYS = {"engine", "preset", "raw", "out", "stages", "tas_file", "probe", "tas_from_probe",
299
+ "presets", "probe_case", "probe_case_module"}
300
+ _ENGINES = {"3.1.4", "3.5", "soda2"}
301
+ #: The netCDF format each UIOOPS engine's writers produce, whatever ``[export].format`` says:
302
+ #: v3.1.4 MATLAB's bare ``'clobber'`` default, v3.5 its own ``netcdf.create`` calls (decode,
303
+ #: proc and sd; the borrowed combine is the fork's and writes NETCDF3_CLASSIC -- measured on the
304
+ #: demo flight 2026-09-26).
305
+ _ENGINE_FORMAT = {"3.1.4": "NETCDF3_CLASSIC", "3.5": "NETCDF4"}
306
+ #: ``"soda2"`` is its own engine, not a UIOOPS version: it runs through
307
+ #: ``arrayprobe soda2 run`` and needs a ``[soda2]`` table holding the driver's ``op`` fields.
308
+
309
+ #: What a ``[run].engine = "soda2"`` file may contain (the SODA-2 port lanes; a project
310
+ #: decision of 2026-09-15 that a SODA-2 config names no profile). The SODA-2
311
+ #: engine has one source tree, so it reads no :class:`FidelityProfile` -- the ``STOCK_V35``
312
+ #: reasoning -- and ``arrayprobe soda2 run`` reads only these sections and, of ``[run]``,
313
+ #: only ``engine``. Everything else a UIOOPS file may carry (``[fidelity]``, ``[shattering]``,
314
+ #: ``[masking]``, ``[export]``, ``[combine]``, ``[run].raw/out/preset/stages/tas_file``) would
315
+ #: be silently ignored, so it is refused -- the same reason a ``[soda2]`` table under a UIOOPS
316
+ #: engine is refused.
317
+ _SODA2_SECTIONS = {"run", "soda2", "enhancements", "outputs", "arm"}
318
+ #: ``jit`` joined ``engine`` on 2026-09-18. It is the one exception to "``[run]`` selects and
319
+ #: locates, never describes", and it is not really an exception: ``jit`` selects a *kernel*,
320
+ #: not a number. ``arrayprobe_soda2.jit_kernels``' flood fill is exact by construction and
321
+ #: ``tests/test_soda2_label_region_jit_identity.py`` asserts the two paths byte-identical with
322
+ #: ``np.array_equal``, so a config that sets it and one that does not produce the same PBP
323
+ #: files -- nothing about the run's science is described here. It is a config key as well as
324
+ #: ``--jit`` because the flag alone left the kernel reachable only from a hand-typed command
325
+ #: line, the shape of the silent --jit no-op fix (a capability nothing connects);
326
+ #: ``--jobs``/``--chunks`` stay flag-only, being per-machine resources rather than a property
327
+ #: of the run.
328
+ _SODA2_RUN_KEYS = {"engine", "jit"}
329
+
330
+
331
+ class ConfigError(ValueError):
332
+ """A config that would pick a side silently, or names something the port cannot honour.
333
+
334
+ Raised by :func:`load_config` once for the whole file: its first line is the first problem
335
+ and the file's path, any further problems follow numbered, and ``.problems`` lists them all.
336
+ """
337
+
338
+ #: Every problem :func:`load_config` found in the file, in the order found; empty for an
339
+ #: error raised before the file's contents could be read (directory, encoding, TOML syntax).
340
+ problems: tuple[str, ...] = ()
341
+
342
+
343
+ class ConfigDecodeError(ConfigError, tomllib.TOMLDecodeError):
344
+ """A config file that is not valid TOML: a :class:`ConfigError`, so every driver reports it
345
+ in one line, and still a ``tomllib.TOMLDecodeError`` for a caller that catches that."""
346
+
347
+
348
+ @dataclass(frozen=True)
349
+ class RunConfig:
350
+ """A validated run configuration -- everything a TOML file is allowed to select.
351
+
352
+ Frozen, and every fidelity-relevant field is filled by :func:`load_config`
353
+ from an explicit key: there is no constructor path that infers a profile or
354
+ supplies a threshold. That is the rule that a config file may select a named variant but
355
+ never set a threshold, expressed in the type -- a config file selects between
356
+ documented MATLAB behaviours, it never invents one, so a caller reading this object can
357
+ trust that anything affecting a computed number was named in the file.
358
+
359
+ ``enhancements`` is a bag of booleans the core deliberately does not
360
+ interpret; it is read only through :meth:`enabled`, by the separately
361
+ installed ``arrayprobe-uiops-enhancements`` layer. ``source`` is the path the
362
+ config was read from, carried so a provenance stamp can name it.
363
+ """
364
+
365
+ profile: FidelityProfile | None
366
+ """The named UIOOPS profile. ``None`` only when ``[run].engine = "soda2"``, which reads no
367
+ profile and whose file may not name one (:data:`_SODA2_SECTIONS`, a project decision
368
+ of 2026-09-15); every UIOOPS-engine config still requires it."""
369
+ shattering_threshold_file: str | None
370
+ """The twelfth ``sizeDist`` argument, verbatim; ``None`` means the section was absent."""
371
+ profile_module: str | None = None
372
+ """``[fidelity].profile_module``, if the file named one -- carried for provenance/logging;
373
+ the import already happened during :func:`load_config`, so this field does not need to be
374
+ re-applied by a caller. See that function for why this exists."""
375
+ authordefaults_stamp: str | None = None
376
+ authordefaults_path: Path | None = None
377
+ """The resolved ``[fidelity].authordefaults`` file, ``None`` otherwise (the default, so a
378
+ config without the key behaves as before). ``run_flight`` carries it to ``--chunks`` workers
379
+ as the ``authordefaults=<path>`` tail token, where it is re-loaded and its hash re-checked."""
380
+ shattering_ia_thresh_type: int | None = None
381
+ """``[shattering].ia_thresh_type``: 2 selects engine 3.5's per-second default threshold;
382
+ ``None`` (absent) leaves the driver's choice, 1 with a threshold file and 0 without."""
383
+ """``authordefaults:<path>#<sha>``, when ``[fidelity].authordefaults``
384
+ named an author-editable defaults file -- ``None`` otherwise, including every config that
385
+ predates this field, so the default behaviour is unchanged (:mod:`arrayprobe.authordefaults`).
386
+ A caller that stamps a ``.call`` sidecar appends this verbatim; it is not re-derivable from
387
+ :attr:`profile` alone, because the generated profile's own name already encodes the file's
388
+ hash but not its path."""
389
+ diode_masks: dict[str, tuple[int, ...]] = field(default_factory=dict)
390
+ export_format: str = "NETCDF3_CLASSIC"
391
+ enhancements: dict[str, bool] = field(default_factory=dict)
392
+ enhancements_declared: bool = False
393
+ """Whether the file carried an ``[enhancements]`` section *at all* -- distinct from
394
+ carrying an empty one. The port does not use it: absent and empty mean the same thing
395
+ here (nothing on). It exists because ``arrayprobe-enhanced run`` refuses a config with
396
+ no enhancement policy rather than guessing one (2026-09-16 usability audit), and the
397
+ loader is the only place that still knows the difference."""
398
+ soda2: dict[str, Any] = field(default_factory=dict)
399
+ """``[soda2]`` verbatim -- the SODA-2 driver's ``op`` fields (~40, unlike any UIOOPS
400
+ section), consumed only by ``arrayprobe soda2 run``. Required when ``[run].engine`` is
401
+ ``"soda2"``; the core does not interpret it."""
402
+ combine: dict[str, str] = field(default_factory=dict)
403
+ """Whatever ``[combine]`` held besides ``borrowed`` -- **provably empty since
404
+ 2026-09-20**, when :data:`_COMBINE_KEYS` began refusing every other key. Kept
405
+ as a field rather than deleted in the same pass, because deleting a public
406
+ dataclass field is a separate change with its own callers to check; nothing in
407
+ ``src``, ``tools`` or either enhancements package reads it (measured by grep,
408
+ 2026-09-20), and the next pass over this class should drop it."""
409
+ run: dict[str, object] = field(default_factory=dict)
410
+ source: str = ""
411
+ borrowed_combine: bool = False
412
+ thresholds_regime: str | None = None
413
+ """``[thresholds].regime``, or ``None`` when absent -- one of
414
+ :data:`arrayprobe.regimes.REGIMES`. Already validated against the registry at load time
415
+ (regime-based configurable thresholds)."""
416
+ thresholds_area_ratio_z: float | None = None
417
+ """``[thresholds].area_ratio_z``, or ``None`` when absent -- a raw override, allowed
418
+ for exactly this field. Already bounds-checked at load time
419
+ (:func:`arrayprobe.regimes.resolve_thresholds`, which raises :class:`ConfigError` here)."""
420
+ thresholds_default_int_arr_thresh: float | None = None
421
+ """``[thresholds].default_int_arr_thresh``, or ``None`` when absent -- as
422
+ :attr:`thresholds_area_ratio_z`, for ``defaultIntArrThresh``."""
423
+ thresholds_tas_max: float | None = None
424
+ """``[thresholds].tas_max`` (m/s), or ``None`` when absent -- ``tasMax`` for an S4 case that
425
+ assigns none (the 2DP), passed to ``sizedist.run(tas_max=)``. Not a fidelity threshold: an
426
+ input MATLAB cannot run without, with no default. Finite and > 0, checked at load time."""
427
+ thresholds_pecan_params: str | None = None
428
+ """``[thresholds].pecan_params``, or ``None`` when absent -- the parameter file standing in
429
+ for ``getPECANparams`` (:mod:`arrayprobe_uiops.pecan_params`), resolved relative to this file
430
+ and parsed at load time."""
431
+ thresholds_declared: bool = False
432
+ """Whether the file carried a ``[thresholds]`` section at all -- distinct from every field in
433
+ it being absent (``regime`` with no raw override is a real, meaningful selection)."""
434
+ v35_i_qc: int | None = None
435
+ """``[v35].iQC`` (iQC and iNewHabit configurable) -- 0 or 1, validated at load time; ``None``
436
+ when the file did not set it, in which case the driver's own ``V35_CALL.i_qc`` default (0)
437
+ applies. Read only when ``[run].engine = "3.5"``."""
438
+ v35_i_new_habit: int | None = None
439
+ """``[v35].iNewHabit`` (iQC and iNewHabit configurable) -- 0 or 1, validated at load time;
440
+ ``None`` when unset, same engine restriction as :attr:`v35_i_qc`."""
441
+ v35_declared: bool = False
442
+ """Whether the file carried a ``[v35]`` section at all -- distinct from a field in it being
443
+ unset (same pattern as :attr:`thresholds_declared`)."""
444
+ arm: dict[str, str] = field(default_factory=dict)
445
+ """``[arm]``, verbatim: ``site_id``/``platform_id``/``facility_id`` (always present
446
+ together when this is non-empty) and optionally ``data_level``. Empty when the file names no
447
+ ``[arm]`` section -- the enhancements driver's ``arm_export`` adapter then names a skip
448
+ rather than falling back to a placeholder identifier (``arm_export.py``'s own rule: these
449
+ three are never invented). Read by
450
+ ``arrayprobe_enhancements.pipeline.apply_enhancements``, never by the port itself."""
451
+ tas_source: str | None = None
452
+ """``[tas].source`` (merged-file airspeed for ORACLES, the non-ORACLES airspeed chain) -- one
453
+ of :data:`arrayprobe.tools.tas_sources.MODES`, or ``None`` when the file names no ``[tas]``
454
+ section (the legacy ``--tas-file`` / ``[run].tas_file`` path, untouched). Read only by
455
+ ``scripts/run_flight.py``."""
456
+ tas_search: tuple[str, ...] = field(default_factory=tuple)
457
+ """``[tas].search`` (the non-ORACLES airspeed chain), resolved relative to this config
458
+ file's own directory (``~`` expanded) -- the directories the ``merge``/``aircraft`` chain
459
+ tiers glob in. Empty when the file names none, which is a real, meaningful selection (no
460
+ directory to search) rather than an omission, exactly as an empty ``[thresholds]`` selection
461
+ would be refused at load time -- see :func:`_load_tas`."""
462
+ outputs: dict[str, bool | str] = field(default_factory=dict)
463
+ """``[outputs]``, verbatim: which of the run's three artefacts the file selects
464
+ (:data:`_OUTPUTS_KEYS`). Empty when the file names no ``[outputs]`` section, and then the run
465
+ writes exactly what it wrote before the section existed. An explicit ``false`` is the opt-out;
466
+ the command line still wins over it. Read only by ``run_flight._apply_config``."""
467
+ tas_cutoff_mps: float | None = None
468
+ """``[tas].cutoff_mps`` -- :class:`~arrayprobe.tools.make_tas_file.TasPolicy`'s ``cutoff_mps``,
469
+ or ``None`` when the file did not set it, in which case the driver's own documented default
470
+ (300 m/s) applies."""
471
+ tas_default_mps: float | None = None
472
+ """``[tas].default_mps`` -- :class:`~arrayprobe.tools.make_tas_file.TasPolicy`'s
473
+ ``default_mps``, or ``None`` when unset (the documented 170 m/s default applies)."""
474
+ time_offset: tuple[int, str, str] | None = None
475
+ """``[time_offset]`` as ``(seconds, evidence, tas_clock)``, already validated by
476
+ ``arrayprobe_uiops.sizedist.TimeOffset.build`` at load time; ``None`` when the file names no
477
+ such section, and then the run passes no offset keyword and stamps nothing. Engine 3.5 only.
478
+ Read by ``run_flight._apply_config``, where any ``--time-offset-*`` flag wins over the
479
+ whole section."""
480
+ tas_declared: bool = False
481
+ """Whether the file carried a ``[tas]`` section at all -- distinct from every field in it
482
+ being unset (same pattern as :attr:`thresholds_declared`, :attr:`v35_declared`)."""
483
+ """``[combine].borrowed`` -- the opt-in for the v3.5 engine's borrowed combine (the first of
484
+ the five path-forward decisions):
485
+ run S4c with the ORACLES fork's ``combine_sizedist.m`` over v3.5 ``sd`` files, labelled so in
486
+ the product's ``.call``. Read only by ``scripts/run_flight.py``/``arrayprobe run``; meaningless
487
+ under the v3.1.4 engine, whose combine is the fork's own already."""
488
+
489
+ def enabled(self, enhancement: str) -> bool:
490
+ """Whether ``[enhancements].<name>`` was set true, **for the port**. Absent means off.
491
+
492
+ Default-off is the contract, not a convenience: an enhancement changes
493
+ what the port computes away from the MATLAB, so it must be opted into
494
+ by name. An unknown name returns ``False`` rather than raising, because
495
+ the core does not know what enhancement names exist -- validating them
496
+ is the enhancements package's job, and refusing here would couple the
497
+ two in the direction ``test_no_enhancement_coupling.py`` forbids.
498
+
499
+ **The enhancements package now answers the same question the same way**
500
+ (the 2026-09-16 cold-start usability audit).
501
+ ``arrayprobe_enhancements.registry.resolve`` reads this same table and also
502
+ defaults every registered enhancement *off*. Between the switchable-enhancements
503
+ rule (2026-09-10) and that audit it defaulted them *on*, opt-out by name, on the
504
+ argument that installing that package was itself the opt-in -- so one TOML
505
+ file meant opposite things to the two drivers. A cold-start usability audit
506
+ measured a config whose only line was ``outoffocus = false`` resolving 31 of
507
+ 40 modules ON and applying four. One file, one meaning, since. Both views are
508
+ pinned by ``enhancements_uiops/tests/test_enhancement_opt_in.py``; the reasoning is
509
+ in ``enhancements_uiops/docs/enhancement_registry_design.md``.
510
+ """
511
+ return bool(self.enhancements.get(enhancement, False))
512
+
513
+
514
+ class _Problems:
515
+ """Collects the problems :func:`load_config` finds, so one run reports all of them.
516
+
517
+ Each message is today's single-error text, unchanged; :meth:`raise_if_any` joins them into
518
+ one :class:`ConfigError` naming the file, with the list on ``.problems``.
519
+ """
520
+
521
+ def __init__(self, path) -> None:
522
+ self.path = path
523
+ self._messages: list[str] = []
524
+ self._cause: BaseException | None = None
525
+
526
+ def add(self, msg: str, cause: BaseException | None = None) -> None:
527
+ self._messages.append(msg)
528
+ if cause is not None and self._cause is None:
529
+ self._cause = cause
530
+
531
+ def __bool__(self) -> bool:
532
+ return bool(self._messages)
533
+
534
+ def __len__(self) -> int:
535
+ return len(self._messages)
536
+
537
+ def raise_if_any(self) -> None:
538
+ if not self._messages:
539
+ return
540
+ msgs = self._messages
541
+ n = len(msgs)
542
+ if n == 1:
543
+ text = f"{msgs[0]} (in {self.path})"
544
+ else:
545
+ text = "\n".join([f"{msgs[0]} (in {self.path}; 1 of {n} problems, the others below)"]
546
+ + [f" {i}. {m}" for i, m in enumerate(msgs[1:], start=2)])
547
+ exc = ConfigError(text)
548
+ exc.problems = tuple(msgs)
549
+ if self._cause is not None:
550
+ raise exc from self._cause
551
+ raise exc
552
+
553
+
554
+ def _check_forbidden(section: str, table: dict, problems: _Problems) -> None:
555
+ bad = sorted(k for k in table if k in _FORBIDDEN)
556
+ if bad:
557
+ problems.add(
558
+ f"[{section}] sets {bad}: fidelity thresholds are chosen by [fidelity].profile "
559
+ f"(one of {sorted(PROFILES)}), never by a raw key")
560
+
561
+
562
+ def _read_toml(path) -> dict:
563
+ """Parse a TOML file the way a Windows user's editor may have saved it.
564
+
565
+ A UTF-8 byte-order mark -- what Windows PowerShell 5.1's ``-Encoding utf8`` writes -- is
566
+ dropped: it carries no content, and ``tomllib`` rejects the whole file over it with
567
+ "Invalid statement (at line 1, column 1)". UTF-16 (PowerShell 5.1's ``>``, Notepad's
568
+ "Unicode") and any other non-UTF-8 bytes are refused by name. Every failure is a
569
+ :class:`ConfigError` (a ``ValueError``, as ``tomllib.TOMLDecodeError`` is, chained from it);
570
+ ``FileNotFoundError`` propagates.
571
+ """
572
+ path = Path(path)
573
+ raw = path.read_bytes()
574
+ if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
575
+ raise ConfigError(f"{path} is saved as UTF-16; TOML must be UTF-8. Re-save it as UTF-8 "
576
+ f"(in PowerShell: Set-Content -Encoding utf8, or Out-File -Encoding "
577
+ f"utf8)")
578
+ if raw.startswith(b"\xef\xbb\xbf"):
579
+ raw = raw[3:]
580
+ try:
581
+ return tomllib.loads(raw.decode("utf-8"))
582
+ except UnicodeDecodeError as exc:
583
+ raise ConfigError(f"{path} is not UTF-8 text ({exc.reason} at byte {exc.start}); "
584
+ f"TOML must be UTF-8") from exc
585
+ except tomllib.TOMLDecodeError as exc:
586
+ raise ConfigDecodeError(f"{path} is not valid TOML: {exc}") from exc
587
+
588
+
589
+ def load_config(path) -> RunConfig:
590
+ """Read a run-configuration TOML file into a validated :class:`RunConfig`.
591
+
592
+ Not a MATLAB behaviour: UIOOPS has no config file, it has driver scripts
593
+ with the constants written in. This loader exists so a run can be
594
+ *described* without editing code, and it is bounded so that description
595
+ can never become a fidelity decision.
596
+
597
+ Every rejection below is a case where accepting the file would let it pick
598
+ a side silently:
599
+
600
+ * an unknown top-level section (a typo'd ``[fidelty]`` would otherwise be
601
+ ignored and the run would use different settings than the file says);
602
+ * any key in :data:`_FORBIDDEN` anywhere -- ``rej_hollow``,
603
+ ``max_edge_img_ar`` and the rest are chosen by naming a profile, never by
604
+ a raw value, because their correct values are a measured property of a
605
+ MATLAB tree;
606
+ * a missing ``[fidelity].profile``, since no profile is ever assumed -- except under
607
+ ``[run].engine = "soda2"``, which reads no profile and may not name one
608
+ (:func:`_load_soda2_config`, by design);
609
+ * ``[shattering]`` present without ``threshold_file``, because an absent
610
+ twelfth ``sizeDist`` argument is itself an output-changing call
611
+ (``sizeDist.m:70``, ``:866``) and must be stated rather than defaulted;
612
+ * a diode number outside 1..128, or a non-boolean enhancement switch.
613
+
614
+ Returns a :class:`RunConfig`. Raises :class:`ConfigError` for all of the
615
+ above; ``FileNotFoundError`` and ``tomllib.TOMLDecodeError`` propagate.
616
+ Every problem in the file is reported at once in that one error, which names the file and
617
+ lists them on ``.problems``; a file that cannot be read as TOML at all fails at once.
618
+ """
619
+ # (The TOMLDecodeError raised is a ConfigDecodeError, a ConfigError too, so the drivers'
620
+ # one-line refusal catches it; a path that is a directory is a ConfigError. The docstring
621
+ # above is rendered into docs/14-api-io-compat.md, so it changes with that page.)
622
+ path = Path(path)
623
+ if path.is_dir():
624
+ # Windows raises PermissionError for open() on a directory, which read as a permissions
625
+ # problem rather than a wrong argument.
626
+ raise ConfigError(f"{path} is a directory; name the .toml file inside it")
627
+ doc = _read_toml(path)
628
+ # From here every problem is collected and all are raised together, naming the file; a
629
+ # check whose input an earlier problem already broke is skipped rather than reported.
630
+ problems = _Problems(path)
631
+ unknown = sorted(set(doc) - _SECTIONS)
632
+ if unknown:
633
+ problems.add(f"unknown section(s) {unknown}; known: {sorted(_SECTIONS)}")
634
+ not_tables = sorted(name for name, table in doc.items() if not isinstance(table, dict))
635
+ if not_tables:
636
+ # `run = "x"` or `masking = [3]` at the top level: every reader below expects a table,
637
+ # and without this the user saw an AttributeError/ValueError traceback instead.
638
+ problems.add(f"{not_tables} must be table(s), written as a [section] header "
639
+ f"with key = value lines under it, not a top-level value")
640
+ problems.raise_if_any()
641
+ for name, table in doc.items():
642
+ _check_forbidden(name, table, problems)
643
+
644
+ # A [soda2] table with no [run].engine is a SODA-2 file too: `arrayprobe soda2 run` runs it
645
+ # (its engine defaults to "soda2") and a UIOOPS engine refuses [soda2], so the SODA-2 rules
646
+ # apply to every file the SODA-2 engine can run, not only to the ones that say so.
647
+ run_table = doc.get("run")
648
+ engine = run_table.get("engine") if isinstance(run_table, dict) else None
649
+ if engine == "soda2" or (engine is None and "soda2" in doc):
650
+ return _load_soda2_config(doc, path, problems)
651
+
652
+ for name, allowed in _SECTION_KEYS.items():
653
+ extra = sorted(set(doc.get(name, {})) - allowed - _FORBIDDEN)
654
+ if extra:
655
+ problems.add(f"[{name}] has unknown key(s) {extra}; known: {sorted(allowed)}")
656
+ diodes_table = doc.get("masking", {}).get("diodes", {})
657
+ diodes_ok = isinstance(diodes_table, dict)
658
+ if not diodes_ok:
659
+ problems.add(f"[masking].diodes must be a table of <file stem> = [diode numbers], "
660
+ f"e.g. [masking.diodes] with base160906064017 = [1, 128]; got "
661
+ f"{diodes_table!r}")
662
+
663
+ fid: Any = doc.get("fidelity")
664
+ has_profile = bool(fid) and "profile" in fid
665
+ has_authordefaults = bool(fid) and "authordefaults" in fid
666
+ # The profile chain runs only on a well-formed [fidelity] and stops at its first problem:
667
+ # each step reads what the one before it established.
668
+ fid_ok = True
669
+ if not has_profile and not has_authordefaults:
670
+ problems.add("[fidelity].profile or [fidelity].authordefaults is required; no "
671
+ "profile is ever assumed")
672
+ fid_ok = False
673
+ if has_profile and has_authordefaults:
674
+ problems.add("[fidelity] names both profile and authordefaults; a run selects "
675
+ "exactly one -- authordefaults already names its own base profile")
676
+ fid_ok = False
677
+ profile: FidelityProfile | None = None
678
+ profile_module = fid.get("profile_module") if fid_ok else None
679
+ if profile_module is not None:
680
+ # Imported for its side effect: a module that calls register_profile()
681
+ # at import time. This is the ONLY way a config file reaches a profile
682
+ # it did not ship with -- it still cannot describe one (the no-raw-thresholds
683
+ # rule is unchanged: the module is Python, written and reviewed like any
684
+ # other registration), but without this a registered profile is
685
+ # invisible to any FRESH process that only has this TOML, which is
686
+ # exactly what every subprocess run_flight.py re-execs is. Found
687
+ # 2026-09-10: a profile registered in the parent process worked with
688
+ # --jobs 1 and silently fell back to the default under --chunks > 1 or
689
+ # --jobs > 1, because each worker re-imports arrayprobe.profiles from
690
+ # scratch and never re-runs whatever registered the profile in the
691
+ # parent. Importing here, in load_config() itself, means every process
692
+ # that loads this same config -- parent or worker -- performs the same
693
+ # registration before resolving [fidelity].profile below.
694
+ try:
695
+ from arrayprobe.selector import canonical_module
696
+ importlib.import_module(canonical_module(str(profile_module)))
697
+ except ImportError as exc:
698
+ # The shipped ARM example keeps its module beside the TOML, and a run from
699
+ # the root without that directory on PYTHONPATH failed here with only "No module
700
+ # named ...": say where the module is and what to set.
701
+ beside = path.resolve().parent / (str(profile_module).replace(".", "/") + ".py")
702
+ hint = (f" -- it is imported by module name, and {beside.name} sits beside this "
703
+ f"config: put {beside.parent} on PYTHONPATH (entries are separated by "
704
+ f"{os.pathsep!r} on this platform)"
705
+ if beside.is_file() else
706
+ " -- it is imported by module name: put the directory that holds it on "
707
+ "PYTHONPATH")
708
+ problems.add(
709
+ f"[fidelity].profile_module {profile_module!r} could not be imported: {exc}{hint}",
710
+ exc)
711
+ fid_ok = False
712
+ authordefaults_stamp = None
713
+ authordefaults_path = None
714
+ if fid_ok and has_authordefaults:
715
+ ad_value = fid["authordefaults"]
716
+ if not isinstance(ad_value, str):
717
+ problems.add(f"[fidelity].authordefaults must be a file name in quotes, "
718
+ f"got {ad_value!r}")
719
+ else:
720
+ ad_path = Path(ad_value)
721
+ if not ad_path.is_absolute():
722
+ ad_path = (path.parent / ad_path).resolve()
723
+ try:
724
+ defaults = load_authordefaults(ad_path)
725
+ except FileNotFoundError as exc:
726
+ problems.add(f"[fidelity].authordefaults {ad_value!r} not found "
727
+ f"(resolved to {ad_path})", exc)
728
+ except AuthorDefaultsError as exc:
729
+ problems.add(str(exc), exc)
730
+ else:
731
+ profile = resolve_profile(defaults)
732
+ authordefaults_stamp = defaults.stamp()
733
+ authordefaults_path = Path(defaults.path)
734
+ elif fid_ok:
735
+ if fid["profile"] not in PROFILES:
736
+ problems.add(f"unknown profile {fid['profile']!r}; known: {sorted(PROFILES)}")
737
+ else:
738
+ profile = PROFILES[fid["profile"]]
739
+
740
+ shat = doc.get("shattering")
741
+ threshold = None
742
+ ia_thresh_type = None
743
+ if shat is not None and "ia_thresh_type" in shat:
744
+ # Engine 3.5's sizeDist type-2 branch (sizeDist.m:1346): the probe case's
745
+ # defaultIntArrThresh per second, no file. Opt-in; absent means the driver's own choice.
746
+ ia_thresh_type = shat["ia_thresh_type"]
747
+ if ia_thresh_type != 2 or isinstance(ia_thresh_type, bool):
748
+ problems.add(f"[shattering].ia_thresh_type must be 2 (the default threshold per "
749
+ f"second); got {ia_thresh_type!r}. Type 1 is selected by "
750
+ f"threshold_file, type 0 by leaving both out")
751
+ if "threshold_file" in shat:
752
+ problems.add("[shattering] names both threshold_file and ia_thresh_type = 2: "
753
+ "type 2 reads no file")
754
+ elif shat is not None:
755
+ if "threshold_file" not in shat:
756
+ problems.add("[shattering] present but threshold_file missing: the twelfth "
757
+ "sizeDist argument must be explicit (an absent file is itself a "
758
+ "documented, output-changing call -- see sizeDist.m:70,866)")
759
+ elif not isinstance(shat["threshold_file"], str):
760
+ problems.add(f"[shattering].threshold_file must be a file name in quotes, "
761
+ f"got {shat['threshold_file']!r}")
762
+ else:
763
+ threshold = shat["threshold_file"]
764
+
765
+ masks: dict[str, tuple[int, ...]] = {}
766
+ for stem, diodes in ((diodes_table or {}) if diodes_ok else {}).items():
767
+ if not isinstance(diodes, list) or not all(isinstance(d, int) and 1 <= d <= 128
768
+ for d in diodes):
769
+ problems.add(f"[masking].diodes.{stem} must be a list of 1-based diode "
770
+ f"numbers in 1..128, got {diodes!r}")
771
+ continue
772
+ masks[str(stem)] = tuple(diodes)
773
+
774
+ export = doc.get("export", {})
775
+ fmt = str(export.get("format", "NETCDF3_CLASSIC"))
776
+ fmt_ok = fmt in ("NETCDF3_CLASSIC", "NETCDF4")
777
+ if not fmt_ok:
778
+ problems.add(f"[export].format must be NETCDF3_CLASSIC or NETCDF4, got {fmt!r}")
779
+
780
+ enh = _enhancement_switches(doc, problems)
781
+
782
+ run = dict(doc.get("run", {}))
783
+ unknown_run = sorted(set(run) - _RUN_KEYS - _FORBIDDEN)
784
+ if unknown_run:
785
+ problems.add(f"[run] has unknown key(s) {unknown_run}; known: {sorted(_RUN_KEYS)}")
786
+ engine_ok = not ("engine" in run and run["engine"] not in _ENGINES)
787
+ if not engine_ok:
788
+ problems.add(f"[run].engine must be one of {sorted(_ENGINES)}, got {run['engine']!r}")
789
+ written = _ENGINE_FORMAT.get(str(run.get("engine")))
790
+ if (fmt_ok and engine_ok and "format" in export and written is not None
791
+ and fmt != written):
792
+ # No writer reads [export].format: the engine fixes it. A file asking for the other
793
+ # format used to load and run, and the products came out in the engine's format anyway.
794
+ problems.add(f"[export].format = {fmt!r} cannot be honoured: engine "
795
+ f"{run['engine']} writes {written}, and no writer reads this key. "
796
+ f"Set format = {written!r} or drop the [export] section")
797
+ soda2 = dict(doc.get("soda2", {}))
798
+ if engine_ok and soda2 and run.get("engine") not in (None, "soda2"):
799
+ # The same reason an unknown section is refused: a UIOOPS run would ignore it, so the
800
+ # file would say more than the run did.
801
+ problems.add(f"[soda2] is read only by the SODA-2 engine; this file names "
802
+ f"[run].engine = {run['engine']!r}")
803
+ if "raw" in run and not (isinstance(run["raw"], list)
804
+ and all(isinstance(r, str) for r in run["raw"])):
805
+ problems.add("[run].raw must be a list of path strings (globs allowed)")
806
+ if "tas_from_probe" in run and not (isinstance(run["tas_from_probe"], list)
807
+ and all(isinstance(r, str)
808
+ for r in run["tas_from_probe"])):
809
+ problems.add("[run].tas_from_probe must be a list of path strings (globs allowed)")
810
+ for key in ("preset", "out", "stages", "tas_file", "probe", "presets", "probe_case",
811
+ "probe_case_module"):
812
+ if key in run and not isinstance(run[key], str):
813
+ problems.add(f"[run].{key} must be a string, got {run[key]!r}")
814
+
815
+ comb = dict(doc.get("combine", {}))
816
+ unknown_combine = sorted(set(comb) - _COMBINE_KEYS - _FORBIDDEN)
817
+ if unknown_combine:
818
+ problems.add(f"[combine] has unknown key(s) {unknown_combine}; known: "
819
+ f"{sorted(_COMBINE_KEYS)}")
820
+ borrowed = comb.pop("borrowed", False)
821
+ if not isinstance(borrowed, bool):
822
+ problems.add(f"[combine].borrowed must be true/false, got {borrowed!r}")
823
+
824
+ thr_regime, thr_area, thr_iat, thr_declared = _load_thresholds(doc.get("thresholds"), path,
825
+ problems)
826
+ thr_tas_max, thr_pecan = _load_s4_case_inputs(doc.get("thresholds"), path, problems)
827
+ v35_i_qc, v35_i_new_habit, v35_declared = _load_v35(doc.get("v35"), run, problems,
828
+ engine_ok)
829
+ arm = _load_arm(doc.get("arm"), problems)
830
+ outputs = _load_outputs(doc.get("outputs"), problems)
831
+ (tas_source, tas_search, tas_cutoff, tas_default,
832
+ tas_declared) = _load_tas(doc.get("tas"), path, problems)
833
+ time_offset = _load_time_offset(doc.get("time_offset"), run, problems, engine_ok)
834
+
835
+ problems.raise_if_any()
836
+ return RunConfig(profile=profile, shattering_threshold_file=threshold,
837
+ shattering_ia_thresh_type=ia_thresh_type,
838
+ profile_module=str(profile_module) if profile_module is not None else None,
839
+ authordefaults_stamp=authordefaults_stamp,
840
+ authordefaults_path=authordefaults_path,
841
+ diode_masks=masks,
842
+ export_format=fmt, enhancements=enh,
843
+ enhancements_declared="enhancements" in doc,
844
+ combine={k: str(v) for k, v in comb.items()},
845
+ run=run, source=str(path), borrowed_combine=borrowed, soda2=soda2,
846
+ thresholds_regime=thr_regime, thresholds_area_ratio_z=thr_area,
847
+ thresholds_default_int_arr_thresh=thr_iat, thresholds_declared=thr_declared,
848
+ thresholds_tas_max=thr_tas_max, thresholds_pecan_params=thr_pecan,
849
+ v35_i_qc=v35_i_qc, v35_i_new_habit=v35_i_new_habit,
850
+ v35_declared=v35_declared, arm=arm, outputs=outputs,
851
+ tas_source=tas_source, tas_search=tas_search,
852
+ tas_cutoff_mps=tas_cutoff, tas_default_mps=tas_default,
853
+ tas_declared=tas_declared, time_offset=time_offset)
854
+
855
+
856
+ def _section_start(table: dict, problems: _Problems) -> tuple[int, bool]:
857
+ """Where a section helper's own problems begin, and whether the section is clean so far.
858
+
859
+ A forbidden key in the section was already reported by :func:`_check_forbidden`; it still
860
+ marks the section as broken, so the section's dependent checks (empty, resolver) are skipped
861
+ rather than reporting a consequence of it.
862
+ """
863
+ return len(problems), not (set(table) & _FORBIDDEN)
864
+
865
+
866
+ def _load_thresholds(thr: dict | None, path: Path,
867
+ problems: _Problems) -> tuple[str | None, float | None, float | None, bool]:
868
+ """``[thresholds]`` (regime-based configurable thresholds) -- the one section exempt from the
869
+ no-raw-thresholds rule.
870
+
871
+ Returns ``(regime, area_ratio_z, default_int_arr_thresh, declared)`` -- the RAW selection, not
872
+ a resolved value, so the caller (``run_flight.py``) can let a command-line flag win over a
873
+ config field-by-field before resolving, the same precedence every other ``--config`` value
874
+ already gets (``_apply_config``'s own docstring: "the command line always wins"). Validated
875
+ here regardless -- an unknown regime name or an out-of-bounds raw value fails at load time,
876
+ before any run consumes hours -- by asking :func:`~arrayprobe.regimes.resolve_thresholds` to
877
+ resolve them (result discarded; only used to validate) with an argument set no config file
878
+ can otherwise construct: naming a project/probe/tree here would need this loader to know a
879
+ run's campaign, which it does not and must not (that stays ``[run].preset`` /
880
+ ``CampaignPreset``'s job) -- so this call only ever exercises the regime and override
881
+ branches, never the project/probe-dependent "stock" fallback.
882
+ """
883
+ if thr is None:
884
+ return None, None, None, False
885
+ if not isinstance(thr, dict):
886
+ raise ConfigError(f"[thresholds] must be a table, got {thr!r}")
887
+ start, clean = _section_start(thr, problems)
888
+ extra = sorted(set(thr) - _THRESHOLD_KEYS - _FORBIDDEN)
889
+ if extra:
890
+ problems.add(f"[thresholds] has unknown key(s) {extra}; known: "
891
+ f"{sorted(_THRESHOLD_KEYS)}")
892
+ regime_name = thr.get("regime")
893
+ if regime_name is not None and (not isinstance(regime_name, str) or not regime_name.strip()):
894
+ problems.add(f"[thresholds].regime must be a non-empty string, got {regime_name!r}")
895
+ area = thr.get("area_ratio_z")
896
+ if area is not None and (not isinstance(area, (int, float)) or isinstance(area, bool)):
897
+ problems.add(f"[thresholds].area_ratio_z must be a number, got {area!r}")
898
+ iat = thr.get("default_int_arr_thresh")
899
+ if iat is not None and (not isinstance(iat, (int, float)) or isinstance(iat, bool)):
900
+ problems.add(f"[thresholds].default_int_arr_thresh must be a number, got {iat!r}")
901
+ if not clean or len(problems) > start:
902
+ # The empty check and the resolver read the values checked above; skip, never report
903
+ # a consequence. Nothing reads the return value: load_config raises before RunConfig.
904
+ return None, None, None, False
905
+ if regime_name is None and area is None and iat is None:
906
+ if "tas_max" in thr or "pecan_params" in thr:
907
+ # Only the S4 case inputs (_load_s4_case_inputs): a declared section, no threshold.
908
+ return None, None, None, True
909
+ problems.add("[thresholds] is present but empty: name a regime, a raw override, "
910
+ "or both, or omit the section entirely")
911
+ return None, None, None, False
912
+ try:
913
+ resolve_thresholds(
914
+ regime_name=regime_name,
915
+ area_ratio_z_override=float(area) if area is not None else None,
916
+ default_int_arr_thresh_override=float(iat) if iat is not None else None,
917
+ override_source=str(path),
918
+ )
919
+ except (ValueError, ThresholdValidationError) as exc:
920
+ problems.add(f"[thresholds]: {exc}", exc)
921
+ return None, None, None, False
922
+ return (regime_name, float(area) if area is not None else None,
923
+ float(iat) if iat is not None else None, True)
924
+
925
+
926
+ def _load_s4_case_inputs(thr: dict | None, path: Path,
927
+ problems: _Problems) -> tuple[float | None, str | None]:
928
+ """``[thresholds].tas_max`` and ``[thresholds].pecan_params`` -- the two ``sizeDist`` inputs
929
+ a UIOOPS case can lack (the 2DP's ``tasMax``; PECAN's ``getPECANparams``), as ``(tas_max,
930
+ pecan_params)``. Validated here so a bad value fails before any run spends hours: ``tas_max``
931
+ finite and > 0; ``pecan_params`` a path, relative to this file, that parses as a parameter
932
+ file. Which case needs them is the driver's check, since only it knows the probe."""
933
+ if not isinstance(thr, dict):
934
+ return None, None
935
+ tas_max = thr.get("tas_max")
936
+ if tas_max is not None:
937
+ if (isinstance(tas_max, bool) or not isinstance(tas_max, (int, float))
938
+ or not math.isfinite(tas_max) or tas_max <= 0):
939
+ problems.add(f"[thresholds].tas_max is an airspeed in m/s, finite and > 0; "
940
+ f"got {tas_max!r}")
941
+ tas_max = None
942
+ else:
943
+ tas_max = float(tas_max)
944
+ pecan = thr.get("pecan_params")
945
+ if pecan is not None:
946
+ if not isinstance(pecan, str) or not pecan.strip():
947
+ problems.add(f"[thresholds].pecan_params must be a path string, got {pecan!r}")
948
+ return tas_max, None
949
+ resolved = (Path(path).parent / Path(pecan).expanduser()).resolve()
950
+ # Imported on use: only a PECAN configuration reaches it.
951
+ from arrayprobe_uiops.pecan_params import load_pecan_params
952
+ try:
953
+ load_pecan_params(resolved)
954
+ except (OSError, ValueError) as exc:
955
+ problems.add(f"[thresholds].pecan_params {pecan!r} ({resolved}): {exc}", exc)
956
+ return tas_max, None
957
+ pecan = str(resolved)
958
+ return tas_max, pecan
959
+
960
+
961
+ def _load_v35(v35: dict | None, run: dict, problems: _Problems,
962
+ engine_ok: bool) -> tuple[int | None, int | None, bool]:
963
+ """``[v35]`` (iQC and iNewHabit configurable) -- ``iQC``/``iNewHabit`` as run configuration.
964
+
965
+ Both are required, no-MATLAB-default positional arguments of
966
+ ``arrayprobe_uiops.imgproc.imgproc_sm_v35`` (its own module docstring); this lets a config file
967
+ *select* between the two documented states (0 or 1) the same way ``[fidelity].profile``
968
+ selects a documented profile -- it cannot invent a third state. Read only under
969
+ ``[run].engine = "3.5"``, because neither key exists under the 3.1.4 engine (v3.1.4 has only
970
+ the Holroyd habit scheme and no ``qc_image`` gate to switch).
971
+
972
+ Returns ``(iQC, iNewHabit, declared)`` -- ``None`` for a field the file did not set, so the
973
+ caller (``scripts/run_flight.py``) can leave ``V35_CALL``'s own default (0) in place for it, and
974
+ ``declared`` distinct from either field being set (:func:`_load_thresholds`'s own pattern).
975
+ """
976
+ if v35 is None:
977
+ return None, None, False
978
+ if not isinstance(v35, dict):
979
+ raise ConfigError(f"[v35] must be a table, got {v35!r}")
980
+ start, clean = _section_start(v35, problems)
981
+ # An engine name [run] already refused says nothing about which engine this file meant.
982
+ if engine_ok and run.get("engine") != "3.5":
983
+ problems.add(f"[v35] is read only by the 3.5 engine; this file names "
984
+ f"[run].engine = {run.get('engine')!r}")
985
+ extra = sorted(set(v35) - _V35_KEYS - _FORBIDDEN)
986
+ if extra:
987
+ problems.add(f"[v35] has unknown key(s) {extra}; known: {sorted(_V35_KEYS)}")
988
+
989
+ def _bit(key: str) -> int | None:
990
+ if key not in v35:
991
+ return None
992
+ val = v35[key]
993
+ if isinstance(val, bool) or not isinstance(val, int) or val not in (0, 1):
994
+ problems.add(f"[v35].{key} must be 0 or 1, got {val!r}")
995
+ return None
996
+ return val
997
+
998
+ i_qc = _bit("iQC")
999
+ i_new_habit = _bit("iNewHabit")
1000
+ if not clean or len(problems) > start:
1001
+ return None, None, False
1002
+ if i_qc is None and i_new_habit is None:
1003
+ problems.add("[v35] is present but empty: set iQC, iNewHabit, or both, or omit "
1004
+ "the section entirely")
1005
+ return None, None, False
1006
+ return i_qc, i_new_habit, True
1007
+
1008
+
1009
+ def _load_time_offset(sec: dict | None, run: dict, problems: _Problems,
1010
+ engine_ok: bool) -> tuple[int, str, str] | None:
1011
+ """``[time_offset]`` -- engine 3.5's probe-clock offset, as ``(seconds, evidence,
1012
+ tas_clock)``.
1013
+
1014
+ The three keys are one setting: all present, or the section omitted. Validated at load time
1015
+ by the engine's own ``TimeOffset.build`` (whole, non-zero seconds under one day; non-empty
1016
+ evidence; ``tas_clock`` one of ``TAS_CLOCKS``), so a bad value fails before any run spends
1017
+ hours. Refused unless ``[run].engine = "3.5"``, as ``run_flight.py`` refuses the flags under
1018
+ 3.1.4 and as :func:`_load_v35` refuses its section.
1019
+ """
1020
+ if sec is None:
1021
+ return None
1022
+ if not isinstance(sec, dict):
1023
+ raise ConfigError(f"[time_offset] must be a table, got {sec!r}")
1024
+ start, clean = _section_start(sec, problems)
1025
+ if engine_ok and run.get("engine") != "3.5":
1026
+ problems.add(f"[time_offset] is engine 3.5 only (a keyword of arrayprobe_uiops's sizeDist; "
1027
+ f"v3.1.4 reproduces the archived record); this file names "
1028
+ f"[run].engine = {run.get('engine')!r}")
1029
+ extra = sorted(set(sec) - set(_TIME_OFFSET_KEYS) - _FORBIDDEN)
1030
+ if extra:
1031
+ problems.add(f"[time_offset] has unknown key(s) {extra}; known: "
1032
+ f"{list(_TIME_OFFSET_KEYS)}")
1033
+ missing = [k for k in _TIME_OFFSET_KEYS if k not in sec]
1034
+ if missing:
1035
+ problems.add(f"[time_offset] is missing {missing}: seconds, evidence and tas_clock are "
1036
+ f"required together, or omit the section")
1037
+ if not clean or len(problems) > start:
1038
+ return None
1039
+ # Imported on use: only a file with this section reaches it.
1040
+ from arrayprobe_uiops.sizedist import TimeOffset
1041
+ try:
1042
+ off = TimeOffset.build(sec["seconds"], sec["evidence"], sec["tas_clock"])
1043
+ except ValueError as exc:
1044
+ problems.add(f"[time_offset]: {exc}", exc)
1045
+ return None
1046
+ return off.seconds, off.evidence, off.tas_clock
1047
+
1048
+
1049
+ def _load_arm(arm: dict | None, problems: _Problems) -> dict[str, str]:
1050
+ """``[arm]`` -- the real ARM site/platform/facility identifiers
1051
+ ``arrayprobe_enhancements.arm_export`` needs to run through the enhancements driver, and
1052
+ never invents on its own (``arm_export.py``'s own docstring: "``site_id``/``facility_id``/
1053
+ ``platform_id`` are never invented"). A config file supplies the user's own already-assigned
1054
+ ARM codes for a real deployment; this loader does not derive, guess or default any of the
1055
+ three -- only ``data_level`` may fall back to ``export()``'s own documented default.
1056
+
1057
+ Returns ``{}`` when the file names no ``[arm]`` section, so
1058
+ :meth:`arrayprobe_enhancements.pipeline._apply_arm_export` (the only consumer) can tell
1059
+ "no section" from "section present" and name a skip rather than fabricate an identifier.
1060
+ """
1061
+ if arm is None:
1062
+ return {}
1063
+ if not isinstance(arm, dict):
1064
+ raise ConfigError(f"[arm] must be a table, got {arm!r}")
1065
+ extra = sorted(set(arm) - _ARM_KEYS - _FORBIDDEN)
1066
+ if extra:
1067
+ problems.add(f"[arm] has unknown key(s) {extra}; known: {sorted(_ARM_KEYS)}")
1068
+ missing = sorted(k for k in _ARM_REQUIRED_KEYS if not arm.get(k))
1069
+ if missing:
1070
+ problems.add(
1071
+ f"[arm] is missing {missing}: site_id, platform_id and facility_id are required "
1072
+ "together when [arm] is present -- they are never invented or defaulted "
1073
+ "(arm_export.py's own rule), so a partial identifier is refused rather than "
1074
+ "completed with a guess")
1075
+ out: dict[str, str] = {}
1076
+ for key in _ARM_KEYS:
1077
+ if key not in arm or key in missing:
1078
+ # A key the missing-identifier problem above already names is not reported twice.
1079
+ continue
1080
+ val = arm[key]
1081
+ if not isinstance(val, str) or not val.strip():
1082
+ problems.add(f"[arm].{key} must be a non-empty string, got {val!r}")
1083
+ continue
1084
+ out[key] = val
1085
+ return out
1086
+
1087
+
1088
+ def _load_outputs(outputs: dict | None, problems: _Problems) -> dict[str, bool | str]:
1089
+ """``[outputs]`` -- each key a true/false selection of one of the run's artefacts.
1090
+
1091
+ Returns ``{}`` for no section, so the driver can tell "the file says nothing" (today's
1092
+ behaviour, unchanged) from "the file opts out" (``false``). A non-boolean or unknown key is a
1093
+ problem, never a coercion: ``"yes"`` is not ``true``.
1094
+ """
1095
+ if outputs is None:
1096
+ return {}
1097
+ if not isinstance(outputs, dict):
1098
+ raise ConfigError(f"[outputs] must be a table, got {outputs!r}")
1099
+ extra = sorted(set(outputs) - _OUTPUTS_KEYS - _FORBIDDEN)
1100
+ if extra:
1101
+ problems.add(f"[outputs] has unknown key(s) {extra}; known: {sorted(_OUTPUTS_KEYS)}")
1102
+ out: dict[str, bool | str] = {}
1103
+ for key in sorted(_OUTPUTS_KEYS & set(outputs)):
1104
+ val = outputs[key]
1105
+ if key == "arm":
1106
+ # "faithful" or false. "enhanced" is selected today by [enhancements]
1107
+ # arm_export = true, so naming it here would be a second switch for one file.
1108
+ if val is False or val == "faithful":
1109
+ out[key] = val
1110
+ else:
1111
+ problems.add(f'[outputs].arm must be "faithful" or false, got {val!r} (the '
1112
+ "enhanced ARM file is selected by [enhancements] arm_export = "
1113
+ "true)")
1114
+ continue
1115
+ if not isinstance(val, bool):
1116
+ problems.add(f"[outputs].{key} must be true/false, got {val!r}")
1117
+ continue
1118
+ out[key] = val
1119
+ return out
1120
+
1121
+
1122
+ def _load_tas(tas: dict | None, path: Path, problems: _Problems,
1123
+ ) -> tuple[str | None, tuple[str, ...], float | None, float | None, bool]:
1124
+ """``[tas]`` (merged-file airspeed for ORACLES, the non-ORACLES airspeed chain) -- the TAS
1125
+ source chain's config-file half.
1126
+
1127
+ Returns ``(source, search, cutoff_mps, default_mps, declared)`` -- the raw selection, so
1128
+ ``scripts/run_flight.py`` can let a ``--tas-source``/``--tas-search``/``--tas-cutoff-mps``/
1129
+ ``--tas-default-mps`` flag win over a config field-by-field, the same precedence every other
1130
+ ``--config`` value already gets. ``cutoff_mps``/``default_mps`` are validated here regardless,
1131
+ by constructing a :class:`~arrayprobe.tools.make_tas_file.TasPolicy` (result discarded, only
1132
+ used to validate) -- an invalid pair fails at load time, before any run consumes hours, the
1133
+ same reason :func:`_load_thresholds` validates its own raw overrides early.
1134
+ """
1135
+ if tas is None:
1136
+ return None, (), None, None, False
1137
+ if not isinstance(tas, dict):
1138
+ raise ConfigError(f"[tas] must be a table, got {tas!r}")
1139
+ start, clean = _section_start(tas, problems)
1140
+ extra = sorted(set(tas) - _TAS_KEYS - _FORBIDDEN)
1141
+ if extra:
1142
+ problems.add(f"[tas] has unknown key(s) {extra}; known: {sorted(_TAS_KEYS)}")
1143
+ source = tas.get("source")
1144
+ if source is not None:
1145
+ if not isinstance(source, str) or source not in tas_sources.MODES:
1146
+ problems.add(f"[tas].source must be one of {tas_sources.MODES}, got {source!r}")
1147
+ search_raw = tas.get("search")
1148
+ search: tuple[str, ...] = ()
1149
+ if search_raw is not None and not (isinstance(search_raw, list)
1150
+ and all(isinstance(d, str) for d in search_raw)):
1151
+ problems.add(f"[tas].search must be a list of directory path strings, got "
1152
+ f"{search_raw!r}")
1153
+ elif search_raw is not None:
1154
+ # Resolved relative to the config file's own directory, the same rule [run].raw and
1155
+ # [fidelity].profile_module's sibling paths use elsewhere in this loader -- a config
1156
+ # names locations relative to itself, not to whatever directory a run happens to start
1157
+ # in. `~` is expanded here rather than left for the caller, because tas_sources.SOURCES'
1158
+ # own glob (arrayprobe.tools.tas_sources._candidates) expects an already-expanded path.
1159
+ search = tuple(str((path.parent / Path(d).expanduser()).resolve())
1160
+ if not Path(d).expanduser().is_absolute()
1161
+ else str(Path(d).expanduser())
1162
+ for d in search_raw)
1163
+ cutoff = tas.get("cutoff_mps")
1164
+ if cutoff is not None and (not isinstance(cutoff, (int, float)) or isinstance(cutoff, bool)):
1165
+ problems.add(f"[tas].cutoff_mps must be a number, got {cutoff!r}")
1166
+ default = tas.get("default_mps")
1167
+ if default is not None and (not isinstance(default, (int, float)) or isinstance(default, bool)):
1168
+ problems.add(f"[tas].default_mps must be a number, got {default!r}")
1169
+ if not clean or len(problems) > start:
1170
+ # The empty check and TasPolicy read the values checked above; skip, never report a
1171
+ # consequence. Nothing reads the return value: load_config raises before RunConfig.
1172
+ return None, (), None, None, False
1173
+ if source is None and search_raw is None and cutoff is None and default is None:
1174
+ problems.add("[tas] is present but empty: name a source, a search directory list, "
1175
+ "a policy override, or some combination, or omit the section entirely")
1176
+ return None, (), None, None, False
1177
+ try:
1178
+ TasPolicy(cutoff_mps=float(cutoff) if cutoff is not None else TasPolicy().cutoff_mps,
1179
+ default_mps=float(default) if default is not None else TasPolicy().default_mps)
1180
+ except ValueError as exc:
1181
+ problems.add(f"[tas]: {exc}", exc)
1182
+ return None, (), None, None, False
1183
+ return (source, search, float(cutoff) if cutoff is not None else None,
1184
+ float(default) if default is not None else None, True)
1185
+
1186
+
1187
+ def _enhancement_switches(doc: dict, problems: _Problems) -> dict[str, bool]:
1188
+ enh = doc.get("enhancements", {})
1189
+ for k, v in enh.items():
1190
+ if not isinstance(v, bool):
1191
+ problems.add(f"[enhancements].{k} must be true/false (opt-in), got {v!r}")
1192
+ return {k: bool(v) for k, v in enh.items()}
1193
+
1194
+
1195
+ def _load_soda2_config(doc: dict, path: Path, problems: _Problems) -> RunConfig:
1196
+ """The ``[run].engine = "soda2"`` branch of :func:`load_config` (the SODA-2 port
1197
+ lanes).
1198
+
1199
+ The author's decision (accepted 2026-09-15) that a SODA-2 config names no profile.
1200
+ The SODA-2 engine has one source tree, so no
1201
+ :class:`FidelityProfile` is required and none may be named: ``profile`` is ``None``. Only
1202
+ :data:`_SODA2_SECTIONS` are accepted, and only ``engine`` in ``[run]``, because
1203
+ ``arrayprobe soda2 run`` reads nothing else -- a ``[fidelity]`` table here would be a
1204
+ profile the run silently ignored. The raw file and output directory are the driver's own
1205
+ ``op`` fields, ``[soda2].fn`` and ``[soda2].outdir``.
1206
+ """
1207
+ # A section outside _SECTIONS was already reported as unknown by load_config.
1208
+ extra = sorted((set(doc) & _SECTIONS) - _SODA2_SECTIONS)
1209
+ if extra:
1210
+ hint = (" -- the SODA-2 engine has one source tree and reads no UIOPS fidelity profile"
1211
+ if "fidelity" in extra else "")
1212
+ problems.add(f'[run].engine = "soda2" reads only {sorted(_SODA2_SECTIONS)}; this '
1213
+ f"file also has {extra}, which the SODA-2 engine would ignore{hint}")
1214
+ run = dict(doc.get("run", {}))
1215
+ extra_run = sorted(set(run) - _SODA2_RUN_KEYS - _FORBIDDEN)
1216
+ if extra_run:
1217
+ problems.add(f'[run].engine = "soda2" reads only {sorted(_SODA2_RUN_KEYS)} in '
1218
+ f"[run]; this file also sets "
1219
+ f"{extra_run} -- the raw file and output directory are the driver's "
1220
+ f"[soda2].fn and [soda2].outdir (or `arrayprobe soda2 run --out`)")
1221
+ if "jit" in run and not isinstance(run["jit"], bool):
1222
+ problems.add(f"[run].jit is a switch and takes true or false; this file sets "
1223
+ f"{run['jit']!r}")
1224
+ soda2 = doc.get("soda2")
1225
+ if not isinstance(soda2, dict) or not soda2:
1226
+ problems.add('[run].engine = "soda2" needs a [soda2] table holding the '
1227
+ "driver's op fields")
1228
+ enh = _enhancement_switches(doc, problems)
1229
+ # [outputs] and [arm] go through the loaders a UIOOPS file uses; which selections the SODA-2
1230
+ # engine has built is decided by `arrayprobe soda2 run`, which refuses the rest by name.
1231
+ outputs = _load_outputs(doc.get("outputs"), problems)
1232
+ arm = _load_arm(doc.get("arm"), problems)
1233
+ problems.raise_if_any()
1234
+ assert isinstance(soda2, dict) # the [soda2] check above added a problem otherwise
1235
+ return RunConfig(profile=None, shattering_threshold_file=None,
1236
+ enhancements=enh,
1237
+ enhancements_declared="enhancements" in doc,
1238
+ run=run, source=str(path), soda2=dict(soda2),
1239
+ outputs=outputs, arm=arm)