arrayprobe 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. arrayprobe/__init__.py +219 -0
  2. arrayprobe/__main__.py +19 -0
  3. arrayprobe/_v314_lazy.py +48 -0
  4. arrayprobe/ai_ready.py +212 -0
  5. arrayprobe/attributed_export.py +1333 -0
  6. arrayprobe/authordefaults.py +267 -0
  7. arrayprobe/cli.py +3510 -0
  8. arrayprobe/combine.py +12 -0
  9. arrayprobe/compare.py +950 -0
  10. arrayprobe/config.py +1239 -0
  11. arrayprobe/constants.py +12 -0
  12. arrayprobe/count_closure.py +204 -0
  13. arrayprobe/diagnostic_views.py +769 -0
  14. arrayprobe/diode_report.py +265 -0
  15. arrayprobe/driver/__init__.py +5 -0
  16. arrayprobe/driver/_load_record.py +331 -0
  17. arrayprobe/driver/preflight_inputs.py +250 -0
  18. arrayprobe/driver/reprocess.py +553 -0
  19. arrayprobe/driver/run_flight.py +8166 -0
  20. arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
  21. arrayprobe/dropsize.py +519 -0
  22. arrayprobe/friendly.py +206 -0
  23. arrayprobe/geometry/__init__.py +77 -0
  24. arrayprobe/geometry/min_rectangle.py +92 -0
  25. arrayprobe/intarr.py +12 -0
  26. arrayprobe/intarr_analysis.py +16 -0
  27. arrayprobe/intarr_plots.py +12 -0
  28. arrayprobe/inventory.py +129 -0
  29. arrayprobe/jit_kernels.py +344 -0
  30. arrayprobe/lwc.py +44 -0
  31. arrayprobe/masks.py +349 -0
  32. arrayprobe/matio.py +410 -0
  33. arrayprobe/matlab_compat.py +13 -0
  34. arrayprobe/ncio.py +26 -0
  35. arrayprobe/particle.py +55 -0
  36. arrayprobe/particle_perimeter.py +12 -0
  37. arrayprobe/products.py +78 -0
  38. arrayprobe/profiles.py +179 -0
  39. arrayprobe/provenance.py +21 -0
  40. arrayprobe/py.typed +11 -0
  41. arrayprobe/readers/__init__.py +9 -0
  42. arrayprobe/readers/dmt.py +603 -0
  43. arrayprobe/readers/mask_csv.py +12 -0
  44. arrayprobe/readers/pms.py +12 -0
  45. arrayprobe/readers/sea.py +433 -0
  46. arrayprobe/readers/tasinfo.py +12 -0
  47. arrayprobe/regimes.py +507 -0
  48. arrayprobe/render.py +728 -0
  49. arrayprobe/reproduce_report.py +149 -0
  50. arrayprobe/review_agreement.py +135 -0
  51. arrayprobe/review_sampling.py +327 -0
  52. arrayprobe/run_page.py +624 -0
  53. arrayprobe/sample_area.py +12 -0
  54. arrayprobe/selector.py +206 -0
  55. arrayprobe/sizing.py +151 -0
  56. arrayprobe/time_convert.py +12 -0
  57. arrayprobe/timing_closure.py +141 -0
  58. arrayprobe/tools/__init__.py +27 -0
  59. arrayprobe/tools/make_demo_flight.py +1089 -0
  60. arrayprobe/tools/make_tas_file.py +760 -0
  61. arrayprobe/tools/probe_comparison.py +569 -0
  62. arrayprobe/tools/synthetic_truth.py +698 -0
  63. arrayprobe/tools/tas_sources.py +705 -0
  64. arrayprobe/triage_context.py +488 -0
  65. arrayprobe/triage_server.py +5215 -0
  66. arrayprobe/tune/__init__.py +15 -0
  67. arrayprobe/tune/diodes.py +400 -0
  68. arrayprobe/tune/distributions.py +300 -0
  69. arrayprobe/tune/sample.py +243 -0
  70. arrayprobe/tune/score.py +230 -0
  71. arrayprobe/tune/settings.py +354 -0
  72. arrayprobe/validate_by_condition.py +208 -0
  73. arrayprobe/validation_report.py +166 -0
  74. arrayprobe-0.1.0.dist-info/METADATA +260 -0
  75. arrayprobe-0.1.0.dist-info/RECORD +189 -0
  76. arrayprobe-0.1.0.dist-info/WHEEL +5 -0
  77. arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
  78. arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
  79. arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
  80. arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
  81. arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
  82. arrayprobe_soda2/__init__.py +131 -0
  83. arrayprobe_soda2/angles.py +143 -0
  84. arrayprobe_soda2/aspect_ratio.py +541 -0
  85. arrayprobe_soda2/backfill.py +100 -0
  86. arrayprobe_soda2/binary_dof.py +181 -0
  87. arrayprobe_soda2/buildindex.py +113 -0
  88. arrayprobe_soda2/decompress_dmt.py +285 -0
  89. arrayprobe_soda2/enhancement_hooks.py +275 -0
  90. arrayprobe_soda2/export_ascii.py +732 -0
  91. arrayprobe_soda2/export_ncdf.py +683 -0
  92. arrayprobe_soda2/export_ncdf_raf.py +396 -0
  93. arrayprobe_soda2/fillholes.py +161 -0
  94. arrayprobe_soda2/find_radius.py +105 -0
  95. arrayprobe_soda2/findsize.py +407 -0
  96. arrayprobe_soda2/fit_poisson.py +170 -0
  97. arrayprobe_soda2/fix2dimage.py +63 -0
  98. arrayprobe_soda2/fixraking.py +162 -0
  99. arrayprobe_soda2/fixstuckbits.py +146 -0
  100. arrayprobe_soda2/hvps4_read_frame.py +121 -0
  101. arrayprobe_soda2/jit_kernels.py +152 -0
  102. arrayprobe_soda2/label_blobs.py +177 -0
  103. arrayprobe_soda2/min_circle_fast.py +320 -0
  104. arrayprobe_soda2/particlesort.py +703 -0
  105. arrayprobe_soda2/pbp_writer.py +558 -0
  106. arrayprobe_soda2/poisson_spot_correct.py +183 -0
  107. arrayprobe_soda2/princomp.py +107 -0
  108. arrayprobe_soda2/probespecs.py +361 -0
  109. arrayprobe_soda2/process_2d.py +1364 -0
  110. arrayprobe_soda2/process_2d_parallel.py +626 -0
  111. arrayprobe_soda2/process_hk.py +512 -0
  112. arrayprobe_soda2/processbuffer_2dc.py +155 -0
  113. arrayprobe_soda2/processbuffer_cip.py +213 -0
  114. arrayprobe_soda2/processbuffer_f2dc.py +139 -0
  115. arrayprobe_soda2/processbuffer_spec.py +441 -0
  116. arrayprobe_soda2/processbuffer_tail.py +350 -0
  117. arrayprobe_soda2/pth_readers.py +245 -0
  118. arrayprobe_soda2/py.typed +11 -0
  119. arrayprobe_soda2/read2dbuffer.py +371 -0
  120. arrayprobe_soda2/reject.py +246 -0
  121. arrayprobe_soda2/reprocess_pbp.py +156 -0
  122. arrayprobe_soda2/sample_area.py +264 -0
  123. arrayprobe_soda2/save_writer.py +480 -0
  124. arrayprobe_soda2/sea.py +324 -0
  125. arrayprobe_soda2/spec_absolutepointers.py +109 -0
  126. arrayprobe_soda2/spec_decompress.py +203 -0
  127. arrayprobe_soda2/spec_index.py +476 -0
  128. arrayprobe_soda2/spec_read_frame.py +286 -0
  129. arrayprobe_soda2/spec_read_hk.py +301 -0
  130. arrayprobe_soda2/spec_readint.py +127 -0
  131. arrayprobe_soda2/timeconv.py +77 -0
  132. arrayprobe_soda2/update_op.py +101 -0
  133. arrayprobe_uiops/__init__.py +45 -0
  134. arrayprobe_uiops/combine.py +192 -0
  135. arrayprobe_uiops/combine_fork.py +359 -0
  136. arrayprobe_uiops/constants.py +830 -0
  137. arrayprobe_uiops/decode_naming.py +113 -0
  138. arrayprobe_uiops/diode_mask.py +250 -0
  139. arrayprobe_uiops/engine_absence.py +41 -0
  140. arrayprobe_uiops/export_oap.py +325 -0
  141. arrayprobe_uiops/geometry_core.py +366 -0
  142. arrayprobe_uiops/habit.py +749 -0
  143. arrayprobe_uiops/habit_core.py +248 -0
  144. arrayprobe_uiops/hollow_size_rule.py +376 -0
  145. arrayprobe_uiops/imgproc.py +2081 -0
  146. arrayprobe_uiops/imgproc_core.py +275 -0
  147. arrayprobe_uiops/intarr.py +167 -0
  148. arrayprobe_uiops/intarr_analysis.py +569 -0
  149. arrayprobe_uiops/intarr_plots.py +119 -0
  150. arrayprobe_uiops/jit_kernels.py +430 -0
  151. arrayprobe_uiops/lwc.py +70 -0
  152. arrayprobe_uiops/matlab_compat.py +860 -0
  153. arrayprobe_uiops/measure.py +346 -0
  154. arrayprobe_uiops/min_circle.py +204 -0
  155. arrayprobe_uiops/min_ellipse.py +161 -0
  156. arrayprobe_uiops/min_rectangle.py +200 -0
  157. arrayprobe_uiops/ncar_2dc_timing.py +100 -0
  158. arrayprobe_uiops/ncio.py +810 -0
  159. arrayprobe_uiops/oap_read.py +228 -0
  160. arrayprobe_uiops/particle.py +51 -0
  161. arrayprobe_uiops/particle_perimeter.py +94 -0
  162. arrayprobe_uiops/particle_physics.py +199 -0
  163. arrayprobe_uiops/pecan_params.py +134 -0
  164. arrayprobe_uiops/probe_cases.py +298 -0
  165. arrayprobe_uiops/product_sanity.py +337 -0
  166. arrayprobe_uiops/profile.py +71 -0
  167. arrayprobe_uiops/profiles.py +756 -0
  168. arrayprobe_uiops/provenance.py +804 -0
  169. arrayprobe_uiops/py.typed +11 -0
  170. arrayprobe_uiops/qc.py +169 -0
  171. arrayprobe_uiops/readers/__init__.py +8 -0
  172. arrayprobe_uiops/readers/mask_csv.py +74 -0
  173. arrayprobe_uiops/readers/pms.py +239 -0
  174. arrayprobe_uiops/readers/tasinfo.py +57 -0
  175. arrayprobe_uiops/rect_ellipse.py +129 -0
  176. arrayprobe_uiops/register_image_assisted.py +25 -0
  177. arrayprobe_uiops/reject.py +501 -0
  178. arrayprobe_uiops/reject_core.py +220 -0
  179. arrayprobe_uiops/sample_area.py +93 -0
  180. arrayprobe_uiops/sizedist.py +1923 -0
  181. arrayprobe_uiops/sizedist_core.py +814 -0
  182. arrayprobe_uiops/sizedist_tables.py +642 -0
  183. arrayprobe_uiops/spec.py +1094 -0
  184. arrayprobe_uiops/spec_core.py +703 -0
  185. arrayprobe_uiops/stray_pixel.py +103 -0
  186. arrayprobe_uiops/tas.py +191 -0
  187. arrayprobe_uiops/time_convert.py +41 -0
  188. uiops/__init__.py +402 -0
  189. uiops/py.typed +11 -0
