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,346 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """v3.5 ``imgProc_sm.m:1204-1291`` -- the per-particle measurement block.
3
+
4
+ The block is inline driver code between the record-time bookkeeping and the
5
+ ``iRectEllipse`` unit: the minimum-enclosing-circle call, the ungated
6
+ ``[EXPERIMENTAL]`` hollow override, the habit call, ``calculate_reject_unified``,
7
+ the area reconstruction, ``AreaR``/``Perimeter``/``sphericity``, the Korolev
8
+ retarget onto ``minR``, the centre-out ``'C'`` override and ``axis_ratio``.
9
+ Nothing else of ``imgProc_sm.m`` is here (no writer, no record loop, no iQC).
10
+
11
+ Every callee is the already-validated port of its own v3.5 file -- ``habit``
12
+ (V2), ``reject`` (V3), ``min_circle`` (V4) -- or the byte-identical
13
+ ``arrayprobe.particle_perimeter``; this module re-translates none of them.
14
+
15
+ Validation: ``octave_oracle/run_v35_measure_bank.py`` slices the block's own
16
+ lines out of the vendored file and runs them under Octave with the real v3.5
17
+ callees and the v3.5 ``CGAL_minR`` MEX; ``tests/test_v35_measure.py`` asserts
18
+ every output of every record against that fixture.
19
+
20
+
21
+ Three things the block does that a reader would not expect,
22
+ all measured and reproduced here as written:
23
+
24
+ * the override's ``is_hollow = 1`` (``:1236``) is overwritten by the reject
25
+ call's ninth output (``:1256-1260``) -- it reaches the file only as the
26
+ ``ihollow`` *input* to the reject function;
27
+ * ``CGAL_minR`` returns a 0-based centre (``CGAL_minR.cpp:80-84``) that
28
+ ``:1218-1219`` index 1-based, so the centre probe reads one pixel toward the
29
+ origin and every particle of two pixels or fewer is ruled hollow;
30
+ * ``sphericity`` (``:1272``) is MATLAB ``mrdivide`` of two growing row vectors
31
+ -- a least-squares slope over the record so far, exact only for ``kk == 1``.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import math
37
+ from dataclasses import dataclass, field
38
+ from typing import Any
39
+
40
+ import numpy as np
41
+
42
+ from arrayprobe_uiops.particle_perimeter import particle_perimeter
43
+ from arrayprobe_uiops.reject_core import RejectConfig
44
+
45
+ from .habit import HolroydNewResult, holroyd, holroyd_new, holroyd_new_hvps
46
+ from .hollow_size_rule import HollowSizeRule, resolve_ihollow, size_um_from_minr
47
+ from .min_circle import cgal_min_r_v35
48
+ from .particle import shadow_mask
49
+ from .reject import calculate_reject_unified
50
+
51
+ __all__ = [
52
+ "RecordGeometry",
53
+ "ParticleMeasurement",
54
+ "RecordMeasurements",
55
+ "STOCK_V35_REJECT_CONFIG",
56
+ "IMAGE_ASSISTED_V35_REJECT_CONFIG",
57
+ "measure_record",
58
+ "sphericity_mrdivide",
59
+ ]
60
+
61
+ #: ``calculate_reject_unified.m:60-66`` (v3.5) assigns these unconditionally at
62
+ #: the top of the function, so under the stock driver they are constants.
63
+ STOCK_V35_REJECT_CONFIG = RejectConfig(
64
+ rej_zero_area=True, rej_split=True, rej_hollow=True,
65
+ shadowed_area=25, max_edge_img_ar=6, max_comp_img_ar=5,
66
+ )
67
+
68
+ #: ``STOCK_V35_REJECT_CONFIG`` with **only** ``rej_hollow`` turned off --
69
+ #: every other field is the unchanged stock v3.5 value, cited on its own line
70
+ #: below against ``calculate_reject_unified.m`` in
71
+ #: ``UIOPS-v3.5/joefinlon-UIOPS-039be82/``.
72
+ #:
73
+ #: **This is NOT a second MATLAB tree's value, unlike
74
+ #: :data:`~arrayprobe.reject.ORACLES_PRODUCTION_REJECT_CONFIG`.** No fork ever
75
+ #: shipped this combination; it is a project decision (author,
76
+ #: 2026-09-18), made from the author's own 200 triage labels
77
+ #: against the hollow test's actual calls on the 2016-09-06 CIP:
78
+ #:
79
+ #: * **205-305 um: the hollow test discards 19 real particles in 25** -- about
80
+ #: 5,654 counts at stake in that bin, ~76% of them real.
81
+ #: * **105-205 um: ambiguous** (11 real / 14 artifact).
82
+ #: * **55-105 um: the test is correct 25/25.**
83
+ #:
84
+ #: This is the isolated half of an A/B that previously confounded two changes at
85
+ #: once (``ORACLES_PRODUCTION_V35`` moves ``rej_hollow`` AND both aspect-ratio
86
+ #: ceilings together), which is why stock showed *more* counts than production at
87
+ #: 55-105 um (R = 1.0396) while showing far fewer at 205-305 um (R = 0.2283) --
88
+ #: the looser aspect ratios were partly cancelling the stricter hollow test. This
89
+ #: profile moves only ``rej_hollow``, so a difference against ``STOCK_V35`` is
90
+ #: attributable to that one axis.
91
+ #:
92
+ #: **Honest caveat, because a single boolean cannot express size-dependent
93
+ #: labels**: turning ``rej_hollow`` off flat also admits the 55-105 um artifacts
94
+ #: the test was correctly catching there -- that bin is 68% artifact even among
95
+ #: particles BOTH configurations accept, so no threshold rescues it, and this
96
+ #: configuration is not optimal in that bin. The follow-on -- a size-dependent
97
+ #: accept/reject rule shaped like the labels themselves -- is new behaviour and
98
+ #: belongs opt-in inside the engine, not as a fourth package; it is not
99
+ #: this constant.
100
+ IMAGE_ASSISTED_V35_REJECT_CONFIG = RejectConfig(
101
+ rej_zero_area=True, # :60 stock sets rej_zero_area on -- unchanged from stock
102
+ rej_split=True, # :61 stock sets rej_split on -- unchanged from stock
103
+ rej_hollow=False, # :62 stock sets rej_hollow on -- OVERRIDDEN 1->0
104
+ shadowed_area=25, # :64 stock shadowed_area 25 -- unchanged from stock
105
+ max_edge_img_ar=6, # :65 stock max_edge_img_ar 6 -- unchanged from stock
106
+ max_comp_img_ar=5, # :66 stock max_comp_img_ar 5 -- unchanged from stock
107
+ )
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class RecordGeometry:
112
+ """The record-level inputs the block reads. Every field is required -- no
113
+ default picks a probe or a ``tasRatio`` (no default silently
114
+ picks a side)."""
115
+
116
+ diodesize: float #: ``handles.diodesize`` (mm/diode), from the probe table ``:141-235``
117
+ diodenum: int #: ``handles.diodenum``; also becomes ``handles.bits_per_slice`` (``:1206``) # noqa: E501
118
+ tas_ratio: float #: ``handles.tasRatio`` (``:709``/``:711``)
119
+ i_new_habit: int #: ``iNewHabit`` -- 0 ``holroyd.m``, 1 ``holroyd_new*.m``
120
+ probename: str #: ``'HVPS'`` selects ``holroyd_new_HVPS.m`` under ``iNewHabit == 1`` (``:1224``) # noqa: E501
121
+ i_calc_all_diode_stats: int = 0 #: ``iCalcAllDiodeStats`` (``:1207-1209``)
122
+ #: The size-dependent hollow rule. Defaults to a DISABLED rule, so every
123
+ #: existing caller is bit-identical -- the rule only ever bypasses the hollow
124
+ #: test above its threshold, and never manufactures a rejection.
125
+ hollow_size_rule: HollowSizeRule = field(default_factory=lambda: HollowSizeRule())
126
+
127
+
128
+ @dataclass
129
+ class ParticleMeasurement:
130
+ """One ``kk`` row of the ``images`` struct, MATLAB field names kept.
131
+
132
+ Source: the ``images`` fields filled in ``imgProc_sm.m:1204-1291`` (UIOOPS v3.5)."""
133
+
134
+ minR: float
135
+ ctx: float
136
+ cty: float
137
+ FS: float
138
+ holroyd_habit: str
139
+ is_hollow: int
140
+ image_length: float
141
+ image_width: float
142
+ image_area: float
143
+ longest_y_within_a_slice: int
144
+ max_top_edge_touching: int
145
+ max_bottom_edge_touching: int
146
+ image_touching_edge: object
147
+ auto_reject: str
148
+ percent_shadow: float
149
+ part_z: float
150
+ sf: float
151
+ area_hole_ratio: float
152
+ max_hole_diameter: float
153
+ edge_at_max_hole: float
154
+ center_in: int
155
+ AreaR: float
156
+ Perimeter: float
157
+ sphericity: float
158
+ axis_ratio: float
159
+ #: ``holroyd_new*``'s seven extra outputs; ``None`` under ``iNewHabit == 0``
160
+ new_habit: HolroydNewResult | None = None
161
+ #: ``images.diode_stats(kk, :)`` when ``iCalcAllDiodeStats``; else ``None``
162
+ diode_stats: np.ndarray | None = None
163
+
164
+
165
+ @dataclass
166
+ class RecordMeasurements:
167
+ """What one record's pass through ``imgProc_sm.m:1204-1291`` (UIOOPS v3.5) leaves behind: the
168
+ per-particle measurements, the accumulated ``diode_stats``, the last ``csum`` and the console
169
+ warnings. Returned by :func:`measure_record`."""
170
+ particles: list[ParticleMeasurement] = field(default_factory=list)
171
+ #: ``diode_stats`` accumulated over the record (``:1210``)
172
+ diode_stats_total: np.ndarray | None = None
173
+ #: the last particle's ``csum`` (``:1211``)
174
+ csum_last: np.ndarray | None = None
175
+ #: the ``:1277`` console warnings, one string per firing
176
+ warnings: list[str] = field(default_factory=list)
177
+
178
+
179
+ def sphericity_mrdivide(image_area: Any, perimeter: Any, tas_ratio: float) -> float:
180
+ """``:1272`` -- ``sqrt(images.image_area/handles.tasRatio)/images.Perimeter``
181
+ with BOTH operands the whole 1 x kk row vectors of the record so far.
182
+
183
+ Source: ``imgProc_sm.m:1272`` (UIOOPS v3.5).
184
+
185
+ ``/`` between two row vectors is MATLAB ``mrdivide``: it solves
186
+ ``x * b = a`` for the scalar ``x`` in the least-squares sense, i.e. the
187
+ slope of ``a`` on ``b`` through the origin. For ``kk == 1`` that is the
188
+ plain per-particle ratio; for every later ``kk`` it is not. Preserved.
189
+ """
190
+ a = np.sqrt(np.asarray(image_area, dtype=float) / tas_ratio)
191
+ b = np.asarray(perimeter, dtype=float)
192
+ if a.size == 1:
193
+ # A faithful 0/0 must still be nan (preserved, not "fixed"); this only
194
+ # silences the RuntimeWarning a real run emitted 3,927 times for it.
195
+ with np.errstate(invalid="ignore", divide="ignore"):
196
+ return float(a[0] / b[0])
197
+ # Octave solves the non-square `a / b` by Householder QR, not by SVD: `lstsq` (gelsd) landed
198
+ # 1 ULP off the Octave golden on Linux where QR matches it (cloud pass 7 item 4).
199
+ q, r = np.linalg.qr(b[:, None])
200
+ # A rank-deficient b (every perimeter 0) or an infinite pivot: Octave returns the
201
+ # minimum-norm solution, 0, where the QR division gives inf or NaN (cloud pass 8, F1;
202
+ # [1 2]/[0 0], [0 0]/[0 0] and [1 2]/[Inf 1] are all 0 under Octave 11.3).
203
+ if r[0, 0] == 0 or np.isinf(r[0, 0]):
204
+ return 0.0
205
+ return float((q.T @ a)[0] / r[0, 0])
206
+
207
+
208
+ def _ascii(shadow: np.ndarray) -> np.ndarray:
209
+ """``ParticlePerimeter.m`` and the C++ read ASCII codes; 48 is shadowed."""
210
+ return np.where(shadow, 48, 49).astype(np.int64)
211
+
212
+
213
+ def _habit_call(shadow: Any, geom: RecordGeometry) -> Any:
214
+ """``:1220-1230`` / ``:1238-1250`` -- which classifier, with which handles."""
215
+ if geom.i_new_habit == 0:
216
+ habit, fs = holroyd(shadow, geom.diodesize, bits_per_slice=geom.diodenum)
217
+ return habit, fs, None
218
+ fn = holroyd_new_hvps if geom.probename == "HVPS" else holroyd_new
219
+ res = fn(shadow, probe_resolution=geom.diodesize, tas_ratio=geom.tas_ratio,
220
+ bits_per_slice=geom.diodenum)
221
+ return res.holroyd_habit, res.F, res
222
+
223
+
224
+ def measure_record(images: Any, geom: RecordGeometry, reject_config: RejectConfig,
225
+ *, jit: bool = False) -> RecordMeasurements:
226
+ """Run ``:1204-1291`` over the particles of one record, in order.
227
+
228
+ Source: ``imgProc_sm.m:1204-1291`` (UIOOPS v3.5); bare line references here are into that file.
229
+
230
+ ``images`` is the sequence of per-particle ``c`` matrices (any form
231
+ :func:`arrayprobe.particle.shadow_mask` accepts; ``'0'`` / 48 / ``True`` is
232
+ shadowed), each ``n_slices x diodenum``. State that persists across ``kk``
233
+ -- ``diode_stats``, and the growing ``image_area``/``Perimeter`` vectors
234
+ that ``sphericity`` reads -- lives here, which is why the unit is a record
235
+ and not a particle.
236
+ """
237
+ out = RecordMeasurements()
238
+ diode_stats = np.zeros(geom.diodenum, dtype=float) # zeros(1, diodenum)
239
+ areas: list[float] = []
240
+ perims: list[float] = []
241
+ csum = None
242
+
243
+ for c in images:
244
+ shadow = shadow_mask(c)
245
+ if shadow.ndim != 2:
246
+ shadow = np.atleast_2d(shadow)
247
+ codes = _ascii(shadow)
248
+ n_slices = shadow.shape[0]
249
+
250
+ # :1207-1211
251
+ row_stats = shadow.sum(axis=0).astype(float) # sum(c=='0', 1)
252
+ diode_stats = diode_stats + row_stats
253
+ csum = row_stats
254
+
255
+ # :1213-1216. ``codes`` is already in the MEX's own orientation -- rows
256
+ # are slices, which is what :1207-1211's sum(c=='0', 1) above and
257
+ # x_img_max = n_slices below both assume -- so it is passed straight
258
+ # through. It was once passed as ``codes.T``,
259
+ # to compensate for min_circle.py scaling the column where
260
+ # CGAL_minR.cpp:75-84 scales the row; that defect was fixed 2026-09-11
261
+ # and the
262
+ # compensation came off with it. ctx is therefore the scaled SLICE
263
+ # centre, which is the axis the hollow window below indexes.
264
+ minR, ctx, cty = cgal_min_r_v35(codes, geom.tas_ratio)
265
+
266
+ # :1218-1236 -- the [EXPERIMENTAL] hollow override, ungated. The window
267
+ # is MATLAB 1-based on a 0-based centre: reproduced, not corrected.
268
+ x_img_max = n_slices
269
+ r_lo = max(1, math.floor(ctx))
270
+ r_hi = min(x_img_max, math.ceil(ctx))
271
+ c_lo = max(1, math.floor(cty))
272
+ c_hi = min(geom.diodenum, math.ceil(cty))
273
+ if r_hi >= r_lo and c_hi >= c_lo:
274
+ window = shadow[r_lo - 1:r_hi, c_lo - 1:c_hi]
275
+ n_unshadowed = int((~window).sum())
276
+ else:
277
+ n_unshadowed = 0 # empty range -> find([]) is empty # noqa: E501
278
+ override = (minR * geom.diodesize < 0.3) and n_unshadowed >= 1
279
+
280
+ if override:
281
+ _, fs, new_res = _habit_call(shadow, geom) # `[~, images.FS(kk)]`
282
+ habit = "s"
283
+ is_hollow = 1
284
+ else:
285
+ habit, fs, new_res = _habit_call(shadow, geom)
286
+ is_hollow = 0
287
+
288
+ # :1256-1260 -- every output reassigned, is_hollow included
289
+ # Two opt-in switches meet on this line, and both default to no-ops.
290
+ # `resolve_ihollow` is the size-dependent rule: above its threshold the
291
+ # hollow verdict is bypassed, because the author's 480 labels measured the
292
+ # hollow test discarding 60-87 % real particles there. `jit` routes the
293
+ # scan pass through arrayprobe_uiops.jit_kernels (6.33x, byte-identical).
294
+ rj = calculate_reject_unified(
295
+ codes, habit,
296
+ resolve_ihollow(is_hollow,
297
+ size_um_from_minr(minR, geom.diodesize),
298
+ geom.hollow_size_rule),
299
+ reject_config, jit=jit)
300
+ is_hollow = rj.is_hollow
301
+
302
+ # :1262-1267
303
+ image_area = float(shadow.sum())
304
+ disttoedge = min(abs(geom.diodenum - cty), cty)
305
+ touching = rj.touching_edge
306
+ touching_is_not_0 = (touching != "0") if isinstance(touching, str) else (touching != ord("0")) # noqa: E501
307
+ if rj.center_in == 1 and touching_is_not_0:
308
+ with np.errstate(divide="ignore", invalid="ignore"):
309
+ image_area = float(np.float64(image_area) * 2 * (rj.width - disttoedge) / rj.width)
310
+
311
+ # :1270-1272
312
+ area_r = 2 * math.sqrt(image_area / 3.1415926 / geom.tas_ratio)
313
+ perimeter = particle_perimeter(codes) / math.sqrt(geom.tas_ratio)
314
+ areas.append(image_area)
315
+ perims.append(perimeter)
316
+ sphericity = sphericity_mrdivide(areas, perims, geom.tas_ratio)
317
+
318
+ # :1274-1280 -- Korolev correction retargeted onto minR
319
+ if rj.reject_status == "H":
320
+ minR = minR / rj.size_factor
321
+ if habit != "s":
322
+ out.warnings.append(f"WARNING: Habit should be spherical but is {habit}")
323
+
324
+ # :1282-1285
325
+ if rj.center_in == 0:
326
+ habit = "C"
327
+
328
+ # :1287-1291
329
+ axis_ratio = rj.p_length / rj.width if rj.width != 0 else 0.0
330
+
331
+ out.particles.append(ParticleMeasurement(
332
+ minR=minR, ctx=ctx, cty=cty, FS=fs, holroyd_habit=habit, is_hollow=is_hollow,
333
+ image_length=rj.p_length, image_width=rj.width, image_area=image_area,
334
+ longest_y_within_a_slice=rj.longest_y, max_top_edge_touching=rj.max_top,
335
+ max_bottom_edge_touching=rj.max_bottom, image_touching_edge=touching,
336
+ auto_reject=rj.reject_status, percent_shadow=rj.percent_shadow_area,
337
+ part_z=rj.part_z, sf=rj.size_factor, area_hole_ratio=rj.area_hole_ratio,
338
+ max_hole_diameter=rj.max_hole_diameter, edge_at_max_hole=rj.edge_at_max_hole,
339
+ center_in=rj.center_in, AreaR=area_r, Perimeter=perimeter, sphericity=sphericity,
340
+ axis_ratio=axis_ratio, new_habit=new_res,
341
+ diode_stats=row_stats.copy() if geom.i_calc_all_diode_stats else None,
342
+ ))
343
+
344
+ out.diode_stats_total = diode_stats
345
+ out.csum_last = csum
346
+ return out
@@ -0,0 +1,204 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Smallest enclosing circle, v3.5's version -- ``CGAL_minR.cpp`` gained a
3
+ true-airspeed-ratio input and a circle-centre output over v3.1.4 (Wei Wu,
4
+ June 3 2019; Joe Finlon, May 12 2019).
5
+
6
+ **What actually changed**, from the real diff (v3.1.4 vs. v3.5's
7
+ ``CGAL_minR.cpp``), not the design doc's earlier one-line summary:
8
+
9
+ * A second input, ``tasRatio``. Every point's *row* coordinate is divided
10
+ by it before the circle is computed. ``CGAL_minR.cpp:75-84`` walks the
11
+ MATLAB array **column-major** -- ``m = mxGetM`` is the row count, and the
12
+ inner loop variable ``j`` indexes ``ICEPIC[i*m+j]``, so ``j`` is the
13
+ **row** and ``i`` the column::
14
+
15
+ for i<n { for j<m { if ICEPIC[i*m+j]=='0' { p[0] = j / *tasRatio;
16
+ p[1] = i; } } }
17
+
18
+ so ``p[0]`` is the scaled row and ``p[1]`` the unscaled column.
19
+ * The output grows from a scalar diameter to a ``1x3`` row: diameter, then
20
+ the enclosing circle's centre in the SAME two coordinates the points were
21
+ given in -- ``B[1] = center[0]`` = centre **row** (scaled),
22
+ ``B[2] = center[1]`` = centre **column** (unscaled), at ``:115-120``.
23
+ ``imgProc_sm.m``'s v3.5 call site reads them as
24
+ ``images.minR(kk)=tempreturn(1)``, ``images.ctx(kk)=tempreturn(2)``,
25
+ ``images.cty(kk)=tempreturn(3)`` (``:1213-1216``) -- so ``ctx`` is the
26
+ scaled-**row** centre, ``cty`` the unscaled-**column** centre, and the
27
+ diameter is ``1 + hypot(drow / tasRatio, dcol)``.
28
+
29
+ **This axis convention was read the wrong way round when this module was
30
+ first written** (``j`` taken as the column), and the error survived
31
+ validation because the square-bank fixture fed the port the transpose of
32
+ the matrix the MEX saw and all 30 of its non-error records are 11x11 --
33
+ two errors that cancel exactly on a square grid. Proven both ways on 60
34
+ non-square records against the real compiled ``CGAL_minR_v35.mex``,
35
+ pinned by
36
+ ``tests/test_v35_min_circle_axis.py``.
37
+ * The empty-*matrix* case (``0 == m*n``, i.e. the array itself has zero rows
38
+ or columns -- unrelated to whether any pixel is shadowed) now sets all
39
+ three outputs to 0.0, printing "No Illuminated Doide!" unconditionally
40
+ (v3.1.4 has the same message, commented out, and only zeroed the single
41
+ scalar).
42
+
43
+ **A non-empty matrix with no shadowed ('0') pixel returns NaN** -- the same
44
+ value the v3.1.4 port returns, and for the same reason. Such an image falls
45
+ through to Miniball with an empty point range in BOTH versions; the v3.5
46
+ diff added no check for it. ``Miniball.hpp:192``'s
47
+ ``assert(points_begin != points_end)`` is what decides the outcome, and
48
+ whether it is live depends entirely on the **build flags**:
49
+
50
+ * Built WITHOUT ``-DNDEBUG`` -- which is what ``mex_build/`` holds, because
51
+ Octave's bare ``mkoctfile`` does not define it -- the assert fires and the
52
+ process aborts. That is what this module was originally written against,
53
+ and it is the wrong oracle: no MATLAB user ever runs that binary.
54
+ * Built WITH ``-DNDEBUG``, **MATLAB's own documented ``mex`` release
55
+ default**, the assert is compiled out, ``pivot_mb`` loops over nothing,
56
+ ``current_sqr_r`` stays at its initial ``-1`` (``Miniball.hpp:183``) and
57
+ the caller takes ``sqrt(-1)``. Re-measured 2026-09-16 by
58
+ rebuilding the unmodified ``CGAL_minR.cpp`` of BOTH versions with
59
+ ``-DNDEBUG`` and running each input in its own Octave process: v3.5
60
+ returns ``[NaN 0 0]``, v3.1.4 returns ``NaN``, exit code 0, neither
61
+ aborts. ``scripts/validation/octave/mex_ndebug_v35_remeasure/
62
+ probe_results.log``.
63
+
64
+
65
+ Raising here was therefore a **behaviour this port invented** and the
66
+ original does not have, and it halted every real flight: 3,932 of 49,637
67
+ particles (7.92 %) on ``base160906064403`` hit this path, and 0 of 66 S3
68
+ blocks completed. Returning ``(nan, 0.0, 0.0)`` is a fidelity correction,
69
+ not an enhancement -- it makes the port match what MATLAB, built as MATLAB
70
+ builds it, actually produces, and it makes v3.5 agree with the v3.1.4 port
71
+ (``arrayprobe.geometry.min_circle.cgal_min_r:199-206``), which was written
72
+ against release behaviour from the start and has consequently never halted.
73
+ Pinned by ``tests/test_v35_min_circle_ndebug_matches_v314.py``.
74
+ :class:`NoShadowedPixelsError` is kept defined for importers and is not
75
+ raised on this path.
76
+
77
+ **Exact arithmetic survives the scaling.** ``tas_ratio`` is a runtime float,
78
+ but ``Fraction(tas_ratio)`` is the EXACT value of that float (Python's
79
+ ``Fraction`` from a float never rounds), so dividing an integer row index by
80
+ it stays exact -- there is still no floating-point tolerance anywhere in the
81
+ circle computation, the same property that makes the v3.1.4 port exact.
82
+ The per-column hull reduction (:func:`arrayprobe.geometry.min_circle.
83
+ _hull_candidates`) is computed on the ORIGINAL, unscaled integer coordinates
84
+ before scaling is applied. It groups by column and keeps the topmost and
85
+ bottommost *row* in each: dividing every row index by the same positive
86
+ ``tas_ratio`` is a monotone map, so it cannot change which point is topmost
87
+ or bottommost within a column, and it does not touch the column values the
88
+ grouping is keyed on. The reduction therefore stays exact whichever side of
89
+ the scaling it runs on, and running it first means the existing v3.1.4
90
+ helper is reused unchanged rather than re-derived.
91
+
92
+ Provenance: ``CGAL_minR.cpp`` (whole file, v3.5); called at
93
+ ``imgProc_sm.m:1213-1215`` (v3.5). ``Miniball.hpp`` unchanged from v3.1.4.
94
+ """
95
+
96
+ from __future__ import annotations
97
+
98
+ import math
99
+ from fractions import Fraction
100
+ from typing import Any
101
+
102
+ import numpy as np
103
+
104
+ from .geometry_core import (
105
+ _from_three,
106
+ _from_two,
107
+ _hull_candidates,
108
+ _shadow_points,
109
+ )
110
+
111
+ __all__ = ["cgal_min_r_v35", "NoShadowedPixelsError"]
112
+
113
+
114
+ class NoShadowedPixelsError(RuntimeError):
115
+ """**Not raised by this module.** It names the
116
+ abort a ``CGAL_minR`` built WITHOUT ``-DNDEBUG`` performs on a non-empty
117
+ matrix with no shadowed pixel. Built WITH ``-DNDEBUG`` -- MATLAB's own
118
+ ``mex`` release default -- the same source returns NaN and exits 0, so
119
+ :func:`cgal_min_r_v35` returns ``(nan, 0.0, 0.0)`` there instead. Kept
120
+ defined so existing importers still resolve. See the module docstring."""
121
+
122
+
123
+ def _min_enclosing_circle_exact_scaled(points: Any, tas_ratio: float) -> Any:
124
+ """:func:`arrayprobe.geometry.min_circle.min_enclosing_circle_exact`,
125
+ generalized to scale each point's **row** (index 0) by ``1 / tas_ratio``
126
+ in exact rational arithmetic before running Welzl's algorithm.
127
+
128
+ Index 0 is the row because ``_shadow_points`` returns ``(row, column)``
129
+ and ``CGAL_minR.cpp:75-84`` divides the row index -- see the module
130
+ docstring for the column-major derivation.
131
+
132
+ Duplicated rather than parameterizing the v3.1.4 function: that function
133
+ is the v3.1.4 port and must stay untouched (its own fidelity claim does
134
+ not involve ``tas_ratio` at all), and the shuffle/incremental logic is
135
+ small enough that copying it here is clearer than threading a scale
136
+ factor through a function whose whole point is "no v3.5 concept leaks
137
+ into it."
138
+ """
139
+ import random
140
+
141
+ inv_tas = Fraction(1) / Fraction(tas_ratio)
142
+ pts = [(Fraction(int(p[0])) * inv_tas, Fraction(int(p[1]))) for p in points]
143
+ if not pts:
144
+ return None
145
+ random.Random(0x6D696E52).shuffle(pts)
146
+
147
+ def contains(circle: Any, p: Any) -> Any:
148
+ cx, cy, r2 = circle
149
+ dx = p[0] - cx
150
+ dy = p[1] - cy
151
+ return dx * dx + dy * dy <= r2
152
+
153
+ circle = (pts[0][0], pts[0][1], Fraction(0))
154
+ for i, p in enumerate(pts):
155
+ if contains(circle, p):
156
+ continue
157
+ circle = (p[0], p[1], Fraction(0))
158
+ for j, q in enumerate(pts[:i]):
159
+ if contains(circle, q):
160
+ continue
161
+ circle = _from_two(p, q)
162
+ for r in pts[:j]:
163
+ if not contains(circle, r):
164
+ circle = _from_three(p, q, r)
165
+ return circle
166
+
167
+
168
+ def cgal_min_r_v35(c: Any, tas_ratio: float) -> tuple[float, float, float]:
169
+ """``CGAL_minR(c, tasRatio)`` -- v3.5's 3-output form.
170
+
171
+ Returns ``(diameter, ctx, cty)`` matching ``imgProc_sm.m``'s own
172
+ ``tempreturn(1)``/``(2)``/``(3)`` unpacking: ``ctx`` is the enclosing
173
+ circle's centre along the (tas-ratio-scaled) **row** axis, ``cty`` along
174
+ the (unscaled) **column** axis. ``c`` must be given in the orientation
175
+ the MEX itself sees -- rows are diodes, columns are slices; passing the
176
+ transpose silently returns the two centres swapped and, whenever
177
+ ``tas_ratio != 1``, a wrong diameter.
178
+
179
+ Two edge cases, both taken from the C++ rather than invented -- see the
180
+ module docstring for the full derivation:
181
+
182
+ * **An empty matrix returns (0.0, 0.0, 0.0).** ``CGAL_minR.cpp`` (v3.5)
183
+ tests ``0 == m*n`` and zeroes all three outputs before touching
184
+ Miniball -- the same test v3.1.4 has, extended to the wider output.
185
+ * **A non-empty matrix with no shadowed pixel returns
186
+ ``(nan, 0.0, 0.0)``.** Measured on the real ``CGAL_minR.cpp`` rebuilt
187
+ with ``-DNDEBUG``, MATLAB's own ``mex`` release default: ``[NaN 0 0]``,
188
+ exit code 0. The same value the earlier translation returns. A non-NDEBUG
189
+ build halts instead; :class:`NoShadowedPixelsError` stays defined
190
+ for importers and is never raised here (see the module docstring).
191
+ """
192
+ a = np.asarray(c)
193
+ if a.size == 0:
194
+ return (0.0, 0.0, 0.0)
195
+ points = _shadow_points(a)
196
+ if len(points) == 0:
197
+ # Miniball leaves current_sqr_r at -1 and the caller takes sqrt(-1);
198
+ # the two centre outputs were never assigned past their 0.0 init.
199
+ return (math.nan, 0.0, 0.0)
200
+ reduced = _hull_candidates(points)
201
+ circle = _min_enclosing_circle_exact_scaled(reduced, tas_ratio)
202
+ center_row, center_col, r2 = circle
203
+ diameter = 1.0 + 2.0 * math.sqrt(float(r2))
204
+ return diameter, float(center_row), float(center_col)