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,248 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Shared leaf: the Holroyd shape statistics both engines use.
3
+
4
+ Moved verbatim from ``arrayprobe.habit``;
5
+ that module re-imports them, so its names still resolve. Pure functions and a
6
+ frozen dataclass: no module state, no numba.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from dataclasses import dataclass
13
+
14
+ import numpy as np
15
+
16
+ from .particle import shadow_mask
17
+
18
+ __all__: list[str] = []
19
+
20
+
21
+ #: ``holroyd.m:108``. A sentinel ceiling, used as ``*3`` for the running
22
+ #: minimum of the slice index. S2 measured particles as long as ``nS = 7829``
23
+ #: slices in the ORACLES raw files, so 18000 still clears real data -- but the
24
+ #: margin is a factor of two, not the factor of a thousand the number suggests.
25
+ MAX_TWOD_DATA_LENGTH = 6000
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class ShapeStats:
30
+ """The nine outputs of ``calc_stat`` (``holroyd.m:105``).
31
+
32
+ Field order follows the MATLAB return list so the two can be read side by
33
+ side. Only ``x_length``, ``y_length``, ``d_length``, ``a_angle``, ``area``,
34
+ ``r2_correlation``, ``F_fine_detail`` and ``S_ratio`` reach the decision
35
+ tree; ``w_width`` is computed, returned, and never used by anything -- which
36
+ is why the ``dmax_y`` defect below has no effect on any UIOOPS output.
37
+ """
38
+
39
+ x_length: float
40
+ y_length: float
41
+ d_length: float
42
+ w_width: float
43
+ a_angle: float
44
+ area: float
45
+ r2_correlation: float
46
+ F_fine_detail: float
47
+ S_ratio: float
48
+
49
+
50
+ def calc_stat(image_buffer, bits_per_slice) -> ShapeStats:
51
+ """``holroyd.m:105-278``, vectorized. Equal to :func:`calc_stat_scalar`.
52
+
53
+ The two scans in the MATLAB are transitions along the row-major and
54
+ column-major flattenings of the image with the state carried across
55
+ boundaries (see :func:`calc_stat_scalar`), so each is exactly the number of
56
+ changes in the flattened sequence prefixed by a lit diode -- one
57
+ ``np.diff`` apiece. Everything else is a sum or an extreme over the
58
+ shadowed pixels, and the rotation is a two-line matrix product.
59
+
60
+ The sentinel initialisers are applied *after* the vectorized reduction
61
+ rather than seeded into it, which reproduces them exactly: a reduction over
62
+ an empty set is undefined in NumPy, but MATLAB's answer in that case is
63
+ simply the sentinel.
64
+ """
65
+ shadow = shadow_mask(image_buffer)
66
+ n_slices = shadow.shape[0]
67
+ if n_slices <= 0:
68
+ raise ValueError("calc_stat requires at least one slice")
69
+
70
+ # MATLAB scans exactly `bits_per_slice` columns whatever the array holds.
71
+ # Reproduce the framing rather than trusting the caller's width: a narrower
72
+ # image would index out of range in MATLAB, a wider one would be truncated.
73
+ if shadow.shape[1] < bits_per_slice:
74
+ raise IndexError(
75
+ f"image has {shadow.shape[1]} diodes, fewer than bits_per_slice={bits_per_slice}"
76
+ )
77
+ shadow = shadow[:, :bits_per_slice]
78
+
79
+ rows, cols = np.nonzero(shadow)
80
+ n_count = int(rows.size)
81
+ tx = rows.astype(np.float64) + 1.0
82
+ ty = cols.astype(np.float64) + 1.0
83
+ area = float(n_count)
84
+
85
+ per_row = shadow.sum(axis=1)
86
+ fully_on_count = int(np.count_nonzero(per_row == bits_per_slice))
87
+ partial_on_count = int(np.count_nonzero(per_row != 0))
88
+
89
+ # holroyd.m:128,170-178 and :193-207. A transition is any change in the
90
+ # flattened sequence; prefixing a lit diode supplies the `spot_on_off = 0`
91
+ # initial state, and not appending one reproduces the missing close.
92
+ row_major = shadow.ravel(order="C")
93
+ col_major = shadow.ravel(order="F")
94
+ p_perimeter_change = int(
95
+ np.count_nonzero(np.diff(np.concatenate(([False], row_major))))
96
+ + np.count_nonzero(np.diff(np.concatenate(([False], col_major))))
97
+ )
98
+
99
+ if n_count:
100
+ max_x, min_x = int(tx.max()), min(MAX_TWOD_DATA_LENGTH * 3, int(tx.min()))
101
+ max_y, min_y = int(ty.max()), min(bits_per_slice, int(ty.min()))
102
+ else:
103
+ max_x, min_x = 0, MAX_TWOD_DATA_LENGTH * 3
104
+ max_y, min_y = 0, bits_per_slice
105
+
106
+ x_length = float(max_x - min_x + 1) if max_x >= min_x else 0.0
107
+ y_length = float(max_y - min_y + 1) if max_y >= min_y else 0.0
108
+
109
+ return _finish(
110
+ n_count=n_count,
111
+ px=tx,
112
+ py=ty,
113
+ area=area,
114
+ sum_x=float(tx.sum()),
115
+ sum_y=float(ty.sum()),
116
+ sum_x2=float((tx * tx).sum()),
117
+ sum_y2=float((ty * ty).sum()),
118
+ sum_xy=float((tx * ty).sum()),
119
+ x_length=x_length,
120
+ y_length=y_length,
121
+ p_perimeter_change=p_perimeter_change,
122
+ fully_on_count=fully_on_count,
123
+ partial_on_count=partial_on_count,
124
+ bits_per_slice=bits_per_slice,
125
+ )
126
+
127
+
128
+ def _finish(
129
+ *,
130
+ n_count,
131
+ px,
132
+ py,
133
+ area,
134
+ sum_x,
135
+ sum_y,
136
+ sum_x2,
137
+ sum_y2,
138
+ sum_xy,
139
+ x_length,
140
+ y_length,
141
+ p_perimeter_change,
142
+ fully_on_count,
143
+ partial_on_count,
144
+ bits_per_slice,
145
+ ) -> ShapeStats:
146
+ """``holroyd.m:222-277`` -- the part after both scans, shared by both paths.
147
+
148
+ Split out because it is identical in the scalar and vectorized versions and
149
+ is where every NaN-producing division lives; keeping one copy means the two
150
+ paths cannot drift on the delicate arithmetic.
151
+
152
+ All arithmetic here runs on ``np.float64`` rather than Python ``float``, for
153
+ one reason: MATLAB divides by zero the way IEEE-754 says to -- ``0/0`` is
154
+ NaN, ``c/0`` is a signed infinity -- and Python raises ``ZeroDivisionError``
155
+ instead. Both cases are *reachable and load-bearing* here (an empty image
156
+ takes the first, a single-slice particle very nearly takes the second), so
157
+ the arithmetic has to be done in a type that produces MATLAB's answer
158
+ instead of being guarded into a different one.
159
+ """
160
+ with np.errstate(divide="ignore", invalid="ignore"):
161
+ area = np.float64(area)
162
+ sum_x, sum_y = np.float64(sum_x), np.float64(sum_y)
163
+ sum_x2, sum_y2, sum_xy = np.float64(sum_x2), np.float64(sum_y2), np.float64(sum_xy)
164
+
165
+ # holroyd.m:222-224. With no shadowed pixel every term is zero, so
166
+ # these are 0 - 0/0 = NaN. MATLAB carries the NaN forward; the caller's
167
+ # `area == 0` test at :45 catches the particle before it matters.
168
+ cross_xy = sum_xy - (sum_x * sum_y / area)
169
+ cross_x2 = sum_x2 - (sum_x * sum_x / area)
170
+ cross_y2 = sum_y2 - (sum_y * sum_y / area)
171
+
172
+ # holroyd.m:226. A particle confined to a single slice has zero
173
+ # variance in x, so this is 0/0 -> NaN, and every comparison downstream
174
+ # is false. That is not a degenerate curiosity: it steers single-slice
175
+ # particles into the *linear* branch at :51 by way of a NaN d_length.
176
+ slope = cross_xy / cross_x2
177
+
178
+ angle_radian = np.arctan(slope)
179
+ a_angle = angle_radian * (180.0 / math.pi)
180
+
181
+ # holroyd.m:232-235. NaN < 0 is false, so a degenerate particle keeps
182
+ # its NaN angle and every downstream comparison fails closed.
183
+ if a_angle < 0:
184
+ a_angle = a_angle + 180.0
185
+ angle_radian = angle_radian + math.pi
186
+
187
+ # holroyd.m:244-249. Folds (pi/2, pi] back into [0, pi/2). The `> pi`
188
+ # arm prints a diagnostic and returns with the outputs unassigned, which
189
+ # in MATLAB is an error; it is unreachable because atan(x) + pi <= pi
190
+ # only when atan(x) <= 0, and that branch has already been taken.
191
+ if (angle_radian > (math.pi / 2.0)) and (angle_radian <= math.pi):
192
+ angle_radian = math.pi - angle_radian
193
+ elif angle_radian > math.pi: # pragma: no cover - unreachable, see above
194
+ raise ValueError(f"HEY: something is wrong here a_angle = {a_angle}")
195
+
196
+ dmin_x = float(MAX_TWOD_DATA_LENGTH * 3)
197
+ dmin_y = float(bits_per_slice)
198
+ dmax_x = 0.0
199
+ dmax_y = 0.0
200
+
201
+ if n_count:
202
+ cos_a, sin_a = np.cos(angle_radian), np.sin(angle_radian)
203
+ new_x = px * cos_a + py * sin_a
204
+ new_y = py * cos_a - px * sin_a
205
+ # holroyd.m:253-264 compares against the sentinels, so a rotated
206
+ # coordinate that never beats one leaves it in place. Two
207
+ # consequences, both preserved:
208
+ #
209
+ # * `dmax_y = 0` is wrong for a quantity that is routinely
210
+ # negative -- `y*cos - x*sin` is below zero for every point of a
211
+ # steeply inclined particle -- so `w_width` is inflated there.
212
+ # * `if (new_x > dmax_x)` is FALSE for NaN, so a NaN slope (a
213
+ # single-slice particle) leaves all four sentinels standing and
214
+ # `d_length` comes out as 1 - 18000 = -17999.
215
+ #
216
+ # `keep` reproduces the second: it is the subset of points MATLAB's
217
+ # comparisons can actually act on. The rotation makes every
218
+ # coordinate NaN at once or none of them, so it is all-or-nothing.
219
+ keep = ~np.isnan(new_x)
220
+ if keep.any():
221
+ dmax_x = max(dmax_x, float(new_x[keep].max()))
222
+ dmin_x = min(dmin_x, float(new_x[keep].min()))
223
+ keep_y = ~np.isnan(new_y)
224
+ if keep_y.any():
225
+ dmax_y = max(dmax_y, float(new_y[keep_y].max()))
226
+ dmin_y = min(dmin_y, float(new_y[keep_y].min()))
227
+
228
+ d_length = np.float64(dmax_x - dmin_x) + 1
229
+ w_width = np.float64(dmax_y - dmin_y) + 1
230
+
231
+ # holroyd.m:270. cross_x2 and cross_y2 are variances and so cannot be
232
+ # negative in exact arithmetic; the product is zero for a single-slice
233
+ # or single-diode particle, and 0/0 is again NaN.
234
+ r2_correlation = cross_xy / np.sqrt(cross_x2 * cross_y2)
235
+ f_fine_detail = np.float64(p_perimeter_change) * d_length / area
236
+ s_ratio = fully_on_count / partial_on_count if partial_on_count != 0 else 0.0
237
+
238
+ return ShapeStats(
239
+ x_length=x_length,
240
+ y_length=y_length,
241
+ d_length=float(d_length),
242
+ w_width=float(w_width),
243
+ a_angle=float(a_angle),
244
+ area=float(area),
245
+ r2_correlation=float(r2_correlation),
246
+ F_fine_detail=float(f_fine_detail),
247
+ S_ratio=float(s_ratio),
248
+ )
@@ -0,0 +1,376 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Size-dependent hollow rejection, calibrated on 480 hand-labelled particles.
3
+
4
+ **What this is.** An opt-in, default-off refinement of ``rej_hollow`` for
5
+ ``arrayprobe_uiops``. Below a size threshold, the hollow test's rejection
6
+ applies exactly as stock does; at or above it, the hollow test's rejection
7
+ is bypassed for that particle -- it is treated as not-hollow for the
8
+ purpose of ``calculate_reject_unified``, so no other branch of that
9
+ function changes. The port reproduces upstream and adds no new package, so this
10
+ is new behaviour, so it ships **inside** the engine it extends rather than
11
+ as a new package, opt-in, default-off, and proven bit-identical to stock
12
+ when off (:func:`resolve_ihollow` returns ``ihollow`` unchanged whenever
13
+ the rule is missing or disabled -- see
14
+ ``tests/test_hollow_size_rule.py::TestBitIdenticalWhenOff``, which checks
15
+ with ``np.array_equal``, never ``allclose``).
16
+
17
+ **The oracle is the author's own labels, not the Octave goldens** (the rule is
18
+ "its own named oracle" -- the Octave goldens validate the stock v3.5 path,
19
+ which this module never touches when off, and cannot validate a labelling
20
+ judgement in any case). 2026-09-18: 480 particles labelled across 16
21
+ cells over two rounds. Fraction of *disputed* particles (particles where
22
+ stock and an image-assisted alternative disagree) that are genuinely real,
23
+ i.e. the fraction stock's hollow test wrongly discards, by
24
+ ``image_diam_minR`` size bin, with Wilson 95% intervals:
25
+
26
+ 55-105 um 0 % [0, 13] n=25
27
+ 105-155 um 45 % [31, 60] n=40
28
+ 155-205 um 60 % [45, 74] n=40
29
+ 205-255 um 63 % [46, 78] n=30
30
+ 255-305 um 87 % [70, 95] n=30
31
+
32
+ **That table is a rendering of :data:`LABELLED_EVIDENCE`, not a separate
33
+ statement of it.** Until 2026-09-21 it lived only here, in prose, while
34
+ :data:`DEFAULT_THRESHOLD_UM` was a typed ``155.0`` -- so the number was
35
+ machine-readable and the evidence justifying it was not, and the two could
36
+ drift apart in silence. A figure audit named that as the reason the
37
+ paper's Section 6 figure could not honestly be drawn. The counts now live in
38
+ :data:`LABELLED_EVIDENCE`, the threshold is :func:`threshold_from_evidence`
39
+ read off them, and
40
+ ``tests/test_hollow_size_rule.py::TestTheDocstringTableIsTheConstant``
41
+ re-parses the five rows above and asserts every percentage, bound and ``n``
42
+ against the computed values -- so editing one without the other fails.
43
+
44
+ Monotonic; crosses 50% between the 105-155 and 155-205 bins. Pooled over
45
+ both labelling rounds, the whole 105-205 band is 53/105 = 50.5% --
46
+ break-even, which is exactly why round 1 (n=25 in that band alone) could
47
+ not resolve it. Below 105 um the labels say no threshold helps at all --
48
+ among particles both configurations already accept, 55-105 um is only 32%
49
+ real, against 78-100% in every bin above it -- so this module does not try
50
+ to buy anything below its threshold; excluding that bin from a downstream
51
+ comparison is a separate decision this module does not make.
52
+
53
+ **155 um is the best estimate, not a sharp boundary.** The 45% [31, 60] and
54
+ 60% [45, 74] Wilson intervals overlap (both n=40, overlapping on
55
+ [45, 60]), so the switch point could sit anywhere the two bins' data
56
+ cannot yet distinguish. This caveat travels with the number here, in code,
57
+ because it must live in the code's docstring:
58
+ see :data:`DEFAULT_THRESHOLD_UM` and
59
+ ``tests/test_hollow_size_rule.py::TestThresholdIsAnEstimateNotAClaim``,
60
+ which both greps this docstring for the caveat and independently
61
+ recomputes the two Wilson intervals from the raw counts to confirm they
62
+ still overlap -- so an edit that quietly changed the numbers, not just the
63
+ words, would also fail.
64
+
65
+ **Boundary convention.** "Below" is ``size_um < threshold_um`` (the hollow
66
+ test's rejection applies, as stock); "at or above" is
67
+ ``size_um >= threshold_um`` (the hollow test's rejection is bypassed). The
68
+ threshold value itself falls on the disabled side, because it is the left
69
+ edge of the 155-205 bin, where the labels already say the hollow test is
70
+ more often wrong than right (60% real). A particle whose size cannot be
71
+ established behaves as stock (``size_um is None`` -> hollow test applies)
72
+ -- this rule only ever narrows what stock rejects for hollow; it never
73
+ invents a new rejection of its own.
74
+
75
+ **What decides ``ihollow``, and where this hooks in.**
76
+ ``arrayprobe_uiops.reject.calculate_reject_unified(image_buffer, habit,
77
+ ihollow, config)`` (``reject.py:208-219``) takes hollow status as a
78
+ required argument rather than computing it -- v3.5 moved that decision to
79
+ the caller (see that module's own docstring, point 1: ``imgProc_sm.m``
80
+ decides hollow status itself in v3.5). The caller is
81
+ ``arrayprobe_uiops.measure.measure_record`` (``measure.py:200-263``), which,
82
+ in order:
83
+
84
+ 1. computes ``minR, ctx, cty = cgal_min_r_v35(codes, geom.tas_ratio)``
85
+ (``measure.py:237``) *before* the reject call. ``minR`` is a raw,
86
+ diode-scaled quantity -- the same one ``imgproc.py:1365`` later writes
87
+ to the output netCDF as ``image_diam_minR`` via ``minR * ds`` (there in
88
+ mm; ``ds`` is ``geom.diodesize``, mm/diode, ``measure.py:113``);
89
+ 2. decides ``is_hollow`` (the ``[EXPERIMENTAL]`` override at
90
+ ``measure.py:239-259``);
91
+ 3. calls ``rj = calculate_reject_unified(codes, habit, is_hollow,
92
+ reject_config)`` (``measure.py:262``).
93
+
94
+ So the size measure available at the decision point is exactly the
95
+ quantity ``image_diam_minR`` is made of, just not yet named that or
96
+ converted to micrometres. :func:`size_um_from_minr` does the same
97
+ ``* diodesize`` step ``imgproc.py:1365`` does, then ``* 1000`` for
98
+ micrometres, to match the units the bins above are stated in. This module
99
+ does not use ``p_length``/``width`` (the diode-count geometry
100
+ ``calculate_reject_unified`` computes internally, for its own aspect-ratio
101
+ tests): those are not what the labels were binned by, and unlike ``minR``
102
+ they are not available before that function is even called.
103
+
104
+ **A preserved defect this sits right next to** (``reject.py:361-375``,
105
+ documented there, not repeated or altered here): inside
106
+ ``calculate_reject_unified``, whatever ``ihollow`` value the caller passes
107
+ in becomes ``hollow_status`` verbatim -- a second, "side" call to
108
+ ``is_it_hollow`` on the transposed buffer computes its own status, but
109
+ that result is thrown away (assigned to a variable never read again), a
110
+ real MATLAB defect preserved rather than fixed. Practically: intercepting
111
+ ``ihollow`` before it reaches ``calculate_reject_unified``, as this module
112
+ does, is equivalent to intercepting ``hollow_status`` itself -- there is
113
+ no other point upstream of ``reject_status`` where a size-dependent
114
+ override could act with a smaller blast radius.
115
+
116
+ **Integration this module does not wire in itself** (by design -- see
117
+ ``_decoded/cip160906/HOLLOW_SIZE_RULE.md`` for the report this shipped
118
+ with). One line at ``measure.py:262``, replacing the ``is_hollow``
119
+ argument:
120
+
121
+ rj = calculate_reject_unified(codes, habit, resolve_ihollow(
122
+ is_hollow, size_um_from_minr(minR, geom.diodesize), hollow_rule),
123
+ reject_config)
124
+
125
+ where ``hollow_rule`` is a :class:`HollowSizeRule` threaded into scope
126
+ (for example, a new ``RecordGeometry`` field defaulting to
127
+ ``HollowSizeRule()``, which is off) -- so no existing call site changes
128
+ behaviour until it explicitly opts in.
129
+ """
130
+ from __future__ import annotations
131
+
132
+ import math
133
+ from dataclasses import dataclass
134
+
135
+ import numpy as np
136
+
137
+ __all__ = [
138
+ "DEFAULT_THRESHOLD_UM",
139
+ "LABELLED_EVIDENCE",
140
+ "HollowSizeRule",
141
+ "LabelledBin",
142
+ "hollow_test_applies",
143
+ "resolve_ihollow",
144
+ "resolve_ihollow_array",
145
+ "size_um_from_minr",
146
+ "threshold_from_evidence",
147
+ "wilson_95",
148
+ ]
149
+
150
+ #: Two-sided 95 % normal quantile, the one used for every interval below.
151
+ _Z95 = 1.959963984540054
152
+
153
+
154
+ def wilson_95(n_success: int, n: int) -> tuple[float, float]:
155
+ """Wilson score interval for a binomial proportion, two-sided 95 %.
156
+
157
+ Wilson rather than Wald because three of the five bins below sit near an
158
+ end of the range -- ``0/25`` among them, where Wald's interval is the
159
+ degenerate ``[0, 0]`` and would make "no threshold helps here" look like
160
+ a certainty rather than the ``[0, 13] %`` it is.
161
+ """
162
+ if n <= 0:
163
+ raise ValueError(f"n must be positive; got {n!r}")
164
+ if not 0 <= n_success <= n:
165
+ raise ValueError(f"n_success must lie in [0, {n}]; got {n_success!r}")
166
+ p = n_success / n
167
+ z2n = _Z95 * _Z95 / n
168
+ centre = (p + z2n / 2.0) / (1.0 + z2n)
169
+ half = (_Z95 / (1.0 + z2n)) * math.sqrt(
170
+ p * (1.0 - p) / n + _Z95 * _Z95 / (4.0 * n * n)
171
+ )
172
+ return max(0.0, centre - half), min(1.0, centre + half)
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class LabelledBin:
177
+ """One size bin of the hand-labelled *disputed* particles.
178
+
179
+ "Disputed" means stock's hollow test rejects the particle and the
180
+ image-assisted alternative would accept it; the label says which side was
181
+ right. :attr:`n_real` is how many of those were judged to be real
182
+ particles -- i.e. how many stock's hollow test wrongly discarded.
183
+
184
+ Only the two counts are stored. The fraction and its interval are
185
+ **computed**, never typed, so there is exactly one place a label can move.
186
+ """
187
+
188
+ band_lo_um: float
189
+ band_hi_um: float
190
+ n_real: int
191
+ n_artifact: int
192
+
193
+ @property
194
+ def n(self) -> int:
195
+ """Labels with a usable verdict in this bin (``real`` + ``artifact``)."""
196
+ return self.n_real + self.n_artifact
197
+
198
+ @property
199
+ def fraction_real(self) -> float:
200
+ """The fraction of stock's rejections in this bin that were real."""
201
+ return self.n_real / self.n
202
+
203
+ @property
204
+ def wilson_95(self) -> tuple[float, float]:
205
+ """:func:`wilson_95` of this bin's counts."""
206
+ return wilson_95(self.n_real, self.n)
207
+
208
+
209
+ #: The author's labelled evidence, the oracle this module's threshold rests on --
210
+ #: the five *elementary* disputed bins (the two wider round-1 bands, 105-205
211
+ #: and 205-305, are supersets of these and are deliberately not listed, so no
212
+ #: particle is counted twice).
213
+ #:
214
+ #: **Counts, not conclusions.** Every percentage and interval this project
215
+ #: quotes for the hollow rule is derived from the four integers per row here:
216
+ #: the module docstring's table, :data:`DEFAULT_THRESHOLD_UM` itself, and the
217
+ #: paper's Section 6 figure. Promoted out of the docstring 2026-09-21 (the
218
+ #: figure audit), which found the threshold machine-readable and its
219
+ #: justification prose -- the precise shape in which a number and its evidence
220
+ #: drift apart with nothing failing.
221
+ #:
222
+ #: Provenance: ``_decoded/cip160906/triage_verdicts/sea_s2.json``, the triage
223
+ #: server's own verdict store, 480 records over 16 queues. The counts are
224
+ #: pinned against a recount of that file in
225
+ #: the tracked CIP hollow-label fixture in ``tests/data``.
226
+ LABELLED_EVIDENCE: tuple[LabelledBin, ...] = (
227
+ LabelledBin(55.0, 105.0, n_real=0, n_artifact=25),
228
+ LabelledBin(105.0, 155.0, n_real=18, n_artifact=22),
229
+ LabelledBin(155.0, 205.0, n_real=24, n_artifact=16),
230
+ LabelledBin(205.0, 255.0, n_real=19, n_artifact=11),
231
+ LabelledBin(255.0, 305.0, n_real=26, n_artifact=4),
232
+ )
233
+
234
+
235
+ def threshold_from_evidence(
236
+ bins: tuple[LabelledBin, ...] = LABELLED_EVIDENCE,
237
+ ) -> float:
238
+ """Where the labels say the hollow test flips from right to wrong.
239
+
240
+ The low edge of the smallest bin in which stock's hollow test is wrong at
241
+ least as often as it is right (``fraction_real >= 0.5``), scanning upward.
242
+ That is the whole rule: the threshold is **read off the labels**, not
243
+ chosen and then justified, so re-labelling moves it and nothing here needs
244
+ editing.
245
+
246
+ Raises :class:`ValueError` if no bin crosses the half -- a state in which
247
+ this module has no evidence for any threshold and should not silently
248
+ supply one.
249
+ """
250
+ for b in sorted(bins, key=lambda x: x.band_lo_um):
251
+ if b.fraction_real >= 0.5:
252
+ return float(b.band_lo_um)
253
+ raise ValueError(
254
+ "no labelled bin reaches a real fraction of 0.5, so the labels "
255
+ "support no threshold; do not default one"
256
+ )
257
+
258
+
259
+ #: The best estimate of where the hollow test flips from right to wrong,
260
+ #: in the same micrometre units as ``image_diam_minR``. **Derived from
261
+ #: :data:`LABELLED_EVIDENCE`, not typed** -- it is 155.0 because that is the
262
+ #: low edge of the first bin the labels put above the half (24/40 = 60 %),
263
+ #: and it moves when a label moves.
264
+ #:
265
+ #: NOT a sharp boundary -- see the module docstring's "155 um is the best
266
+ #: estimate" section. Pass a different value to
267
+ #: ``HollowSizeRule(threshold_um=...)`` instead of editing anything here: the
268
+ #: labels cannot justify more precision than one number, and a future
269
+ #: campaign, probe, or larger label set will want to move it without touching
270
+ #: this module's logic.
271
+ DEFAULT_THRESHOLD_UM: float = threshold_from_evidence()
272
+
273
+
274
+ @dataclass(frozen=True)
275
+ class HollowSizeRule:
276
+ """Configuration for the size-dependent hollow rejection.
277
+
278
+ ``enabled=False`` is the default, and makes every function below a
279
+ strict passthrough of ``ihollow`` -- see
280
+ ``tests/test_hollow_size_rule.py::TestBitIdenticalWhenOff``.
281
+
282
+ ``threshold_um`` is a parameter, not a constant: the labels behind
283
+ :data:`DEFAULT_THRESHOLD_UM` (480 hand-labelled particles) cannot justify more
284
+ precision than one estimate, and that estimate is not a sharp boundary
285
+ -- the 45% [31, 60] and 60% [45, 74] Wilson intervals it sits between
286
+ overlap, both at n=40. A future campaign, probe, or bigger label set
287
+ will want to move this number without editing this module's code.
288
+ """
289
+
290
+ enabled: bool = False
291
+ threshold_um: float = DEFAULT_THRESHOLD_UM
292
+
293
+ def __post_init__(self) -> None:
294
+ if not math.isfinite(self.threshold_um) or self.threshold_um <= 0:
295
+ raise ValueError(
296
+ "threshold_um must be a finite, positive number of "
297
+ f"micrometres; got {self.threshold_um!r}"
298
+ )
299
+
300
+
301
+ def hollow_test_applies(rule: HollowSizeRule | None, size_um: float | None) -> bool:
302
+ """Whether the hollow test's rejection should apply, as stock does, to a
303
+ particle of this size under this rule.
304
+
305
+ ``True`` (apply as stock) when ``rule`` is ``None`` or ``rule.enabled``
306
+ is ``False``, when no size could be established (``size_um is None`` --
307
+ stock is always the conservative fallback), or when
308
+ ``size_um < rule.threshold_um``. ``False`` (bypass the hollow test's
309
+ rejection) only when the rule is enabled AND
310
+ ``size_um >= rule.threshold_um`` -- the threshold value itself is on
311
+ the disabled side; see the module docstring's "Boundary convention".
312
+ """
313
+ if rule is None or not rule.enabled:
314
+ return True
315
+ if size_um is None:
316
+ return True
317
+ return size_um < rule.threshold_um
318
+
319
+
320
+ def resolve_ihollow(
321
+ ihollow: int, size_um: float | None, rule: HollowSizeRule | None = None
322
+ ) -> int:
323
+ """The ``ihollow`` value ``calculate_reject_unified`` should receive,
324
+ with the size-dependent rule applied.
325
+
326
+ Returns ``int(ihollow)`` unchanged whenever :func:`hollow_test_applies`
327
+ is ``True`` (stock -- always true when ``rule`` is ``None`` or
328
+ disabled); returns ``0`` (not hollow) otherwise. Never turns a stock
329
+ ``0`` into a ``1``: this rule only narrows what stock rejects for
330
+ hollow, matching the module docstring's note on the preserved
331
+ ``hollow_status``/``ihollow`` defect at
332
+ ``arrayprobe_uiops/reject.py:361-375`` -- the caller's ``ihollow`` is what
333
+ decides ``hollow_status``, unchanged by anything downstream, so this is
334
+ the only point with leverage on the outcome.
335
+ """
336
+ if hollow_test_applies(rule, size_um):
337
+ return int(ihollow)
338
+ return 0
339
+
340
+
341
+ def resolve_ihollow_array(
342
+ ihollow: np.ndarray, size_um: np.ndarray, rule: HollowSizeRule | None = None
343
+ ) -> np.ndarray:
344
+ """Vectorised :func:`resolve_ihollow`, for retroactively applying the
345
+ rule across an already-decoded record's ``is_hollow``/
346
+ ``image_diam_minR`` columns, rather than one particle at a time inside
347
+ ``arrayprobe_uiops.measure.measure_record``. Not used by the pipeline
348
+ itself -- offered for the kind of bulk recompute this project's own
349
+ reproducibility checks already do (e.g. the check that the habit column
350
+ reproduces from a decoded file on disk).
351
+
352
+ ``size_um`` entries that are NaN are treated as "no size established"
353
+ (stock applies), matching :func:`hollow_test_applies`'s ``None`` case.
354
+ """
355
+ ihollow_arr = np.asarray(ihollow).astype(np.int64, copy=False)
356
+ if rule is None or not rule.enabled:
357
+ return ihollow_arr.copy()
358
+ size_arr = np.asarray(size_um, dtype=np.float64)
359
+ stock_applies = np.isnan(size_arr) | (size_arr < rule.threshold_um)
360
+ return np.where(stock_applies, ihollow_arr, 0)
361
+
362
+
363
+ def size_um_from_minr(minr: float, diodesize_mm: float) -> float:
364
+ """The size measure available where the hollow decision is made.
365
+
366
+ ``arrayprobe_uiops/measure.py:237`` computes ``minR`` before the
367
+ ``:262`` reject call; ``minr * diodesize_mm`` is exactly what
368
+ ``arrayprobe_uiops/imgproc.py:1365`` later writes to the output netCDF as
369
+ ``image_diam_minR`` (there in mm, ``diodesize_mm`` being
370
+ ``RecordGeometry.diodesize``). This function does that same
371
+ multiplication and then converts mm to micrometres (``* 1000``) to
372
+ match the units :data:`DEFAULT_THRESHOLD_UM` and the hand labels are
373
+ stated in. Not a new geometric computation -- the same quantity, read
374
+ one call earlier and in different units.
375
+ """
376
+ return float(minr) * float(diodesize_mm) * 1000.0