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,860 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """MATLAB language semantics that NumPy does not reproduce.
3
+
4
+ This module exists so that a line-by-line transliteration of UIOOPS v3.1.4 keeps
5
+ MATLAB's behaviour, including its bugs. Every helper carries the file:line of
6
+ the UIOOPS call site that motivates it. MATLAB source of truth:
7
+ ``UIOPS-v3.1.4/joefinlon-UIOPS-ba5e67c/``.
8
+
9
+
10
+
11
+ Fidelity doctrine: preserve bugs, do not fix them. A "fix" that changes output
12
+ is a defect here. Behaviour-changing deviations belong behind opt-in flags that
13
+ default OFF.
14
+
15
+ Integer semantics below were verified in Octave 11.3.0 on 2026-08-19 (Octave
16
+ implements MATLAB-compatible saturating integer arithmetic)::
17
+
18
+ class(int16(37)*0.010) -> int16 int16(37)*0.010 -> 0
19
+ int16(50)*0.010 -> 1 int16(-50)*0.010 -> -1
20
+ int16(300)^2 -> 32767 int16(5)/int16(2) -> 3
21
+ sqrt(int16(10)) -> 3.1623 (a DOUBLE -- sqrt promotes)
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import datetime as _dt
27
+ import math
28
+
29
+ import numpy as np
30
+
31
+ __all__ = [
32
+ "mround", "mint8", "mint16", "mint32", "mdouble",
33
+ "madd", "msub", "mmul", "mdiv", "mpow", "msqrt", "mmax",
34
+ "mcolon", "mfind",
35
+ "dec2bin", "dec2bin_concat", "dec2bin_bits", "bin2dec",
36
+ "nansum", "nanmean",
37
+ "datenum", "datestr",
38
+ "mchar", "REJECT_CODES", "REJECT_CODE_WORDS", "UNREACHABLE_REJECT_CODES", "HOLROYD_HABITS",
39
+ "mvertcat", "mhorzcat", "mdiff",
40
+ "MGrowVector",
41
+ "to0", "to1",
42
+ "MatlabIndexError",
43
+ ]
44
+
45
+
46
+ class MatlabIndexError(IndexError):
47
+ """Raised where MATLAB raises ``Index exceeds matrix dimensions``.
48
+
49
+ A run that would have died in MATLAB must die here too: returning a
50
+ truncated result instead would silently turn a failed run into a
51
+ plausible-looking one.
52
+
53
+ Three call sites so far. The earlier translation's SPEC reader raises it under
54
+ :attr:`~arrayprobe.profiles.FidelityProfile.spec_buffer_guard` ``False``
55
+ (the production variant, which predates the 2017-03-08 guards);
56
+ ``dropsize.py`` raises it for a negative chord, where ``dropsize.m:220-222``
57
+ indexes its lookup tables with ``round(chord * 10)`` and never checks the
58
+ sign; and the earlier translation's ``sizeDist`` raises it for a single-particle last block
59
+ under
60
+ ``tree='production'``, where the production-variant ``sizeDist.m:713-716`` indexes
61
+ an empty ``diff`` result at ``end`` == 0 (an earlier port version had
62
+ been applying stock's Finlon 02/09/18 guard to a tree that has none, so it
63
+ completed where MATLAB aborts).
64
+ """
65
+
66
+
67
+ # --------------------------------------------------------------------------
68
+ # Rounding and integer casts
69
+ # --------------------------------------------------------------------------
70
+
71
+ def mround(x):
72
+ """MATLAB ``round``: half away from zero, elementwise.
73
+
74
+ Python and NumPy round half to even -- ``np.round(2.5) == 2`` but MATLAB
75
+ ``round(2.5) == 3``.
76
+
77
+ ``floor(abs(x) + 0.5)`` is NOT this function: the addition itself rounds, so
78
+ ``0.49999999999999994`` and every odd integer above 2^52 came out one too
79
+ high (the same defect a review fixed in the v3.5 helpers, its findings
80
+ 2 and 6). ``abs(x) - floor(abs(x))`` is exact for every finite double, so the
81
+ half is tested on that instead.
82
+
83
+ Provenance: ``dropsize.m:198`` and ``dropsize.m:219``, where the result is
84
+ used directly as a 1-based lookup-table index (``dropsize.m:199-200,220-221``),
85
+ so an off-by-one changes the reported diameter. ``dropsize`` is called from
86
+ ``imgProc_sm.m:834``.
87
+ """
88
+ a = np.asarray(x, dtype=np.float64)
89
+ out = np.sign(a) * _round_abs_half_up(np.abs(a))
90
+ # sign(0)*... is 0.0, and NaN/inf propagate unchanged.
91
+ return out if out.ndim else out[()]
92
+
93
+
94
+ def _round_abs_half_up(a):
95
+ """``round`` of a non-negative array, half up, with no rounding in the test:
96
+ ``a - floor(a)`` is exact for every finite double. NaN and inf pass through
97
+ (``inf - inf`` is NaN, which compares False, so ``floor(inf)`` is kept)."""
98
+ f = np.floor(a)
99
+ with np.errstate(invalid="ignore"):
100
+ return f + (a - f >= 0.5)
101
+
102
+
103
+ def _saturating_cast(x, dtype):
104
+ """MATLAB integer cast: round half away from zero, then saturate.
105
+
106
+ MATLAB never wraps on integer overflow -- it clamps to the type's range.
107
+ ``int16(300)^2`` is 32767, not 90000 and not the wrapped 24464.
108
+ """
109
+ info = np.iinfo(dtype)
110
+ a = np.asarray(x, dtype=np.float64)
111
+ r = np.sign(a) * _round_abs_half_up(np.abs(a))
112
+ # NaN casts to 0 in MATLAB; +/-inf saturate.
113
+ r = np.where(np.isnan(r), 0.0, r)
114
+ r = np.clip(r, info.min, info.max)
115
+ out = r.astype(dtype)
116
+ return out if out.ndim else out[()]
117
+
118
+
119
+ def mint8(x):
120
+ """MATLAB ``int8(x)`` -- rounds half away from zero, saturates."""
121
+ return _saturating_cast(x, np.int8)
122
+
123
+
124
+ def mint16(x):
125
+ """MATLAB ``int16(x)``.
126
+
127
+ Provenance: ``imgProc_sm.m:898`` ``int16(images.auto_reject)`` and
128
+ ``imgProc_sm.m:923`` ``int16(images.holroyd_habit)``.
129
+ """
130
+ return _saturating_cast(x, np.int16)
131
+
132
+
133
+ def mint32(x):
134
+ """MATLAB ``int32(x)``."""
135
+ return _saturating_cast(x, np.int32)
136
+
137
+
138
+ def mdouble(x):
139
+ """MATLAB ``double(x)``."""
140
+ out = np.asarray(x, dtype=np.float64)
141
+ return out if out.ndim else out[()]
142
+
143
+
144
+ # --------------------------------------------------------------------------
145
+ # Integer-contaminating arithmetic (design doc trap T1)
146
+ # --------------------------------------------------------------------------
147
+
148
+ def _int_dtype_of(*operands):
149
+ """Return the MATLAB integer dtype governing a binary op, or None.
150
+
151
+ In MATLAB an integer operand wins over a double operand: the result keeps
152
+ the integer type, rounding half away from zero and saturating. Verified in
153
+ Octave: ``class(int16(37)*0.010)`` is ``int16``.
154
+
155
+ CALLER TRAP: a bare Python ``int`` literal (``2``, not ``2.0``) becomes an
156
+ integer-dtype NumPy scalar and will be picked up here as though it were a
157
+ MATLAB integer-typed operand -- even though a numeric literal in MATLAB
158
+ source is ``double``. Found 2026-08-27 porting ``sizeDist.m:760``
159
+ (``.../2 * diodesize``): ``mdiv(sum_array, 2)`` silently forced integer
160
+ rounding on an already-``double`` ``sum_array``. Always pass ``2.0``, not
161
+ ``2``, for a MATLAB literal operand.
162
+ """
163
+ for op in operands:
164
+ dt = np.asarray(op).dtype
165
+ if np.issubdtype(dt, np.integer):
166
+ return dt
167
+ return None
168
+
169
+
170
+ def _binary(a, b, fn):
171
+ dt = _int_dtype_of(a, b)
172
+ raw = fn(np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64))
173
+ if dt is None:
174
+ return raw if raw.ndim else raw[()]
175
+ return _saturating_cast(raw, dt)
176
+
177
+
178
+ def madd(a, b):
179
+ """MATLAB ``a + b`` with integer dominance and saturation."""
180
+ return _binary(a, b, np.add)
181
+
182
+
183
+ def msub(a, b):
184
+ """MATLAB ``a - b`` with integer dominance and saturation."""
185
+ return _binary(a, b, np.subtract)
186
+
187
+
188
+ def mmul(a, b):
189
+ """MATLAB ``a .* b`` with integer dominance and saturation.
190
+
191
+ This is the integer-saturation trap. ``sizeDist.m:770-771`` reads
192
+ ``image_width``/``image_length``, declared ``'short'`` (int16) at
193
+ ``imgProc_sm.m:295,299``. With ``diodesize == 0.010`` for the 2DS
194
+ (``sizeDist.m:179,264,368``), ``sizeDist.m:882,884,886,890`` produce an
195
+ int16 array that is almost entirely ZERO. That contaminates ``area_ratio``
196
+ at ``sizeDist.m:984`` and therefore ``auto_reject`` at ``:985``.
197
+
198
+ Only ``d_choice == 6`` (``sizeDist.m:892``) escapes -- which is exactly what
199
+ ``run_sizeDist_Munich.m:16`` uses, presumably why the bug survived. NumPy
200
+ would give float64 here and silently FIX the bug, breaking bit-for-bit
201
+ comparison against the reference output.
202
+ """
203
+ return _binary(a, b, np.multiply)
204
+
205
+
206
+ def mdiv(a, b):
207
+ """MATLAB ``a ./ b`` with integer dominance, rounding and saturation.
208
+
209
+ MATLAB integer division ROUNDS, it does not truncate:
210
+ ``int16(5)/int16(2) == 3``. Verified in Octave.
211
+ """
212
+ with np.errstate(divide="ignore", invalid="ignore"):
213
+ return _binary(a, b, np.divide)
214
+
215
+
216
+ def mpow(a, b):
217
+ """MATLAB ``a .^ b`` with integer dominance and saturation.
218
+
219
+ ``int16(300)^2 == 32767``. Relevant at ``sizeDist.m:888``, where
220
+ ``im_width.^2 + im_length.^2`` saturates before the sqrt.
221
+ """
222
+ return _binary(a, b, np.power)
223
+
224
+
225
+ def msqrt(x):
226
+ """MATLAB ``sqrt`` -- PROMOTES an integer argument to double.
227
+
228
+ This does NOT follow the saturating-integer rule that mmul/mpow follow.
229
+ Verified in Octave: ``sqrt(int16(10))`` is 3.1623, class ``double``.
230
+
231
+ Consequence for ``sizeDist.m:888``
232
+ (``sqrt(im_width.^2+im_length.^2) * diodesize``): the squares and their sum
233
+ saturate as int16, sqrt then promotes to double, and the final multiply
234
+ stays double. So ``d_choice == 4`` escapes the zero-collapse that hits
235
+ d_choice 1, 2, 3 and 5 -- but carries int16 saturation INSIDE the radicand,
236
+ which bites once im_width or im_length exceeds 181 diodes.
237
+ """
238
+ with np.errstate(invalid="ignore"):
239
+ out = np.sqrt(np.asarray(x, dtype=np.float64))
240
+ return out if out.ndim else out[()]
241
+
242
+
243
+ def mmax(a, b):
244
+ """MATLAB two-argument ``max`` with integer dominance.
245
+
246
+ Provenance: ``sizeDist.m:890`` ``max(im_width, im_length) * diodesize``.
247
+ """
248
+ return _binary(a, b, np.maximum)
249
+
250
+
251
+ # --------------------------------------------------------------------------
252
+ # The colon operator and find
253
+ # --------------------------------------------------------------------------
254
+
255
+ def _first_or_empty(v):
256
+ """MATLAB collapses a vector colon operand to its first element."""
257
+ a = np.atleast_1d(np.asarray(v))
258
+ if a.size == 0:
259
+ return None
260
+ return a.reshape(-1)[0]
261
+
262
+
263
+ def mcolon(a, b, step=1):
264
+ """MATLAB ``a:b`` including its operand-collapsing rule.
265
+
266
+ MATLAB uses only the FIRST element of a vector operand, and yields an empty
267
+ range if either operand is empty. Returns a 1-based integer ndarray; use
268
+ :func:`to0` at the array boundary.
269
+
270
+ All four call sites are latent UIOOPS bugs preserved deliberately:
271
+
272
+ * ``sizeDist.m:98-99`` ``timehhmmss(find(diff(timehhmmss)<0)+1:end)``
273
+ * ``sizeDist.m:657-658`` same, on ``image_time_hhmmssall``
274
+ * ``sizeDist.m:1036`` the reacceptance loop over the shattering events,
275
+ whose range runs from the first ``find`` of the event starts to the first
276
+ ``find`` of the event ends
277
+ * ``sizeDist.m:1169`` same, in the fixed-threshold branch
278
+
279
+ In sites 1 and 2 an empty ``find`` makes the whole assignment a silent
280
+ no-op, so this must not raise. In sites 3 and 4 a descending range (an
281
+ event that ends before the first one begins) yields an empty loop.
282
+ """
283
+ lo = _first_or_empty(a)
284
+ hi = _first_or_empty(b)
285
+ if lo is None or hi is None:
286
+ return np.array([], dtype=np.int64)
287
+ return np.arange(lo, hi + (1 if step > 0 else -1), step, dtype=np.int64)
288
+
289
+
290
+ def mfind(condition):
291
+ """MATLAB ``find``: 1-based indices of nonzero elements.
292
+
293
+ Orientation follows MATLAB: a row input gives a row, anything else gives a
294
+ column. Orientation matters downstream -- ``sizeDist.m:686``
295
+ ``start_all = find(startindex)-1`` and ``IntArrAnalysis.m:37-38``.
296
+ """
297
+ a = np.asarray(condition)
298
+ idx = np.flatnonzero(a) + 1
299
+ if a.ndim == 2 and a.shape[0] == 1:
300
+ return idx.reshape(1, -1)
301
+ return idx.reshape(-1, 1) if a.ndim == 2 else idx
302
+
303
+
304
+ # --------------------------------------------------------------------------
305
+ # Binary string conversion
306
+ # --------------------------------------------------------------------------
307
+
308
+ _ZERO = ord("0")
309
+ _ONE = ord("1")
310
+
311
+
312
+ def dec2bin(v, width=None):
313
+ """MATLAB ``dec2bin(V, N)`` -> ``(M, W)`` uint8 array of ASCII '0'/'1'.
314
+
315
+ ``width`` is a MINIMUM, not a maximum: MATLAB widens rather than truncating
316
+ when a value needs more bits. ``imgProc_sm.m:568-571`` depends on this --
317
+ it compares ``size(c,2)`` against ``diodenum`` and RETURNS from the whole
318
+ function on mismatch. Masking to N bits would make that guard dead code.
319
+
320
+ Raises ValueError on negative input, matching MATLAB. Reachable at
321
+ ``imgProc_sm.m:562`` via ``65535 - data(start:j-1,:)``.
322
+
323
+ Returns ASCII codes so that call sites transliterate directly:
324
+ ``imgProc_sm.m:802,804,805`` do ``sum(c=='0',1)``.
325
+
326
+ Provenance: ``imgProc_sm.m:556`` (2DC, 4x8), ``:559-560`` (2DS/Fast2DC, 8x8),
327
+ ``:563-564`` (HVPS, 8x16), ``:582``, ``:589-590``, ``:655-656``, ``:699``;
328
+ ``calculate_reject_unified.m:491,642`` call it without a width.
329
+ """
330
+ a = np.atleast_1d(np.asarray(v))
331
+ if a.size and np.any(a < 0):
332
+ raise ValueError(
333
+ "dec2bin: negative input (MATLAB errors here; reachable at "
334
+ "imgProc_sm.m:562 when data exceeds 65535)"
335
+ )
336
+ vals = a.reshape(-1).astype(np.int64)
337
+ needed = 1 if vals.size == 0 else max(1, int(max(vals, default=0)).bit_length())
338
+ w = needed if width is None else max(int(width), needed)
339
+ shifts = np.arange(w - 1, -1, -1, dtype=np.int64)
340
+ bits = (vals[:, None] >> shifts[None, :]) & 1
341
+ return (bits + _ZERO).astype(np.uint8)
342
+
343
+
344
+ def dec2bin_bits(v, width=None):
345
+ """Boolean form of :func:`dec2bin` for the hot path (True == '1')."""
346
+ return dec2bin(v, width) == _ONE
347
+
348
+
349
+ def dec2bin_concat(columns, width):
350
+ """The ``[dec2bin(X(:,1),w), dec2bin(X(:,2),w), ...]`` idiom, fused.
351
+
352
+ Returns the ``(nslices, ncols*width)`` char matrix MATLAB calls ``c``.
353
+ Provenance: ``imgProc_sm.m:556``, ``:559-560``, ``:563-564``.
354
+ """
355
+ cols = np.asarray(columns)
356
+ if cols.ndim == 1:
357
+ cols = cols.reshape(-1, 1)
358
+ return np.hstack([dec2bin(cols[:, k], width) for k in range(cols.shape[1])])
359
+
360
+
361
+ def bin2dec(chars):
362
+ """MATLAB ``bin2dec``. Row -> float scalar; ``(M,N)`` -> ``(M,)`` float64.
363
+
364
+ Returns double, as MATLAB does. UIOOPS never exceeds 40 bits
365
+ (``imgProc_sm.m:591``), so double precision is exact throughout.
366
+
367
+ Provenance: ``imgProc_sm.m:583``, ``:591``, ``:658-662`` (1-based inclusive
368
+ substring slices of a 1x40 row), ``:699``;
369
+ ``calculate_reject_unified.m:465-485,599-635``.
370
+ """
371
+ if isinstance(chars, str):
372
+ a = np.frombuffer(chars.encode("ascii"), dtype=np.uint8).reshape(1, -1)
373
+ else:
374
+ a = np.asarray(chars, dtype=np.uint8)
375
+ if a.ndim == 1:
376
+ a = a.reshape(1, -1)
377
+ bits = (a == _ONE).astype(np.float64)
378
+ w = a.shape[1]
379
+ weights = np.power(2.0, np.arange(w - 1, -1, -1, dtype=np.float64))
380
+ out = bits @ weights
381
+ return float(out[0]) if out.size == 1 else out
382
+
383
+
384
+ # --------------------------------------------------------------------------
385
+ # NaN-aware reductions
386
+ # --------------------------------------------------------------------------
387
+
388
+ def _matlab_axis(x, dim):
389
+ """MATLAB reduces along the first non-singleton dimension by default."""
390
+ a = np.asarray(x)
391
+ if dim is not None:
392
+ return a, int(dim) - 1 # MATLAB dims are 1-based
393
+ if a.ndim <= 1:
394
+ return a, 0
395
+ for i, n in enumerate(a.shape):
396
+ if n != 1:
397
+ return a, i
398
+ return a, 0
399
+
400
+
401
+ def msum(x, dim=None):
402
+ """MATLAB ``sum``, accumulated **in order**.
403
+
404
+ NumPy sums pairwise: it splits the array into blocks and adds partial sums,
405
+ which is more accurate and is *not* what MATLAB or Octave do. Both walk the
406
+ vector once, so the two disagree by 1-5 ULP on a long row -- invisible until
407
+ a bit-exactness claim rests on it. S4 measured it: with ``np.nansum``, 20 of
408
+ 4,110 values of ``sizeDist``'s ``n`` and 23 of ``re`` missed the Octave
409
+ oracle by 2-5 ULP; accumulating in order made all three variables exact.
410
+
411
+ ``np.cumsum`` is the sequential accumulator, and taking its last element is
412
+ the whole reduction -- vectorised, and verified equal to a Python loop across
413
+ sizes 3 to 5,000 and eight decades of magnitude.
414
+
415
+ ``dim`` is 1-based; None means MATLAB's first-non-singleton rule.
416
+ """
417
+ a, axis = _matlab_axis(x, dim)
418
+ a = np.asarray(a, dtype=np.float64)
419
+ if a.size == 0:
420
+ # A 1-D empty input has no surviving dimension to preserve -- MATLAB's
421
+ # own `sum([])` is the scalar 0. But for ndim>=2 (e.g. sizeDist.py's
422
+ # (n_sec, num_bins) accumulators under a degenerate zero-second
423
+ # window), MATLAB's `sum` along an empty axis keeps the OTHER
424
+ # dimensions' shape: `sum(zeros(0,5), 2)` is `0x1`, not a bare 0.
425
+ # Found 2026-08-27: the old `if a.shape[axis]==0: return zeros(...)`
426
+ # below this comment was unreachable dead code, because any
427
+ # zero-length axis already makes `a.size == 0` and this branch fires
428
+ # first -- silently collapsing a shape-preserving empty result to a
429
+ # bare float wherever a sibling axis (not just the reduced one) was
430
+ # the one that was empty.
431
+ survivor_shape = np.delete(a.shape, axis)
432
+ if survivor_shape.size == 0:
433
+ return 0.0
434
+ return np.zeros(tuple(survivor_shape), dtype=np.float64)
435
+ return np.take(np.cumsum(a, axis=axis), -1, axis=axis)
436
+
437
+
438
+ def msum_extra(x):
439
+ """Octave's ``sum(x, dim, "extra")`` -- the double-double accumulator.
440
+
441
+ **Not a MATLAB function.** MATLAB's ``sum`` has no ``"extra"`` option and
442
+ MATLAB's ``mean`` does not compensate. This exists because Octave 11.3
443
+ rewrote ``mean`` to go through ``robust_mean_sum``, which calls
444
+ ``sum(..., "extra")``, so the Octave *oracle* is more accurate than the
445
+ MATLAB it stands in for wherever a plain ``mean`` appears. Keeping the two
446
+ behaviours separate is the only honest way to report a bit-exactness result
447
+ that touches ``mean``: see ``docs/developer/OCTAVE_AS_ORACLE.md``.
448
+
449
+ Transcribes the accumulator rather than substituting a stand-in: a running
450
+ (hi, lo) pair updated by Knuth's two-sum, which is what Octave's
451
+ ``mx_inline_xsum`` maintains. Measured against the S4 oracle on all 94
452
+ non-empty seconds of ``ar``, it agrees exactly -- as do Neumaier summation
453
+ and ``math.fsum``, which is the expected outcome for vectors this short and
454
+ is why the *mechanism* was transcribed instead of any of them being adopted
455
+ on the strength of agreeing.
456
+
457
+ One dimension only; that is the whole of the need.
458
+ """
459
+ hi = 0.0
460
+ lo = 0.0
461
+ for v in np.asarray(x, dtype=np.float64).reshape(-1):
462
+ s = hi + v
463
+ b = s - hi
464
+ lo += (hi - (s - b)) + (v - b)
465
+ hi = s
466
+ return hi + lo
467
+
468
+
469
+ def nansum(x, dim=None):
470
+ """MATLAB ``nansum``: NaNs treated as zero; all-NaN and empty both give 0.
471
+
472
+ ``dim`` is 1-based; None means MATLAB's first-non-singleton rule, which
473
+ differs from NumPy's "reduce everything". Summation order is MATLAB's --
474
+ see :func:`msum`.
475
+
476
+ Provenance: ``sizeDist.m:1380,1398,1401,1404,1407,1410`` (accepted
477
+ particles) and ``:1535,1553,1556,1559,1562,1565`` (rejected twins);
478
+ ``:1769`` and ``:1784`` pass dim=2 explicitly.
479
+
480
+ Only NaN is replaced; ``Inf`` passes through, so ``nansum([Inf NaN 1])``
481
+ is ``Inf`` and ``nansum([Inf -Inf NaN])`` is ``NaN`` (Octave-measured).
482
+ An earlier version used ``np.nan_to_num`` here, which also mapped
483
+ ``+-Inf`` to ``+-realmax``, so v3.5's zero-live-time seconds wrote
484
+ ``n = realmax/10`` where MATLAB writes ``Inf``.
485
+ """
486
+ a, axis = _matlab_axis(x, dim)
487
+ a = np.asarray(a, dtype=np.float64)
488
+ if a.size == 0:
489
+ return 0.0
490
+ return msum(np.where(np.isnan(a), 0.0, a), dim=(axis + 1))
491
+
492
+
493
+ def nanmean(x, dim=None):
494
+ """MATLAB ``nanmean``: all-NaN and empty both give NaN, silently.
495
+
496
+ NumPy emits ``RuntimeWarning: Mean of empty slice`` where MATLAB is silent;
497
+ the sizeDist loop hits this for every empty size bin, so the warning is
498
+ suppressed rather than allowed to flood the logs.
499
+
500
+ Provenance: ``sizeDist.m:1383,1388,1391,1394`` and ``:1538,1542,1545,1549``.
501
+ """
502
+ a, axis = _matlab_axis(x, dim)
503
+ a = np.asarray(a, dtype=np.float64)
504
+ if a.size == 0:
505
+ # Same shape-preservation issue as msum (see its comment): a sibling
506
+ # axis being empty, not just the reduced one, still needs the
507
+ # surviving dimensions kept, not collapsed to a bare scalar.
508
+ survivor_shape = np.delete(a.shape, axis)
509
+ if survivor_shape.size == 0:
510
+ return np.float64(np.nan)
511
+ return np.full(tuple(survivor_shape), np.nan, dtype=np.float64)
512
+ good = ~np.isnan(a)
513
+ total = msum(np.where(good, a, 0.0), dim=(axis + 1))
514
+ n = np.count_nonzero(good, axis=axis)
515
+ with np.errstate(invalid="ignore", divide="ignore"):
516
+ out = np.where(n > 0, total / np.where(n > 0, n, 1), np.nan)
517
+ return out if out.ndim else np.float64(out)
518
+
519
+
520
+ # --------------------------------------------------------------------------
521
+ # Dates
522
+ # --------------------------------------------------------------------------
523
+
524
+ _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
525
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
526
+
527
+ # Days from 1 March to the start of each month, January first: the year is
528
+ # counted from March so that the leap day falls at its end.
529
+ _MONTHSTART = np.array([306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275],
530
+ dtype=np.float64)
531
+ _MONTHLENGTH = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
532
+ dtype=np.float64)
533
+
534
+
535
+ def _is_leap_year(y):
536
+ return ((np.mod(y, 4) == 0) & (np.mod(y, 100) != 0)) | (np.mod(y, 400) == 0)
537
+
538
+
539
+ def _datenum_fields(y, mo, d, h, mi, s):
540
+ """The serial day number, operation for operation as Octave 11.3's ``datenum.m``.
541
+
542
+ Proleptic Gregorian arithmetic on doubles, with no calendar object, so year
543
+ 0 and earlier work as they do in the interpreter. Every step below is one
544
+ statement of that file, in its order, because the order fixes the last bit
545
+ of the result: the time of day is ``(H + (M + S/60)/60)/24``, which differs
546
+ from ``H/24 + M/1440 + S/86400`` by one ulp on about a third of instants.
547
+ Held bit for bit against ``tests/data/datenum_octave_golden.json``.
548
+ """
549
+ if all(np.ndim(c) == 0 and math.isfinite(c) for c in (y, mo, d, h, mi, s)):
550
+ return np.float64(_datenum_scalar(*(float(c) for c in (y, mo, d, h, mi, s))))
551
+ y, mo, d, h, mi, s = np.broadcast_arrays(
552
+ *[np.asarray(c, dtype=np.float64) for c in (y, mo, d, h, mi, s)])
553
+ y, mo, d = y.copy(), mo.copy(), d.copy()
554
+ mo[mo < 1] = 1 # months below 1 are set to 1, not rolled back
555
+ if np.any(mo != np.fix(mo)): # a fractional month becomes days
556
+ frac = mo - np.floor(mo)
557
+ mo = np.floor(mo)
558
+ mi_idx = (np.mod(mo - 1, 12)).astype(np.intp)
559
+ idx = (mi_idx + 1 != 2) | ~_is_leap_year(np.floor(y))
560
+ d[idx] += frac[idx] * _MONTHLENGTH[mi_idx[idx]]
561
+ d[~idx] += frac[~idx] * 29
562
+ y += np.ceil((mo - 14) / 12) # the year starts in March; months > 12 roll over
563
+ d += _MONTHSTART[np.mod(mo - 1, 12).astype(np.intp)] + 60
564
+ if np.any(y != np.fix(y)): # a fractional year becomes days
565
+ frac = y - np.floor(y)
566
+ y = np.floor(y)
567
+ d += frac * (365 + _is_leap_year(y + 1))
568
+ d += 365 * y + np.floor(y / 4) - np.floor(y / 100) + np.floor(y / 400)
569
+ return d + (h + (mi + s / 60) / 60) / 24
570
+
571
+
572
+ def _datenum_scalar(y, mo, d, h, mi, s):
573
+ """:func:`_datenum_fields` for six Python floats, the same IEEE operations in
574
+ the same order (per-particle callers would otherwise pay NumPy's overhead)."""
575
+ if mo < 1:
576
+ mo = 1.0
577
+ if mo != math.trunc(mo):
578
+ frac = mo - math.floor(mo)
579
+ mo = float(math.floor(mo))
580
+ k = int(mo - 1) % 12
581
+ fy = math.floor(y)
582
+ leap = (fy % 4 == 0 and fy % 100 != 0) or fy % 400 == 0
583
+ d += frac * (_MONTHLENGTH_T[k] if (k + 1 != 2 or not leap) else 29)
584
+ y += math.ceil((mo - 14) / 12)
585
+ d += _MONTHSTART_T[int(mo - 1) % 12] + 60
586
+ if y != math.trunc(y):
587
+ frac = y - math.floor(y)
588
+ y = float(math.floor(y))
589
+ y1 = y + 1
590
+ leap = (y1 % 4 == 0 and y1 % 100 != 0) or y1 % 400 == 0
591
+ d += frac * (365 + leap)
592
+ d += 365 * y + math.floor(y / 4) - math.floor(y / 100) + math.floor(y / 400)
593
+ return d + (h + (mi + s / 60) / 60) / 24
594
+
595
+
596
+ _MONTHSTART_T = tuple(float(v) for v in _MONTHSTART)
597
+ _MONTHLENGTH_T = tuple(float(v) for v in _MONTHLENGTH)
598
+
599
+
600
+ def datenum(y, mo=None, d=None, h=0, mi=0, s=0):
601
+ """MATLAB ``datenum`` -> serial day number.
602
+
603
+ Accepts three to six scalar/array components, broadcast together, or a
604
+ single ``(N,3)`` to ``(N,6)`` date-vector array (``IntArrAnalysis.m:304-306``).
605
+
606
+ The result is written to netCDF as ``'double'`` under ``'units'`` =
607
+ ``'MATLAB datetime'`` (``IntArrAnalysis.m:265-267,273-275``), so it is part
608
+ of the output contract -- a POSIX timestamp would be wrong.
609
+
610
+ Reproduces Octave's ``datenum`` bit for bit (the Octave bank
611
+ ``run_datenum_bank.py``, dev repository only):
612
+ a month below 1 is set to 1; days, hours, minutes and seconds out of range
613
+ carry linearly, which ``IntArrAnalysis.m:302`` and the ``+240000`` midnight
614
+ fixes at ``sizeDist.m:98`` rely on; months above 12 roll into later years;
615
+ fractional months and years become days; year 0 and earlier are ordinary.
616
+ So MATLAB's zero-date time-of-day idiom ``datenum(0,0,0,H,M,S)`` returns
617
+ exactly the time-of-day fraction ``(H + (M + S/60)/60)/24``.
618
+ """
619
+ if mo is None:
620
+ vec = np.atleast_2d(np.asarray(y, dtype=np.float64))
621
+ if not 3 <= vec.shape[1] <= 6:
622
+ raise ValueError("datenum: a single argument must be an (N,3) to (N,6) date vector")
623
+ cols = [vec[:, k] for k in range(vec.shape[1])]
624
+ cols += [np.zeros(vec.shape[0])] * (6 - vec.shape[1])
625
+ out = _datenum_fields(*cols)
626
+ return out if out.size != 1 else float(out[0])
627
+ if d is None:
628
+ raise TypeError("datenum: give the year, month and day, or one date-vector array")
629
+ out = _datenum_fields(y, mo, d, h, mi, s)
630
+ if out.ndim == 0:
631
+ return float(out)
632
+ return out
633
+
634
+
635
+ def datestr(dt=None, fmt=None):
636
+ """MATLAB ``datestr``.
637
+
638
+ Default format is MATLAB's ``'dd-mmm-yyyy HH:MM:SS'``.
639
+ ``'yyyy/mm/dd HH:MM:SS'`` is the only explicit format UIOOPS uses
640
+ (``imgProc_sm.m:221``, ``sizeDist.m:1810``, ``IntArrAnalysis.m:252``), where
641
+ it becomes the non-deterministic ``'Creation Time'`` global attribute --
642
+ exclude it from byte comparisons.
643
+ """
644
+ when = _dt.datetime.now() if dt is None else dt
645
+ if fmt is None:
646
+ return (f"{when.day:02d}-{_MONTHS[when.month - 1]}-{when.year:04d} "
647
+ f"{when.hour:02d}:{when.minute:02d}:{when.second:02d}")
648
+ pyfmt = (fmt.replace("yyyy", "%Y").replace("mm", "%m").replace("dd", "%d")
649
+ .replace("HH", "%H").replace("MM", "%M").replace("SS", "%S"))
650
+ return when.strftime(pyfmt)
651
+
652
+
653
+ # --------------------------------------------------------------------------
654
+ # char <-> numeric coercion
655
+ # --------------------------------------------------------------------------
656
+
657
+ def mchar(c):
658
+ """MATLAB's implicit char->numeric coercion. ``mchar('S') == 83``.
659
+
660
+ ``imgProc_sm.m:323`` declares ``image_auto_reject`` as ``'short'`` and
661
+ ``:898`` writes ``int16(images.auto_reject)`` from a CHAR array.
662
+ ``sizeDist.m:769`` reads it back as int16 and then assigns character
663
+ literals into it -- ``:809`` ='D', ``:871`` ='I', ``:985`` ='z',
664
+ ``:1009,1012,1017`` ='S', ``:1042,1176`` ='R' -- and compares against them
665
+ at ``:1047,1060``. MATLAB coerces silently; NumPy raises.
666
+
667
+ Also ``imgProc_sm.m:897`` computes ``images.image_touching_edge - '0'``.
668
+ """
669
+ if isinstance(c, str):
670
+ if len(c) == 1:
671
+ return ord(c)
672
+ return np.array([ord(ch) for ch in c], dtype=np.int16)
673
+ return c
674
+
675
+
676
+ #: Reject codes. **Corrected 2026-08-20 against the emitting code**, not
677
+ #: only the ``Description`` attribute at ``imgProc_sm.m:325-329``: that
678
+ #: attribute lists seven codes where ``calculate_reject_unified`` emits eleven,
679
+ #: and it names one that no path produces. Anything decoding
680
+ #: ``image_auto_reject`` from the file's own metadata will mis-bucket the rest.
681
+ REJECT_CODES = {
682
+ "0": 48, # accepted
683
+ "a": 97, # aspect ratio outside [1/5, 5] (calculate_reject_unified.m:270)
684
+ "p": 112, # < 25% of the bounding rectangle (:276)
685
+ "s": 115, # split image (:235)
686
+ "z": 122, # zero area (:122, :264)
687
+ "h": 104, # hollow, no measurable hole ratio (:322)
688
+ "H": 72, # hollow, Korolev correction applied (:332)
689
+ "u": 117, # hollow, area-to-hole ratio too big (:344, :348, :352)
690
+ # --- emitted but ABSENT from the netCDF Description ---
691
+ "A": 65, # > 80% of the block shadowed (:229)
692
+ "i": 105, # side scans contradict the hollow verdict (:338)
693
+ # --- from sizeDist, added downstream of imgProc ---
694
+ "D": 68, # DMT DOF / SPEC overload (sizeDist.m:809)
695
+ "I": 73, # inter-arrival (sizeDist.m:871)
696
+ "R": 82, # shattering reacceptance (sizeDist.m:1042,1176)
697
+ "S": 83, # shattering (sizeDist.m:1009,1012,1017)
698
+ }
699
+
700
+ #: Each code of :data:`REJECT_CODES` (and :data:`UNREACHABLE_REJECT_CODES`) in words, from the
701
+ #: emitting lines cited beside each code above. ``'z'`` is written twice: by
702
+ #: ``calculate_reject_unified`` for zero area, and by ``sizeDist`` for an area ratio below its cut.
703
+ REJECT_CODE_WORDS = {
704
+ "0": "accepted",
705
+ "a": "aspect ratio beyond the contained-particle ceiling or its reciprocal",
706
+ "p": "too little of the bounding rectangle shadowed",
707
+ "s": "split image",
708
+ "z": "zero area (image stage), or area ratio below the cut (sizeDist)",
709
+ "h": "hollow, no measurable hole ratio",
710
+ "H": "hollow, Korolev correction applied",
711
+ "u": "hollow, area-to-hole ratio too big",
712
+ "A": "more than 80% of the block shadowed",
713
+ "i": "side scans contradict the hollow verdict",
714
+ "D": "DMT depth of field / SPEC overload",
715
+ "I": "inter-arrival",
716
+ "R": "shattering reacceptance",
717
+ "S": "shattering",
718
+ "t": "aspect ratio beyond the edge-particle ceiling (documented; no path emits it)",
719
+ "f": "zero area image (documented; no path emits it)",
720
+ }
721
+
722
+ #: Codes the ``Description`` attribute declares but no code path can produce.
723
+ #:
724
+ #: * ``'t'`` (116) is documented as "aspect ratio > 5 + image touching edge",
725
+ #: but :272 requires the ratio to exceed ``max_edge_img_ar = 6`` *after* :269
726
+ #: has already rejected everything above ``max_comp_img_ar = 5``. Six being
727
+ #: the larger of the two makes the edge test strictly weaker than the one
728
+ #: before it, so it never fires. (The attribute states the two thresholds the
729
+ #: other way round -- which is the ordering that would make ``'t'``
730
+ #: reachable.)
731
+ #: * ``'f'`` (102) is documented as "zero area image" and appears in no branch.
732
+ UNREACHABLE_REJECT_CODES = {"t": 116, "f": 102}
733
+
734
+ #: Holroyd habit codes, from the Description attribute at ``imgProc_sm.m:424-427``.
735
+ HOLROYD_HABITS = {
736
+ "M": 77, "C": 67, "d": 100, "t": 116, "o": 111,
737
+ "l": 108, "a": 97, "g": 103, "s": 115, "h": 104, "i": 105,
738
+ }
739
+
740
+
741
+ # --------------------------------------------------------------------------
742
+ # Orientation-sensitive helpers
743
+ # --------------------------------------------------------------------------
744
+
745
+ def _as_2d_col(a):
746
+ a = np.asarray(a)
747
+ return a.reshape(-1, 1) if a.ndim <= 1 else a
748
+
749
+
750
+ def mvertcat(*arrays):
751
+ """MATLAB ``[a; b; ...]``.
752
+
753
+ Provenance: ``sizeDist.m:815`` ``int_arr = [0;diff(Time_in_seconds)]`` and
754
+ ``:713`` ``count_all = [diff(start_all); NumofPart-start_all(end)]`` -- both
755
+ only make sense because ``netcdf.getVar`` returns a COLUMN for a 1-D
756
+ variable (the column-orientation gap in the netCDF-shim design record).
757
+ """
758
+ return np.vstack([_as_2d_col(a) for a in arrays if np.asarray(a).size or True])
759
+
760
+
761
+ def mhorzcat(*arrays):
762
+ """MATLAB ``[a, b, ...]``."""
763
+ parts = []
764
+ for a in arrays:
765
+ a = np.asarray(a)
766
+ parts.append(a.reshape(1, -1) if a.ndim <= 1 else a)
767
+ return np.hstack(parts)
768
+
769
+
770
+ def mdiff(x, dim=None):
771
+ """MATLAB ``diff``: along the first non-singleton dimension by default."""
772
+ a, axis = _matlab_axis(x, dim)
773
+ return np.diff(a, axis=axis)
774
+
775
+
776
+ class MGrowVector:
777
+ """A 1-based MATLAB vector that auto-extends with zero fill.
778
+
779
+ MATLAB grows an array on out-of-range assignment and fills the gap with 0
780
+ (numeric). A Python port using ``list.append`` gets this wrong whenever the
781
+ index skips.
782
+
783
+ Provenance: ``IntArrAnalysis.m:37-38`` (``intarr(1)=0`` then
784
+ ``intarr(2:length(tempTime))=diff(tempTime)``), ``:106,109``;
785
+ ``imgProc_sm.m:575-577,601,697-699`` (the ``images.*`` accumulators indexed
786
+ by ``kk``).
787
+
788
+ Note the companion hazard: ``imgProc_sm.m:863`` does ``clear c ind_matrix``
789
+ inside the per-particle loop. That ``clear`` is load-bearing -- keeping
790
+ ``ind_matrix`` alive across particles would leak stale rows from a longer
791
+ previous particle into ``dec2bin(ind_matrix(:,k))`` at ``:556/559/563``.
792
+ """
793
+
794
+ def __init__(self, dtype=np.float64):
795
+ self._a = np.zeros(0, dtype=dtype)
796
+ self._dtype = dtype
797
+
798
+ def _grow(self, n):
799
+ if n > self._a.size:
800
+ pad = np.zeros(n - self._a.size, dtype=self._dtype)
801
+ self._a = np.concatenate([self._a, pad])
802
+
803
+ def __setitem__(self, i, value):
804
+ """1-based assignment; accepts an int or a 1-based slice."""
805
+ if isinstance(i, slice):
806
+ start = 1 if i.start is None else i.start
807
+ stop = i.stop
808
+ self._grow(stop)
809
+ self._a[start - 1:stop] = value
810
+ else:
811
+ self._grow(i)
812
+ self._a[i - 1] = value
813
+
814
+ def __getitem__(self, i):
815
+ if isinstance(i, slice):
816
+ start = 1 if i.start is None else i.start
817
+ return self._a[start - 1:i.stop]
818
+ return self._a[i - 1]
819
+
820
+ def __len__(self):
821
+ return self._a.size
822
+
823
+ def asarray(self):
824
+ """A **copy** of the grown vector, 0-based, as an ordinary ndarray.
825
+
826
+ A copy rather than a view on purpose: the caller is usually handing the
827
+ result to a netCDF write or to a comparison, while this object may keep
828
+ growing afterwards, and a view would silently change length or be
829
+ invalidated by the next reallocation in :meth:`_grow`.
830
+
831
+ Length is the highest index ever assigned, with the skipped positions
832
+ holding the zeros MATLAB fills them with -- not the number of
833
+ assignments made.
834
+ """
835
+ return self._a.copy()
836
+
837
+ def __repr__(self):
838
+ return f"MGrowVector({self._a!r})"
839
+
840
+
841
+ # --------------------------------------------------------------------------
842
+ # Index-base conversion
843
+ # --------------------------------------------------------------------------
844
+
845
+ def to0(i):
846
+ """MATLAB 1-based index -> Python 0-based.
847
+
848
+ Convention for this port: keep MATLAB 1-based indices visible in the code
849
+ and convert only at the array boundary, so the source's deliberate +/-1
850
+ differences stay visually identical. Several sites MIX 1-based MATLAB
851
+ indices with 0-based netCDF starts in one expression, so a uniform global
852
+ shift double-shifts them -- see ``sizeDist.m:686`` vs ``:955``,
853
+ ``sizeDist.m:818,822,833``, ``imgProc_sm.m:452-453,555,558,582,589,655``.
854
+ """
855
+ return np.asarray(i) - 1 if np.ndim(i) else i - 1
856
+
857
+
858
+ def to1(i):
859
+ """Python 0-based index -> MATLAB 1-based. See :func:`to0`."""
860
+ return np.asarray(i) + 1 if np.ndim(i) else i + 1