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,344 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Opt-in accelerated kernels for the particle-image stage -- ``imgproc_sm(..., jit=True)``.
3
+
4
+ **Space: the port.** Every kernel here returns the same value as the function it
5
+ replaces, bit for bit, so a run with ``jit=True`` writes the same bytes as one
6
+ without (``tests/test_imgproc_jit_identity.py`` runs both and compares the files).
7
+ It is opt-in and defaults off, and numba -- an optional extra
8
+ (``pip install "arrayprobe[jit]"``) -- is imported only when a caller asks for it, never
9
+ by ``import arrayprobe``.
10
+
11
+ Which kernels, and why only these: the function-level profile of S3 on a dense
12
+ ORACLES window ranked the
13
+ per-particle work. Each kernel below is one of its hot rows and is exact by
14
+ construction -- integer or boolean logic only, no floating-point expression is
15
+ evaluated in a different order or by a different library:
16
+
17
+ ``dec2bin_concat``
18
+ The ``[dec2bin(X(:,1),w), ...]`` framing idiom, fused into one NumPy shift
19
+ over all columns. Integer bit extraction; identical by construction. Falls
20
+ back to :func:`arrayprobe.matlab_compat.dec2bin_concat` whenever a column
21
+ would need MATLAB's widening (a value wider than ``width`` bits) or the input
22
+ holds a negative, so both of those behaviours stay in one place.
23
+ ``particle_perimeter``
24
+ ``ParticlePerimeter.m``'s 4-neighbour boundary count, as a numba loop over
25
+ the image. Integer comparisons and a counter.
26
+ ``cgal_min_r``
27
+ The minimum enclosing circle. :mod:`arrayprobe.geometry.min_circle` computes
28
+ it in exact rational arithmetic (``fractions.Fraction``); the kernel runs the
29
+ *same* Welzl pass, over the same shuffled candidates, with every circle held
30
+ in homogeneous integers ``(X, Y, R2, D)`` -- centre ``(X/D, Y/D)``, squared
31
+ radius ``R2/D**2``, ``D > 0`` -- so every predicate is the same exact
32
+ comparison the Fraction path makes. Every int64 operation is guarded to keep
33
+ magnitudes below ``2**62``; if any would exceed it, the kernel reports failure
34
+ and the particle is recomputed on the Fraction path. The final ``sqrt`` is
35
+ taken in Python on ``R2 / D**2`` as Python integers, which is correctly
36
+ rounded -- the same float ``float(Fraction(R2, D**2))`` gives. So the guarded
37
+ path is exact whenever it answers and the fallback is the original whenever it
38
+ does not.
39
+
40
+ How often the guard trips (derived, then measured): every circle Welzl builds
41
+ is the smallest one through its fixed points containing a subset, so none is
42
+ larger than the final circle; on a 2D-S image (128 x at most 1700 pixels)
43
+ that bounds the centre to a few thousand diodes, ``D`` (four times a triangle's
44
+ area) below 4.4e5, and ``R2`` below ~6e17 -- inside the guard. Measured: 0
45
+ fallbacks in 21,916 dense-cloud particles. The guard is still there because
46
+ the kernel accepts any shape below ``2**15``, and the test suite drives it
47
+ with coordinates near that to prove it refuses rather than overflows.
48
+
49
+ What stays out, on purpose: :func:`arrayprobe.habit.holroyd` (its rotation and
50
+ ``arctan``/``cos``/``sin`` are floating point, where a different libm or an FMA
51
+ contraction can move a ULP -- not provable here).
52
+
53
+ **``arrayprobe.reject.calculate_reject_unified`` -- corrected 2026-09-18.**
54
+ Its hot kernels are only partly "already numba-compiled in ``reject.py``,
55
+ measured and fuzz-tested there", and a real v3.5 CIP production profile
56
+ (``_decoded/cip160906/V35_JIT.md``,
57
+ ``_decoded/cip160906/V35_REJECT_JIT.md``) showed it does not
58
+ cover what actually runs hot on that path. What ``reject.py`` (this v3.1.4 module's
59
+ sibling) actually compiles, measured by reading ``_ensure_numba_loaded``
60
+ rather than assumed from the function names alone:
61
+
62
+ - :func:`arrayprobe.reject.scan_slice` and
63
+ :func:`arrayprobe.reject.is_it_hollow_sidescan` dispatch to numba kernels
64
+ whenever numba is importable -- unconditionally, not gated by any
65
+ ``jit=`` flag, the opposite posture from the kernels in *this* module.
66
+ - :func:`arrayprobe.reject.is_it_hollow` (the **non**-sidescan scan) is only
67
+ partly covered: its internal ``scan_slice`` calls benefit, but its own
68
+ ``_pack``/``_popcount``/``mask_start_end`` calls are the plain-Python
69
+ bodies even when numba is present -- unlike ``is_it_hollow_sidescan``,
70
+ it never got a single fused kernel for its own loop.
71
+ - :func:`arrayprobe.reject.calculate_reject_unified` itself -- the per-slice
72
+ scanning pass, the aspect-ratio/threshold ladder, the Korolev lookup --
73
+ has no numba dispatch of any kind; it benefits only indirectly, through
74
+ ``scan_slice``.
75
+
76
+ None of this reaches the **v3.5 engine** at all: ``arrayprobe_uiops.reject``
77
+ has its own, differently-algorithmed ``calculate_reject_unified`` and
78
+ ``is_it_hollow`` (v3.5 dropped v3.1.4's middle-third restriction and its
79
+ pack/bitshift hollow test for a direct ``bitand``), sharing only
80
+ ``scan_slice`` with this module. Measured on a real v3.5 CIP production
81
+ pass, ``calculate_reject_unified`` was the single largest cost centre in a
82
+ full ``imgproc_sm_v35`` call -- larger than either kernel in this module's
83
+ own table. v3.5 now has its own opt-in kernels for it,
84
+ :mod:`arrayprobe_uiops.jit_kernels` (``calculate_reject_unified(jit=True)`` /
85
+ ``is_it_hollow(jit=True)``), which fuse each whole per-particle loop into
86
+ one compiled call rather than one dispatch per slice. This v3.1.4 module's
87
+ own kernels are unchanged by that work.
88
+ """
89
+
90
+ from __future__ import annotations
91
+
92
+ import math
93
+ import random
94
+
95
+ import numpy as np
96
+
97
+ from arrayprobe_uiops import geometry_core as _mc
98
+
99
+ from .matlab_compat import dec2bin_concat as _dec2bin_concat_reference
100
+ from .particle import shadow_mask
101
+
102
+ __all__ = ["JitKernels", "load", "FALLBACKS"]
103
+
104
+ _ZERO = ord("0")
105
+
106
+ #: Particles whose minimum-circle kernel hit the int64 guard and were recomputed
107
+ #: on the exact Fraction path, since the process started. Measured, not
108
+ #: assumed: the profile record reports the rate on the dense window.
109
+ FALLBACKS = {"min_circle": 0}
110
+
111
+
112
+ # --------------------------------------------------------------------------
113
+ # dec2bin_concat -- NumPy, no numba needed.
114
+ # --------------------------------------------------------------------------
115
+
116
+
117
+ def dec2bin_concat(columns, width):
118
+ """Fused :func:`arrayprobe.matlab_compat.dec2bin_concat`; same array, same dtype."""
119
+ cols = np.asarray(columns)
120
+ if cols.ndim == 1:
121
+ cols = cols.reshape(-1, 1)
122
+ vals = cols.astype(np.int64)
123
+ w = int(width)
124
+ if vals.size == 0 or vals.min() < 0 or (vals.max() >> w) != 0:
125
+ # Empty, negative (MATLAB errors) or widening (a column needs > w bits):
126
+ # the reference handles each of those, per column, exactly as MATLAB.
127
+ return _dec2bin_concat_reference(columns, width)
128
+ shifts = np.arange(w - 1, -1, -1, dtype=np.int64)
129
+ bits = (vals[:, :, None] >> shifts[None, None, :]) & 1
130
+ return (bits.reshape(vals.shape[0], vals.shape[1] * w) + _ZERO).astype(np.uint8)
131
+
132
+
133
+ # --------------------------------------------------------------------------
134
+ # Pure-Python kernel bodies; numba compiles them on first use (see load()).
135
+ # --------------------------------------------------------------------------
136
+
137
+
138
+ def _perimeter_kernel(c):
139
+ m, n = c.shape
140
+ count = 0
141
+ for i in range(m):
142
+ for j in range(n):
143
+ if c[i, j] == 48:
144
+ if (i + 1 >= m or c[i + 1, j] != 48
145
+ or i == 0 or c[i - 1, j] != 48
146
+ or j + 1 >= n or c[i, j + 1] != 48
147
+ or j == 0 or c[i, j - 1] != 48):
148
+ count += 1
149
+ return count
150
+
151
+
152
+ def _hull_kernel(mask):
153
+ """Per column, ascending: (topmost row, col), (bottommost row, col).
154
+
155
+ The same list, in the same order, as ``min_circle._hull_candidates`` builds
156
+ from ``np.nonzero`` + a stable sort by column.
157
+ """
158
+ m, n = mask.shape
159
+ out = np.empty((2 * n, 2), dtype=np.int64)
160
+ k = 0
161
+ for j in range(n):
162
+ lo = -1
163
+ hi = -1
164
+ for i in range(m):
165
+ if mask[i, j]:
166
+ if lo < 0:
167
+ lo = i
168
+ hi = i
169
+ if lo >= 0:
170
+ out[k, 0] = lo
171
+ out[k, 1] = j
172
+ out[k + 1, 0] = hi
173
+ out[k + 1, 1] = j
174
+ k += 2
175
+ return out[:k]
176
+
177
+
178
+ _LIM = 1 << 62
179
+
180
+
181
+ def _welzl_kernel(pts):
182
+ """Welzl over homogeneous int64 circles; returns (ok, R2, D).
183
+
184
+ Mirrors ``min_circle.min_enclosing_circle_exact`` line for line. ``ok`` is
185
+ False when a product would exceed 2**62 or a square 2**62 (so a sum of two
186
+ squares stays below 2**63); the caller then recomputes on the Fraction path.
187
+ """
188
+ lim = _LIM
189
+ n = pts.shape[0]
190
+ # circle = (X, Y, R2, D): centre (X/D, Y/D), r2 = R2 / D**2, D > 0.
191
+ cx = pts[0, 0]
192
+ cy = pts[0, 1]
193
+ cr = 0
194
+ cd = 1
195
+ for i in range(n):
196
+ p0 = pts[i, 0]
197
+ p1 = pts[i, 1]
198
+ # _contains(circle, p)
199
+ if abs(p0) > lim // cd or abs(p1) > lim // cd:
200
+ return False, 0, 0
201
+ dx = p0 * cd - cx
202
+ dy = p1 * cd - cy
203
+ if abs(dx) >= 3037000499 or abs(dy) >= 3037000499: # isqrt(2**63 - 1)
204
+ return False, 0, 0
205
+ if dx * dx >= lim or dy * dy >= lim:
206
+ return False, 0, 0
207
+ if dx * dx + dy * dy <= cr:
208
+ continue
209
+ cx, cy, cr, cd = p0, p1, 0, 1
210
+ for j in range(i):
211
+ q0 = pts[j, 0]
212
+ q1 = pts[j, 1]
213
+ if abs(q0) > lim // cd or abs(q1) > lim // cd:
214
+ return False, 0, 0
215
+ dx = q0 * cd - cx
216
+ dy = q1 * cd - cy
217
+ if abs(dx) >= 3037000499 or abs(dy) >= 3037000499:
218
+ return False, 0, 0
219
+ if dx * dx >= lim or dy * dy >= lim:
220
+ return False, 0, 0
221
+ if dx * dx + dy * dy <= cr:
222
+ continue
223
+ # _from_two(p, q): centre (p+q)/2, r2 = |p-q|**2 / 4.
224
+ ex = p0 - q0
225
+ ey = p1 - q1
226
+ cx, cy, cr, cd = p0 + q0, p1 + q1, ex * ex + ey * ey, 2
227
+ for r in range(j):
228
+ r0 = pts[r, 0]
229
+ r1 = pts[r, 1]
230
+ if abs(r0) > lim // cd or abs(r1) > lim // cd:
231
+ return False, 0, 0
232
+ dx = r0 * cd - cx
233
+ dy = r1 * cd - cy
234
+ if abs(dx) >= 3037000499 or abs(dy) >= 3037000499:
235
+ return False, 0, 0
236
+ if dx * dx >= lim or dy * dy >= lim:
237
+ return False, 0, 0
238
+ if dx * dx + dy * dy <= cr:
239
+ continue
240
+ # _from_three(p, q, r). Coordinates are pixel indices (< 2**15,
241
+ # checked by the caller), so d, a2.. and the numerators below
242
+ # stay far inside int64 before any guard is needed.
243
+ d = 2 * (p0 * (q1 - r1) + q0 * (r1 - p1) + r0 * (p1 - q1))
244
+ if d == 0:
245
+ # Collinear: the widest of the three two-point circles,
246
+ # ties keeping the earlier one (Fraction's `>` is strict).
247
+ ex = p0 - q0
248
+ ey = p1 - q1
249
+ bx, by, br = p0 + q0, p1 + q1, ex * ex + ey * ey
250
+ ex = p0 - r0
251
+ ey = p1 - r1
252
+ if ex * ex + ey * ey > br:
253
+ bx, by, br = p0 + r0, p1 + r1, ex * ex + ey * ey
254
+ ex = q0 - r0
255
+ ey = q1 - r1
256
+ if ex * ex + ey * ey > br:
257
+ bx, by, br = q0 + r0, q1 + r1, ex * ex + ey * ey
258
+ cx, cy, cr, cd = bx, by, br, 2
259
+ continue
260
+ a2 = p0 * p0 + p1 * p1
261
+ b2 = q0 * q0 + q1 * q1
262
+ c2 = r0 * r0 + r1 * r1
263
+ ux = a2 * (q1 - r1) + b2 * (r1 - p1) + c2 * (p1 - q1)
264
+ uy = a2 * (r0 - q0) + b2 * (p0 - r0) + c2 * (q0 - p0)
265
+ if d < 0:
266
+ d = -d
267
+ ux = -ux
268
+ uy = -uy
269
+ # r2 = (ax - ux/d)**2 + (ay - uy/d)**2 = R2 / d**2.
270
+ if abs(p0) > lim // d or abs(p1) > lim // d:
271
+ return False, 0, 0
272
+ ex = p0 * d - ux
273
+ ey = p1 * d - uy
274
+ if abs(ex) >= 3037000499 or abs(ey) >= 3037000499:
275
+ return False, 0, 0
276
+ if ex * ex >= lim or ey * ey >= lim:
277
+ return False, 0, 0
278
+ cx, cy, cr, cd = ux, uy, ex * ex + ey * ey, d
279
+ return True, cr, cd
280
+
281
+
282
+ # --------------------------------------------------------------------------
283
+ # The loaded kernel set.
284
+ # --------------------------------------------------------------------------
285
+
286
+
287
+ class JitKernels:
288
+ """The compiled kernels, and the drop-in functions imgproc calls through."""
289
+
290
+ def __init__(self, njit):
291
+ opts = {"cache": True, "boundscheck": True} # fastmath stays OFF
292
+ self._perimeter = njit(**opts)(_perimeter_kernel)
293
+ self._hull = njit(**opts)(_hull_kernel)
294
+ self._welzl = njit(**opts)(_welzl_kernel)
295
+ self.dec2bin_concat = dec2bin_concat
296
+
297
+ def particle_perimeter(self, c) -> int:
298
+ """Drop-in for :func:`arrayprobe.particle_perimeter.particle_perimeter`."""
299
+ a = np.asarray(c)
300
+ if a.ndim != 2 or a.dtype.kind not in "iu":
301
+ from .particle_perimeter import particle_perimeter
302
+ return particle_perimeter(c)
303
+ return int(self._perimeter(np.ascontiguousarray(a)))
304
+
305
+ def cgal_min_r(self, c) -> float:
306
+ """Drop-in for :func:`arrayprobe_uiops.geometry_core.cgal_min_r`."""
307
+ a = np.asarray(c)
308
+ if a.size == 0:
309
+ return 0.0
310
+ mask = np.ascontiguousarray(shadow_mask(a))
311
+ if mask.ndim != 2 or not mask.any():
312
+ return _mc.cgal_min_r(c) # NaN (no shadowed pixel) or an unusual shape
313
+ cand = self._hull(mask)
314
+ pts = [(int(r), int(k)) for r, k in cand]
315
+ random.Random(_mc._SEED).shuffle(pts)
316
+ ok = False
317
+ if max(mask.shape) < (1 << 15):
318
+ ok, r2, d = self._welzl(np.asarray(pts, dtype=np.int64))
319
+ if not ok:
320
+ FALLBACKS["min_circle"] += 1
321
+ return _mc.cgal_min_r(c)
322
+ # Python ints: int / int is correctly rounded, so this is exactly
323
+ # float(Fraction(r2, d*d)) -- what math.sqrt(Fraction) evaluates.
324
+ return 1.0 + 2.0 * math.sqrt(int(r2) / (int(d) * int(d)))
325
+
326
+
327
+ _LOADED: JitKernels | None = None
328
+
329
+
330
+ def load() -> JitKernels:
331
+ """Import numba and compile (or load from cache) the kernels, once per process."""
332
+ global _LOADED
333
+ if _LOADED is None:
334
+ try:
335
+ from numba import njit
336
+ except ImportError as exc: # pragma: no cover - exercised only without the extra
337
+ raise ModuleNotFoundError(
338
+ "imgproc_sm(jit=True) / --jit needs numba, an optional extra: "
339
+ 'pip install "arrayprobe[jit]" ("arrayprobe[pinned]" installs the tested pin). '
340
+ "The default "
341
+ "(jit=False) writes the same bytes without it."
342
+ ) from exc
343
+ _LOADED = JitKernels(njit)
344
+ return _LOADED
arrayprobe/lwc.py ADDED
@@ -0,0 +1,44 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Liquid water content from a particle size distribution.
3
+
4
+ Ported from: lwc_calc.m (UIOOPS v3.1.4)
5
+
6
+ ``lwc_calc.m`` is byte-identical in v3.1.4 and v3.5, so the one translation lives in the v3.5
7
+ engine, ``arrayprobe_uiops.lwc``: code both engines share sits there and the v3.1.4 package
8
+ imports it, never the reverse. This module re-exports it **lazily** (PEP 562 ``__getattr__``),
9
+ so importing ``arrayprobe.lwc`` -- and through it ``arrayprobe.sizedist`` and
10
+ ``arrayprobe.cli`` -- loads no v3.5 engine module; the first access to ``lwc_calc`` does.
11
+ Callers of ``arrayprobe.lwc.lwc_calc`` get the same function object as
12
+ ``arrayprobe_uiops.lwc.lwc_calc``, so the computed bytes cannot differ between the engines.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ #: Declared so the public surface is explicit rather than whatever happens not to
20
+ #: start with an underscore. The Phase-1 shims at ``<name>.py`` in the original flat layout import
21
+ #: these names directly, CONSTANTS INCLUDED -- omitting a constant here would not
22
+ #: break them, but omitting one from a shim does, which is why they are listed.
23
+ #: Every name here is re-exported from ``arrayprobe_uiops.lwc`` on first access.
24
+ __all__ = [
25
+ "lwc_calc",
26
+ ]
27
+
28
+ if TYPE_CHECKING: # pragma: no cover - static typing only, never executed
29
+ from arrayprobe_uiops.lwc import lwc_calc as lwc_calc
30
+
31
+
32
+ def __getattr__(name: str) -> Any:
33
+ """Resolve a public name from ``arrayprobe_uiops.lwc`` on first access, and cache it."""
34
+ if name in __all__:
35
+ from arrayprobe_uiops import lwc as _home
36
+
37
+ value = getattr(_home, name)
38
+ globals()[name] = value
39
+ return value
40
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
41
+
42
+
43
+ def __dir__() -> list[str]:
44
+ return sorted(set(globals()) | set(__all__))