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/compare.py ADDED
@@ -0,0 +1,950 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Diff-triage: align two UIOOPS output files, then compare them by tolerance class.
3
+
4
+ This is the comparison stage, and it is deliberately built *before* S4 rather than after it.
5
+ S4 is where mismatches against a reference product start arriving — for this project
6
+ that meant the ORACLES 2016 2D-S products, but the tool assumes nothing about which
7
+ campaign or probe produced either side — and the expensive part of a mismatch is
8
+ never noticing it — it is working out *which stage caused it*. A comparison tool
9
+ built during the panic is a tool built to confirm whatever the author already
10
+ suspects.
11
+
12
+ Two ideas carry the whole design.
13
+
14
+ **Align before comparing.** A naive element-wise diff of two per-particle files is
15
+ worthless the moment the particle *counts* differ: one extra particle at index 12
16
+ makes every subsequent row disagree, and a real one-particle framing difference
17
+ presents as "all 41 variables are wrong". So particles are joined on identity first
18
+ — ``(Date, Time, parent_rec_num, position_start, position_end)``, every component
19
+ framing-derived — and the join statistics are reported *before* any value is looked
20
+ at. Unmatched particles are summarised as **runs** rather than counts, because one
21
+ run of 300 is a different problem from 300 isolated singletons and the count alone
22
+ cannot tell them apart.
23
+
24
+ **Not every variable deserves the same verdict.** Asserting bit-equality on an
25
+ accumulated float is a test that fails for reasons no-one can act on; asserting
26
+ nothing on an integer count throws away the strongest evidence available. So each
27
+ variable is assigned a :class:`ToleranceClass`, and each class gets comparison
28
+ semantics *and a reporting style* that suits it — a confusion matrix for a
29
+ categorical code, drift-against-index for an accumulator, bit-equality for a count.
30
+
31
+ The classes are A–G, and the assignment is :data:`PROC_CLASSES` for the imgProc
32
+ per-particle file and :data:`SD_CLASSES` for the ``sizeDist`` size-distribution
33
+ file. Anything unassigned is reported as ``UNCLASSIFIED`` rather than silently
34
+ defaulted: a new variable appearing in a file is a fact about the file, and
35
+ picking a tolerance for it without deciding is how a comparison quietly stops
36
+ meaning anything.
37
+
38
+ **Both file kinds are handled, and the alignment differs between them.** A proc
39
+ file joins on particle identity. A sd file has no particles left in it, and its
40
+ one-second stamp turns out not to identify a row either — 256 of the ORACLES
41
+ 09/06 TAS sidecar's 4,110 rows are exact duplicates of their predecessor — so it
42
+ joins positionally on the ``Time`` index and verifies ``time`` as an ordinary
43
+ class-A variable. :func:`file_kind` decides which from the file's *dimensions*,
44
+ never from its name; that is the S2 rule, learned the hard way.
45
+
46
+ Class **G** was added at S4 for a situation the original six had no slot for: a
47
+ value where the Octave oracle and MATLAB genuinely disagree and the port
48
+ deliberately follows MATLAB. Octave 11.3's ``mean`` routes through
49
+ ``robust_mean_sum``, which uses a compensated accumulator MATLAB has no
50
+ equivalent of, so bit-equality with the oracle would be the *wrong* bar for the
51
+ one variable built with a plain ``mean``.
52
+ """
53
+
54
+ from __future__ import annotations
55
+
56
+ from dataclasses import dataclass, field
57
+ from typing import Any
58
+
59
+ import numpy as np
60
+
61
+ __all__ = [
62
+ "ToleranceClass",
63
+ "CLASSES",
64
+ "PROC_CLASSES",
65
+ "PROC_CLASSES_V35",
66
+ "SD_CLASSES",
67
+ "JOIN_KEY",
68
+ "SD_JOIN_KEY",
69
+ "JoinResult",
70
+ "VariableVerdict",
71
+ "ComparisonReport",
72
+ "join_particles",
73
+ "join_seconds",
74
+ "compare_variables",
75
+ "compare_proc_files",
76
+ "compare_sd_files",
77
+ "compare_files",
78
+ "file_kind",
79
+ "format_report",
80
+ ]
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Tolerance classes
85
+ # ---------------------------------------------------------------------------
86
+
87
+ @dataclass(frozen=True)
88
+ class ToleranceClass:
89
+ """One of the A-G comparison regimes, and whether a difference in it fails.
90
+
91
+ A class bundles two things that must travel together: *how* two values are
92
+ judged equal, and *what a difference means*. Splitting them is how a
93
+ comparison stops meaning anything -- a bit-equality assertion on an
94
+ accumulated float fails for reasons nobody can act on, and a loose
95
+ tolerance on an integer count throws away the strongest evidence in the
96
+ file.
97
+
98
+ ``rule`` is prose because it is written for the person reading a report,
99
+ not consumed by code; the executable half lives in
100
+ :func:`compare_variables`, which switches on ``key``. ``asserts`` is the
101
+ part that decides a verdict: a class with ``asserts=False`` is reported and
102
+ never blocks acceptance (see :meth:`ComparisonReport.accepted`).
103
+
104
+ Instances are the values of :data:`CLASSES`; nothing else constructs one.
105
+ """
106
+
107
+ key: str
108
+ name: str
109
+ rule: str
110
+ """How a difference is judged."""
111
+ asserts: bool
112
+ """Whether a difference in this class is a *failure*, or only information."""
113
+
114
+
115
+ CLASSES: dict[str, ToleranceClass] = {
116
+ "A": ToleranceClass(
117
+ "A", "bit-exact",
118
+ "Integers, ASCII codes, counts and bin edges. Any difference at all is a "
119
+ "failure — these carry no floating-point slack, so a mismatch is a real "
120
+ "disagreement about what happened, never a rounding artefact.",
121
+ asserts=True,
122
+ ),
123
+ "B": ToleranceClass(
124
+ "B", "closed-form float",
125
+ "Floats produced by a short arithmetic expression with no accumulation. "
126
+ "Tolerance is a few ULP (rtol 1e-12, atol 0). A difference larger than "
127
+ "that is a different formula, not a different rounding order.",
128
+ asserts=True,
129
+ ),
130
+ "C": ToleranceClass(
131
+ "C", "accumulated float",
132
+ "Values built by summing along the record, so error grows with index. "
133
+ "Reported as drift against index — first divergence, slope, endpoint — "
134
+ "rather than as a single max, because the max alone cannot distinguish "
135
+ "a steady accumulation from one bad element.",
136
+ asserts=False,
137
+ ),
138
+ "D": ToleranceClass(
139
+ "D", "algorithm substitution",
140
+ "Computed by a different implementation of the same mathematical object "
141
+ "(the smallest enclosing circle). Agreement is a theorem, not a "
142
+ "coincidence, so the tolerance is real but loose: atol 1e-9.",
143
+ asserts=True,
144
+ ),
145
+ "E": ToleranceClass(
146
+ "E", "legitimately version-dependent",
147
+ "Categorical outputs that two MATLAB versions may genuinely disagree on. "
148
+ "**Never asserted.** Reported as a confusion matrix, because 'how many "
149
+ "differ' is the wrong question and 'which code became which' is the right "
150
+ "one — the shape of the matrix names the divergent branch.",
151
+ asserts=False,
152
+ ),
153
+ "F": ToleranceClass(
154
+ "F", "preserved defect",
155
+ "A value whose agreement is asserted *because a preserved defect makes it "
156
+ "so*. Held separately from A so that a fidelity decision is never confused "
157
+ "with an ordinary equality.",
158
+ asserts=True,
159
+ ),
160
+ "G": ToleranceClass(
161
+ "G", "oracle more accurate than MATLAB",
162
+ "A value where the Octave oracle and MATLAB genuinely differ and the port "
163
+ "deliberately follows MATLAB, so bit-equality with the oracle is the WRONG "
164
+ "bar. Asserted within a stated ULP budget (rtol 1e-14, atol 0), which is "
165
+ "loose enough for the known cause and far too tight to hide a real "
166
+ "disagreement. Added at S4, when Octave 11.3's `mean` turned out to use a "
167
+ "compensated accumulator (`sum(...,\"extra\")` via `robust_mean_sum`) that "
168
+ "MATLAB has no equivalent of.",
169
+ asserts=True,
170
+ ),
171
+ }
172
+
173
+
174
+ #: The join key. Every component is framing-derived — decided before any
175
+ #: measurement is taken from the particle image — so a difference in a *measured*
176
+ #: quantity can never move a particle from one side of the join to the other.
177
+ #: Neither ``position`` nor ``particle_num`` identifies a particle on its own, and
178
+ #: ``parent_rec_num`` restarts per input file, which is why ``Date`` and ``Time``
179
+ #: are in the key at all.
180
+ JOIN_KEY = ("Date", "Time", "parent_rec_num", "position")
181
+
182
+
183
+ PROC_CLASSES: dict[str, str] = {
184
+ # -- A: integers, counts, flags, and floats that hold integer values --------
185
+ "Date": "A",
186
+ "Time": "A",
187
+ "msec": "A",
188
+ "SliceCount": "A",
189
+ "DMT_DOF_SPEC_OVERLOAD": "A",
190
+ "Particle_number_all": "A",
191
+ "position": "A",
192
+ "particle_time": "A",
193
+ "particle_millisec": "A",
194
+ # A raw clock count. Declared double, integer-valued, so bit-equality is the
195
+ # right bar despite the type.
196
+ "particle_microsec": "A",
197
+ "parent_rec_num": "A",
198
+ "particle_num": "A",
199
+ "image_length": "A",
200
+ "image_width": "A",
201
+ # A count of shadowed pixels. Double in the file, integer in fact.
202
+ "image_area": "A",
203
+ "image_longest_y": "A",
204
+ "image_max_top_edge_touching": "A",
205
+ "image_max_bottom_edge_touching": "A",
206
+ # Tri-valued {-48, 0, 68}, not boolean.
207
+ "image_touching_edge": "A",
208
+ "image_hollow": "A",
209
+ "image_center_in": "A",
210
+ "edge_at_max_hole": "A",
211
+ "max_hole_diameter": "A",
212
+ "bin_stats": "A",
213
+
214
+ # -- B: short closed-form arithmetic ---------------------------------------
215
+ "image_axis_ratio": "B",
216
+ "image_diam_circle_fit": "B",
217
+ "image_diam_horiz_chord": "B",
218
+ "image_diam_horiz_chord_corr": "B",
219
+ "image_diam_following_bamex_code": "B",
220
+ "image_diam_vert_chord": "B",
221
+ "image_diam_AreaR": "B",
222
+ "image_perimeter": "B",
223
+ "percent_shadow_area": "B",
224
+ "part_z": "B",
225
+ "size_factor": "B",
226
+ "area_hole_ratio": "B",
227
+
228
+ # -- C: accumulated along the record ---------------------------------------
229
+ "Time_in_seconds": "C",
230
+ "inter_arrival": "C",
231
+
232
+ # -- D: our geometry against CGAL's ----------------------------------------
233
+ "image_diam_minR": "D",
234
+
235
+ # -- E: categorical, and genuinely version-dependent ------------------------
236
+ "image_auto_reject": "E",
237
+ "holroyd_habit": "E",
238
+ }
239
+
240
+ #: v3.5's ``imgProc_sm`` writes four per-particle variables v3.1.4 never did
241
+ #: (``arrayprobe_uiops/imgproc.py:715-716, 736-737``; v3.5 ``imgProc_sm.m:1359-1360, 1381-1382``).
242
+ #: ``PROC_CLASSES`` stays the v3.1.4 table (``tests/test_compare.py`` pins it to the v3.1.4
243
+ #: profiles' variable lists); a v3.5 proc file is compared with THIS table, or
244
+ #: ``compare_files`` reports the four as unclassified and ``accepted()`` is False (measured
245
+ #: 2026-09-13 on the demo flight -- exactly these four, nothing else).
246
+ PROC_CLASSES_V35: dict[str, str] = {
247
+ **PROC_CLASSES,
248
+ # Centre of the minimum enclosing circle, unscaled -- the same substituted algorithm
249
+ # that produces image_diam_minR, so the same class.
250
+ "image_xpos": "D",
251
+ "image_ypos": "D",
252
+ # Closed-form ratios of already-compared quantities: Perim*Diam/Area; sqrt(area)/perim.
253
+ "fine_detail_ratio": "B",
254
+ "sphericity": "B",
255
+ # The default-on stray-pixel correction (engine 3.5 driver): a count of pixels removed,
256
+ # integer in fact, and the minimum-enclosing-circle diameter before the correction --
257
+ # the same substituted algorithm as image_diam_minR, so the same class.
258
+ "image_stray_pixels_removed": "A",
259
+ "image_diam_minR_uncorrected": "D",
260
+ }
261
+
262
+ #: The join key for a size-distribution file. There is no particle identity left
263
+ #: at this stage -- every variable is per second -- so the key is the one-second
264
+ #: timestamp the file carries in ``time``.
265
+ SD_JOIN_KEY = ("Time index",)
266
+
267
+
268
+ SD_CLASSES: dict[str, str] = {
269
+ # -- A: bit-exact, and measured so against the S4 oracle on a real flight --
270
+ # 24 of the 25 written variables reproduce the Octave run bit for bit, so
271
+ # anything less than bit-equality here is a genuine disagreement. Nothing in
272
+ # this file is an integer, which makes that a strong statement rather than a
273
+ # cheap one: it says the whole 1 Hz loop, the sample volume and the
274
+ # normalisation all reduce in MATLAB's order.
275
+ "time": "A",
276
+ "bin_min": "A",
277
+ "bin_max": "A",
278
+ "bin_mid": "A",
279
+ "bin_dD": "A",
280
+ "conc_minR": "A",
281
+ "area": "A",
282
+ "n": "A",
283
+ "total_area": "A",
284
+ "mass": "A",
285
+ "habitsd": "A",
286
+ "re": "A",
287
+ "massBL": "B",
288
+ "Reject_ratio": "A",
289
+ "vt": "B",
290
+ "Prec_rate": "B",
291
+ "habitmsd": "A",
292
+ "Calcd_area": "A",
293
+ "count": "A",
294
+ "mean_perimeter": "A",
295
+ "sum_IntArr": "A",
296
+ "sample_vol": "A",
297
+
298
+ # -- Reclassified A -> B on 2026-09-08, by cross-platform measurement ------
299
+ # `massBL` and `vt` sat in A, the class whose own rule reads "Integers, ASCII
300
+ # codes, counts and bin edges ... these carry no floating-point slack". They
301
+ # are neither. `massBL` is `0.115/1000 * area ** 1.218` (sizedist.py:1223,
302
+ # sizeDist.m:844) and `vt` comes out of single_vt.m -- closed-form floats
303
+ # through a fractional power and transcendental functions, which is the
304
+ # written definition of B.
305
+ #
306
+ # They were in A for an honest but single-platform reason: measured equal,
307
+ # bit for bit, against the Octave goldens. Every one of those measurements
308
+ # was taken on the same Windows machine that built the goldens, so both
309
+ # sides called the same libm and the same rounding came out twice. The first
310
+ # cross-platform CI run took the measurement somewhere else and it did not
311
+ # survive:
312
+ #
313
+ # Linux-6.17.0 / glibc 2.39 / numpy 2.5.2
314
+ # massBL n_diff=2/256 max_abs=1.59e-22 (values ~2.7e-08 to 3.3e-07)
315
+ # massBL n_diff=2/384 max_abs=5.29e-23
316
+ # macOS vt differs in the same shape
317
+ #
318
+ # That is a relative difference of order 1e-15 on two cells in 256 -- the
319
+ # last bits of a double, which is what glibc's pow() and Microsoft's UCRT
320
+ # pow() are permitted to disagree about. A different formula would move
321
+ # every cell and move it far; this moves two, by 1e-22. B's tolerance is
322
+ # rtol 1e-12, four orders of magnitude above what was measured, so the port
323
+ # is still held to a bound that a real disagreement could not pass.
324
+ #
325
+ # NOTHING ELSE IS RECLASSIFIED. `mass`, `re`, `Prec_rate` and `Calcd_area`
326
+ # are derived floats sitting in A on the same single-platform evidence and
327
+ # are under exactly the same suspicion -- but no platform has yet produced a
328
+ # difference in them, and this project does not move a classification on
329
+ # analogy. They move if and when something measures them.
330
+ #
331
+ # -- Prec_rate (and REJ_Prec_rate) reclassified A -> B on 2026-10-02 ------
332
+ # Measured: CI run 37074378298 (master c00fdf8), Linux-6.17.0 / glibc 2.39 /
333
+ # numpy 2.5.3, stock-tree PIP cases of test_sizedist_stock_divergences:
334
+ # Prec_rate n_diff=1/384 max_abs=3.31e-24 at 1.46971e-08 (clamp)
335
+ # Prec_rate n_diff=1/320 max_abs=3.31e-24 at 1.46971e-08 (pt1abs)
336
+ # i.e. rel 2.3e-16, two ULP (ulp of 1.47e-08 is 2^-79 = 1.65e-24), in one
337
+ # cell. `Prec_rate` is sum(mass * vt) / binwidth * 10 / svol (sizedist.py
338
+ # particle_pr = particle_mass * particle_vt), and vt comes out of single_vt
339
+ # through exp/log/pow -- the variable `vt` already moved to B on macOS for
340
+ # this reason. REJ_Prec_rate is the same expression on the rejected
341
+ # population and moves with it, as REJ_massBL and REJ_vt did.
342
+
343
+ # -- F: exact BECAUSE a preserved defect makes it so ------------------------
344
+ # `conc_AreaR` is identically zero (the double-scaled area-ratio concentration:
345
+ # sizeDist.m:669 scaling an already-scaled diameter), and `mean_area_ratio` is a
346
+ # column-major reshape of the array MATLAB meant to transpose (:1981). Both agree exactly, and
347
+ # both would agree exactly with a "fixed" port too if the fix were applied on
348
+ # both sides -- which is why they are held apart from A.
349
+ "conc_AreaR": "F",
350
+ "mean_area_ratio": "F",
351
+
352
+ # -- G: the oracle is more accurate than the MATLAB it stands in for --------
353
+ "ar": "G",
354
+
355
+ # -- The optional-branch variables, classified 2026-09-06 -------------------
356
+ # `iCreateBad` and `iCreateAspectRatio` add 21 more variables, and until this
357
+ # date NONE of them had a class -- because no test had ever run sizeDist with
358
+ # either flag on, so nothing ever asked. A comparison that touched them
359
+ # reported UNCLASSIFIED, which blocks acceptance: the comparator was right to
360
+ # refuse, and the refusal was invisible for want of a caller.
361
+ #
362
+ # All 21 are A on measurement, not by analogy: stock v3.1.4 run under Octave
363
+ # with iCreateAspectRatio=1 and iCreateBad=1 over the same proc file agrees
364
+ # with the port in every cell of every one of them, NaN positions included
365
+ # (octave_oracle/run_s4_aspectratio_bank.py, 46/46 variables, 2 seconds x 128
366
+ # bins). The rejected-population block is the accepted one line for line, so
367
+ # bit-equality there is what its shared transcription predicts.
368
+ "REJ_conc_minR": "A",
369
+ "REJ_conc_AreaR": "A",
370
+ "REJ_area": "A",
371
+ "REJ_n": "A",
372
+ "REJ_total_area": "A",
373
+ "REJ_mass": "A",
374
+ "REJ_massBL": "B",
375
+ "REJ_habitsd": "A",
376
+ "REJ_habitmsd": "A",
377
+ "REJ_re": "A",
378
+ "REJ_vt": "B",
379
+ "REJ_Prec_rate": "B",
380
+ "REJ_Calcd_area": "A",
381
+ "REJ_count": "A",
382
+ "REJ_mean_perimeter": "A",
383
+ "REJ_mean_area_ratio": "A",
384
+ "REJ_ar": "A",
385
+ # The two this bank was built for. They were written all-NaN by the port
386
+ # until 2026-09-06 while MATLAB filled them (:1257-1263, :1978-1979); the
387
+ # class records that they now agree, which is a different statement from
388
+ # "both are NaN" -- 14 of the 256 accepted cells and 8 of the 256 rejected
389
+ # ones carry real numbers in this fixture.
390
+ "mean_aspect_ratio_rectangle": "A",
391
+ "mean_aspect_ratio_ellipse": "A",
392
+ "REJ_mean_aspect_ratio_rectangle": "A",
393
+ "REJ_mean_aspect_ratio_ellipse": "A",
394
+ }
395
+
396
+ _CLASS_TOL = {"B": (1e-12, 0.0), "D": (0.0, 1e-9), "G": (1e-14, 0.0)}
397
+
398
+ #: Values that mean "this branch did not compute me" rather than a measurement.
399
+ #: A mismatch in one of these is a *branch* difference, and saying so is more
400
+ #: useful than reporting a numeric delta.
401
+ SENTINELS: dict[str, tuple[str, Any]] = {
402
+ "image_axis_ratio": ("0.0 for every edge-touching particle", 0.0),
403
+ "image_diam_minR": ("NaN for an all-lit image", np.nan),
404
+ "particle_time": ("identically zero for probetype 2", 0),
405
+ "particle_millisec": ("identically zero for probetype 2", 0),
406
+ }
407
+
408
+
409
+ # ---------------------------------------------------------------------------
410
+ # Join
411
+ # ---------------------------------------------------------------------------
412
+
413
+ def describe_differences(report) -> str:
414
+ """One line per non-EXACT variable, carrying the MEASUREMENT.
415
+
416
+ A bit-exactness assertion that fails with only a variable name cannot
417
+ distinguish the two things it could possibly mean: one ulp of a platform's
418
+ libm, or a real disagreement about the physics. The first cross-platform CI
419
+ run (2026-09-08) failed on Linux with ``['massBL']`` and on macOS with
420
+ ``['vt']`` and said nothing else -- both are derived quantities computed
421
+ through fractional powers and transcendental functions, exactly where two
422
+ libm implementations are allowed to differ in the last bit, but nothing in
423
+ the message established that. Every bit-exactness test in this repository
424
+ formats its failure through here so the log says which.
425
+ """
426
+ import platform
427
+ bad = [v for v in report.variables if v.verdict != "EXACT"]
428
+ if not bad:
429
+ return "none"
430
+ rows = "; ".join(
431
+ f"{v.name} [{v.tclass}] {v.verdict} n_diff={v.n_diff}/{v.n_total} "
432
+ f"max_abs={v.max_abs:.6g} {v.detail}" for v in bad)
433
+ return f"on {platform.platform()} / numpy {np.__version__}: {rows}"
434
+
435
+
436
+ @dataclass
437
+ class JoinResult:
438
+ """Which rows of two files are the same thing, decided before any value is read.
439
+
440
+ Produced by :func:`join_particles` (proc files, joined on the identity
441
+ tuple :data:`JOIN_KEY`) or :func:`join_seconds` (sd files, joined
442
+ positionally on the ``Time`` index). Everything in
443
+ :func:`compare_variables` is indexed through ``left_index``/``right_index``,
444
+ so a bad join makes every subsequent verdict meaningless -- which is why
445
+ the join statistics are reported above the value table rather than below
446
+ it.
447
+
448
+ The unmatched rows are kept as index arrays, not counts, so
449
+ :meth:`unmatched_runs` can distinguish one abandoned record from a
450
+ systematic framing difference.
451
+ """
452
+
453
+ left_index: np.ndarray
454
+ """Indices into A of matched particles, in A's order."""
455
+ right_index: np.ndarray
456
+ """Indices into B of the same particles."""
457
+ left_only: np.ndarray
458
+ right_only: np.ndarray
459
+ n_left: int
460
+ n_right: int
461
+ duplicate_keys: int = 0
462
+ """Keys appearing more than once on either side.
463
+
464
+ Not expected, and worth surfacing loudly if it happens: it would mean the
465
+ join key does not identify a particle, which invalidates every value
466
+ comparison built on top of it.
467
+ """
468
+
469
+ @property
470
+ def n_matched(self) -> int:
471
+ """Rows present on both sides. Equal to ``left_index.size`` by construction."""
472
+ return int(self.left_index.size)
473
+
474
+ @property
475
+ def join_fraction(self) -> float:
476
+ """Matched, as a fraction of the larger side. 1.0 iff both sides align."""
477
+ denom = max(self.n_left, self.n_right)
478
+ return float(self.n_matched / denom) if denom else 1.0
479
+
480
+ def unmatched_runs(self, side: str = "left") -> list[tuple[int, int]]:
481
+ """Consecutive unmatched indices, collapsed to ``(start, length)`` runs.
482
+
483
+ The distinction this exists to preserve: 300 unmatched particles in one
484
+ run is a single event -- most likely a record abandoned early -- while
485
+ 300 singletons scattered through the file is a systematic framing
486
+ difference. The counts are identical and the diagnoses are not.
487
+ """
488
+ idx = np.sort(self.left_only if side == "left" else self.right_only)
489
+ if idx.size == 0:
490
+ return []
491
+ breaks = np.flatnonzero(np.diff(idx) != 1)
492
+ starts = np.concatenate(([0], breaks + 1))
493
+ ends = np.concatenate((breaks, [idx.size - 1]))
494
+ return [(int(idx[s]), int(idx[e] - idx[s] + 1)) for s, e in zip(starts, ends, strict=True)]
495
+
496
+
497
+ def _key_columns(ds, n):
498
+ """Build the (n, k) integer key matrix from a netCDF dataset."""
499
+ cols = []
500
+ for name in JOIN_KEY:
501
+ if name not in ds.variables:
502
+ raise KeyError(
503
+ f"join key component {name!r} is missing from the file; "
504
+ f"available: {', '.join(sorted(ds.variables))}"
505
+ )
506
+ v = np.asarray(ds.variables[name][:])
507
+ if v.ndim == 1:
508
+ cols.append(v.reshape(n, 1))
509
+ else:
510
+ # `position` is (pos_count, time) in MATLAB and therefore (time,
511
+ # pos_count) as stored. Take whichever axis is the particle axis
512
+ # rather than assuming, since a transposed write is exactly the kind
513
+ # of defect this tool exists to find.
514
+ arr = v if v.shape[0] == n else v.T
515
+ cols.append(arr.reshape(n, -1))
516
+ return np.hstack([c.astype(np.int64) for c in cols])
517
+
518
+
519
+ def join_particles(ds_a, ds_b) -> JoinResult:
520
+ """Align two per-particle files on particle identity.
521
+
522
+ Returns index arrays into each side. Order is A's order, so a report can be
523
+ read against the left-hand file.
524
+ """
525
+ n_a = len(ds_a.dimensions["time"])
526
+ n_b = len(ds_b.dimensions["time"])
527
+ ka = _key_columns(ds_a, n_a)
528
+ kb = _key_columns(ds_b, n_b)
529
+
530
+ # Structured void view gives exact tuple equality without hashing floats.
531
+ va = np.ascontiguousarray(ka).view([("", ka.dtype)] * ka.shape[1]).ravel()
532
+ vb = np.ascontiguousarray(kb).view([("", kb.dtype)] * kb.shape[1]).ravel()
533
+
534
+ dup = int(n_a - np.unique(va).size) + int(n_b - np.unique(vb).size)
535
+
536
+ common, ia, ib = np.intersect1d(va, vb, return_indices=True)
537
+ order = np.argsort(ia)
538
+ ia, ib = ia[order], ib[order]
539
+
540
+ left_only = np.setdiff1d(np.arange(n_a), ia)
541
+ right_only = np.setdiff1d(np.arange(n_b), ib)
542
+ del common
543
+ return JoinResult(ia, ib, left_only, right_only, n_a, n_b, duplicate_keys=dup)
544
+
545
+
546
+ # ---------------------------------------------------------------------------
547
+ # Value comparison
548
+ # ---------------------------------------------------------------------------
549
+
550
+ @dataclass
551
+ class VariableVerdict:
552
+ """The comparison outcome for one netCDF variable, in its tolerance class.
553
+
554
+ ``verdict`` is the coarse answer and ``detail`` the class-appropriate
555
+ evidence behind it -- a drift slope for an accumulator, the worst absolute
556
+ difference for a closed-form float, a per-value breakdown for a
557
+ categorical. ``confusion`` is populated only for the categorical classes,
558
+ mapping ``(left_value, right_value)`` to how often that substitution
559
+ happened; for a reject-code or habit-code variable that table is the whole
560
+ diagnosis, where ``n_diff`` alone would say only that something moved.
561
+
562
+ Whether the verdict *counts against* the run is not stored here: it is
563
+ :attr:`failed`, which asks the variable's :class:`ToleranceClass`.
564
+ """
565
+
566
+ name: str
567
+ tclass: str
568
+ verdict: str
569
+ """``EXACT`` · ``WITHIN`` · ``DIFF`` · ``SHAPE`` · ``MISSING`` · ``INFO``."""
570
+ n_diff: int = 0
571
+ n_total: int = 0
572
+ max_abs: float = 0.0
573
+ detail: str = ""
574
+ confusion: dict[tuple[float, float], int] = field(default_factory=dict)
575
+
576
+ @property
577
+ def failed(self) -> bool:
578
+ """A bad verdict *in a class that asserts* -- the two halves are separate.
579
+
580
+ ``DIFF`` on a class-C accumulator is information and not a failure;
581
+ the same verdict on a class-A count is a real disagreement about what
582
+ happened. An unknown class falls back to A, the strictest, so a
583
+ variable nobody has classified cannot be quietly excused.
584
+ """
585
+ return self.verdict in ("DIFF", "SHAPE", "MISSING") and CLASSES.get(
586
+ self.tclass, CLASSES["A"]
587
+ ).asserts
588
+
589
+
590
+ def _values(ds, name, index):
591
+ v = np.asarray(ds.variables[name][:])
592
+ if v.ndim == 1 and v.shape[0] == index.size + (v.shape[0] - index.size):
593
+ pass
594
+ return v
595
+
596
+
597
+ def _aligned(ds, name, index, n_particles):
598
+ """Pull `name` and select the joined particles, whatever the axis order."""
599
+ v = np.asarray(ds.variables[name][:])
600
+ if v.ndim == 1:
601
+ if v.shape[0] != n_particles:
602
+ return v # a per-bin variable such as bin_stats
603
+ return v[index]
604
+ axis = 0 if v.shape[0] == n_particles else 1
605
+ return np.take(v, index, axis=axis)
606
+
607
+
608
+ def compare_variables(ds_a, ds_b, join: JoinResult,
609
+ classes: dict[str, str] | None = None) -> list[VariableVerdict]:
610
+ """Compare every variable of A against B over the joined particles."""
611
+ classes = PROC_CLASSES if classes is None else classes
612
+ out: list[VariableVerdict] = []
613
+
614
+ for name in ds_a.variables:
615
+ tclass = classes.get(name, "?")
616
+ if name not in ds_b.variables:
617
+ out.append(VariableVerdict(name, tclass, "MISSING",
618
+ detail="absent from the right-hand file"))
619
+ continue
620
+
621
+ a = _aligned(ds_a, name, join.left_index, join.n_left).astype(np.float64)
622
+ b = _aligned(ds_b, name, join.right_index, join.n_right).astype(np.float64)
623
+ if a.shape != b.shape:
624
+ out.append(VariableVerdict(name, tclass, "SHAPE",
625
+ detail=f"{a.shape} vs {b.shape}"))
626
+ continue
627
+
628
+ both_nan = np.isnan(a) & np.isnan(b)
629
+ equal = both_nan | (a == b)
630
+ n_diff = int(np.count_nonzero(~equal))
631
+ diff = np.where(both_nan, 0.0, np.abs(a - b))
632
+ max_abs = float(np.nanmax(diff)) if diff.size else 0.0
633
+
634
+ if tclass == "?":
635
+ out.append(VariableVerdict(
636
+ name, "?", "INFO", n_diff, a.size, max_abs,
637
+ detail="UNCLASSIFIED — assign a tolerance class before trusting "
638
+ "this row either way",
639
+ ))
640
+ continue
641
+
642
+ if n_diff == 0:
643
+ out.append(VariableVerdict(name, tclass, "EXACT", 0, a.size, 0.0,
644
+ detail=_sentinel_note(name)))
645
+ continue
646
+
647
+ if tclass == "E":
648
+ out.append(VariableVerdict(
649
+ name, tclass, "INFO", n_diff, a.size, max_abs,
650
+ detail=_confusion_detail(a, b, equal),
651
+ confusion=_confusion(a, b, equal),
652
+ ))
653
+ elif tclass == "C":
654
+ out.append(VariableVerdict(name, tclass, "INFO", n_diff, a.size,
655
+ max_abs, detail=_drift_detail(a, b, equal)))
656
+ elif tclass in _CLASS_TOL:
657
+ rtol, atol = _CLASS_TOL[tclass]
658
+ close = both_nan | np.isclose(a, b, rtol=rtol, atol=atol, equal_nan=True)
659
+ n_out = int(np.count_nonzero(~close))
660
+ out.append(VariableVerdict(
661
+ name, tclass, "WITHIN" if n_out == 0 else "DIFF",
662
+ n_out if n_out else n_diff, a.size, max_abs,
663
+ detail=(f"{n_diff} not bit-equal, all within tolerance"
664
+ if n_out == 0
665
+ else f"{n_out} outside rtol={rtol:g} atol={atol:g}")
666
+ + _sentinel_note(name, prefix="; "),
667
+ ))
668
+ else: # A and F both demand bit-equality
669
+ out.append(VariableVerdict(
670
+ name, tclass, "DIFF", n_diff, a.size, max_abs,
671
+ detail=_first_offenders(a, b, equal) + _sentinel_note(name, prefix="; "),
672
+ ))
673
+ # A variable only the right-hand file carries is as much a disagreement as one only the
674
+ # left carries; iterating the left file alone never saw it, and the gate passed.
675
+ for name in ds_b.variables:
676
+ if name not in ds_a.variables:
677
+ out.append(VariableVerdict(name, classes.get(name, "?"), "MISSING",
678
+ detail="absent from the left-hand file"))
679
+ return out
680
+
681
+
682
+ def _sentinel_note(name, prefix=""):
683
+ if name not in SENTINELS:
684
+ return ""
685
+ return f"{prefix}sentinel: {SENTINELS[name][0]}"
686
+
687
+
688
+ def _first_offenders(a, b, equal, k=3):
689
+ idx = np.flatnonzero(~equal.ravel())[:k]
690
+ if idx.size == 0:
691
+ return ""
692
+ af, bf = a.ravel(), b.ravel()
693
+ parts = [f"[{int(i)}] {af[i]:g} vs {bf[i]:g}" for i in idx]
694
+ return "first: " + ", ".join(parts)
695
+
696
+
697
+ def _confusion(a, b, equal):
698
+ out: dict[tuple[float, float], int] = {}
699
+ for left, right in zip(a.ravel()[~equal.ravel()], b.ravel()[~equal.ravel()], strict=True):
700
+ out[(float(left), float(right))] = out.get((float(left), float(right)), 0) + 1
701
+ return out
702
+
703
+
704
+ def _confusion_detail(a, b, equal, k=4):
705
+ pairs = sorted(_confusion(a, b, equal).items(), key=lambda kv: -kv[1])[:k]
706
+ if not pairs:
707
+ return ""
708
+ shown = ", ".join(f"{_code(x)}->{_code(y)} x{n}" for (x, y), n in pairs)
709
+ return "top transitions: " + shown
710
+
711
+
712
+ def _code(v):
713
+ """Render a categorical value as its ASCII character where that is what it is."""
714
+ iv = int(v)
715
+ if 32 <= iv < 127:
716
+ return f"{iv}({chr(iv)!r})"
717
+ return str(iv)
718
+
719
+
720
+ def _drift_detail(a, b, equal):
721
+ bad = np.flatnonzero(~equal.ravel())
722
+ if bad.size == 0:
723
+ return ""
724
+ d = (a.ravel() - b.ravel())
725
+ first = int(bad[0])
726
+ # Slope of the difference against index: a steady accumulation has one, a
727
+ # single bad element does not.
728
+ if bad.size >= 2:
729
+ slope = float(np.polyfit(bad.astype(float), d[bad], 1)[0])
730
+ else:
731
+ slope = 0.0
732
+ return (f"first divergence at particle {first}; "
733
+ f"drift slope {slope:.3g} per particle; "
734
+ f"endpoint delta {d[-1]:.6g}")
735
+
736
+
737
+ # ---------------------------------------------------------------------------
738
+ # Top level
739
+ # ---------------------------------------------------------------------------
740
+
741
+ @dataclass
742
+ class ComparisonReport:
743
+ """One whole file-against-file comparison: the alignment, then every variable.
744
+
745
+ Returned by :func:`compare_proc_files`, :func:`compare_sd_files` and
746
+ :func:`compare_files`, and rendered for a human by :func:`format_report`.
747
+ The ordering of the fields is the ordering of the report on purpose: a
748
+ reader must see how well the two files aligned, and any ``notes`` about
749
+ that alignment, before a single value verdict -- a 98 % join makes the
750
+ value table describe a different population on each side.
751
+
752
+ :meth:`accepted` is the gate; :attr:`failures` and :attr:`unclassified` are
753
+ the two ways it can be closed.
754
+ """
755
+
756
+ join: JoinResult
757
+ variables: list[VariableVerdict]
758
+ left: str = ""
759
+ right: str = ""
760
+ join_key: tuple[str, ...] = JOIN_KEY
761
+ """What the join was on -- particle identity, or the one-second row index."""
762
+ notes: list[str] = field(default_factory=list)
763
+ """Things about the alignment a reader must see before the value table."""
764
+
765
+ @property
766
+ def failures(self) -> list[VariableVerdict]:
767
+ """Variables that disagreed *in a class that asserts* (see
768
+ :attr:`VariableVerdict.failed`). Empty is one of the two conditions
769
+ :meth:`accepted` requires."""
770
+ return [v for v in self.variables if v.failed]
771
+
772
+ @property
773
+ def unclassified(self) -> list[VariableVerdict]:
774
+ """Variables present in the files but absent from the class table.
775
+
776
+ Reported separately rather than folded into :attr:`failures` because
777
+ the two need different actions: a failure is a disagreement to explain,
778
+ an unclassified variable is a decision nobody has made yet. Both block
779
+ acceptance -- a variable nobody has judged is not evidence of agreement.
780
+ """
781
+ return [v for v in self.variables if v.tclass == "?"]
782
+
783
+ def accepted(self, min_join=0.999) -> bool:
784
+ """The comparison stage's acceptance gate: >=99.9% join and no asserting class in failure.
785
+
786
+ Unclassified variables block acceptance too. A variable nobody has
787
+ decided about is not evidence of agreement, and letting it pass silently
788
+ is how the gate stops meaning anything.
789
+ """
790
+ return (self.join.join_fraction >= min_join
791
+ and not self.failures
792
+ and not self.unclassified
793
+ and self.join.duplicate_keys == 0)
794
+
795
+
796
+ def compare_proc_files(path_a, path_b, classes=None) -> ComparisonReport:
797
+ """Join and compare two imgProc per-particle files. Requires ``netCDF4``."""
798
+ import netCDF4
799
+
800
+ with netCDF4.Dataset(str(path_a)) as a, netCDF4.Dataset(str(path_b)) as b:
801
+ join = join_particles(a, b)
802
+ variables = compare_variables(a, b, join, classes)
803
+ return ComparisonReport(join, variables, str(path_a), str(path_b))
804
+
805
+
806
+ def join_seconds(ds_a, ds_b) -> tuple[JoinResult, list[str]]:
807
+ """Align two size-distribution files on their ``Time`` index.
808
+
809
+ A sd file has no particle identity left in it -- ``sizeDist`` reduces every
810
+ particle to a per-second row -- and, crucially, **the HHMMSS stamp in
811
+ ``time`` does not identify a row.** Measured on an archived 2D-S flight's TAS
812
+ sidecar: 4,110 rows carry 3,854 distinct stamps, because 256 rows are exact
813
+ duplicates of their predecessor down to the millisecond (``64923.4`` twice,
814
+ and so on). ``sizeDist`` processes such a second twice and advances to the
815
+ *next* particle block on the repeat, so the duplication is real in the
816
+ output too.
817
+
818
+ So the join is **positional**: row *i* of one file is row *i* of the other,
819
+ because both were produced from the same TAS vector and ``Time`` is that
820
+ vector's index. That is not a weaker join than a keyed one here -- it is the
821
+ only correct one -- and it is checked rather than assumed: ``time`` is itself
822
+ a compared variable in class A, so a positional misalignment shows up as a
823
+ ``time`` mismatch before anything else is believed.
824
+
825
+ Returns the join and any notes worth printing above the table.
826
+ """
827
+ n_a = len(ds_a.dimensions["Time"])
828
+ n_b = len(ds_b.dimensions["Time"])
829
+ n = min(n_a, n_b)
830
+ idx = np.arange(n)
831
+
832
+ notes = []
833
+ stamps = np.asarray(ds_a.variables["time"][:]).astype(np.int64).ravel()
834
+ repeats = int(stamps.size - np.unique(stamps).size)
835
+ if repeats:
836
+ notes.append(
837
+ f"{repeats} of {stamps.size} one-second stamps are repeats, so `time` "
838
+ "does not identify a row; the join is positional on the Time index "
839
+ "and `time` is verified as an ordinary class-A variable"
840
+ )
841
+ if n_a != n_b:
842
+ notes.append(
843
+ f"Time axes differ in length ({n_a} vs {n_b}); compared over the "
844
+ f"first {n} rows only"
845
+ )
846
+
847
+ return JoinResult(idx, idx,
848
+ np.arange(n, n_a), np.arange(n, n_b),
849
+ n_a, n_b, duplicate_keys=0), notes
850
+
851
+
852
+ def compare_sd_files(path_a, path_b, classes=None) -> ComparisonReport:
853
+ """Join and compare two ``sizeDist`` size-distribution files."""
854
+ import netCDF4
855
+
856
+ classes = SD_CLASSES if classes is None else classes
857
+ with netCDF4.Dataset(str(path_a)) as a, netCDF4.Dataset(str(path_b)) as b:
858
+ join, notes = join_seconds(a, b)
859
+ variables = compare_variables(a, b, join, classes)
860
+ return ComparisonReport(join, variables, str(path_a), str(path_b),
861
+ join_key=SD_JOIN_KEY, notes=notes)
862
+
863
+
864
+ def file_kind(path) -> str:
865
+ """``"proc"`` or ``"sd"``, from the dimensions rather than the filename.
866
+
867
+ A filename is not evidence -- the standing rule from the decode stage, and the reason this
868
+ reads the structure instead. A proc file dimensions its particle axis
869
+ ``time`` (lower case, one row per particle); a sd file dimensions its
870
+ one-second axis ``Time`` alongside ``CIPcorrlen``.
871
+ """
872
+ import netCDF4
873
+
874
+ with netCDF4.Dataset(str(path)) as ds:
875
+ if "CIPcorrlen" in ds.dimensions and "Time" in ds.dimensions:
876
+ return "sd"
877
+ if "time" in ds.dimensions:
878
+ return "proc"
879
+ raise ValueError(
880
+ f"{path}: neither a proc file (dimension 'time') nor a sizeDist file "
881
+ f"(dimensions 'Time' and 'CIPcorrlen'); has {sorted(ds.dimensions)}"
882
+ )
883
+
884
+
885
+ def compare_files(path_a, path_b, classes=None) -> ComparisonReport:
886
+ """Compare two UIOOPS files, choosing the join from what they are."""
887
+ kind_a, kind_b = file_kind(path_a), file_kind(path_b)
888
+ if kind_a != kind_b:
889
+ raise ValueError(
890
+ f"cannot compare a {kind_a} file against a {kind_b} file: "
891
+ f"{path_a} vs {path_b}"
892
+ )
893
+ if kind_a == "sd":
894
+ return compare_sd_files(path_a, path_b, classes)
895
+ return compare_proc_files(path_a, path_b, classes)
896
+
897
+
898
+ def format_report(report: ComparisonReport, verbose: bool = False,
899
+ accepted: bool | None = None) -> str:
900
+ """Render a report.
901
+
902
+ ``accepted`` overrides the verdict line. The CLI passes the decision it
903
+ computed over the WHOLE file, so that filtering the table with ``--var``
904
+ cannot turn a failing comparison into a green one.
905
+ """
906
+ j = report.join
907
+ lines = [
908
+ f"left : {report.left}",
909
+ f"right: {report.right}",
910
+ "",
911
+ "JOIN " + " | ".join(report.join_key),
912
+ f" matched {j.n_matched} of {j.n_left} left / {j.n_right} right "
913
+ f"({j.join_fraction * 100:.4f}%)",
914
+ ]
915
+ lines += [f" note: {n}" for n in report.notes]
916
+ if j.duplicate_keys:
917
+ lines.append(
918
+ f" !! {j.duplicate_keys} duplicate keys — the join key does not "
919
+ "identify a particle here, so every value comparison below is suspect"
920
+ )
921
+ noun = "seconds" if report.join_key == SD_JOIN_KEY else "particles"
922
+ for side, only in (("left", j.left_only), ("right", j.right_only)):
923
+ if only.size:
924
+ runs = j.unmatched_runs(side)
925
+ biggest = max(runs, key=lambda r: r[1])
926
+ lines.append(
927
+ f" {side}-only: {only.size} {noun} in {len(runs)} run(s); "
928
+ f"largest run {biggest[1]} from index {biggest[0]}"
929
+ )
930
+
931
+ lines += ["", f"{'VARIABLE':34s} {'CLS':4s} {'VERDICT':8s} {'N DIFF':>9s} DETAIL"]
932
+ for v in sorted(report.variables, key=lambda x: (x.verdict == "EXACT", x.name)):
933
+ if v.verdict == "EXACT" and not verbose:
934
+ continue
935
+ n = f"{v.n_diff}/{v.n_total}" if v.n_total else "-"
936
+ lines.append(f"{v.name:34s} {v.tclass:4s} {v.verdict:8s} {n:>9s} {v.detail}")
937
+
938
+ exact = sum(1 for v in report.variables if v.verdict == "EXACT")
939
+ lines += [
940
+ "",
941
+ f"{exact}/{len(report.variables)} variables bit-exact over the joined "
942
+ f"{'seconds' if report.join_key == SD_JOIN_KEY else 'particles'}.",
943
+ f"ACCEPTED: {report.accepted() if accepted is None else accepted}",
944
+ ]
945
+ if report.unclassified:
946
+ lines.append(
947
+ " blocked by unclassified variables: "
948
+ + ", ".join(v.name for v in report.unclassified)
949
+ )
950
+ return "\n".join(lines)