@@ -0,0 +1,2081 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """v3.5 ``imgProc_sm.m`` -- the driver and writer around the measurement block.
3
+
4
+ ``imgProc_sm.m`` v3.5 (``UIOPS-v3.5/joefinlon-UIOPS-039be82/imgProc_sm.m``,
5
+ 1417 lines) is 23 hunks away from v3.1.4's. The per-particle measurement
6
+ block ``:1204-1291`` is already ported and Octave-validated as
7
+ :func:`arrayprobe_uiops.measure.measure_record`. This module is everything
8
+ around it: the signature, the probe table, the output-file definition, the
9
+ record loop, the particle loop (image extraction, particle time), the writer.
10
+ It calls ``measure_record`` and re-translates nothing that it does.
11
+
12
+ **Scope, extended by V-PT (2026-09-16).** The first port covered probetype 2 alone and
13
+ raised :class:`~arrayprobe.imgproc.UnportedProbeType` for the rest. All four
14
+ probetypes now run -- 0 (2DC/2DP), 1 (CIP/PIP), 2 (2DS/HVPS/3VCPI) and 3
15
+ (Fast2DC) -- each asserted against its own Octave golden built by
16
+ ``octave_oracle/run_v35_probetype013_bank.py`` (thirteen cases,
17
+ ``tests/data/v35_probetype013_oracle.json``, ``tests/test_v35_imgproc_probetypes.py``)
18
+ and, for 2DC, against the independent A15 pair as well
19
+ (``tests/test_v35_2dc_octave_oracle.py``). The refusal is **narrowed, not
20
+ deleted**: it now fires on an unported *timing branch*
21
+ (:data:`PORTED_TIMINGS_V35`) and names what a new probetype would need.
22
+
23
+ What V-PT had to translate afresh is small, because the two releases' probe
24
+ framing and the probetype-0/3 timing blocks are byte-identical (v3.1.4
25
+ ``:574-686`` == v3.5 ``:855-967``; ``read_binary_PMS.m`` / ``read_binary_DMT.m``
26
+ / ``read_binary_SEA.m`` byte-identical too -- all measured). New in v3.5 and
27
+ therefore newly written here: the **GCPEx CIP clock-offset table**
28
+ (``:976-1074``, :data:`_GCPEX_CIP_TABLE`) with its whole-vector carry fixup
29
+ (``:1081-1093``, :func:`_normalise_part_time`); the probetype-1
30
+ ``int_arrival`` carry-over across record boundaries (``:1110-1115``); and the
31
+ corrupt-boundary scan's narrowing to ``(PECAN or GCPEx) AND probetype==1``
32
+ (``:685``, ``:736`` -- v3.1.4 gated on the project name alone).
33
+
34
+ **The probetype-2 stage, as first ported:** both ``iRectEllipse``
35
+ values (``iRectEllipse=1``, ``:1293-1301``/``:1361-1374``, ported as
36
+ :func:`arrayprobe_uiops.rect_ellipse.rect_ellipse_for_image` -- doctrine layer 2,
37
+ real compiled ``CGAL_RectSize``/``CGAL_EllipseSize`` MEX oracles, both
38
+ ``hasExtendedOutputs`` schemas), both ``iQC`` values (``iQC=1``, the
39
+ ``:801-846`` denoise pass, ported as
40
+ :func:`arrayprobe_uiops.qc.qc_image`), both ``iNewHabit`` values, both
41
+ ``iCalcAllDiodeStats`` values, and the optional ``tasRatio`` series
42
+ (``varargin{3}``).
43
+
44
+ **Reuse from the earlier translation**, allowed because the corresponding MATLAB is
45
+ unchanged between the two releases and guarded by
46
+ ``tests/test_v35_imgproc.py::TestReuseIsNotAccidental``:
47
+ :func:`arrayprobe_uiops.imgproc_core._read_record_header`,
48
+ :func:`arrayprobe.imgproc._time_in_seconds_from_tas` (the probetype-2 time
49
+ block ``:1117-1185`` is byte-identical to v3.1.4's -- the first-particle
50
+ ``int_arrival`` carry-over ``:1102-1115`` is CIP/PIP only),
51
+ :data:`arrayprobe.imgproc.TAS_FALLBACK`, :data:`arrayprobe.imgproc.ROLLBACK_SECONDS`,
52
+ :class:`arrayprobe.imgproc.UnportedProbeType`,
53
+ :class:`arrayprobe.imgproc.VariableSpec`, :func:`arrayprobe.matlab_compat.dec2bin_concat`
54
+ and :mod:`arrayprobe_uiops.ncio`. Not reused: :class:`arrayprobe.imgproc.ImageWidthMismatch` --
55
+ the earlier translation raises it in place of MATLAB's silent ``return``; this port keeps the MATLAB
56
+ behaviour instead (see the ``:850-853`` entry below), so the exception is never thrown here.
57
+
58
+ **Oracle: layer 2 only.** No archived product was ever written by v3.5, so the
59
+ only ground truth is the vendored program itself run under Octave
60
+ (``octave_oracle/run_v35_imgproc_bank.py``, Part B of the stage plan).
61
+
62
+ Preserved as written (each with a regression test named after its line):
63
+
64
+ * ``:858`` -- ``particle_num = mod(kk, 66536)``, the 65536 typo, unchanged
65
+ from v3.1.4;
66
+ * ``:1376-1377`` -- ``varid29`` (``edge_at_max_hole``) receives
67
+ ``max_hole_diameter`` and ``varid30`` (``max_hole_diameter``) receives
68
+ ``edge_at_max_hole``: the two variables are swapped on the way to disk;
69
+ * ``:356`` / ``:1329`` -- ``Particle_number_all`` is *defined* under
70
+ ``probetype~=0 || probetype~=3`` (always true) and *written* under ``&&``;
71
+ * ``:1394`` -- ``bin_stats`` is rewritten whole every record, no start/count;
72
+ * ``:709`` -- ``tasRatio(i)`` is indexed by the absolute record number, so a
73
+ chunked run must pass the whole-file series (the absolute-record tasRatio index);
74
+ * ``:850-853`` -- an image not ``diodenum`` wide makes MATLAB ``return`` from
75
+ the whole function, silently, with the file holding whatever was written so
76
+ far. Reproduced here as a close-and-return that also appends to
77
+ :data:`WIDTH_MISMATCH_RETURNS`, so the loss is measurable after the fact.
78
+ """
79
+
80
+ from __future__ import annotations
81
+
82
+ import contextlib
83
+ import math
84
+ from collections.abc import Sequence
85
+ from dataclasses import dataclass
86
+ from datetime import datetime
87
+ from typing import Any
88
+
89
+ import numpy as np
90
+
91
+ from arrayprobe_uiops.imgproc_core import (
92
+ ROLLBACK_SECONDS,
93
+ TAS_FALLBACK,
94
+ UnportedProbeType,
95
+ VariableSpec,
96
+ _particle_time_fast2dc,
97
+ _particle_time_pms,
98
+ _pecan_pip_hour_offset,
99
+ _read_record_header,
100
+ _time_in_seconds_from_tas,
101
+ )
102
+ from arrayprobe_uiops.matlab_compat import (
103
+ MGrowVector,
104
+ bin2dec,
105
+ dec2bin_concat,
106
+ madd,
107
+ mint8,
108
+ mmul,
109
+ )
110
+ from arrayprobe_uiops.reject_core import RejectConfig
111
+
112
+ from . import diode_mask, ncio, provenance
113
+ from . import ncar_2dc_timing as _ncar_2dc
114
+ from . import stray_pixel as _stray_pixel
115
+ from .habit import _matlab_round
116
+ from .measure import (
117
+ HolroydNewResult,
118
+ ParticleMeasurement,
119
+ RecordGeometry,
120
+ measure_record,
121
+ )
122
+
123
+ # Re-exported deliberately, as sizedist re-exports probe_cases: the driver
124
+ # reaches `arrayprobe_uiops` only through the `uiops` selector, which is keyed by the v3.1.4
125
+ # port's module names, and `stray_pixel` has none. Naming the two stamp strings here makes them
126
+ # reachable as `_v35().module("imgproc").STRAY_PIXEL_STAMP_ON` for the `.call` stamp.
127
+ from .ncar_2dc_timing import STAMP_OFF as NCAR_2DC_TIMING_STAMP_OFF
128
+ from .ncar_2dc_timing import STAMP_ON as NCAR_2DC_TIMING_STAMP_ON
129
+ from .qc import qc_image
130
+ from .rect_ellipse import RectEllipse, rect_ellipse_for_image
131
+ from .stray_pixel import STAMP_OFF as STRAY_PIXEL_STAMP_OFF
132
+ from .stray_pixel import STAMP_ON as STRAY_PIXEL_STAMP_ON
133
+
134
+ __all__ = [
135
+ "PROBES_V35",
136
+ "NCAR_2DC_TIMING_STAMP_ON",
137
+ "NCAR_2DC_TIMING_STAMP_OFF",
138
+ "STRAY_PIXEL_STAMP_ON",
139
+ "STRAY_PIXEL_STAMP_OFF",
140
+ "PARTICLE_NUM_MODULUS_V35",
141
+ "WRITER_GAPS",
142
+ "WRITER_CHUNKING",
143
+ "POSITION_CHUNK_PARTICLES",
144
+ "WIDTH_MISMATCH_RETURNS",
145
+ "CORRUPT_RECORDS",
146
+ "SHARED_WITH_V314",
147
+ "PORTED_TIMINGS_V35",
148
+ "CHUNKABLE_TIMINGS_V35",
149
+ "PRIMABLE_TIMINGS_V35",
150
+ "ChunkingNotEquivalent",
151
+ "ProbeV35",
152
+ "imgproc_variables_v35",
153
+ "imgproc_sm_v35",
154
+ "merge_chunks_v35",
155
+ "prefix_scan_v35",
156
+ "chunk_primes_v35",
157
+ "particle_num_v35",
158
+ "gcpex_cip_offsets",
159
+ ]
160
+
161
+ #: Names imported unchanged from the v3.1.4 port -- the guard test asserts
162
+ #: identity for each, so a silent copy cannot drift.
163
+ SHARED_WITH_V314 = (
164
+ "ROLLBACK_SECONDS",
165
+ "TAS_FALLBACK",
166
+ "UnportedProbeType",
167
+ "VariableSpec",
168
+ # V-PT. The probetype-0/3 particle-time blocks (v3.5 :861-934) are
169
+ # byte-identical to v3.1.4's :580-652 -- measured, not assumed: the diff
170
+ # between the two releases touches no line of v3.1.4's 574-686 span.
171
+ "_particle_time_pms",
172
+ "_particle_time_fast2dc",
173
+ # v3.5 :946-973 == v3.1.4 :665-693, the PECAN/PIP hour offset.
174
+ "_pecan_pip_hour_offset",
175
+ )
176
+
177
+ # Re-exported so the reuse guard can see them by name on this module.
178
+ _REUSED = (ROLLBACK_SECONDS, TAS_FALLBACK)
179
+
180
+ #: ``imgProc_sm.m:858`` (v3.5) -- ``mod(kk,66536)``. The same typo as v3.1.4's
181
+ #: ``:577``; the literal is kept here, in the v3.5 module, so the module
182
+ #: describes its own source line and the test can mutate it in one place.
183
+ PARTICLE_NUM_MODULUS_V35 = 66536
184
+
185
+ #: Encoding details of v3.5's writer this port does not reproduce, in the same
186
+ #: shape as :data:`arrayprobe_uiops.spec.WRITER_GAPS`.
187
+ #:
188
+ #: ``deflate``
189
+ #: Every ``defVar`` is followed by ``netcdf.defVarDeflate(f, varid, true,
190
+ #: true, 9)`` (shuffle + zlib level 9). :func:`arrayprobe_uiops.ncio.def_var`
191
+ #: exposes no deflate parameter, so the port's file is uncompressed. This
192
+ #: is invisible to every reader: the arrays read back are identical either
193
+ #: way, which ``tests/test_v35_imgproc.py::TestWriterGaps`` measures rather
194
+ #: than asserts.
195
+ #:
196
+ #: ``chunking``
197
+ #: v3.5's ``imgProc_sm.m`` sets no chunking, so netCDF-C's default stores
198
+ #: ``position`` as ``[1, 2]`` on disk, one HDF5 chunk per particle. By the
199
+ #: author's decision (2026-09-30) the port stores it in
200
+ #: :data:`WRITER_CHUNKING`'s ``[1024, 2]`` blocks instead, because that
201
+ #: per-chunk cost dominated the measured write and read of the variable
202
+ #: (measured). Every
203
+ #: value read back is identical, which
204
+ #: ``tests/test_v35_position_chunking.py`` measures.
205
+ WRITER_GAPS = ("deflate", "chunking")
206
+
207
+ #: Particles per ``position`` chunk: 1,024 x 2 ``short`` = 4,096 bytes, the
208
+ #: chunk size in bytes netCDF-C gives ``Date`` and ``Time_in_seconds`` by default.
209
+ POSITION_CHUNK_PARTICLES = 1024
210
+
211
+ #: Chunk sizes the writer sets, in MATLAB order like each variable's dims
212
+ #: (``position`` is ``(pos_count, time)``, so ``[1024, 2]`` on disk). A variable
213
+ #: not named keeps the library default. :data:`WRITER_GAPS` ``chunking``.
214
+ WRITER_CHUNKING: dict[str, tuple[int, ...]] = {"position": (2, POSITION_CHUNK_PARTICLES)}
215
+
216
+ #: ``(record, slice)`` of every ``:850-853`` return taken -- see the module
217
+ #: docstring. Cleared at the start of every :func:`imgproc_sm_v35` call.
218
+ WIDTH_MISMATCH_RETURNS: list[tuple[int, int]] = []
219
+
220
+ #: ``(record, n_corrupt, n_good)`` per record the ``:736-747`` scan rejected.
221
+ #: MATLAB only ``fprintf``\\ s this and drops the record's particles silently
222
+ #: from the product, so the loss is recorded here to stay measurable after the
223
+ #: fact. Cleared at the start of every :func:`imgproc_sm_v35` call.
224
+ CORRUPT_RECORDS: list[tuple[int, int, int]] = []
225
+
226
+ #: ``{record: n_sync_words_converted}`` for a ``ncar_2dc_timing_fix=True`` probetype-0 run
227
+ #: (module ``ncar_2dc_timing``; 0 where the gate or ``fix2dimage.pro`` left a record unchanged).
228
+ #: Not UIOOPS state. Cleared at the start of every :func:`imgproc_sm_v35` call.
229
+ NCAR_2DC_SYNCS_CONVERTED: dict[int, int] = {}
230
+
231
+
232
+ class ProbeV35:
233
+ """One ``case`` of the probe ``switch`` (``:134-235``), plus the framing
234
+ constants the record loop selects on ``probetype``.
235
+
236
+ The framing fields are **not** in the ``switch``: they are the literals
237
+ ``:720-726`` (the read shape), ``:755-760`` (``start_first``), ``:754``
238
+ (``boundary_needs_time``), ``:764-772`` (``image_slice_offset``, which is
239
+ also the offset in the zero-image guard) and ``:785-795`` (``image_invert``
240
+ / ``image_word_bits``) select per probetype. Each was read from v3.5's own
241
+ file at those lines and, for probetypes 0/1/3, **measured** byte-identical
242
+ to v3.1.4's -- the diff between the two releases touches none of
243
+ ``imgProc_sm.m`` 574-686 (v3.1.4) / 855-967 (v3.5), and the framing lines
244
+ outside that span differ only in the corrupt-boundary gate (V-PT, below).
245
+ They carry the same values as :data:`arrayprobe.constants.IMGPROC_CONFIG`,
246
+ which ``tests/test_v35_imgproc_probetypes.py`` asserts field by field
247
+ rather than trusting this comment.
248
+ """
249
+
250
+ __slots__ = ("boundary", "boundarytime", "ds", "diodenum", "probetype",
251
+ "read_width", "read_slices", "start_first", "boundary_needs_time",
252
+ "image_slice_offset", "image_invert", "image_word_bits", "timing")
253
+
254
+ def __init__(self, boundary: Any, boundarytime: Any, ds: Any, diodenum: Any, probetype: Any, *,
255
+ read_width: Any = 8, read_slices: Any = 1700, start_first: Any = 1,
256
+ boundary_needs_time: Any = True, image_slice_offset: Any = 0,
257
+ image_invert: Any = False, image_word_bits: Any = 16,
258
+ timing: Any = "spec") -> None:
259
+ self.boundary = tuple(boundary)
260
+ self.boundarytime = boundarytime
261
+ self.ds = ds
262
+ self.diodenum = diodenum
263
+ self.probetype = probetype
264
+ self.read_width = read_width
265
+ self.read_slices = read_slices
266
+ self.start_first = start_first
267
+ self.boundary_needs_time = boundary_needs_time
268
+ self.image_slice_offset = image_slice_offset
269
+ self.image_invert = image_invert
270
+ self.image_word_bits = image_word_bits
271
+ self.timing = timing
272
+
273
+
274
+ _SPEC_BOUNDARY = (43690,) * 8
275
+ _DMT_BOUNDARY = (170,) * 8
276
+
277
+ _PMS_FRAMING = dict(read_width=4, read_slices=1024, start_first=2, # :721
278
+ boundary_needs_time=True, image_slice_offset=1, # :754, :765
279
+ image_invert=False, image_word_bits=8, timing="pms") # :785-787
280
+ _DMT_FRAMING = dict(read_width=8, read_slices=1700, start_first=2, # :726
281
+ boundary_needs_time=False, image_slice_offset=0, # :754
282
+ image_invert=False, image_word_bits=8, timing="dmt") # :788-791
283
+ _F2DC_FRAMING = dict(_DMT_FRAMING, read_slices=512, timing="fast2dc") # :723
284
+ _SPEC_FRAMING = dict(read_width=8, read_slices=1700, start_first=1, # :725, :759
285
+ boundary_needs_time=True, image_slice_offset=0,
286
+ image_invert=True, image_word_bits=16, timing="spec") # :792-795
287
+
288
+ #: ``:134-235``, every case, verbatim. ``2DC``'s v3.5 change (``ds`` 0.025 ->
289
+ #: 0.03, ``:141``) is recorded here where a reader of the v3.1.4 table would
290
+ #: look for it.
291
+ PROBES_V35: dict[str, ProbeV35] = {
292
+ "2DC": ProbeV35((255, 255, 255, 255), 85, 0.03, 32, 0, **_PMS_FRAMING),
293
+ "2DP": ProbeV35((255, 255, 255, 255), 85, 0.200, 32, 0, **_PMS_FRAMING),
294
+ "CIP": ProbeV35(_DMT_BOUNDARY, float("nan"), 0.025, 64, 1, **_DMT_FRAMING),
295
+ "PIP": ProbeV35(_DMT_BOUNDARY, float("nan"), 0.100, 64, 1, **_DMT_FRAMING),
296
+ "HVPS": ProbeV35(_SPEC_BOUNDARY, 0, 0.150, 128, 2, **_SPEC_FRAMING),
297
+ "2DS": ProbeV35(_SPEC_BOUNDARY, 0, 0.010, 128, 2, **_SPEC_FRAMING),
298
+ "3VCPI_H": ProbeV35(_SPEC_BOUNDARY, 0, 0.050, 128, 2, **_SPEC_FRAMING),
299
+ "3VCPI_V": ProbeV35(_SPEC_BOUNDARY, 0, 0.010, 128, 2, **_SPEC_FRAMING),
300
+ "Fast2DC": ProbeV35((170, 170, 170), float("nan"), 0.025, 64, 3, **_F2DC_FRAMING),
301
+ }
302
+
303
+ #: ``:725`` -- the probetype-2 read is a literal ``[8,1700,1]``.
304
+ _READ_WIDTH_PT2 = 8
305
+ _READ_SLICES_PT2 = 1700
306
+
307
+ #: Which timing branches this port has transcribed for v3.5. Every entry here
308
+ #: is asserted against its own Octave golden; :class:`UnportedProbeType` still
309
+ #: fires for anything outside it, naming what is missing.
310
+ PORTED_TIMINGS_V35 = ("spec", "pms", "dmt", "fast2dc")
311
+
312
+
313
+ def particle_num_v35(kk: int) -> int:
314
+ """``:858`` -- ``mod(kk,66536)``. Preserved.
315
+
316
+ Source: ``imgProc_sm.m:858`` (UIOOPS v3.5)."""
317
+ return kk % PARTICLE_NUM_MODULUS_V35
318
+
319
+
320
+ # --------------------------------------------------------------------------
321
+ # The output variable table (:318-660), in the file's own definition order
322
+ # --------------------------------------------------------------------------
323
+
324
+ def _v(name: Any, xtype: Any, units: Any, description: Any, dims: Any = ("time",)) -> Any:
325
+ return VariableSpec(name=name, xtype=xtype, dims=tuple(dims),
326
+ units=units, description=description)
327
+
328
+
329
+ _HOLROYD_HABIT_DESCRIPTION = {
330
+ # :587-590
331
+ 1: ('ASCII habit code following the Holroyd (1987) algorithm '
332
+ '("M" or 77: zero image; "C" or 67: center-out image; "t" or 116: tiny; '
333
+ '"o" or 111: bad/split; "l" or 108: linear; "a" or 97: aggregate; '
334
+ '"g" or 103: graupel; "s" or 115: sphere; '
335
+ '"h" or 104: hexagonal; "i" or 105: irregular; "d" or 100: dendrite)'),
336
+ # :592-595
337
+ 0: ('ASCII habit code following the Holroyd (1987) algorithm '
338
+ '("M" or 77: zero image; "C" or 67: center-out image; "t" or 116: tiny; '
339
+ '"o" or 111: oriented; "l" or 108: linear; "a" or 97: aggregate; '
340
+ '"g" or 103: graupel; "s" or 115: sphere; '
341
+ '"h" or 104: hexagonal; "i" or 105: irregular; "d" or 100: dendrite)'),
342
+ }
343
+
344
+
345
+ def imgproc_variables_v35(*, iRectEllipse: int, iCalcAllDiodeStats: int, iQC: int, # noqa: N803
346
+ iNewHabit: int, extended_ellipse_outputs: bool | None, # noqa: N803
347
+ probetype: int) -> tuple[VariableSpec, ...]:
348
+ """The ``netcdf.defVar`` sequence of ``:318-660`` for one configuration.
349
+
350
+ Source: the ``netcdf.defVar`` block of ``imgProc_sm.m`` (UIOOPS v3.5), from ``:317``; bare line
351
+ references here are into that file.
352
+
353
+ ``extended_ellipse_outputs`` stands in for the ``persistent
354
+ hasExtendedOutputs`` probe (``:255-272``): a recorded flag, not a runtime
355
+ probe of whichever ``CGAL_EllipseSize`` binary is on the path (upstream finding:
356
+ the binary-dependent output schema).
357
+ ``probetype`` is accepted for symmetry with the MATLAB but has no effect on
358
+ the table -- ``Particle_number_all``'s gate ``:356`` is
359
+ ``probetype~=0 || probetype~=3``, which is true for every probetype.
360
+ """
361
+ del probetype # :356's `||` makes the gate unconditional; see the docstring
362
+ out: list[VariableSpec] = [
363
+ _v("Date", "int", "YYYYMMDD", "Date of image record in which the particle resides"),
364
+ _v("Time", "int", "HHMMSS", "Time (UTC) of image record in which the particle resides"),
365
+ _v("msec", "short", "ms", "Sub-second time of image record in which the particle resides"),
366
+ _v("Time_in_seconds", "double", "sec", "Time since probe was activated"),
367
+ _v("SliceCount", "short", "--", "Number of slices containing particle"),
368
+ _v("DMT_DOF_SPEC_OVERLOAD", "double", "ms (Fast2DC/2DC/2DP only)",
369
+ "Unitless flag denoting out-of-focus (DMT) or overloaded (SPEC) particles. "
370
+ "Dead time for corresponding image record for PMS probes."),
371
+ _v("Particle_number_all", "int", "--", "Index of particle in 2-D buffer"),
372
+ _v("position", "short", "--",
373
+ "Slice within image record where particle is first sampled", ("pos_count", "time")),
374
+ _v("particle_time", "int", "HHMMSS", "Particle time (not available for 2DS/HVPS/3VCPI)"),
375
+ # :369 -- the unclosed parenthesis is the file's.
376
+ _v("particle_millisec", "short", "ms",
377
+ "Sub-second particle time (not available for 2DS/HVPS/3VCPI"),
378
+ _v("particle_microsec", "double", "microsec",
379
+ "Sub-second particle time (unitless clock count for 2DS/HVPS/3VCPI)"),
380
+ _v("parent_rec_num", "int", "--", "Index of image record in which the particle resides"),
381
+ _v("particle_num", "short", "--", "Particle index within current image record"),
382
+ ]
383
+ if iQC == 1: # :401-411
384
+ out += [
385
+ _v("subparticle_num", "short", "--", "Number of subparticles in image"),
386
+ _v("subparticle_mindist", "short", "--",
387
+ "Minimum distance between subparticles in image"),
388
+ ]
389
+ out += [
390
+ _v("image_length", "short", "--",
391
+ "Particle length in time direction using # photodiodes"),
392
+ _v("image_width", "short", "--",
393
+ "Particle length in photodiode direction using # photodiodes"),
394
+ _v("image_area", "double", "mm^2", "Projected area using the # shadowed photodiodes"),
395
+ _v("image_longest_y", "short", "--",
396
+ "Longest vertically-oriented chord through particle in time direction"),
397
+ _v("image_max_top_edge_touching", "short", "--",
398
+ "Maximum # of times the bottom diode is shadowed in succession"),
399
+ _v("image_max_bottom_edge_touching", "short", "--",
400
+ "Maximum # of times the top diode is shadowed in succession"),
401
+ _v("image_touching_edge", "byte", "--",
402
+ "0 denotes image entirely in array; 1 denotes image touching edge"),
403
+ _v("image_auto_reject", "short", "--",
404
+ 'ASCII reject code ("0" or 48: accepted; "a" or 97: aspect ratio > 6; '
405
+ '"t" or 116: aspect ratio > 5 + image touching edge; '
406
+ '"p" or 112: < 25% shadowed diodes in rectangle encompassing particle; '
407
+ '"h" or 104 or 72 or 117: hollow particle; "s" or 115: split image; '
408
+ '"z" or 122: zero area image; "f" or 102: zero area image)'),
409
+ _v("image_hollow", "byte", "--", "0 denotes not hollow; 1 denotes a hollow image"),
410
+ _v("image_center_in", "byte", "--",
411
+ "0 denotes center of particle outside array; 1 denotes center is inside"),
412
+ _v("image_axis_ratio", "double", "--",
413
+ "Ratio between maximum vertical length and maximum horizontal length"),
414
+ # :455-479 -- the five chord/circle-fit diameters are commented out in v3.5.
415
+ _v("image_diam_minR", "double", "mm", "Dmax of smallest circle enclosing the particle"),
416
+ _v("image_diam_AreaR", "double", "mm", "Area equivalent diameter"),
417
+ _v("image_xpos", "double", "--",
418
+ "Particle center x (time) position of minimum enclosing circle"),
419
+ _v("image_ypos", "double", "--",
420
+ "Particle center y (diode) position of minimum enclosing circle"),
421
+ _v("image_perimeter", "double", "mm", "Perimeter following the particle boundary"),
422
+ ]
423
+ if iRectEllipse == 1: # :506-557
424
+ out += [
425
+ _v("image_RectangleL", "double", "mm",
426
+ "Length of smallest rectangle enclosing the particle"),
427
+ _v("image_RectangleW", "double", "mm",
428
+ "Width of smallest rectangle enclosing the particle"),
429
+ _v("image_RectangleAngle", "double", "radians",
430
+ "Angle of rectangle with respect to the time direction"),
431
+ _v("image_EllipseL", "double", "mm",
432
+ "Length of smallest ellipse enclosing the particle"),
433
+ _v("image_EllipseW", "double", "mm",
434
+ "Width of smallest ellipse enclosing the particle"),
435
+ # :543 -- 'rectangle', in the ellipse variable's own description.
436
+ _v("image_EllipseAngle", "double", "radians",
437
+ "Angle of rectangle with respect to the time direction"),
438
+ ]
439
+ if extended_ellipse_outputs: # :547-557
440
+ out += [
441
+ _v("image_EllipseX", "double", "--",
442
+ "Center position of ellipse with respect to the time direction"),
443
+ _v("image_EllipseY", "double", "--",
444
+ "Center position of ellipse with respect to the photodiode direction"),
445
+ ]
446
+ out += [
447
+ _v("percent_shadow_area", "double", "percent",
448
+ "Ratio between the projected area and L*W"),
449
+ _v("edge_at_max_hole", "short", "--",
450
+ "# diodes between edges of the particle for the slice "
451
+ "containing the largest gap inside the particle"),
452
+ _v("max_hole_diameter", "short", "--",
453
+ "Diameter of the largest hole inside the particle"),
454
+ _v("part_z", "double", "--",
455
+ "Particle depth in object plane calculated via lookup table"),
456
+ _v("size_factor", "double", "--",
457
+ "Dmax reduction factor folowing Korolev (2007) correction"),
458
+ _v("holroyd_habit", "short", "--", _HOLROYD_HABIT_DESCRIPTION[1 if iNewHabit == 1 else 0]),
459
+ _v("fine_detail_ratio", "double", "--", "Perim*Diam/Area following Holroyd (1987)"),
460
+ _v("sphericity", "double", "--", "sqrt(area)/perim following McFarquhar et al. (2005)"),
461
+ ]
462
+ if iNewHabit == 1: # :610-645
463
+ out += [
464
+ _v("width_length_percentile", "double", "mm",
465
+ "Minimum difference between the 25th and 75th percentiles of particle "
466
+ "length and width"),
467
+ _v("circle_area_ratio", "double", "--",
468
+ "Ratio between particle area and that of the approximated smallest circle "
469
+ "enclosing the particle"),
470
+ _v("edge_maximum_dimension_ratio", "double", "--",
471
+ "Ratio between number of diodes illuminated along the frame edge with the "
472
+ "most illuminated diodes and the particle maximum dimension"),
473
+ _v("maximum_gap", "double", "mm",
474
+ "Maximum gap between any two separate illuminated areas along the x or y axes"),
475
+ _v("opacity_coefficient", "double", "--",
476
+ "Fraction (0-1) approximating the transparency of a particle"),
477
+ _v("aspect_ratio", "double", "--",
478
+ "Ratio between length of longest axis and length of shortest axis of particle"),
479
+ _v("holroyd_perimeter", "double", "mm",
480
+ "Particle perimeter following Holroyd (1987) including perimeter added by "
481
+ "holes within particle"),
482
+ ]
483
+ out += [
484
+ _v("area_hole_ratio", "double", "--",
485
+ "Ratio between the projected area and the area of hole inside particle"),
486
+ _v("inter_arrival", "double", "sec",
487
+ "Inter-arrival time between particles "
488
+ "(use diff(time_in_seconds) for all but 2DC/2DP)"),
489
+ _v("bin_stats", "int", "--",
490
+ "# times specified photodiode is shadowed for particles in this file", ("bin_count",)),
491
+ ]
492
+ if iCalcAllDiodeStats: # :652-657
493
+ out.append(_v("image_bin_stats", "int", "--",
494
+ "# times specified photodiode is shadowed for each particle",
495
+ ("bin_count", "time")))
496
+ return tuple(out)
497
+
498
+
499
+ # --------------------------------------------------------------------------
500
+ # The driver
501
+ # --------------------------------------------------------------------------
502
+
503
+
504
+ @contextlib.contextmanager
505
+ def _patched_measure_perimeter(kernels: Any) -> Any:
506
+ """Route :func:`arrayprobe_uiops.measure.measure_record`'s per-particle
507
+ ``particle_perimeter`` call through the numba kernel, for the duration of
508
+ one ``imgproc_sm_v35(jit=True)`` call.
509
+
510
+ ``measure.py`` is out of this change's file scope, so
511
+ this is the only way to reach the call without editing its source:
512
+ ``measure.py`` does ``from arrayprobe.particle_perimeter import
513
+ particle_perimeter``, which binds the name in **measure's own** module
514
+ namespace at import time -- patching ``arrayprobe.particle_perimeter``
515
+ itself afterward would not reach that already-bound name. So the target
516
+ is ``arrayprobe_uiops.measure.particle_perimeter``, restored unconditionally
517
+ on the way out (including on an exception), and reentrant only in the
518
+ sense that a ``None`` ``kernels`` is a no-op -- ``imgproc_sm_v35`` does
519
+ not call itself recursively, so nested patching is not a real case.
520
+
521
+ Fails loudly rather than silently skipping the speedup if the target is
522
+ ever gone: a JIT flag that quietly does nothing is exactly the original
523
+ bug (``--jit`` on v3.5 accepted and ignored), and this module exists to
524
+ not repeat it.
525
+ """
526
+ if kernels is None:
527
+ yield
528
+ return
529
+ from arrayprobe_uiops import measure as _measure_mod
530
+
531
+ if not hasattr(_measure_mod, "particle_perimeter"):
532
+ raise AttributeError(
533
+ "arrayprobe_uiops.measure no longer imports particle_perimeter by that "
534
+ "name -- imgproc_sm_v35(jit=True)'s monkeypatch target is gone, so the "
535
+ "speedup would silently stop applying. Update _patched_measure_perimeter "
536
+ "in imgproc.py to match."
537
+ )
538
+ original = _measure_mod.particle_perimeter
539
+ _measure_mod.particle_perimeter = kernels.particle_perimeter
540
+ try:
541
+ yield
542
+ finally:
543
+ _measure_mod.particle_perimeter = original
544
+
545
+
546
+ def imgproc_sm_v35(
547
+ infile: Any,
548
+ outfile: Any,
549
+ probename: str,
550
+ n: int,
551
+ nEvery: int, # noqa: N803 -- MATLAB's name
552
+ projectname: str,
553
+ *,
554
+ iRectEllipse: int = 0, # noqa: N803
555
+ iCalcAllDiodeStats: int = 0, # noqa: N803
556
+ iQC: int = 0, # noqa: N803
557
+ iNewHabit: int, # noqa: N803
558
+ reject_config: RejectConfig,
559
+ tas_time: Any,
560
+ tas: Any,
561
+ tas_ratio: Any = None,
562
+ software: str,
563
+ creation_time: str | None = None,
564
+ extended_ellipse_outputs: bool | None = None,
565
+ progress: Any = None,
566
+ jit: bool = False,
567
+ prime: tuple[float, float] | None = None,
568
+ stamp_profile: str | None = None,
569
+ tas_qc: dict[str, Any] | None = None,
570
+ shadow_diode: Sequence[int] | np.ndarray | diode_mask.ShadowDiodeMask | None = None,
571
+ stray_pixel_fix: bool = False,
572
+ ncar_2dc_timing_fix: bool = False,
573
+ ) -> int:
574
+ """``imgProc_sm(infile, outfile, probename, n, nEvery, projectname, iRectEllipse,
575
+ iCalcAllDiodeStats, iQC, iNewHabit, tasTime, tas[, tasRatio])`` (v3.5).
576
+
577
+ Required, no default -- each is a fidelity decision no default may make:
578
+ ``iNewHabit``; ``tas_time`` / ``tas`` (``varargin{1..2}``, arrays, the
579
+ aircraft series ``:186-188``); ``software`` (replaces ``:283-285``'s bare
580
+ relative ``fopen('version.txt')`` -- the vendored file reads
581
+ ``UIOOPS_v3.5``, upstream's own spelling); and ``reject_config``.
582
+
583
+ ``reject_config`` is required rather than fixed to ``STOCK_V35_REJECT_CONFIG``.
584
+ ``calculate_reject_unified.m`` assigns its thresholds
585
+ unconditionally at the top of the function, and the archived production tree
586
+ ships a **modified copy of that file**, so the configuration is a fidelity
587
+ decision in exactly the sense ``profiles.py``'s header means. A fixed value
588
+ would also put one of the v3.5 port's three whole-program Octave goldens --
589
+ ``oraclesprod_v35.nc``, run against the production reject tree -- out of reach entirely.
590
+
591
+ ``tas_ratio`` is ``varargin{3}``: indexed by the **absolute** record ``i``
592
+ (``:709``), so a chunked run must pass the whole-file series (upstream finding: the
593
+ absolute-record tasRatio index). ``None`` is the ``iTAS == 0`` path,
594
+ ``handles.tasRatio = 1.0`` (``:711``).
595
+
596
+ ``extended_ellipse_outputs`` must be given (``True``/``False``) iff
597
+ ``iRectEllipse == 1``, and must be ``None`` otherwise.
598
+
599
+ ``jit``
600
+ Speed only, **default off** (space: the port). ``True`` routes
601
+ the two v3.5 call sites whose MATLAB is unchanged from v3.1.4 --
602
+ ``dec2bin_concat`` (this module's own framing/timing unpacks) and
603
+ ``particle_perimeter`` (inside :func:`arrayprobe_uiops.measure.
604
+ measure_record`) -- through :mod:`arrayprobe_uiops.jit_kernels`, which
605
+ reuses the earlier translation's already-proven compiled kernels rather than
606
+ re-translating them. Exact by construction, so the file written is
607
+ the same bytes (``tests/test_v35_imgproc_jit_identity.py`` runs both
608
+ and compares). v3.5's OWN hot kernel, ``cgal_min_r_v35``, is not
609
+ included -- see :mod:`arrayprobe_uiops.jit_kernels`'s module docstring
610
+ for the measured numbers and why. Needs numba, imported only here.
611
+
612
+ ``prime``
613
+ The ``(part_time_prev, time_in_seconds_prev)`` pair a serial run holds
614
+ at the top of this chunk's first record, from :func:`prefix_scan_v35`.
615
+ **Default ``None``, which is a whole-file run and changes nothing.**
616
+ ``"spec"`` timing only: it is the state that crosses a
617
+ probetype-2 chunk seam, and handing it over is what makes a chunked
618
+ pass reproduce the serial one *bit for bit* rather than approximately
619
+ -- a left-fold resumed from its own exact partial value is the same
620
+ fold, where a post-hoc offset re-rounds every element. The other three
621
+ timings either carry nothing across a seam or have their one crossing
622
+ quantity repaired exactly by :func:`merge_chunks_v35`, so passing
623
+ ``prime`` there is refused rather than silently ignored.
624
+
625
+ ``shadow_diode``
626
+ Stuck diodes to re-illuminate: 1-based diode numbers, or a
627
+ :class:`arrayprobe_uiops.diode_mask.ShadowDiodeMask` (from
628
+ ``arrayprobe tune diodes``). **Default ``None``, and an empty list,
629
+ change nothing** (``tests/test_v35_shadow_diode.py``). Stock v3.5 has
630
+ no masking; this is the production fork's ``c(:,shadow_diode)='1'``
631
+ (nine-argument ``imgProc_sm``, extraction ``:286-292``), applied by
632
+ :func:`arrayprobe_uiops.diode_mask.reilluminate` right after the image
633
+ is decoded into characters and before the ``iQC`` clean-up
634
+ (``:801-846``), so ``qc_image`` sees the re-illuminated image. A diode
635
+ number past the probe's width widens the image, as MATLAB does, and
636
+ the ``:850-853`` width check then ends the run.
637
+
638
+ Returns the number of particles written.
639
+ """
640
+ try:
641
+ probe = PROBES_V35[probename]
642
+ except KeyError:
643
+ raise ValueError(f"unknown probename {probename!r}; v3.5 knows "
644
+ f"{sorted(PROBES_V35)}") from None
645
+ if probe.timing not in PORTED_TIMINGS_V35:
646
+ raise UnportedProbeType( # pragma: no cover -- every shipped probe is ported
647
+ f"{probename!r} is probetype {probe.probetype} ({probe.timing!r} timing): "
648
+ f"this port transcribes {sorted(PORTED_TIMINGS_V35)} only. A new probetype "
649
+ "needs its own particle-time branch (imgProc_sm.m:861-1116) and its own "
650
+ "Octave golden before it can run here."
651
+ )
652
+ # :167-234 -- tasTime/tas are ``varargin{1,2}`` and are read ONLY in the
653
+ # probetype-2 ``case`` arms. Requiring them for a 2DC run would invent an
654
+ # input the MATLAB never reads; accepting them silently would hide that.
655
+ if probe.probetype == 2:
656
+ if tas_time is None or tas is None:
657
+ raise ValueError(
658
+ f"{probename!r} is probetype 2: imgProc_sm.m:167-170/:180-185 read "
659
+ "tasTime=varargin{1} and tas=varargin{2}, so both are required."
660
+ )
661
+ elif tas_time is not None or tas is not None:
662
+ raise ValueError(
663
+ f"{probename!r} is probetype {probe.probetype}: imgProc_sm.m's probe switch "
664
+ "assigns tasTime/tas only in the probetype-2 cases (:167-170, :180-185, "
665
+ ":196-199, :211-214), so this run would read neither. Pass tas_time=None, "
666
+ "tas=None."
667
+ )
668
+ # ``tas_ratio`` (``varargin{3}``) is deliberately NOT gated on probetype:
669
+ # ``:229-234``'s ``length(varargin)==3`` is probe-independent and ``:709``
670
+ # sets ``handles.tasRatio`` for every probetype, even though the header
671
+ # documents it as 2DS/HVPS-only and ``:1347`` is its one consumer.
672
+ if prime is not None:
673
+ if probe.timing != "spec":
674
+ raise ValueError(
675
+ f"prime= is {probe.timing!r} timing's to refuse: only probetype 2 "
676
+ "accumulates across a chunk seam (imgProc_sm.m:1131-1180). "
677
+ f"{probename!r} is probetype {probe.probetype}; 'pms'/'fast2dc' carry "
678
+ "nothing across, and 'dmt' carries inter_arrival alone, which "
679
+ "merge_chunks_v35 repairs exactly. Pass prime=None."
680
+ )
681
+ if len(prime) != 2 or any(p is None for p in prime):
682
+ raise ValueError(
683
+ "prime= must be the two floats (part_time_prev, time_in_seconds_prev); "
684
+ "a chunk with no preceding particle -- the first chunk of a file -- "
685
+ "takes prime=None, which is what prefix_scan_v35 returns for it."
686
+ )
687
+ if n == 1:
688
+ raise ValueError(
689
+ "prime= with n=1: the first chunk has no preceding particle, so a "
690
+ "serial run holds part_time_prev unset there (imgProc_sm.m:1136). "
691
+ "Priming it would start the accumulation from a state the reference "
692
+ "run never had. Pass prime=None for n=1."
693
+ )
694
+ if iQC == 1:
695
+ raise ValueError(
696
+ "prime= with iQC=1 is refused: qc_image (:801-846) can change an "
697
+ "image's width, so the :850-853 width-mismatch return can fire "
698
+ "mid-file, and prefix_scan_v35 cannot know where a serial run would "
699
+ "have stopped without doing the QC pass it exists to skip. Run "
700
+ "iQC=1 serially."
701
+ )
702
+ if iRectEllipse == 1 and extended_ellipse_outputs is None:
703
+ raise ValueError(
704
+ "iRectEllipse=1 needs extended_ellipse_outputs=True/False: imgProc_sm.m:255-272 "
705
+ "decides the output schema by probing whichever CGAL_EllipseSize is on the "
706
+ "path (persistent hasExtendedOutputs) and records the outcome nowhere; here "
707
+ "it is a recorded flag."
708
+ )
709
+ if iRectEllipse != 1 and extended_ellipse_outputs is not None:
710
+ raise ValueError(
711
+ "extended_ellipse_outputs is meaningful only with iRectEllipse=1 (:255, "
712
+ ":547); passing it otherwise would describe a schema the file cannot have."
713
+ )
714
+ if tas is not None:
715
+ tas = np.asarray(tas, dtype=float).ravel()
716
+ tas_time = np.asarray(tas_time, dtype=float).ravel()
717
+ ratios = None if tas_ratio is None else np.asarray(tas_ratio, dtype=float).ravel()
718
+
719
+ kernels = None
720
+ if jit:
721
+ # Imported here, never at module level: numba costs seconds to import
722
+ # and the default (jit=False) path must not pay for it.
723
+ from . import jit_kernels as _v35_jit_kernels
724
+ kernels = _v35_jit_kernels.load()
725
+
726
+ diodenum = probe.diodenum
727
+ boundary = np.asarray(probe.boundary)
728
+ boundarytime = probe.boundarytime
729
+
730
+ WIDTH_MISMATCH_RETURNS.clear()
731
+ CORRUPT_RECORDS.clear()
732
+ NCAR_2DC_SYNCS_CONVERTED.clear()
733
+
734
+ src = ncio.open(infile, "nowrite")
735
+ try:
736
+ # :275-277 -- `size_mat = dimlen` is read and never used; the read stays.
737
+ ncio.inq_dim(src, 2)
738
+ _, img_count = ncio.inq_dim(src, 0)
739
+ diode_stats = np.zeros(diodenum, dtype=np.float64)
740
+
741
+ out = _create_output(outfile, diodenum, projectname, infile, probename,
742
+ iRectEllipse, iCalcAllDiodeStats, iQC, iNewHabit,
743
+ extended_ellipse_outputs, software, creation_time,
744
+ stamp_profile, tas_qc, stray_pixel_fix,
745
+ ncar_2dc_timing_fix=ncar_2dc_timing_fix)
746
+ try:
747
+ with _patched_measure_perimeter(kernels):
748
+ return _process_records(
749
+ src, out, probe, n, nEvery, int(img_count), boundary, boundarytime,
750
+ diode_stats, tas, tas_time,
751
+ RunOptions(
752
+ ratios=ratios, projectname=projectname, probename=probename,
753
+ iCalcAllDiodeStats=iCalcAllDiodeStats, iQC=iQC,
754
+ iNewHabit=iNewHabit, iRectEllipse=iRectEllipse,
755
+ extended_ellipse_outputs=extended_ellipse_outputs,
756
+ reject_config=reject_config, kernels=kernels,
757
+ shadow_diode=shadow_diode, stray_pixel_fix=stray_pixel_fix,
758
+ ncar_2dc_timing_fix=ncar_2dc_timing_fix,
759
+ ),
760
+ progress, prime,
761
+ )
762
+ finally:
763
+ ncio.close(out)
764
+ finally:
765
+ ncio.close(src)
766
+
767
+
768
+ def _create_output(outfile: Any, diodenum: Any, projectname: Any, infile: Any,
769
+ probename: Any, iRectEllipse: Any, # noqa: N803
770
+ iCalcAllDiodeStats: Any, iQC: Any, iNewHabit: Any, # noqa: N803
771
+ extended_ellipse_outputs: Any,
772
+ software: Any, creation_time: Any, stamp_profile: Any,
773
+ tas_qc: dict[str, Any] | None = None,
774
+ stray_pixel_fix: bool = False,
775
+ ncar_2dc_timing_fix: bool = False) -> Any:
776
+ """``:289-660``, plus the in-file provenance attributes (not MATLAB output): the engine
777
+ and profile always, and ``tas_qc``'s keys as ``arrayprobe_<key>`` when a caller passes the
778
+ stage's airspeed record. No variable depends on either."""
779
+ f = ncio.create(outfile, "clobber", format="NETCDF4") # :289
780
+ ncio.def_dim(f, "time", ncio.get_constant("NC_UNLIMITED")) # :290
781
+ ncio.def_dim(f, "pos_count", 2) # :291
782
+ ncio.def_dim(f, "bin_count", diodenum) # :292
783
+
784
+ nc_global = ncio.get_constant("NC_GLOBAL")
785
+ ncio.put_att(f, nc_global, "Software", software) # :295
786
+ # :296 -- 'Institution' is commented out in v3.5.
787
+ ncio.put_att(f, nc_global, "Creation Time",
788
+ creation_time if creation_time is not None
789
+ else datetime.now().strftime("%Y/%m/%d %H:%M:%S")) # :297
790
+ ncio.put_att(f, nc_global, "Description",
791
+ "Contains size, morphological, and other particle properties "
792
+ "from an uncompressed image file.") # :298
793
+ ncio.put_att(f, nc_global, "Project", projectname) # :300
794
+ ncio.put_att(f, nc_global, "Image Source", str(infile)) # :301
795
+ ncio.put_att(f, nc_global, "Probe Type", probename) # :302
796
+ if iRectEllipse and iCalcAllDiodeStats: # :303-314
797
+ active = "Rectangle & elliptical fits & per-particle diode statistics"
798
+ elif iRectEllipse:
799
+ active = "Rectangle & elliptical fits"
800
+ elif iCalcAllDiodeStats:
801
+ active = "Per-particle diode statistics"
802
+ else:
803
+ active = "None"
804
+ ncio.put_att(f, nc_global, "Optional parameters active", active)
805
+ # In-file provenance: arrayprobe_engine / arrayprobe_profile, not MATLAB output. The
806
+ # Octave-golden comparisons exclude both, as they exclude 'Creation Time'.
807
+ for name, value in provenance.engine_attrs(engine="3.5", profile=stamp_profile).items():
808
+ ncio.put_att(f, nc_global, name, value)
809
+ # Sorted, as the .tasqc.json sidecar is, so a re-run from the sidecar writes the same order.
810
+ for key, value in sorted((tas_qc or {}).items()):
811
+ ncio.put_att(f, nc_global, f"{provenance.ATTR_PREFIX}{key}", value)
812
+ if stray_pixel_fix:
813
+ # Only when on, so a correction-off file is byte-identical to one written before it.
814
+ ncio.put_att(f, nc_global, "arrayprobe_stray_pixel", _stray_pixel.STAMP_ON)
815
+ if ncar_2dc_timing_fix:
816
+ # Only when on, as above: a correction-off file is byte-identical to upstream's.
817
+ ncio.put_att(f, nc_global, "arrayprobe_ncar_2dc_timing", _ncar_2dc.STAMP_ON)
818
+
819
+ dimid = {"time": 0, "pos_count": 1, "bin_count": 2}
820
+ for spec in imgproc_variables_v35(
821
+ iRectEllipse=iRectEllipse, iCalcAllDiodeStats=iCalcAllDiodeStats, iQC=iQC,
822
+ iNewHabit=iNewHabit, extended_ellipse_outputs=extended_ellipse_outputs, probetype=2,
823
+ ):
824
+ # chunksizes: not MATLAB's (it sets none) -- WRITER_GAPS["chunking"].
825
+ varid = ncio.def_var(f, spec.name, spec.xtype, [dimid[d] for d in spec.dims],
826
+ chunksizes=WRITER_CHUNKING.get(spec.name))
827
+ ncio.put_att(f, varid, "Units", spec.units)
828
+ ncio.put_att(f, varid, "Description", spec.description)
829
+ # defVarDeflate(f, varid, true, true, 9) -- WRITER_GAPS["deflate"]
830
+ if stray_pixel_fix:
831
+ # Not MATLAB output; defined after every MATLAB variable, so their ids are unchanged.
832
+ for name, xtype, units, desc in STRAY_PIXEL_VARIABLES:
833
+ varid = ncio.def_var(f, name, xtype, [dimid["time"]])
834
+ ncio.put_att(f, varid, "Units", units)
835
+ ncio.put_att(f, varid, "Description", desc)
836
+ ncio.end_def(f) # :660
837
+ return f
838
+
839
+
840
+ class ChunkingNotEquivalent(ValueError):
841
+ """Raised when a chunked v3.5 S3 pass could not reproduce the serial run.
842
+
843
+ Not a capability gap to be worked around with a looser comparison: the
844
+ named quantity is genuinely a running accumulation over the whole file,
845
+ so the chunked result would be *different output*, not *the same output
846
+ computed differently*.
847
+ """
848
+
849
+
850
+ #: Which v3.5 timing branches a chunked S3 pass reproduces **bit for bit**.
851
+ #:
852
+ #: The discriminator is whether a particle's own written values depend on state
853
+ #: that survives ``:1402``'s ``clear`` and therefore crosses a chunk seam.
854
+ #: Measured per branch, not assumed (``tests/test_v35_imgproc_merge_chunks.py``):
855
+ #:
856
+ #: ``"dmt"`` (probetype 1, CIP/PIP)
857
+ #: ``time_in_seconds`` is built from the record's own header bits alone
858
+ #: (``:1100``), so it is record-local. Only ``inter_arrival`` reaches
859
+ #: across, as the single subtraction ``t - time_in_seconds_prev``
860
+ #: (``:1110-1114``, new in v3.5), and :func:`merge_chunks_v35` repairs
861
+ #: exactly that -- see its ``inter_arrival`` note.
862
+ #: ``"pms"`` (probetype 0, 2DC/2DP) and ``"fast2dc"`` (probetype 3)
863
+ #: ``_particle_time_pms`` / ``_particle_time_fast2dc`` are called without
864
+ #: ``time_in_seconds_prev`` and never read it; every written quantity is
865
+ #: record-local, so concatenation alone is exact.
866
+ #:
867
+ #: ``"spec"`` (probetype 2, 2DS/HVPS/3VCPI) is **deliberately absent**.
868
+ #: ``:1131-1180`` accumulates: ``Time_in_seconds = time_in_seconds_prev +
869
+ #: (part_time - part_time_prev) * scale``, a running sum from the first
870
+ #: particle of the file (:func:`arrayprobe.imgproc._time_in_seconds_from_tas`).
871
+ #: A chunk that starts with ``part_time_prev is None`` restarts that sum at
872
+ #: ``part_time * scale`` (``:763-765``), so every particle after the first seam
873
+ #: carries a different absolute time -- **measured**: 53 of 99 particles on the
874
+ #: 25-record 2DS fixture, split three ways. The offset cannot be repaired
875
+ #: bit-exactly afterwards, because re-adding it re-rounds every element
876
+ #: (floating-point addition is not associative), and it cannot be primed
877
+ #: without having already processed every earlier record. Refused rather than
878
+ #: approximated.
879
+ CHUNKABLE_TIMINGS_V35 = ("dmt", "pms", "fast2dc")
880
+
881
+ #: Which timings are chunkable **only when each chunk is primed**.
882
+ #:
883
+ #: ``"spec"``'s accumulation is real -- the paragraph above is accurate about
884
+ #: what crosses the seam and about why a post-hoc offset cannot repair it. What
885
+ #: it got wrong was one word: it said the seam state "cannot be primed without
886
+ #: having already **processed** every earlier record". Every earlier record
887
+ #: must be **scanned**, which is a different and much cheaper thing: the two
888
+ #: scalars are functions of the record header and the particle's own header
889
+ #: words (``:1123``) alone, and :func:`prefix_scan_v35` reaches them without
890
+ #: unpacking a single image or calling ``measure_record``.
891
+ #:
892
+ #: Measured on the tracked 25-record 2DS fixture
893
+ #: (``tests/test_v35_sizedist_chunk_priming.py``): primed chunks concatenate to
894
+ #: the serial run with **all 40 variables** equal by ``np.array_equal``,
895
+ #: ``Time_in_seconds`` equal as *bytes*, and a one-ULP perturbation of the
896
+ #: primed accumulator detected -- so the comparison discriminates. The unprimed
897
+ #: control disagrees in ``Time_in_seconds`` alone (53 of 99 particles, at most
898
+ #: 2 ULP; re-measured 2026-09-27 by ``paper/figures/fig14_chunk_priming.py``) and
899
+ #: on no measured variable. This comment said ``{Time_in_seconds, int_arrival}``
900
+ #: until then: ``inter_arrival`` is record-local for ``"spec"`` timing and never
901
+ #: differs, and the test asserts only a subset of that pair.
902
+ PRIMABLE_TIMINGS_V35 = ("spec",)
903
+
904
+
905
+ def prefix_scan_v35(infile: Any, probename: str, stop_record: int, *, # noqa: N803
906
+ tas_time: Any, tas: Any, iQC: int = 0, # noqa: N803
907
+ progress: Any = None) -> tuple[float, float] | None:
908
+ """The ``prime=`` pair a serial run holds at the top of ``stop_record``.
909
+
910
+ Replays ``imgProc_sm.m:693-1180``'s **scan** over records
911
+ ``1 .. stop_record-1`` and returns ``(part_time_prev, time_in_seconds_prev)``
912
+ -- or ``None`` when no particle precedes that record, which is a chunk that
913
+ needs no priming (the first chunk of a file always). The return value is
914
+ what :func:`imgproc_sm_v35`'s ``prime=`` takes, unchanged.
915
+
916
+ **What it deliberately does not do.** No ``dec2bin_concat``, no
917
+ ``measure_record``, no reject pass, no habit -- that is where a run's time
918
+ goes, and none of it is read by ``:1131-1180``. The accumulation sees only
919
+ the record header (``:1132``, the TAS lookup key), the boundary walk that
920
+ locates each particle (``:751-779``), and ``part_time`` from the particle's
921
+ own header words (``:1123``). ``tests/test_v35_sizedist_chunk_priming.py``
922
+ spies ``measure_record`` during a full-file scan and asserts it is called
923
+ **zero** times: a scan that measured would prime correctly and save nothing.
924
+
925
+ **The width check, carried arithmetically.** ``:850-853`` exits the whole
926
+ function when an unpacked image is not ``diodenum`` wide. For ``iQC == 0``
927
+ that width is ``read_width * image_word_bits``, a constant of the file, so
928
+ the check cannot fire mid-file without firing on the very first particle --
929
+ and it is decided here without unpacking anything. ``iQC == 1`` is refused
930
+ outright: ``qc_image`` can change a width mid-file, so a scan cannot know
931
+ where a serial run would have stopped without doing the work it exists to
932
+ skip.
933
+
934
+ **``tas_time``/``tas`` are required and must be the run's own series.** The
935
+ fold is ``time_in_seconds_prev + (part_time - part_time_prev) * scale``
936
+ under both arms of ``:1131-1170``, but ``scale`` is built from the TAS
937
+ lookup, so a scan run against a different series -- or against the empty
938
+ arrays that select ``TAS_FALLBACK`` (170) -- lands on a *different* pair and
939
+ primes the chunk wrongly. No default: this is the same fidelity decision
940
+ :func:`imgproc_sm_v35` refuses to make for probetype 2, and a silently
941
+ wrong prime is worse than a refusal because the output still looks like a
942
+ serial run.
943
+
944
+ ``progress`` is called as ``progress(i, stop_record - 1)`` per record. Pass
945
+ one for a long scan: a chunk worker that is silent for its whole prefix is
946
+ indistinguishable from a hung one to ``--worker-stall-min``.
947
+ """
948
+ probe = _primable_probe(probename, iQC)
949
+ if tas is None or tas_time is None:
950
+ raise ValueError(
951
+ "prefix_scan_v35 needs the run's own tas_time/tas: the accumulation's "
952
+ "scale comes from the TAS lookup (:1131-1170), so scanning with empty "
953
+ "arrays takes the TAS_FALLBACK arm and primes the chunk with a number "
954
+ "no serial run ever held. Pass the same series the run will use."
955
+ )
956
+ tas = np.asarray(tas, dtype=float).ravel()
957
+ tas_time = np.asarray(tas_time, dtype=float).ravel()
958
+
959
+ return _scan_seam_states(infile, probe, [int(stop_record)], tas, tas_time,
960
+ progress)[0]
961
+
962
+
963
+ def chunk_primes_v35(infile: Any, probename: str, n_every: int, chunks: int, *, # noqa: N803
964
+ tas_time: Any, tas: Any, iQC: int = 0, # noqa: N803
965
+ progress: Any = None) -> list[tuple[float, float] | None]:
966
+ """Every chunk's ``prime=`` pair, in **one** pass over the file.
967
+
968
+ Returns a list of length ``chunks``: element ``k-1`` is what chunk ``k``
969
+ (records ``(k-1)*n_every+1 ..``) must be given. The first is always
970
+ ``None`` -- no particle precedes record 1.
971
+
972
+ **Why the driver calls this and not :func:`prefix_scan_v35` per chunk.**
973
+ Each worker scanning its own prefix reads ``chunks/2`` files' worth in
974
+ total and makes the last worker scan almost the whole file before it starts
975
+ processing. One pass in the parent costs a single read, and the seam states
976
+ are then just N points along the same walk. The arithmetic is identical
977
+ either way -- this is a scheduling choice, not a fidelity one, and
978
+ ``tests/test_v35_sizedist_chunk_priming.py`` asserts the two agree.
979
+ """
980
+ chunks = int(chunks)
981
+ if chunks < 1:
982
+ raise ValueError(f"chunks must be >= 1, got {chunks}")
983
+ probe = _primable_probe(probename, iQC)
984
+ stops = [(k - 1) * int(n_every) + 1 for k in range(1, chunks + 1)]
985
+ if tas is None or tas_time is None:
986
+ raise ValueError(
987
+ "chunk_primes_v35 needs the run's own tas_time/tas -- see prefix_scan_v35.")
988
+ # Each stop is a chunk's first record, so one past the file's last record is a
989
+ # chunk with no records (the scan itself accepts n_file + 1, the end state).
990
+ src = ncio.open(infile, "nowrite")
991
+ try:
992
+ _, n_file = ncio.inq_dim(src, 0)
993
+ finally:
994
+ ncio.close(src)
995
+ # Chunk 1 is always allowed: a run of an empty file holds one chunk and no seam,
996
+ # and a refusal advising fewer chunks could not be followed.
997
+ if chunks > 1 and stops[-1] > n_file:
998
+ raise ValueError(
999
+ f"chunk {chunks} would start at record {stops[-1]}, past the file's {n_file} "
1000
+ "records: that chunk would be empty. Use no more chunks than ceil(records / "
1001
+ "n_every) (arrayprobe.driver.run_flight._chunk_plan).")
1002
+ return _scan_seam_states(infile, probe, stops, np.asarray(tas, dtype=float).ravel(),
1003
+ np.asarray(tas_time, dtype=float).ravel(), progress)
1004
+
1005
+
1006
+ def _primable_probe(probename: str, iQC: int) -> Any: # noqa: N803
1007
+ """Shared validation for the two scan entry points."""
1008
+ try:
1009
+ probe = PROBES_V35[probename]
1010
+ except KeyError:
1011
+ raise ValueError(f"unknown probename {probename!r}; v3.5 knows "
1012
+ f"{sorted(PROBES_V35)}") from None
1013
+ if probe.timing not in PRIMABLE_TIMINGS_V35:
1014
+ raise ValueError(
1015
+ f"prefix scanning is for {sorted(PRIMABLE_TIMINGS_V35)} timing; {probename!r} "
1016
+ f"is probetype {probe.probetype} ({probe.timing!r}), which carries no "
1017
+ "whole-file accumulation and is already in CHUNKABLE_TIMINGS_V35."
1018
+ )
1019
+ if iQC == 1:
1020
+ raise ValueError(
1021
+ "prefix scanning refuses iQC=1: qc_image (:801-846) can change an image's "
1022
+ "width, so :850-853's return can fire mid-file and a scan cannot locate it "
1023
+ "without unpacking every image. Run iQC=1 serially."
1024
+ )
1025
+ if probe.read_width * probe.image_word_bits != probe.diodenum:
1026
+ raise ValueError(
1027
+ f"{probename!r}: an unpacked image is {probe.read_width * probe.image_word_bits} "
1028
+ f"wide against diodenum={probe.diodenum}, so imgProc_sm.m:850-853 returns at the "
1029
+ "first particle and a serial run writes nothing. Nothing to prime."
1030
+ )
1031
+ return probe
1032
+
1033
+
1034
+ #: The seven per-record time fields :func:`arrayprobe_uiops.imgproc_core._read_record_header`
1035
+ #: reads (``:206-212``), in its order.
1036
+ _RECORD_HEADER_NAMES = ("year", "month", "day", "hour", "minute", "second", "millisec")
1037
+
1038
+
1039
+ def _scan_seam_states(infile: Any, probe: Any, stop_records: Any, tas: Any, tas_time: Any,
1040
+ progress: Any) -> Any:
1041
+ """One boundary walk; the seam state captured at each of ``stop_records``.
1042
+
1043
+ ``stop_records`` must be ascending. Returns one entry per stop, each the
1044
+ ``(part_time_prev, time_in_seconds_prev)`` pair held at the *top* of that
1045
+ record, or ``None`` when no particle precedes it.
1046
+
1047
+ Byte-identical to :func:`_scan_seam_states_reference` and faster by three
1048
+ changes that alter no arithmetic and no visited state:
1049
+
1050
+ * the seven record-header fields are read once for every record, where the
1051
+ reference makes seven one-element reads per record;
1052
+ * the boundary walk is one array comparison per record. The reference's
1053
+ ``while`` loop (``:751``) advances ``j`` by one on every path and changes
1054
+ ``start`` only at a boundary row, so the boundary rows alone carry the state;
1055
+ they are found with ``flatnonzero`` and the ``start`` bookkeeping and the
1056
+ fold then run, unchanged and in the same order, over those rows only;
1057
+ * the TAS samples at the record's own second are selected once per record.
1058
+ ``_time_in_seconds_from_tas`` selects ``tas_time == temp_time`` itself, and
1059
+ ``temp_time`` is fixed for a record, so handing it the pre-selected samples
1060
+ gives it the same elements in the same order.
1061
+ """
1062
+ stops = [int(s) for s in stop_records]
1063
+ # strict=False, and deliberately: the two operands differ in length by one by
1064
+ # construction (adjacent-pair scan), so strict=True would raise on every call.
1065
+ if any(b < a for a, b in zip(stops, stops[1:], strict=False)):
1066
+ raise ValueError(f"stop_records must be ascending, got {stops}")
1067
+ out: list[tuple[float, float] | None] = []
1068
+ part_time_prev: float | None = None
1069
+ time_in_seconds_prev: float | None = None
1070
+ boundary = np.asarray(probe.boundary)
1071
+ boundary_words = boundary.size
1072
+ pending = list(stops)
1073
+ last_record = max(stops) if stops else 1
1074
+
1075
+ def _capture(record: int) -> None:
1076
+ """Record the state held at the *top* of every stop at or below ``record``."""
1077
+ while pending and pending[0] <= record:
1078
+ pending.pop(0)
1079
+ # Both Optionals are set together (:1178, :1180) and start out None, so
1080
+ # the second test only makes that invariant visible to the type checker.
1081
+ out.append(None if part_time_prev is None or time_in_seconds_prev is None
1082
+ else (part_time_prev, float(time_in_seconds_prev)))
1083
+
1084
+ src = ncio.open(infile, "nowrite")
1085
+ try:
1086
+ data_varid = ncio.inq_var_id(src, "data") # :719
1087
+ header: dict[str, Any] = {}
1088
+ if last_record > 1: # records 1 .. last-1
1089
+ for name in _RECORD_HEADER_NAMES: # :695-701, in bulk
1090
+ header[name] = np.ravel(
1091
+ ncio.get_var(src, ncio.inq_var_id(src, name), 0, last_record - 1))
1092
+ # The file's own record count (dimension 0, as :277 reads it), not the
1093
+ # size of the read above. A stop at n_file + 1 is the state after the last
1094
+ # record, which a scan may ask for; a chunk *starting* there is empty, and
1095
+ # chunk_primes_v35, whose stops are chunk starts, refuses that itself.
1096
+ _, n_file = ncio.inq_dim(src, 0)
1097
+ if last_record > n_file + 1:
1098
+ raise ValueError(
1099
+ f"seam stop at record {last_record} is past the end of the file's "
1100
+ f"{n_file} records. Use no more chunks than ceil(records / n_every) "
1101
+ "(arrayprobe.driver.run_flight._chunk_plan).")
1102
+ for i in range(1, last_record): # :693
1103
+ _capture(i)
1104
+ if progress is not None:
1105
+ progress(i, last_record - 1)
1106
+ rec = {name: float(header[name][i - 1]) for name in _RECORD_HEADER_NAMES}
1107
+ data = ncio.read_image_record(src, data_varid, i - 1,
1108
+ probe.read_width, probe.read_slices)
1109
+ nrow = data.shape[0]
1110
+ # The walk visits every j from 1 until data[j-1, 0] == -1 or j == nrow (:751).
1111
+ neg = np.flatnonzero(data[:nrow - 1, 0] == -1)
1112
+ jstop = int(neg[0]) + 1 if neg.size else nrow # walk is j in [1, jstop)
1113
+ if boundary_words > data.shape[1]:
1114
+ continue # array_equal of unequal lengths is False at every j
1115
+ is_boundary = (data[:jstop - 1, :boundary_words] == boundary).all(axis=1)
1116
+ if probe.boundary_needs_time: # :754
1117
+ is_boundary &= data[1:jstop, 0] == probe.boundarytime
1118
+ start = 0 # :730
1119
+ tas_rec: Any = None
1120
+ for j in (np.flatnonzero(is_boundary) + 1).tolist(): # 1-based, ascending
1121
+ if start == 0: # :755-761
1122
+ start = probe.start_first
1123
+ if (start + probe.image_slice_offset) > (j - 1): # :764-777
1124
+ start = j + 2
1125
+ continue
1126
+ h = j # header_loc - 1, :779
1127
+ part_time = float(data[h, 6]) * 2 ** 16 + float(data[h, 7]) # :1123
1128
+ if tas_rec is None:
1129
+ # :727's key, built as _time_in_seconds_from_tas builds it, once.
1130
+ temp_time = (float(rec["hour"]) * 10000 + float(rec["minute"]) * 100
1131
+ + float(rec["second"]))
1132
+ at_second = tas_time == temp_time
1133
+ tas_rec = (tas[at_second], tas_time[at_second])
1134
+ t = _time_in_seconds_from_tas(
1135
+ part_time, probe.ds, rec, tas_rec[0], tas_rec[1],
1136
+ part_time_prev, time_in_seconds_prev) # :1131-1170
1137
+ part_time_prev = part_time # :1178
1138
+ time_in_seconds_prev = t # :1180
1139
+ start = j + 2 # :1311
1140
+ _capture(last_record)
1141
+ finally:
1142
+ ncio.close(src)
1143
+
1144
+ assert not pending, f"seam states not captured for records {pending}"
1145
+ return out
1146
+
1147
+
1148
+ def _scan_seam_states_reference(infile: Any, probe: Any, stop_records: Any, tas: Any,
1149
+ tas_time: Any, progress: Any) -> Any:
1150
+ """The literal slice-by-slice walk, kept as the oracle for :func:`_scan_seam_states`.
1151
+
1152
+ Not called in production; ``tests/test_v35_prefix_scan_fast.py`` compares the
1153
+ production scan against it bit for bit. Its logic is untouched from the version
1154
+ that shipped before the vectorised walk.
1155
+ """
1156
+ stops = [int(s) for s in stop_records]
1157
+ # strict=False, and deliberately: the two operands differ in length by one by
1158
+ # construction (adjacent-pair scan), so strict=True would raise on every call.
1159
+ if any(b < a for a, b in zip(stops, stops[1:], strict=False)):
1160
+ raise ValueError(f"stop_records must be ascending, got {stops}")
1161
+ out: list[tuple[float, float] | None] = []
1162
+ part_time_prev: float | None = None
1163
+ time_in_seconds_prev: float | None = None
1164
+ boundary = np.asarray(probe.boundary)
1165
+ boundary_words = boundary.size
1166
+ pending = list(stops)
1167
+ last_record = max(stops) if stops else 1
1168
+
1169
+ def _capture(record: int) -> None:
1170
+ """Record the state held at the *top* of every stop at or below ``record``."""
1171
+ while pending and pending[0] <= record:
1172
+ pending.pop(0)
1173
+ # part_time_prev and time_in_seconds_prev are always set together
1174
+ # (:965-966 below) and start out both None (:921-922), so this is
1175
+ # a single invariant, not two independent Optionals -- the extra
1176
+ # `or time_in_seconds_prev is None` only makes that visible to the
1177
+ # type checker; it never changes which branch executes.
1178
+ out.append(None if part_time_prev is None or time_in_seconds_prev is None
1179
+ else (part_time_prev, float(time_in_seconds_prev)))
1180
+
1181
+ src = ncio.open(infile, "nowrite")
1182
+ try:
1183
+ data_varid = ncio.inq_var_id(src, "data") # :719
1184
+ for i in range(1, last_record): # :693
1185
+ _capture(i)
1186
+ if progress is not None:
1187
+ progress(i, last_record - 1)
1188
+ rec = _read_record_header(src, i) # :695-701
1189
+ data = ncio.read_image_record(src, data_varid, i - 1,
1190
+ probe.read_width, probe.read_slices)
1191
+ j = 1 # :729
1192
+ start = 0 # :730
1193
+ while data[j - 1, 0] != -1 and j < data.shape[0]: # :751
1194
+ is_boundary = np.array_equal(data[j - 1, :boundary_words], boundary)
1195
+ if probe.boundary_needs_time: # :754
1196
+ is_boundary = bool(is_boundary) and data[j, 0] == probe.boundarytime
1197
+ if not is_boundary:
1198
+ j += 1
1199
+ continue
1200
+ if start == 0: # :755-761
1201
+ start = probe.start_first
1202
+ if (start + probe.image_slice_offset) > (j - 1): # :764-777
1203
+ start = j + 2
1204
+ j += 1
1205
+ continue
1206
+ h = j # header_loc - 1, :779
1207
+ part_time = float(data[h, 6]) * 2 ** 16 + float(data[h, 7]) # :1123
1208
+ t = _time_in_seconds_from_tas(
1209
+ part_time, probe.ds, rec, tas, tas_time,
1210
+ part_time_prev, time_in_seconds_prev) # :1131-1170
1211
+ part_time_prev = part_time # :1178
1212
+ time_in_seconds_prev = t # :1180
1213
+ start = j + 2 # :1311
1214
+ j += 1 # :1316
1215
+ _capture(last_record)
1216
+ finally:
1217
+ ncio.close(src)
1218
+
1219
+ assert not pending, f"seam states not captured for records {pending}"
1220
+ return out
1221
+
1222
+
1223
+ def merge_chunks_v35(chunk_paths: Any, outfile: Any, *, projectname: Any, infile: Any,
1224
+ probename: Any, # noqa: N803
1225
+ iNewHabit: Any, software: Any, iRectEllipse: Any = 0, # noqa: N803
1226
+ iCalcAllDiodeStats: Any = 0, # noqa: N803
1227
+ iQC: Any = 0, extended_ellipse_outputs: Any = None, # noqa: N803
1228
+ creation_time: Any = None,
1229
+ stopped_at: Any = None, primed: Any = False, stamp_profile: Any = None,
1230
+ tas_qc: dict[str, Any] | None = None,
1231
+ stray_pixel_fix: bool = False) -> int:
1232
+ """Stitch N chunk-local v3.5 proc files into one whole-file result.
1233
+
1234
+ ``stray_pixel_fix`` must state what every chunk worker ran with: when True the two
1235
+ :data:`STRAY_PIXEL_VARIABLES` and the ``arrayprobe_stray_pixel`` attribute are carried into
1236
+ the merge exactly as a serial ``stray_pixel_fix=True`` run writes them (the correction is
1237
+ per particle image, and no particle spans a record, so a record-range seam cannot split
1238
+ one). A chunk whose stray-pixel variables disagree with it is refused, never dropped.
1239
+
1240
+ The v3.5 counterpart of the earlier translation's ``merge_chunks``, and the
1241
+ same mechanism: each chunk file is an ordinary :func:`imgproc_sm_v35` call
1242
+ over a disjoint, **ordered** record range (the ``n``/``nEvery`` API a
1243
+ whole-file run already uses with ``n=1``). Chunks must be passed in the
1244
+ record order the split was made in -- nothing on disk records which range a
1245
+ chunk covers, so this cannot detect a reordering.
1246
+
1247
+ **The cross-record state audit, per quantity** (the reason this is a
1248
+ fidelity function and not a plumbing one):
1249
+
1250
+ * ``kk`` is **record-local** -- ``:1312`` increments it per particle and
1251
+ ``:1402`` resets it to 1 for every record that wrote, so it is 1 at the
1252
+ top of every record and a seam cannot renumber anything. ``particle_num
1253
+ = mod(kk, 66536)`` (``:858``, the preserved 65536 typo) therefore counts
1254
+ *within a record*, not across the file, and needs no merging.
1255
+ * ``parent_rec_num`` (``:857``) is the **absolute** record ``i``, because
1256
+ the loop is written over absolute record numbers in both cases.
1257
+ * ``tasRatio`` (``:709``) is indexed by that same absolute ``i``, so every
1258
+ chunk worker must be handed the **whole-file** series -- which
1259
+ :func:`imgproc_sm_v35` enforces itself, raising ``IndexError`` rather
1260
+ than silently reading the wrong element.
1261
+ * ``w``/``wstart`` are chunk-local write indices; concatenation in chunk
1262
+ order is what merges them.
1263
+ * ``diode_stats``/``bin_stats`` accumulate per file and merge by summation.
1264
+ * ``inter_arrival`` is the **one** quantity a seam genuinely breaks, and
1265
+ only on ``"dmt"`` timing -- see below.
1266
+ * ``part_time_prev``/``time_in_seconds_prev`` on ``"spec"`` timing are what
1267
+ ``primed=True`` asserts were handed to every chunk after the first, as
1268
+ :func:`imgproc_sm_v35`'s ``prime=``. Without that assertion the merge
1269
+ still refuses ``"spec"`` -- see :data:`CHUNKABLE_TIMINGS_V35` and
1270
+ :data:`PRIMABLE_TIMINGS_V35`.
1271
+
1272
+ ``primed`` is the caller's statement that it did the priming, and this
1273
+ function **cannot verify it**: nothing on disk records whether a chunk was
1274
+ primed, exactly as nothing records which record range it covers. Passing
1275
+ ``primed=True`` over unprimed chunks produces a silently wrong file. The
1276
+ driver that splits the work is the one place that knows, so it is the one
1277
+ place that may pass it -- ``scripts/run_flight.py`` does, next to the
1278
+ ``prefix_scan_v35`` call whose result it fed in.
1279
+
1280
+ **The ``inter_arrival`` seam repair (probetype 1 only), and why it is
1281
+ exact.** ``:1110-1114`` writes ``t - time_in_seconds_prev`` for every
1282
+ particle, where ``time_in_seconds_prev`` is the immediately preceding
1283
+ particle's ``t`` -- carried across record boundaries, new in v3.5. At the
1284
+ top of a chunk that variable is ``None``, so the chunk's first particle
1285
+ gets ``0.0`` where the serial run would have written a real difference.
1286
+ Both operands are on disk as ``Time_in_seconds`` (``:305``, ``double``),
1287
+ and ``t`` itself is record-local, so recomputing the difference here uses
1288
+ **the identical pair of float64 values and the identical IEEE
1289
+ subtraction** the serial run performed. It is the same number, not a
1290
+ close one -- asserted with ``np.array_equal`` on the bytes, not
1291
+ ``allclose``.
1292
+
1293
+ ``stopped_at`` is the 1-based index of the first chunk whose worker hit the
1294
+ ``:850-853`` width-mismatch ``return``. MATLAB exits the *whole function*
1295
+ there, leaving every later record unprocessed, so the serial-equivalent
1296
+ merge keeps chunks ``1..stopped_at`` (that chunk's own file already ends
1297
+ where MATLAB would have stopped) and **discards the rest** -- which a
1298
+ chunked run computed only because its later workers never saw the
1299
+ mismatch. ``None`` means no chunk returned early.
1300
+
1301
+ Returns the merged particle count.
1302
+ """
1303
+ if not chunk_paths:
1304
+ raise ValueError("merge_chunks_v35: no chunk files given")
1305
+
1306
+ try:
1307
+ probe = PROBES_V35[probename]
1308
+ except KeyError:
1309
+ raise ValueError(f"unknown probename {probename!r}; v3.5 knows "
1310
+ f"{sorted(PROBES_V35)}") from None
1311
+ if probe.timing not in CHUNKABLE_TIMINGS_V35:
1312
+ if not (primed and probe.timing in PRIMABLE_TIMINGS_V35):
1313
+ raise ChunkingNotEquivalent(
1314
+ f"{probename!r} is probetype {probe.probetype} ({probe.timing!r} timing): an "
1315
+ "UNPRIMED chunked v3.5 S3 pass cannot reproduce the serial run. "
1316
+ "imgProc_sm.m:1131-1180 accumulates Time_in_seconds across the WHOLE file "
1317
+ "(time_in_seconds_prev + (part_time - part_time_prev) * scale), so a chunk "
1318
+ "restarts that sum at :763-765 and every particle after a seam differs. "
1319
+ f"Chunkable without priming: {sorted(CHUNKABLE_TIMINGS_V35)}. "
1320
+ f"Chunkable WITH priming: {sorted(PRIMABLE_TIMINGS_V35)} -- give each chunk "
1321
+ "after the first the prefix_scan_v35 pair as imgproc_sm_v35(prime=...), "
1322
+ "then merge with primed=True. Otherwise run this probe serially."
1323
+ )
1324
+ elif primed:
1325
+ raise ValueError(
1326
+ f"primed=True with {probename!r} ({probe.timing!r} timing): that timing is "
1327
+ "chunkable without priming and imgproc_sm_v35 refuses prime= for it, so "
1328
+ "primed=True here asserts something no chunk worker could have done."
1329
+ )
1330
+
1331
+ chunk_paths = list(chunk_paths)
1332
+ if stopped_at is not None:
1333
+ if not 1 <= stopped_at <= len(chunk_paths):
1334
+ raise ValueError(
1335
+ f"stopped_at={stopped_at} is not a 1-based index into {len(chunk_paths)} chunks")
1336
+ chunk_paths = chunk_paths[:stopped_at]
1337
+
1338
+ specs = imgproc_variables_v35(
1339
+ iRectEllipse=iRectEllipse, iCalcAllDiodeStats=iCalcAllDiodeStats, iQC=iQC,
1340
+ iNewHabit=iNewHabit, extended_ellipse_outputs=extended_ellipse_outputs,
1341
+ probetype=probe.probetype,
1342
+ )
1343
+ # "time" is not always dims[0] -- `position` (:311, ("pos_count","time")) and
1344
+ # `image_bin_stats` (:649, ("bin_count","time")) are MATLAB-order, reversed
1345
+ # from every other time-indexed variable.
1346
+ time_specs = [s for s in specs if "time" in s.dims]
1347
+ other_specs = [s for s in specs if "time" not in s.dims]
1348
+
1349
+ stray_names = [name for name, *_ in STRAY_PIXEL_VARIABLES]
1350
+ readers = [ncio.open(p, "nowrite") for p in chunk_paths]
1351
+ try:
1352
+ for path, ds in zip(chunk_paths, readers, strict=True):
1353
+ has = [name in ds._ds.variables for name in stray_names]
1354
+ if any(has) != bool(stray_pixel_fix) or len(set(has)) != 1:
1355
+ raise ValueError(
1356
+ f"merge_chunks_v35: chunk {path} has stray-pixel variables {has} but the "
1357
+ f"merge was called with stray_pixel_fix={bool(stray_pixel_fix)}; every chunk "
1358
+ "must be computed with the run's stray-pixel setting")
1359
+ chunk_arrays = [
1360
+ {spec.name: ncio.get_var(ds, ncio.inq_var_id(ds, spec.name)) for spec in specs}
1361
+ for ds in readers
1362
+ ]
1363
+ if stray_pixel_fix:
1364
+ for arrays, ds in zip(chunk_arrays, readers, strict=True):
1365
+ for name in stray_names:
1366
+ arrays[name] = ncio.get_var(ds, ncio.inq_var_id(ds, name))
1367
+ finally:
1368
+ for ds in readers:
1369
+ ncio.close(ds)
1370
+
1371
+ diodenum = probe.diodenum
1372
+ counts = [int(arrays[time_specs[0].name].shape[
1373
+ time_specs[0].dims.index("time")]) for arrays in chunk_arrays]
1374
+
1375
+ if probe.timing == "dmt":
1376
+ _repair_inter_arrival_seams(chunk_arrays, counts)
1377
+
1378
+ out = _create_output(outfile, diodenum, projectname, infile, probename,
1379
+ iRectEllipse, iCalcAllDiodeStats, iQC, iNewHabit,
1380
+ extended_ellipse_outputs, software, creation_time,
1381
+ stamp_profile, tas_qc, stray_pixel_fix=bool(stray_pixel_fix))
1382
+ try:
1383
+ var = {spec.name: ncio.inq_var_id(out, spec.name) for spec in specs}
1384
+ if stray_pixel_fix:
1385
+ var.update({name: ncio.inq_var_id(out, name) for name in stray_names})
1386
+ wstart = 0
1387
+ for arrays, count in zip(chunk_arrays, counts, strict=True):
1388
+ if count == 0:
1389
+ continue
1390
+ for spec in time_specs:
1391
+ data = arrays[spec.name]
1392
+ if spec.dims[0] != "time":
1393
+ # get_var hands back MATLAB shape (<other>, time);
1394
+ # write_record_block wants on-disk/C order (time, <other>).
1395
+ # Keyed on the dims, not the name, so a new MATLAB-order
1396
+ # variable could not be added without being handled.
1397
+ ncio.write_record_block(out, var[spec.name], wstart, data.T)
1398
+ else:
1399
+ ncio.put_var(out, var[spec.name], wstart, count, data)
1400
+ if stray_pixel_fix:
1401
+ for name in stray_names:
1402
+ ncio.put_var(out, var[name], wstart, count, arrays[name])
1403
+ wstart += count
1404
+
1405
+ for spec in other_specs:
1406
+ # `bin_stats` is rewritten whole every record (:1394, no start/count)
1407
+ # inside the particle-write block, which a record that found no
1408
+ # particle never reaches. A chunk with zero particles therefore
1409
+ # leaves it at the netCDF fill value, not 0, and summing that in
1410
+ # would corrupt the merge. A chunk with count > 0 ends with the
1411
+ # write from its last particle-bearing record, whose value is
1412
+ # already that chunk's complete total (diode_stats accumulates over
1413
+ # every particle in the chunk, not just that record), so skipping
1414
+ # the zero-count chunks is exact, not approximate.
1415
+ merged = np.zeros(diodenum)
1416
+ for arrays, count in zip(chunk_arrays, counts, strict=True):
1417
+ if count == 0:
1418
+ continue
1419
+ merged = merged + np.asarray(arrays[spec.name]).reshape(-1)
1420
+ ncio.put_var(out, var[spec.name], merged)
1421
+ finally:
1422
+ ncio.close(out)
1423
+
1424
+ return wstart
1425
+
1426
+
1427
+ def _repair_inter_arrival_seams(chunk_arrays: Any, counts: Any) -> None:
1428
+ """``:1110-1114`` across a chunk seam -- see :func:`merge_chunks_v35`.
1429
+
1430
+ Rewrites element 0 of every non-empty chunk's ``inter_arrival`` except the
1431
+ first, in place, to the difference the serial run computed. Empty chunks
1432
+ are stepped over rather than treated as a seam: they wrote nothing, so the
1433
+ serial run's ``time_in_seconds_prev`` at the next particle is still the
1434
+ last particle of the previous *non-empty* chunk.
1435
+ """
1436
+ prev_last_t = None
1437
+ for arrays, count in zip(chunk_arrays, counts, strict=True):
1438
+ if count == 0:
1439
+ continue
1440
+ # get_var hands a 1-D netCDF variable back as a MATLAB column vector,
1441
+ # shape (time, 1) -- flatten to index it, and put the original shape
1442
+ # back so the writer below still sees what it expects.
1443
+ t = np.asarray(arrays["Time_in_seconds"]).reshape(-1)
1444
+ if prev_last_t is not None:
1445
+ ia = np.array(arrays["inter_arrival"]) # explicit copy, never a view
1446
+ shape = ia.shape
1447
+ flat = ia.reshape(-1)
1448
+ # The identical float64 subtraction :1114 performs, on the identical
1449
+ # pair of operands -- not a reconstruction of it.
1450
+ flat[0] = t[0] - prev_last_t
1451
+ arrays["inter_arrival"] = flat.reshape(shape)
1452
+ prev_last_t = t[-1]
1453
+
1454
+
1455
+ class _Record:
1456
+ """The per-record accumulators MATLAB ``clear``\\ s at ``:1402``."""
1457
+
1458
+ def __init__(self) -> None:
1459
+ self.images: list[np.ndarray] = []
1460
+ self.position: list[tuple[int, int]] = []
1461
+ self.parent_rec_num: list[int] = []
1462
+ self.particle_num: list[int] = []
1463
+ self.rec_time: list[float] = []
1464
+ self.rec_date: list[float] = []
1465
+ self.rec_millisec: list[float] = []
1466
+ self.num_subparticles: list[int] = []
1467
+ self.dist_min: list[int] = []
1468
+ # The ten accumulators MATLAB indexes by ``kk`` and that a later
1469
+ # particle -- or, for the GCPEx-CIP wraparound ``:1081-1093``, a WHOLE-
1470
+ # VECTOR assignment -- reads back. A plain list cannot express either,
1471
+ # so these are 1-based :class:`MGrowVector`\\ s, the same type the
1472
+ # v3.1.4 port uses and the same type its reused timing helpers write to.
1473
+ self.particle_DOF = MGrowVector()
1474
+ self.particle_partNum = MGrowVector()
1475
+ self.particle_sliceCount = MGrowVector()
1476
+ self.part_hour = MGrowVector()
1477
+ self.part_min = MGrowVector()
1478
+ self.part_sec = MGrowVector()
1479
+ self.part_mil = MGrowVector()
1480
+ self.part_micro = MGrowVector()
1481
+ self.time_in_seconds = MGrowVector()
1482
+ self.int_arrival = MGrowVector()
1483
+
1484
+
1485
+ #: The two per-particle variables a ``stray_pixel_fix=True`` run adds
1486
+ #: (absent when off).
1487
+ STRAY_PIXEL_VARIABLES = (
1488
+ ("image_stray_pixels_removed", "short", "count",
1489
+ "Stray pixels zeroed before sizing (arrayprobe correction, 0 when untouched)"),
1490
+ ("image_diam_minR_uncorrected", "double", "mm",
1491
+ "image_diam_minR before the stray-pixel correction (NaN when untouched)"),
1492
+ )
1493
+
1494
+
1495
+ @dataclass(frozen=True)
1496
+ class RunOptions:
1497
+ """The run-invariant flags :func:`_process_records` reads (2026-09-25 code review).
1498
+
1499
+ Plumbing only: each field is the object the caller passed, held by reference (``ratios`` is
1500
+ not copied), and ``_process_records`` rebinds every field to the local of the same name
1501
+ before its first statement, so its body reads exactly what it read when these were ten
1502
+ positional parameters.
1503
+ """
1504
+ ratios: Any
1505
+ projectname: str
1506
+ probename: str
1507
+ iCalcAllDiodeStats: int # noqa: N815
1508
+ iQC: int # noqa: N815
1509
+ iNewHabit: int # noqa: N815
1510
+ iRectEllipse: int # noqa: N815
1511
+ extended_ellipse_outputs: Any
1512
+ reject_config: Any
1513
+ kernels: Any = None
1514
+ shadow_diode: Any = None
1515
+ stray_pixel_fix: bool = False
1516
+ ncar_2dc_timing_fix: bool = False
1517
+
1518
+
1519
+ def _process_records(src: Any, out: Any, probe: Any, n: Any, nEvery: Any, # noqa: N803
1520
+ img_count: Any, boundary: Any, boundarytime: Any,
1521
+ diode_stats: Any, tas: Any, tas_time: Any, opts: RunOptions, progress: Any,
1522
+ prime: Any = None) -> int:
1523
+ """``:663-1405`` -- the record loop and the particle loop, all four probetypes.
1524
+
1525
+ The ten run-invariant flags arrive bundled in ``opts`` (:class:`RunOptions`) and are
1526
+ unpacked to locals of their former names first thing below.
1527
+
1528
+ ``kernels`` is ``None`` (the reference ``dec2bin_concat``) or an
1529
+ :class:`arrayprobe_uiops.jit_kernels.V35JitKernels`, whose ``dec2bin_concat``
1530
+ is a drop-in returning identical values.
1531
+
1532
+ ``prime`` is ``None`` or the ``(part_time_prev, time_in_seconds_prev)`` pair
1533
+ a serial run holds at the top of record ``(n-1)*nEvery+1`` -- see
1534
+ :func:`prefix_scan_v35`. It seeds the two locals below instead of
1535
+ ``None``/``None``, which is the whole of prefix-priming: ``:1136``'s
1536
+ ``exist('part_time_prev','var')`` is then true at the chunk's first
1537
+ particle, exactly as it is mid-file in a serial run.
1538
+ """
1539
+ ratios = opts.ratios
1540
+ projectname = opts.projectname
1541
+ probename = opts.probename
1542
+ iCalcAllDiodeStats = opts.iCalcAllDiodeStats # noqa: N806
1543
+ iQC = opts.iQC # noqa: N806
1544
+ iNewHabit = opts.iNewHabit # noqa: N806
1545
+ iRectEllipse = opts.iRectEllipse # noqa: N806
1546
+ extended_ellipse_outputs = opts.extended_ellipse_outputs
1547
+ reject_config = opts.reject_config
1548
+ kernels = opts.kernels
1549
+ shadow_diode = opts.shadow_diode
1550
+ ds = probe.ds
1551
+ diodenum = probe.diodenum
1552
+ probetype = probe.probetype
1553
+ to_chars = dec2bin_concat if kernels is None else kernels.dec2bin_concat
1554
+ var = {spec.name: k for k, spec in enumerate(imgproc_variables_v35(
1555
+ iRectEllipse=iRectEllipse, iCalcAllDiodeStats=iCalcAllDiodeStats, iQC=iQC,
1556
+ iNewHabit=iNewHabit, extended_ellipse_outputs=extended_ellipse_outputs,
1557
+ probetype=probetype,
1558
+ ))}
1559
+ stray_fix = bool(opts.stray_pixel_fix)
1560
+ # The NCAR 2DC timing-word correction applies to probetype 0 only (imgProc_sm.m:137-139).
1561
+ ncar_fix = bool(opts.ncar_2dc_timing_fix) and probetype == 0
1562
+ if stray_fix:
1563
+ for name, *_ in STRAY_PIXEL_VARIABLES:
1564
+ var[name] = len(var)
1565
+ data_varid = ncio.inq_var_id(src, "data") # :719
1566
+
1567
+ kk = 1 # :663
1568
+ w = -1 # :664
1569
+ wstart = 0 # :665
1570
+ # Not in the :1402 clear list: persist across records within the chunk.
1571
+ # ``prime`` seeds them at a chunk boundary; ``None`` is a whole-file run and
1572
+ # is what ``n == 1`` always gets.
1573
+ part_time_prev: float | None = None if prime is None else float(prime[0])
1574
+ time_in_seconds_prev: float | None = None if prime is None else float(prime[1])
1575
+ total = 0
1576
+
1577
+ # :685-688 / :736-749 -- v3.5 narrowed v3.1.4's project-only gate to
1578
+ # ``(PECAN or GCPEx) AND probetype==1``: a 2DS run under projectname
1579
+ # 'PECAN' scanned for corrupt DMT boundaries in v3.1.4 and does not here.
1580
+ corrupt_scan = projectname in ("PECAN", "GCPEx") and probetype == 1
1581
+ boundary_words = boundary.size # :754
1582
+
1583
+ last = min(n * nEvery, img_count)
1584
+ for i in range(int((n - 1) * nEvery + 1), int(last) + 1): # :693
1585
+ if progress is not None:
1586
+ progress(i, int(last))
1587
+ rec = _read_record_header(src, i) # :695-701
1588
+ if ratios is not None: # :707-712
1589
+ if i > ratios.size:
1590
+ raise IndexError(
1591
+ f"imgProc_sm.m:709: tasRatio({i}) is out of range for a series of "
1592
+ f"length {ratios.size}. varargin{{3}} is indexed by the ABSOLUTE record "
1593
+ "number, so a chunked run must pass the whole-file series (V20)."
1594
+ )
1595
+ tas_ratio_i = float(ratios[i - 1])
1596
+ else:
1597
+ tas_ratio_i = 1.0
1598
+ data = ncio.read_image_record(src, data_varid, i - 1,
1599
+ probe.read_width, probe.read_slices) # :720-727
1600
+ if ncar_fix:
1601
+ # Not UIOOPS: NCAR 2DC sync/timing words -> 0x55 before :754 frames (ncar_2dc_timing).
1602
+ data, n_conv = _ncar_2dc.convert_record(data)
1603
+ NCAR_2DC_SYNCS_CONVERTED[i] = n_conv
1604
+
1605
+ j = 1 # :729
1606
+ start = 0 # :730
1607
+ num_crpt_bnds = 0 # :748
1608
+ if corrupt_scan: # :736-747
1609
+ member_sum = np.isin(data, boundary).sum(axis=1)
1610
+ num_good_bnds = int(np.sum(member_sum == 8))
1611
+ num_crpt_bnds = int(np.sum((member_sum > 4) & (member_sum < 8)))
1612
+ if num_crpt_bnds > 0:
1613
+ CORRUPT_RECORDS.append((i, num_crpt_bnds, num_good_bnds))
1614
+
1615
+ acc = _Record()
1616
+ # :751
1617
+ while data[j - 1, 0] != -1 and j < data.shape[0] and num_crpt_bnds < 1:
1618
+ # :754 -- probetypes 0/2 need BOTH the boundary row and the
1619
+ # boundarytime word at the head of the next row; probetypes 1 and 3
1620
+ # take the `|| probetype==1 || probetype==3` disjunct, which exists
1621
+ # precisely because their boundarytime is NaN and isequal(NaN,NaN)
1622
+ # is false. Do not "fix" that into a NaN-tolerant compare.
1623
+ is_boundary = np.array_equal(data[j - 1, :boundary_words], boundary)
1624
+ if probe.boundary_needs_time:
1625
+ is_boundary = bool(is_boundary) and data[j, 0] == boundarytime
1626
+ if not is_boundary:
1627
+ j += 1
1628
+ continue
1629
+ if start == 0: # :755-761
1630
+ start = probe.start_first
1631
+ # :764-777 -- probetype 0 tests `start+1 > j-1`, the others
1632
+ # `start > j-1`; the offset is the same one the image slice uses.
1633
+ if (start + probe.image_slice_offset) > (j - 1):
1634
+ start = j + 2
1635
+ j += 1
1636
+ continue
1637
+ header_loc = j + 1 # :779
1638
+ w += 1 # :780
1639
+
1640
+ # :785-795
1641
+ ind_matrix = data[start - 1 + probe.image_slice_offset:j - 1, :]
1642
+ if probe.image_invert:
1643
+ ind_matrix = 65535 - ind_matrix
1644
+ c = to_chars(ind_matrix, probe.image_word_bits)
1645
+ if shadow_diode is not None: # fork :286-292, before iQC
1646
+ c = diode_mask.reilluminate(c, shadow_diode)
1647
+
1648
+ if iQC == 1: # :801-846
1649
+ c, n_sub, d_min = qc_image(c)
1650
+ acc.num_subparticles.append(n_sub)
1651
+ acc.dist_min.append(d_min)
1652
+
1653
+ if c.shape[1] != diodenum: # :850-853
1654
+ # MATLAB prints a width-mismatch message and returns -- the
1655
+ # whole function exits, the current record unwritten.
1656
+ WIDTH_MISMATCH_RETURNS.append((i, j))
1657
+ return total
1658
+
1659
+ acc.images.append(c)
1660
+ acc.position.append((start, j - 1)) # :856
1661
+ acc.parent_rec_num.append(i) # :857
1662
+ acc.particle_num.append(particle_num_v35(kk)) # :858
1663
+
1664
+ if probe.timing == "spec":
1665
+ # :1117-1185 -- byte-identical to v3.1.4's probetype-2 block.
1666
+ h = header_loc - 1
1667
+ acc.particle_DOF[kk] = float(int(data[h, 3]) & 32768) # :1119
1668
+ acc.particle_partNum[kk] = float(data[h, 4]) # :1120
1669
+ acc.particle_sliceCount[kk] = float(data[h, 5]) # :1121
1670
+ part_time = float(data[h, 6]) * 2 ** 16 + float(data[h, 7]) # :1123
1671
+ acc.part_micro[kk] = part_time # :1124
1672
+ # :1125-1128 -- the other four are literal zeros, which is why
1673
+ # :1336's particle_time is a column of zeros for probetype 2.
1674
+ acc.part_mil[kk] = 0.0
1675
+ acc.part_sec[kk] = 0.0
1676
+ acc.part_min[kk] = 0.0
1677
+ acc.part_hour[kk] = 0.0
1678
+ t = _time_in_seconds_from_tas(part_time, ds, rec, tas, tas_time,
1679
+ part_time_prev, time_in_seconds_prev)
1680
+ acc.time_in_seconds[kk] = t # :1131-1170
1681
+ # :1172-1176 -- kk>1 ? diff : 0. Per record; NOT carried across
1682
+ # records (that change, :1110-1115, is probetype 1 only).
1683
+ acc.int_arrival[kk] = (t - acc.time_in_seconds[kk - 1]) if kk > 1 else 0.0
1684
+ part_time_prev = part_time # :1178
1685
+ time_in_seconds_prev = t # :1180
1686
+ elif probe.timing == "pms":
1687
+ # :861-868 + :901-934 -- byte-identical to v3.1.4's, so the
1688
+ # v3.1.4 translation is reused rather than re-transcribed.
1689
+ _particle_time_pms(acc, kk, data, header_loc, src, i, probe, ind_matrix)
1690
+ elif probe.timing == "fast2dc":
1691
+ # :869-878 + :901-934 -- likewise byte-identical.
1692
+ _particle_time_fast2dc(acc, kk, data, header_loc, src, i, ind_matrix)
1693
+ else: # :935-1115
1694
+ time_in_seconds_prev = _particle_time_dmt_v35(
1695
+ acc, kk, data, start, rec, projectname, probename, time_in_seconds_prev,
1696
+ to_chars)
1697
+
1698
+ acc.rec_time.append(rec["hour"] * 10000 + rec["minute"] * 100 + rec["second"]) # :1193
1699
+ acc.rec_date.append(rec["year"] * 10000 + rec["month"] * 100 + rec["day"]) # :1194
1700
+ acc.rec_millisec.append(rec["millisec"]) # :1195
1701
+
1702
+ start = j + 2 # :1311
1703
+ kk += 1 # :1312
1704
+ j += 1 # :1316
1705
+
1706
+ if kk > 1: # :1320
1707
+ count = w - wstart + 1
1708
+ geom = RecordGeometry(diodesize=ds, diodenum=diodenum, tas_ratio=tas_ratio_i,
1709
+ i_new_habit=iNewHabit, probename=probename,
1710
+ i_calc_all_diode_stats=iCalcAllDiodeStats)
1711
+ # `jit=jit`, NOT omitted: measure_record forwards it to
1712
+ # calculate_reject_unified, whose compiled scan pass measured 6.33x on a
1713
+ # real production pass. Leaving it off here is what made --jit reach the
1714
+ # framing kernels and silently skip the reject path -- the same defect
1715
+ # shape, recreated on 2026-09-18 and caught by asking whether the number
1716
+ # was reachable rather than whether the kernel existed.
1717
+ stray_removed: list[int] = []
1718
+ stray_uncorrected: list[float] = []
1719
+ if stray_fix:
1720
+ # Not MATLAB: the opt-in stray-pixel correction, before :1204 so the kept
1721
+ # piece is re-sized and re-tested by the unchanged code below.
1722
+ fixed = [_stray_pixel.correct_engine_image(c) for c in acc.images]
1723
+ for k, (c_new, removed) in enumerate(fixed):
1724
+ stray_removed.append(removed)
1725
+ if removed:
1726
+ # What a correction-off run writes as image_diam_minR (:1356).
1727
+ orig = measure_record([acc.images[k]], geom, reject_config,
1728
+ jit=kernels is not None)
1729
+ stray_uncorrected.append(orig.particles[0].minR * ds)
1730
+ acc.images[k] = c_new
1731
+ else:
1732
+ stray_uncorrected.append(np.nan)
1733
+ res = measure_record(acc.images, geom, reject_config,
1734
+ jit=kernels is not None) # :1204-1291
1735
+ diode_stats += res.diode_stats_total # :1210
1736
+ rect_ellipse: list[RectEllipse] | None = ( # :1293-1301
1737
+ [rect_ellipse_for_image(c, extended=bool(extended_ellipse_outputs))
1738
+ for c in acc.images]
1739
+ if iRectEllipse == 1 else None
1740
+ )
1741
+ _write_block(out, var, acc, res.particles, wstart, count, ds, tas_ratio_i,
1742
+ diode_stats, diodenum, iNewHabit, iCalcAllDiodeStats, iQC,
1743
+ rect_ellipse, extended_ellipse_outputs, probe.timing, probetype)
1744
+ if stray_fix:
1745
+ ncio.put_var(out, var["image_stray_pixels_removed"], wstart, count,
1746
+ np.asarray(stray_removed, dtype=np.int16)[:count])
1747
+ ncio.put_var(out, var["image_diam_minR_uncorrected"], wstart, count,
1748
+ np.asarray(stray_uncorrected, dtype=np.float64)[:count])
1749
+ total += count
1750
+ wstart = w + 1 # :1401
1751
+ kk = 1 # :1402
1752
+ # :1405 `clear images` -- acc goes out of scope either way.
1753
+
1754
+ return total
1755
+
1756
+
1757
+ #: ``:976-1074`` -- the GCPEx CIP clock-offset table, **new in v3.5** (Joe
1758
+ #: Finlon, 02/13/19); v3.1.4 has no GCPEx branch at all. Each entry is
1759
+ #: ``(month, day) -> (threshold, (hour, minute, second)) ...``, read in order,
1760
+ #: the first threshold the record's seconds-from-midnight falls under winning,
1761
+ #: with ``None`` as the final catch-all. Transcribed line by line from the
1762
+ #: vendored file; every value cites its own line.
1763
+ _GCPEX_CIP_TABLE: dict[tuple[int, int], tuple[tuple[float | None, tuple[int, int, int]], ...]] = {
1764
+ (1, 19): ((55660.09, (14, 40, 53)), # :980-981
1765
+ (62372.095, (15, 27, 46)), # :982-984
1766
+ (None, (17, 19, 33))), # :985-986
1767
+ (1, 28): ((57830.0, (15, 46, 36)), # :991-992
1768
+ (None, (16, 3, 50))), # :993-994
1769
+ (1, 30): ((None, (22, 36, 48)),), # :996-997
1770
+ (1, 31): ((4989.0, (-1, -23, -11)), # :1001-1002
1771
+ (5977.0, (1, 23, 9)), # :1003-1004
1772
+ (None, (1, 39, 37))), # :1005-1006
1773
+ (2, 12): ((13679.0, (2, 59, 0)), # :1011-1012
1774
+ (13733.0, (3, 47, 59)), # :1013-1014
1775
+ (17575.0, (3, 48, 53)), # :1015-1016
1776
+ (17693.0, (4, 52, 55)), # :1017-1018
1777
+ (18138.0, (4, 54, 53)), # :1019-1020
1778
+ (19843.0, (5, 2, 18)), # :1021-1022
1779
+ (19903.0, (5, 30, 43)), # :1023-1024
1780
+ (19942.0, (5, 31, 43)), # :1025-1026
1781
+ (20850.0, (5, 32, 22)), # :1027-1028
1782
+ (20994.0, (5, 47, 30)), # :1029-1030
1783
+ (21028.0, (5, 49, 54)), # :1031-1032
1784
+ (21642.0, (5, 50, 28)), # :1033-1034
1785
+ (None, (6, 0, 42))), # :1035-1036
1786
+ (2, 18): ((44534.0, (9, 38, 33)), # :1041-1042
1787
+ (57000.0, (12, 22, 14)), # :1043-1044
1788
+ (None, (15, 37, 35))), # :1045-1046
1789
+ (2, 24): ((48513.0, (11, 32, 3)), # :1051-1052
1790
+ (48868.0, (13, 28, 3)), # :1053-1054
1791
+ (49743.0, (13, 34, 28)), # :1055-1056
1792
+ (50088.0, (13, 49, 3)), # :1057-1058
1793
+ (52887.0, (13, 54, 48)), # :1059-1060
1794
+ (52958.0, (14, 41, 27)), # :1061-1062
1795
+ (53045.0, (14, 42, 38)), # :1063-1064
1796
+ (60000.0, (14, 44, 5)), # :1065-1066
1797
+ (71047.0, (16, 38, 49)), # :1067-1068
1798
+ (None, (19, 43, 38))), # :1069-1070
1799
+ }
1800
+
1801
+ #: ``:980-985`` -- the 01/19 chain is the ONE date whose thresholds are tested
1802
+ #: against ``recTime_secFromMidnight + handles.millisec/1000``; every other
1803
+ #: date tests the whole-second value alone. Read from the source, not
1804
+ #: generalised: applying the millisecond term to the other dates would move
1805
+ #: particles across a boundary at the sub-second level.
1806
+ _GCPEX_USES_MILLISEC = frozenset({(1, 19)})
1807
+
1808
+
1809
+ def _matlab_int16(x: float) -> float:
1810
+ """MATLAB's conversion of a double result to ``int16``: round half away
1811
+ from zero, then saturate to ``[-32768, 32767]``. Returned as a float.
1812
+ The rounding is :func:`arrayprobe_uiops.habit._matlab_round`, not
1813
+ ``floor(abs(x) + 0.5)``, which rounds ``0.49999999999999994`` up."""
1814
+ if math.isnan(x):
1815
+ return 0.0 # int16(NaN) is 0
1816
+ r = float(_matlab_round(x))
1817
+ return float(min(max(r, -32768.0), 32767.0))
1818
+
1819
+
1820
+ def gcpex_cip_offsets(rec: Any) -> tuple[int, int, int]:
1821
+ """``:976-1074`` -- ``(hour, minute, second)`` offset for one image record.
1822
+
1823
+ Source: ``imgProc_sm.m:976-1074`` (UIOOPS v3.5).
1824
+
1825
+ ``rec`` is :func:`arrayprobe_uiops.imgproc_core._read_record_header`'s dict, i.e. the
1826
+ record's own ``handles.month``/``day``/``hour``/``minute``/``second``/
1827
+ ``millisec`` -- never a particle-level time. A date with no entry returns
1828
+ ``(0, 0, 0)`` (``:1072-1073``).
1829
+ """
1830
+ key = (int(rec["month"]), int(rec["day"]))
1831
+ chain = _GCPEX_CIP_TABLE.get(key)
1832
+ if chain is None:
1833
+ return (0, 0, 0) # :1072-1073
1834
+ t = rec["hour"] * 3600 + rec["minute"] * 60 + rec["second"] # :978-979
1835
+ if key in _GCPEX_USES_MILLISEC:
1836
+ # :980-985 -- `handles.millisec` comes from `netcdf.getVar` on a
1837
+ # `'short'` variable (read_binary_DMT.m:41), so it is int16:
1838
+ # `millisec/1000.` is int16 and `recTime + (...)` is int16 too, both
1839
+ # rounded half away from zero and saturated. The sum therefore never
1840
+ # exceeds 32767, every 01/19 record takes the first branch, and
1841
+ # :982-986 are dead (Octave golden tests/data/
1842
+ # v35_gcpex_time_octave_golden.json, "nc" rows). Pass 6.
1843
+ t = _matlab_int16(t + _matlab_int16(float(rec["millisec"]) / 1000.0))
1844
+ for threshold, offsets in chain:
1845
+ if threshold is None or t < threshold:
1846
+ return offsets
1847
+ raise AssertionError( # pragma: no cover -- every chain ends with None
1848
+ f"imgProc_sm.m:976-1074: no GCPEx branch matched {key} at t={t}"
1849
+ )
1850
+
1851
+
1852
+ def _normalise_part_time(acc: _Record) -> None:
1853
+ """``:1081-1093`` -- the carry/borrow fixup, **new in v3.5** and GCPEx-CIP only.
1854
+
1855
+ Three things about it are load-bearing and easy to get wrong:
1856
+
1857
+ * it is a **whole-vector** assignment, not an ``(kk)`` one, so every
1858
+ particle accumulated so far in the current record is re-normalised on
1859
+ every subsequent particle;
1860
+ * the masks are recomputed between the ``>= 60`` pair and the ``< 0`` pair
1861
+ (``part_sec`` has moved in between), but *not* within a pair;
1862
+ * the hour wrap (``:1089``, ``:1093``) reads the hour that ``:1087`` /
1863
+ ``:1091`` has just written.
1864
+ """
1865
+ ph = acc.part_hour.asarray()
1866
+ pm = acc.part_min.asarray()
1867
+ ps = acc.part_sec.asarray()
1868
+ n = ph.size
1869
+ if n == 0: # pragma: no cover -- called only after part_hour(kk) is set
1870
+ return
1871
+
1872
+ m = ps >= 60 # :1081-1082
1873
+ pm[m] += 1
1874
+ ps[m] -= 60
1875
+ m = ps < 0 # :1084-1085
1876
+ pm[m] -= 1
1877
+ ps[m] += 60
1878
+ m = pm >= 60 # :1087-1088
1879
+ ph[m] += 1
1880
+ pm[m] -= 60
1881
+ ph[ph >= 24] -= 24 # :1089
1882
+ m = pm < 0 # :1091-1092
1883
+ ph[m] -= 1
1884
+ pm[m] += 60
1885
+ ph[ph < 0] += 24 # :1093
1886
+
1887
+ acc.part_hour[1:n] = ph
1888
+ acc.part_min[1:n] = pm
1889
+ acc.part_sec[1:n] = ps
1890
+
1891
+
1892
+ def _particle_time_dmt_v35(acc: _Record, kk: Any, data: Any, start: Any, rec: Any,
1893
+ projectname: Any, probename: Any,
1894
+ time_in_seconds_prev: Any, to_chars: Any = dec2bin_concat) -> Any:
1895
+ """``:935-1115`` -- the probetype-1 (CIP/PIP) branch.
1896
+
1897
+ ``to_chars`` is ``dec2bin_concat`` (the reference) or a JIT drop-in
1898
+ (see :func:`_process_records`).
1899
+
1900
+ **This is the one probetype whose timing v3.5 genuinely changed**, in two
1901
+ ways, both dated 02/13/19 by Joe Finlon and both absent from v3.1.4:
1902
+
1903
+ * the GCPEx CIP offset table :data:`_GCPEX_CIP_TABLE` and its
1904
+ :func:`_normalise_part_time` fixup (``:976-1093``);
1905
+ * ``images.int_arrival`` is now differenced against
1906
+ ``time_in_seconds_prev``, which is never cleared at ``:1402`` and so
1907
+ **carries across record boundaries** inside a chunk -- v3.1.4 reset it to
1908
+ 0 for the first particle of every record (``:704-708``). So the first
1909
+ particle of every record but the first now gets a real inter-arrival
1910
+ time instead of a zero. Returns the new ``time_in_seconds_prev``.
1911
+
1912
+ Everything else here (``:936-943``, ``:946-973``, ``:1096-1100``) is
1913
+ byte-identical to v3.1.4's ``:654-701``. Reads from ``start-1`` (MATLAB
1914
+ 1-based), not ``header_loc``.
1915
+ """
1916
+ s = start - 2 # data(start-1, ...) MATLAB 1-based -> Python row index.
1917
+
1918
+ bin_convert = to_chars(data[s:s + 1, 1:6], 8) # :936-937
1919
+ acc.part_hour[kk] = bin2dec(bin_convert[:, 0:5]) # :939
1920
+ acc.part_min[kk] = bin2dec(bin_convert[:, 5:11]) # :940
1921
+ acc.part_sec[kk] = bin2dec(bin_convert[:, 11:17]) # :941
1922
+ acc.part_mil[kk] = bin2dec(bin_convert[:, 17:27]) # :942
1923
+ # :943. Despite the name and the 'microsec' netCDF attribute, this is
1924
+ # SECONDS -- a 13-bit count times 125e-9 (A13). Preserved, not rescaled.
1925
+ acc.part_micro[kk] = bin2dec(bin_convert[:, 27:40]) * 125e-9
1926
+
1927
+ if projectname == "PECAN" and probename == "PIP": # :946-973
1928
+ # Byte-identical to v3.1.4 :665-693, so its translation is reused.
1929
+ # Only the hour offset is ever non-zero in the table.
1930
+ acc.part_hour[kk] = _pecan_pip_hour_offset(rec, acc.part_hour[kk])
1931
+ elif projectname == "GCPEx" and probename == "CIP": # :976-1093
1932
+ d_h, d_m, d_s = gcpex_cip_offsets(rec)
1933
+ acc.part_hour[kk] = acc.part_hour[kk] + d_h # :1077
1934
+ acc.part_min[kk] = acc.part_min[kk] + d_m # :1078
1935
+ acc.part_sec[kk] = acc.part_sec[kk] + d_s # :1079
1936
+ _normalise_part_time(acc) # :1081-1093
1937
+
1938
+ acc.particle_sliceCount[kk] = float(int(data[s, 0]) & 127) # :1096
1939
+ acc.particle_DOF[kk] = float(int(data[s, 0]) & 128) # :1097
1940
+ # :1098 -- the same dec2bin(_,8)/bin2dec idiom, not a plain 256*hi+lo.
1941
+ acc.particle_partNum[kk] = bin2dec(to_chars(data[s:s + 1, 6:8], 8))
1942
+
1943
+ t = float(acc.part_hour[kk] * 3600 + acc.part_min[kk] * 60 + acc.part_sec[kk]
1944
+ + acc.part_mil[kk] / 1000 + acc.part_micro[kk]) # :1100
1945
+ acc.time_in_seconds[kk] = t
1946
+ # :1110-1114 -- `exist('time_in_seconds_prev','var')` is false only for the
1947
+ # very first particle of the whole chunk.
1948
+ acc.int_arrival[kk] = 0.0 if time_in_seconds_prev is None else t - time_in_seconds_prev
1949
+ return t # :1115
1950
+
1951
+
1952
+ def _percent_shadow(p: ParticleMeasurement) -> float:
1953
+ """``:1303-1309`` -- overwrites the reject function's value with the
1954
+ area-equivalent circle ratio, real pi."""
1955
+ if p.image_length > p.image_width:
1956
+ return p.image_area / (np.pi * p.image_length ** 2 / 4)
1957
+ if p.image_width != 0:
1958
+ return p.image_area / (np.pi * p.image_width ** 2 / 4)
1959
+ return 0.0
1960
+
1961
+
1962
+ def _touching_edge_minus_zero(v: Any) -> int:
1963
+ """``:1351`` -- ``images.image_touching_edge - '0'``: a char ``'0'``/``'t'``,
1964
+ or the numeric initialiser 0 from the zero-slice path, which writes -48."""
1965
+ if isinstance(v, str):
1966
+ return ord(v) - ord("0")
1967
+ return int(v) - ord("0")
1968
+
1969
+
1970
+ def _particle_time_write_v35(acc: _Record, timing: str) -> Any:
1971
+ """``:1336`` -- ``part_hour(:)*10000+part_min(:)*100+part_sec(:)``.
1972
+
1973
+ The A15 int8 saturation is v3.1.4's finding and survives unchanged into
1974
+ v3.5, because the lines that cause it are byte-identical: ``:906-908``
1975
+ seeds ``part_hour``/``part_min``/``part_sec`` from ``handles.hour``/
1976
+ ``minute``/``second``, which ``netcdf.getVar`` returns as int8 for the
1977
+ PMS raw format (``read_binary_PMS.m``, itself byte-identical between the
1978
+ two releases -- **measured**), MATLAB array-growth inherits the class, and
1979
+ MATLAB integer arithmetic saturates. So probetypes 0 and 3 write 127 for
1980
+ virtually every real record, exactly as they do under v3.1.4. Probetype 1
1981
+ escapes because ``bin2dec`` returns double; probetype 2 because
1982
+ ``:1125-1128`` assigns literal zeros.
1983
+ """
1984
+ ph, pm, ps = acc.part_hour.asarray(), acc.part_min.asarray(), acc.part_sec.asarray()
1985
+ if timing not in ("pms", "fast2dc"):
1986
+ return ph * 10000 + pm * 100 + ps
1987
+ return madd(madd(mmul(mint8(ph), 10000), mmul(mint8(pm), 100)), mint8(ps))
1988
+
1989
+
1990
+ def _write_block(out: Any, var: Any, acc: _Record, parts: list[ParticleMeasurement],
1991
+ wstart: Any, count: Any,
1992
+ ds: Any, tas_ratio_i: Any, diode_stats: Any, diodenum: Any,
1993
+ iNewHabit: Any, iCalcAllDiodeStats: Any, # noqa: N803
1994
+ iQC: Any, rect_ellipse: list[RectEllipse] | None, # noqa: N803
1995
+ extended_ellipse_outputs: bool | None, timing: str, probetype: int) -> None:
1996
+ """``:1323-1398`` -- one record's particles, in **putVar order**."""
1997
+ def put(name: Any, values: Any) -> None:
1998
+ ncio.put_var(out, var[name], wstart, count, np.asarray(values)[:count])
1999
+
2000
+ def col(attr: Any) -> Any:
2001
+ return [getattr(p, attr) for p in parts]
2002
+
2003
+ put("Time", acc.rec_time) # :1323
2004
+ put("Date", acc.rec_date) # :1324
2005
+ put("Time_in_seconds", acc.time_in_seconds.asarray()) # :1326
2006
+ put("SliceCount", acc.particle_sliceCount.asarray()) # :1327
2007
+ put("DMT_DOF_SPEC_OVERLOAD", acc.particle_DOF.asarray()) # :1328
2008
+ if probetype not in (0, 3): # :1329-1331
2009
+ put("Particle_number_all", acc.particle_partNum.asarray())
2010
+ put("msec", acc.rec_millisec) # :1333
2011
+ ncio.write_record_block(out, var["position"], wstart,
2012
+ np.asarray(acc.position, dtype=np.int64)[:count]) # :1335
2013
+ put("particle_time", _particle_time_write_v35(acc, timing)) # :1336
2014
+ put("particle_millisec", acc.part_mil.asarray()) # :1337
2015
+ put("particle_microsec", acc.part_micro.asarray()) # :1338
2016
+ put("parent_rec_num", acc.parent_rec_num) # :1339
2017
+ put("particle_num", acc.particle_num) # :1340
2018
+ if iQC == 1: # :1341-1344
2019
+ put("subparticle_num", acc.num_subparticles)
2020
+ put("subparticle_mindist", acc.dist_min)
2021
+ put("image_length", col("image_length")) # :1345
2022
+ put("image_width", col("image_width")) # :1346
2023
+ put("image_area", np.asarray(col("image_area")) * ds * ds / tas_ratio_i) # :1347
2024
+ put("image_longest_y", col("longest_y_within_a_slice")) # :1348
2025
+ put("image_max_top_edge_touching", col("max_top_edge_touching")) # :1349
2026
+ put("image_max_bottom_edge_touching", col("max_bottom_edge_touching")) # :1350
2027
+ put("image_touching_edge", # :1351
2028
+ [_touching_edge_minus_zero(p.image_touching_edge) for p in parts])
2029
+ put("image_auto_reject", [ord(p.auto_reject) for p in parts]) # :1352
2030
+ put("image_hollow", col("is_hollow")) # :1353
2031
+ put("image_center_in", col("center_in")) # :1354
2032
+ put("image_axis_ratio", col("axis_ratio")) # :1355
2033
+ put("image_diam_minR", np.asarray(col("minR")) * ds) # :1356
2034
+ put("image_diam_AreaR", np.asarray(col("AreaR")) * ds) # :1357
2035
+ put("image_perimeter", np.asarray(col("Perimeter")) * ds) # :1358
2036
+ put("image_xpos", col("ctx")) # :1359 -- unscaled
2037
+ put("image_ypos", col("cty")) # :1360 -- unscaled
2038
+ if rect_ellipse is not None: # :1361-1374
2039
+ put("image_RectangleL", [ds * r.rect_l for r in rect_ellipse])
2040
+ put("image_RectangleW", [ds * r.rect_w for r in rect_ellipse])
2041
+ put("image_RectangleAngle", [r.rect_angle for r in rect_ellipse])
2042
+ if extended_ellipse_outputs: # :1367-1370
2043
+ put("image_EllipseX", [r.ell_x for r in rect_ellipse]) # unscaled
2044
+ put("image_EllipseY", [r.ell_y for r in rect_ellipse]) # unscaled
2045
+ put("image_EllipseL", [ds * r.ell_l for r in rect_ellipse])
2046
+ put("image_EllipseW", [ds * r.ell_w for r in rect_ellipse])
2047
+ put("image_EllipseAngle", [r.ell_angle for r in rect_ellipse])
2048
+ put("percent_shadow_area", [_percent_shadow(p) for p in parts]) # :1375
2049
+ # :1376-1377 -- THE SWAP, unchanged from v3.1.4. varid29 is
2050
+ # edge_at_max_hole and receives max_hole_diameter; varid30 is
2051
+ # max_hole_diameter and receives edge_at_max_hole. Preserved.
2052
+ put("edge_at_max_hole", col("max_hole_diameter"))
2053
+ put("max_hole_diameter", col("edge_at_max_hole"))
2054
+ put("part_z", col("part_z")) # :1378
2055
+ put("size_factor", col("sf")) # :1379
2056
+ put("holroyd_habit", [ord(p.holroyd_habit) for p in parts]) # :1380
2057
+ put("fine_detail_ratio", col("FS")) # :1381
2058
+ put("sphericity", col("sphericity")) # :1382
2059
+ if iNewHabit == 1: # :1383-1391
2060
+ nh: list[HolroydNewResult] = []
2061
+ for p in parts:
2062
+ # geom.i_new_habit == 1 (the caller of measure_record, above)
2063
+ # guarantees :func:`arrayprobe_uiops.measure._habit_call` always
2064
+ # returns a populated ``HolroydNewResult`` -- ``new_habit`` is
2065
+ # ``None`` only on the ``i_new_habit == 0`` path.
2066
+ assert p.new_habit is not None
2067
+ nh.append(p.new_habit)
2068
+ put("width_length_percentile", np.asarray([r.w_l_p for r in nh]) * ds)
2069
+ put("circle_area_ratio", [r.c_r for r in nh])
2070
+ put("edge_maximum_dimension_ratio", [r.e_d_r for r in nh])
2071
+ put("maximum_gap", np.asarray([r.m_g for r in nh]) * ds)
2072
+ put("opacity_coefficient", [r.O for r in nh])
2073
+ put("aspect_ratio", [r.a_r for r in nh])
2074
+ put("holroyd_perimeter", np.asarray([r.p for r in nh]) * ds)
2075
+ put("area_hole_ratio", col("area_hole_ratio")) # :1392
2076
+ put("inter_arrival", acc.int_arrival.asarray()) # :1393
2077
+ ncio.put_var(out, var["bin_stats"], diode_stats) # :1394 -- whole, every record
2078
+ if iCalcAllDiodeStats: # :1396-1398
2079
+ block = np.asarray([p.diode_stats for p in parts], dtype=np.float64)[:count]
2080
+ ncio.write_record_block(out, var["image_bin_stats"], wstart,
2081
+ block.reshape(count, diodenum))