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,119 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """The production-variant ``IntArrAnalysis_time.m:220-291``: the contoured inter-arrival figure.
3
+
4
+ Opt-in and decoupled from the core port: importing :mod:`arrayprobe.intarr_analysis`, or
5
+ any other module in this package, never requires matplotlib. This module is the one place that
6
+ does, and it is imported lazily inside :func:`plot_intarr_contour` itself, not at module load.
7
+
8
+ **Reproduces the source figure's data, axes and contour levels** -- the 69-bin contour
9
+ (:data:`arrayprobe.intarr_analysis.CONTOUR_BINS`, ``:220``), the fill levels
10
+ (:data:`arrayprobe.intarr_analysis.CONTOUR_LEVELS`, ``0.005:0.005:0.1`` at ``:272``), the three
11
+ threshold overlay lines (``:278-280``), the log y-axis over ``[1e-7, 1]`` (``:282``) and an
12
+ ``HH:MM`` time x-axis (``datetick('x','HH:MM')``, also ``:282``).
13
+
14
+ **``fix_b8=False`` (default, matching every real run of the source) reproduces the NaN
15
+ pre-10:00 timestamps** on the three overlay lines' own time axis: :func:`arrayprobe.intarr_analysis.
16
+ overlay_time_axis` returns NaN for every particle before 10:00:00 in a file that also has one at
17
+ or after it, and matplotlib -- like MATLAB's own ``plot`` -- renders a NaN x-value as a gap in
18
+ the line, not a crash and not a zero. The filled contour itself is drawn against
19
+ :func:`arrayprobe.intarr_analysis.contour_time_axis`, the source's *other*, width-aware time
20
+ formula (``:258-269``), which is not B8-affected, so the contour fill is identical either way --
21
+ only the three overlay lines can show the gap. A separate, also opt-in ``fix_b8=True`` gives the
22
+ corrected overlay axis instead.
23
+
24
+ Axis *values* are pinned directly, against a real Octave run of the source's own
25
+ ``num2str``/``str2double``/``datenum`` logic, in ``tests/test_intarr_analysis.py`` --
26
+ deliberately not by image comparison, which cannot check a NaN gap's position, only tests here
27
+ check that this module's plotting *call* does not crash and places the right data on the right
28
+ axes.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import datetime as _dt
34
+ import math
35
+
36
+ import numpy as np
37
+
38
+ from .intarr_analysis import (
39
+ CONTOUR_BINS,
40
+ CONTOUR_LEVELS,
41
+ contour_data,
42
+ contour_time_axis,
43
+ overlay_time_axis,
44
+ )
45
+
46
+ __all__ = ["plot_intarr_contour"]
47
+
48
+ #: MATLAB day 1 is 0000-01-01; Python's ``date.fromordinal(1)`` is 0001-01-01 -- the same
49
+ #: constant :mod:`arrayprobe.matlab_compat` uses (``_DATENUM_OFFSET``), restated here rather than
50
+ #: imported across a private name so this module's only coupling to matlab_compat stays the
51
+ #: public :func:`arrayprobe.matlab_compat.datenum` that ``intarr_analysis`` itself already uses.
52
+ _DATENUM_TO_ORDINAL_OFFSET = 366
53
+
54
+
55
+ def _datenum_to_mpl_num(value, mdates):
56
+ """One MATLAB serial datenum -> matplotlib's numeric date-axis value; NaN stays NaN (a gap)."""
57
+ if not np.isfinite(value):
58
+ return float("nan")
59
+ whole = math.floor(value)
60
+ frac = value - whole
61
+ day = _dt.date.fromordinal(int(whole) - _DATENUM_TO_ORDINAL_OFFSET)
62
+ when = _dt.datetime.combine(day, _dt.time()) + _dt.timedelta(seconds=frac * 86400.0)
63
+ return mdates.date2num(when)
64
+
65
+
66
+ def plot_intarr_contour(int_arr, timehhmmss, date, threshold, threshold_ww, threshold_ak,
67
+ *, population_size, date_string="", fix_b8=False):
68
+ """``:220-291`` -- draw the contoured inter-arrival-time figure with matplotlib.
69
+
70
+ ``int_arr``, ``timehhmmss``, ``date`` are the same per-particle arrays
71
+ :func:`arrayprobe.intarr_analysis.analyse` and :func:`arrayprobe.intarr_analysis.
72
+ contour_data` take. ``threshold``, ``threshold_ww``, ``threshold_ak`` are ``analyse``'s own
73
+ per-particle outputs (all three are always returned; see that module's docstring).
74
+ ``population_size`` must be the same block size used for the fit (``analyse``'s
75
+ ``out["population_size"]``), since the contour loop (``:225``) reuses it rather than
76
+ re-deriving it.
77
+
78
+ Returns ``(fig, ax)``. Never called at import time; matplotlib is imported here, lazily.
79
+ """
80
+ import matplotlib
81
+ matplotlib.use("Agg")
82
+ import matplotlib.dates as mdates
83
+ import matplotlib.pyplot as plt
84
+
85
+ hist, new_time, new_date = contour_data(int_arr, timehhmmss, date, population_size)
86
+ row_sums = hist.sum(axis=1, keepdims=True)
87
+ with np.errstate(divide="ignore", invalid="ignore"):
88
+ z = (hist / row_sums).T # :240-241,271
89
+
90
+ x_datenum = contour_time_axis(new_time, new_date) # :258-269, not B8-affected
91
+ overlay_datenum = overlay_time_axis(timehhmmss, date, fix_b8=fix_b8) # :243-250, B8
92
+
93
+ x_num = np.asarray([_datenum_to_mpl_num(v, mdates) for v in x_datenum])
94
+ overlay_num = np.asarray([_datenum_to_mpl_num(v, mdates) for v in overlay_datenum])
95
+
96
+ bin_centres = CONTOUR_BINS[:-1] + np.diff(CONTOUR_BINS) / 2 # :221,229
97
+
98
+ fig, ax = plt.subplots()
99
+ fig.patch.set_facecolor("w") # :257 set(gcf,'color','w')
100
+ cs = ax.contourf(x_num, bin_centres, z, levels=CONTOUR_LEVELS, cmap="jet") # :271-272,276
101
+ fig.colorbar(cs, ax=ax)
102
+ (line_thr,) = ax.plot(overlay_num, threshold, "g", linewidth=2) # :278, 2*lower peak
103
+ (line_ww,) = ax.plot(overlay_num, threshold_ww, "b", linewidth=2) # :279, freq. min (fit)
104
+ (line_ak,) = ax.plot(overlay_num, threshold_ak, "r", linewidth=2) # :280, freq. min (hist)
105
+
106
+ ax.set_ylim(1e-7, 1) # :282
107
+ ax.set_yscale("log")
108
+ ax.xaxis_date()
109
+ ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M")) # :282 datetick('x','HH:MM')
110
+ ax.set_title(f"Inter-arrival Time Frequency for {date_string}") # :283
111
+ ax.set_xlabel("Time") # :284
112
+ ax.set_ylabel("Inter-arrival Time [sec]")
113
+ # :285-286's legend has a fourth entry, 'frequency', for the contour fill itself -- omitted
114
+ # here since a filled contourf has no single Line2D handle to attach it to without a proxy
115
+ # artist, and this plot is not checked for pixel/legend content (see the module docstring).
116
+ ax.legend([line_thr, line_ww, line_ak],
117
+ ["2*lower peak", "freq. min between peaks from fit",
118
+ "freq. min between peaks in hist"], fontsize=6, loc="upper left") # :285-286
119
+ return fig, ax
@@ -0,0 +1,430 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """S3's opt-in accelerated kernels for the v3.5 engine --
3
+ ``imgproc_sm_v35(..., jit=True)``.
4
+
5
+ **Space: the port.** Every function here returns the same value as the one it
6
+ replaces, bit for bit, so a run with ``jit=True`` writes the same bytes as one
7
+ without (``tests/test_v35_imgproc_jit_identity.py`` runs both and compares the
8
+ files). It is opt-in and defaults off; numba is imported only when a caller
9
+ asks for it, never by ``import arrayprobe_uiops`` (same posture as
10
+ :mod:`arrayprobe.jit_kernels`).
11
+
12
+ **``arrayprobe/jit_kernels.py`` is the pattern, not the answer copied.** One should
13
+ not assume the v3.1.4 kernel list (``dec2bin_concat``,
14
+ ``particle_perimeter``, ``cgal_min_r``) transfers as a set, because v3.5's
15
+ measurement loop (:func:`arrayprobe_uiops.measure.measure_record`) is not
16
+ v3.1.4's: it calls a v3.5-only ``cgal_min_r_v35`` (a different function, with
17
+ a ``tas_ratio`` input and a 3-output centre return -- see
18
+ :mod:`arrayprobe_uiops.min_circle`), and its hottest single cost center measured
19
+ below turned out to be ``calculate_reject_unified``, which is not on v3.1.4's
20
+ list at all. Measured on a real v3.5 CIP production pass (naming
21
+ the kernels with numbers), 50 records / 3,085 particles of
22
+ ``_decoded/cip160906/sea_s1.CIP.cdf`` under the real production call
23
+ (``iRectEllipse=0, iCalcAllDiodeStats=0, iQC=0, iNewHabit=0, tas_ratio=None``
24
+ -- ``_decoded/cip160906/v35_prod/proc.sea_s1.CIP.nc.call``), cProfile
25
+ cumulative time (instrumented, so useful for ranking, not for absolute
26
+ wall-clock proportions):
27
+
28
+ ============================================ ======= ============
29
+ function calls cumulative s
30
+ ============================================ ======= ============
31
+ ``calculate_reject_unified`` (v35 reject.py) 3,085 7.367
32
+ ``dec2bin_concat`` (matlab_compat.py) 9,255 5.874
33
+ ``cgal_min_r_v35`` (v35 min_circle.py) 3,085 4.124
34
+ ``particle_perimeter`` (arrayprobe, shared) 3,085 3.050 (3.043 self)
35
+ ============================================ ======= ============
36
+
37
+ Two of these are ported here; two are not, and this module says why for each:
38
+
39
+ ``dec2bin_concat``
40
+ All 9,255 calls measured above trace to :mod:`arrayprobe_uiops.imgproc`'s
41
+ own three call sites (the framing unpack, once per particle, plus the two
42
+ housekeeping unpacks inside ``_particle_time_dmt_v35``, CIP/PIP timing
43
+ only) -- none come from ``reject.py``. It is the exact same
44
+ ``arrayprobe.matlab_compat.dec2bin_concat`` v3.1.4 accelerates (imported
45
+ by name in ``imgproc.py``, never re-translated for v3.5), so v3.1.4's
46
+ already-proven, already-tested fused-NumPy kernel
47
+ (:func:`arrayprobe.jit_kernels.dec2bin_concat`, no numba needed) is
48
+ reused directly below rather than copied -- one proof of exactness, not
49
+ two.
50
+ ``particle_perimeter``
51
+ Also the exact same ``arrayprobe.particle_perimeter.particle_perimeter``
52
+ v3.1.4 accelerates (``measure.py``'s own module docstring: "the
53
+ byte-identical ``arrayprobe.particle_perimeter``; this module
54
+ re-translates none of them"). v3.1.4's compiled numba kernel
55
+ (:func:`arrayprobe.jit_kernels.JitKernels.particle_perimeter`) is reused
56
+ directly for the same reason. *Reaching* the call, which is inside
57
+ :func:`arrayprobe_uiops.measure.measure_record` rather than in
58
+ :mod:`arrayprobe_uiops.imgproc` itself, is the harder part -- see
59
+ ``imgproc.py``'s ``_patched_measure_perimeter``.
60
+
61
+ ``cgal_min_r_v35`` -- **still left unported, measured, not guessed.** v3.5's
62
+ call is not v3.1.4's ``cgal_min_r``: it takes ``tas_ratio`` and returns a
63
+ 3-tuple ``(diameter, ctx, cty)`` (the enclosing circle's centre, new in
64
+ v3.5), computed by scaling one axis in exact ``Fraction`` arithmetic
65
+ before Welzl's algorithm (:mod:`arrayprobe_uiops.min_circle`). v3.1.4's
66
+ ``_welzl_kernel`` neither takes a scale nor returns a centre, so it is
67
+ not a drop-in; an exact numba equivalent would be new kernel code (a
68
+ homogeneous-coordinate Welzl pass that also carries the winning centre
69
+ through every branch), not a reuse, and proving *that* exact needs more
70
+ fuzz-testing than one session's time-box affords carefully. Real CIP
71
+ production always runs ``tas_ratio == 1.0`` exactly (``tas_ratio=None``
72
+ in the call above; probetype 1 never reads ``varargin{3}``'s series --
73
+ see ``imgproc_sm_v35``'s own probetype guard), which would let such a
74
+ kernel degenerate to v3.1.4's existing int64 Welzl pass for the radius
75
+ and add only the centre bookkeeping -- still the next highest-value
76
+ target, still not attempted.
77
+
78
+ ``calculate_reject_unified`` -- **ported 2026-09-18**,
79
+ the session that measured it
80
+ as the single largest cost centre above. ``arrayprobe/jit_kernels.py``'s
81
+ docstring called reject's hot kernels "already numba-compiled in
82
+ reject.py" -- true only for ``is_it_hollow_sidescan`` there (v3.1.4's
83
+ *other* hollow scan), and not reached by the v3.5 engine at all: v3.5's
84
+ ``calculate_reject_unified`` (this module's own, `arrayprobe_uiops/reject.py`)
85
+ has its own rewritten ``is_it_hollow`` (no middle-third restriction, a
86
+ direct ``bitand`` instead of a pack/bitshift reconstruction) that never
87
+ called anything from v3.1.4's ``reject.py`` except the shared
88
+ ``scan_slice`` -- see that module's corrected docstring for the full
89
+ accounting.
90
+
91
+ The real cost was never "interpreted Python" so much as **per-slice
92
+ dispatch overhead**: ``scan_slice`` already dispatches to a numba kernel
93
+ whenever numba is importable (unconditionally, not opt-in -- see
94
+ ``reject.HAVE_NUMBA`` in the earlier translation), but it still pays a Python-level call,
95
+ an ``np.asarray``/``ascontiguousarray`` conversion and a
96
+ :class:`~arrayprobe_uiops.reject_core.SliceScan` construction on *every one* of the
97
+ 47,198 calls the profile counted. The fix here fuses each whole
98
+ per-particle loop into one compiled call instead of one call per slice:
99
+
100
+ ``reject_scan_pass``
101
+ ``calculate_reject_unified``'s own per-slice pass (longest_y, touch,
102
+ the bottom/top edge extents, max/min width, area, the split
103
+ detector) -- every particle takes this path, and the real production
104
+ config (``ORACLES_PRODUCTION_V35``, ``rej_hollow=False``) means this
105
+ pass is *all* of what the profile above measured; the hollow branch
106
+ below never ran in that profile.
107
+ ``is_it_hollow``
108
+ v3.5's rewritten hollow scan -- not exercised by the production
109
+ config above (``rej_hollow=False``), but reachable from
110
+ ``STOCK_V35_REJECT_CONFIG`` and any fork with ``rej_hollow=True``,
111
+ and explicitly the function the porting brief named for its
112
+ preserved defects (the ``ihollow``-overwrite at ``reject.py:364-365``,
113
+ the discarded ``hollow_status_side1`` at :367-375, the array-truthiness
114
+ ``bufandold.all()`` defect inside ``is_it_hollow`` itself). Proven
115
+ identical on real CIP image content under a ``rej_hollow=True``
116
+ variant of the production config, since production itself never
117
+ takes this branch.
118
+
119
+ Left on the Python path, and why: the Korolev lookup
120
+ (``_z_d_lookup``/``_edge_0_lookup``) and the habit-dependent
121
+ ``area_hole_ratio`` checks run once per particle, not once per slice --
122
+ not measured hot, and numba's limited string handling would make the
123
+ ``habit`` comparisons (``habit == "i"``, ``habit == "h"``) more trouble
124
+ than the near-zero benefit justifies. ``_vertical_split``'s one
125
+ ``scan_slice`` call (once per particle, not per slice) is likewise
126
+ left calling the existing shared dispatcher unchanged.
127
+ """
128
+
129
+ from __future__ import annotations
130
+
131
+ from typing import Any
132
+
133
+ import numpy as np
134
+
135
+ __all__ = ["V35JitKernels", "load"]
136
+
137
+ #: Guards the njit-decoration in V35JitKernels.__init__ against running twice
138
+ #: in one process -- see that method's docstring comment for why a second
139
+ #: construction is a real, reachable case, not hypothetical.
140
+ _KERNELS_COMPILED = False
141
+
142
+
143
+ # --------------------------------------------------------------------------
144
+ # Pure-Python kernel bodies for calculate_reject_unified's two hot loops.
145
+ # numba compiles them on first use, in load() below -- see that function's
146
+ # docstring for why the leaf kernels (_scan_row_kernel, _mask_start_end_kernel)
147
+ # must be compiled, and their MODULE GLOBALS rebound to the compiled
148
+ # Dispatcher, before the composite kernels that call them by name are
149
+ # themselves compiled (mirrors arrayprobe.reject._ensure_numba_loaded's own
150
+ # ordering, which the same constraint applies to).
151
+ # --------------------------------------------------------------------------
152
+
153
+
154
+ def _scan_row_kernel(row: Any) -> Any:
155
+ """Same value as ``arrayprobe_uiops.reject_core.scan_slice`` on one boolean row:
156
+ ``(min_pos, max_pos, n_lite)``, 1-based, ``(0, 0, 0)`` when empty. A
157
+ separate copy rather than an import, because the shared function's own
158
+ numba dispatch is rebound as a module global the first time *it* runs
159
+ (``reject._ensure_numba_loaded`` in the earlier translation) -- importing that name here
160
+ would race whichever module loads numba first. Proven equal to the
161
+ shared dispatcher by fuzz in ``test_v35_reject_jit_identity.py``."""
162
+ n = row.shape[0]
163
+ min_pos = 0
164
+ max_pos = 0
165
+ n_lite = 0
166
+ for k in range(n):
167
+ if row[k]:
168
+ if min_pos == 0:
169
+ min_pos = k + 1
170
+ max_pos = k + 1
171
+ n_lite += 1
172
+ return min_pos, max_pos, n_lite
173
+
174
+
175
+ def _mask_start_end_kernel(end_mask: Any, start_mask: Any, row: Any, bits_per_slice: Any) -> Any:
176
+ """Same value as ``arrayprobe_uiops.reject_core.mask_start_end`` (v3.5's
177
+ ``is_it_hollow`` never calls the ``end_mask > bits_per_slice``
178
+ auto-extend arm -- see that function's docstring -- but the ``max()`` is
179
+ kept anyway, verbatim, rather than assumed away)."""
180
+ if start_mask == 0 and end_mask == 0:
181
+ return ~row
182
+ size = bits_per_slice if bits_per_slice > end_mask else end_mask
183
+ result = np.zeros(size, dtype=np.bool_)
184
+ result[start_mask - 1:end_mask] = ~row[start_mask - 1:end_mask]
185
+ return result
186
+
187
+
188
+ def _reject_scan_pass_kernel(shadow: Any, n_slices: Any, bits_per_slice: Any,
189
+ rej_split: Any) -> Any:
190
+ """``calculate_reject_unified``'s own per-slice pass (v3.5 reject.py,
191
+ the loop immediately before ``center_in`` is computed) -- every particle
192
+ takes this path, fused into one compiled call instead of ``n_slices``
193
+ separate ``scan_slice`` dispatches. ``met_image``/``ndrops`` are
194
+ loop-local bookkeeping the caller never reads back, so they are not
195
+ returned (matching what the Python body itself discards)."""
196
+ longest_y = 0
197
+ touch = 0
198
+ bottom_min_x = -1
199
+ bottom_max_x = -1
200
+ top_min_x = -1
201
+ top_max_x = -1
202
+ max_width = 1
203
+ min_width = bits_per_slice
204
+ min_length = -1
205
+ max_length = -1
206
+ total_area = 0
207
+ met_image = 0
208
+ ndrops = 0
209
+ split = 0
210
+
211
+ for i in range(1, n_slices + 1):
212
+ min_pos, max_pos, n_lite = _scan_row_kernel(shadow[i - 1])
213
+ if n_lite > longest_y:
214
+ longest_y = n_lite
215
+
216
+ if n_lite > 0:
217
+ if touch == 0:
218
+ if max_pos == bits_per_slice or min_pos == 1:
219
+ touch = 1
220
+ if min_pos == 1:
221
+ if bottom_min_x == -1:
222
+ bottom_min_x = i
223
+ if bottom_max_x < i:
224
+ bottom_max_x = i
225
+ if max_pos == bits_per_slice:
226
+ if top_min_x == -1:
227
+ top_min_x = i
228
+ if top_max_x < i:
229
+ top_max_x = i
230
+ if max_pos > max_width:
231
+ max_width = max_pos
232
+ if min_pos < min_width:
233
+ min_width = min_pos
234
+ if min_length == -1:
235
+ min_length = i
236
+ max_length = i
237
+ else:
238
+ max_length = i
239
+ total_area += n_lite
240
+
241
+ if met_image == 0 and n_lite > 0:
242
+ met_image = 1
243
+ ndrops += 1
244
+ if ndrops > 1 and rej_split:
245
+ split = 1
246
+ elif met_image == 1 and n_lite == 0:
247
+ met_image = 0
248
+
249
+ return (longest_y, touch, bottom_min_x, bottom_max_x, top_min_x, top_max_x,
250
+ max_width, min_width, min_length, max_length, total_area, split)
251
+
252
+
253
+ def _is_it_hollow_kernel(shadow: Any, slices: Any) -> Any:
254
+ """v3.5's ``is_it_hollow`` (``arrayprobe_uiops/reject.py``), fused into one
255
+ compiled call. Line-for-line translation of that function's body --
256
+ including the ``possibly_hollow``/``status`` state machine and the
257
+ PRESERVED DEFECT documented there (MATLAB's ``if bufandold > 0`` on an
258
+ array means "every element nonzero", replicated with ``.all()``, not the
259
+ evidently-intended ``.any()``).
260
+
261
+ ``old``'s ``None`` sentinel becomes a same-shape placeholder array that is
262
+ never read before being freshly assigned -- the same invariant the
263
+ Python body's own comment (and ``reject._is_it_hollow_sidescan_kernel`` in the earlier
264
+ translation, the precedent this mirrors) relies on: every branch that reads ``old``
265
+ is reached only under ``possibly_hollow == 1``, and the only two sites
266
+ that set ``possibly_hollow = 1`` assign ``old`` in the same breath.
267
+ ``old`` is always exactly ``bits_per_slice`` wide here (unlike the
268
+ sidescan kernel's capped-at-32 caller, v3.5's ``bits_per_slice`` is the
269
+ row's own true width, so ``mask_start_end``'s ``end_mask`` -- itself a
270
+ valid column position -- can never exceed it), so the placeholder and
271
+ every real assignment share one fixed shape per call, which is what lets
272
+ numba type ``old`` as a stable loop-carried variable.
273
+ """
274
+ bits_per_slice = shadow.shape[1]
275
+
276
+ start_img = 0
277
+ end_img = 0
278
+ for i in range(1, slices + 1):
279
+ zero_amt = shadow[i - 1].sum() # counts LIT pixels -- MATLAB's own naming, preserved
280
+ if zero_amt > 0 and start_img == 0:
281
+ start_img = i
282
+ if zero_amt == 0 and start_img > 0:
283
+ end_img = i
284
+ if i == slices and end_img == 0:
285
+ if start_img == 0:
286
+ start_img = 1
287
+ end_img = slices
288
+
289
+ max_hole_diameter = 0
290
+ edge_at_max_hole = 0
291
+ status = 0
292
+ possibly_hollow = 0
293
+ old = np.zeros(bits_per_slice, dtype=np.bool_) # placeholder; see docstring
294
+
295
+ for i in range(start_img, end_img + 1):
296
+ row = shadow[i - 1]
297
+ min_pos, max_pos, n_lite = _scan_row_kernel(row)
298
+ num_empty = max_pos - min_pos + 1 - n_lite
299
+
300
+ # v3.5 removed v3.1.4's middle-third restriction here -- no i/span
301
+ # guard, unlike arrayprobe.reject.is_it_hollow. Preserved by omission.
302
+ if num_empty > max_hole_diameter:
303
+ max_hole_diameter = num_empty
304
+ edge_at_max_hole = max_pos - min_pos + 1
305
+
306
+ lit_row = ~row
307
+
308
+ if possibly_hollow == 1 and status == 0:
309
+ if n_lite > 0 and n_lite != max_pos - min_pos + 1:
310
+ newandold = lit_row & old
311
+ if not newandold.any():
312
+ status = 1
313
+ else:
314
+ old = _mask_start_end_kernel(max_pos, min_pos, row, bits_per_slice)
315
+ elif n_lite > 0:
316
+ bufandold = lit_row & old
317
+ hole_size = old.sum()
318
+ cover_size = bufandold.sum()
319
+ # PRESERVED DEFECT: see this function's own docstring.
320
+ if bufandold.shape[0] > 0 and bufandold.all():
321
+ if cover_size <= 0.65 * hole_size:
322
+ status = 1
323
+ possibly_hollow = 0
324
+ elif i > 1:
325
+ status = 1
326
+ else:
327
+ possibly_hollow = 0
328
+ else:
329
+ possibly_hollow = 0
330
+ elif status == 0:
331
+ if n_lite > 0 and n_lite != max_pos - min_pos + 1:
332
+ old = _mask_start_end_kernel(max_pos, min_pos, row, bits_per_slice)
333
+ possibly_hollow = 1
334
+
335
+ return status, edge_at_max_hole, max_hole_diameter
336
+
337
+
338
+ class V35JitKernels:
339
+ """Wraps :mod:`arrayprobe.jit_kernels`'s already-compiled, already-proven
340
+ kernels for the two v3.5 call sites that use the identical underlying
341
+ function (``particle_perimeter``, ``dec2bin_concat``), plus this
342
+ module's own compiled kernels for ``calculate_reject_unified``'s two hot
343
+ loops, which have no earlier kernel to reuse -- v3.5's ``arrayprobe_uiops.reject`` is a
344
+ from-scratch translation of a changed MATLAB function (see its module
345
+ docstring), not the file the earlier translation accelerates."""
346
+
347
+ def __init__(self, v314_kernels: Any, njit: Any) -> None:
348
+ self.particle_perimeter = v314_kernels.particle_perimeter
349
+ self.dec2bin_concat = v314_kernels.dec2bin_concat
350
+
351
+ # Leaf kernels first, and REBOUND AS MODULE GLOBALS (not just local
352
+ # names) before the composite kernels below are decorated -- numba
353
+ # resolves a called name against the function's __globals__ at
354
+ # compile time (lazy, on first actual invocation), so
355
+ # _reject_scan_pass_kernel/_is_it_hollow_kernel must see the
356
+ # already-compiled Dispatcher, not the plain Python function, when
357
+ # numba gets around to typing their bodies. Mirrors
358
+ # arrayprobe.reject._ensure_numba_loaded's own ordering exactly.
359
+ #
360
+ # IDEMPOTENT, unlike a naive rebind: _LOADED normally makes this
361
+ # class a per-process singleton, but a caller can legitimately reset
362
+ # _LOADED (this module's own tests do, to exercise the "numba
363
+ # missing" error path) and construct a second instance in the same
364
+ # process. numba refuses to re-`njit` a function that is already a
365
+ # compiled Dispatcher (measured: raises TypeError), so the module
366
+ # globals are decorated at most once per process, guarded by
367
+ # _KERNELS_COMPILED -- exactly the boolean-flag shape
368
+ # arrayprobe.reject._ensure_numba_loaded uses for the same reason.
369
+ global _scan_row_kernel, _mask_start_end_kernel
370
+ global _reject_scan_pass_kernel, _is_it_hollow_kernel
371
+ global _KERNELS_COMPILED
372
+ if not _KERNELS_COMPILED:
373
+ opts = {"cache": True, "boundscheck": True} # fastmath stays OFF (correctness)
374
+ _scan_row_kernel = njit(**opts)(_scan_row_kernel)
375
+ _mask_start_end_kernel = njit(**opts)(_mask_start_end_kernel)
376
+ _reject_scan_pass_kernel = njit(**opts)(_reject_scan_pass_kernel)
377
+ _is_it_hollow_kernel = njit(**opts)(_is_it_hollow_kernel)
378
+ _KERNELS_COMPILED = True
379
+ self._scan_row = _scan_row_kernel # exposed for direct fuzzing, mirrors
380
+ # arrayprobe.jit_kernels.JitKernels's
381
+ # own _perimeter/_hull/_welzl attributes
382
+ self._mask_start_end = _mask_start_end_kernel
383
+ self._scan_pass = _reject_scan_pass_kernel
384
+ self._hollow = _is_it_hollow_kernel
385
+
386
+ def reject_scan_pass(self, shadow: Any, n_slices: Any, bits_per_slice: Any,
387
+ rej_split: Any) -> Any:
388
+ """Drop-in for ``calculate_reject_unified``'s own per-slice loop.
389
+ Returns ``(longest_y, touch, bottom_min_x, bottom_max_x, top_min_x,
390
+ top_max_x, max_width, min_width, min_length, max_length, total_area,
391
+ split)`` -- every local the loop computes that the rest of the
392
+ function reads afterward."""
393
+ arr = np.ascontiguousarray(np.asarray(shadow, dtype=bool))
394
+ result = self._scan_pass(arr, int(n_slices), int(bits_per_slice), bool(rej_split))
395
+ return tuple(int(v) for v in result)
396
+
397
+ def is_it_hollow(self, shadow: Any, slices: Any) -> Any:
398
+ """Drop-in for :func:`arrayprobe_uiops.reject.is_it_hollow`. Returns
399
+ ``(status, edge_at_max_hole, max_hole_diameter)``."""
400
+ arr = np.ascontiguousarray(np.asarray(shadow, dtype=bool))
401
+ status, edge_at_max_hole, max_hole_diameter = self._hollow(arr, int(slices))
402
+ return int(status), int(edge_at_max_hole), int(max_hole_diameter)
403
+
404
+
405
+ _LOADED: V35JitKernels | None = None
406
+
407
+
408
+ def load() -> V35JitKernels:
409
+ """Import numba (via :mod:`arrayprobe.jit_kernels`) and compile this
410
+ module's own kernels, once per process. Raises with a v3.5-specific
411
+ message if numba is absent; the default (``jit=False``) path -- for
412
+ ``imgproc_sm_v35``, ``calculate_reject_unified`` and ``is_it_hollow``
413
+ alike -- never calls this."""
414
+ global _LOADED
415
+ if _LOADED is None:
416
+ from arrayprobe import jit_kernels as _v314
417
+
418
+ try:
419
+ v314_kernels = _v314.load()
420
+ from numba import njit
421
+ except ImportError as exc:
422
+ raise ModuleNotFoundError(
423
+ "imgproc_sm_v35(jit=True) / calculate_reject_unified(jit=True) / "
424
+ "is_it_hollow(jit=True) need numba, an optional extra: "
425
+ 'pip install "arrayprobe[jit]" ("arrayprobe[pinned]" installs the tested pin). '
426
+ "The default "
427
+ "(jit=False) writes the same bytes without it."
428
+ ) from exc
429
+ _LOADED = V35JitKernels(v314_kernels, njit)
430
+ return _LOADED
@@ -0,0 +1,70 @@
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; byte-identical in v3.5, so one translation serves both).
5
+ This is its one home: ``arrayprobe.lwc`` re-exports it lazily, on first access (nothing outside
6
+ the v3.1.4 package imports it, and code the engines share lives in the v3.5 engine).
7
+ """
8
+
9
+ #: Declared so the public surface is explicit rather than whatever happens not to
10
+ #: start with an underscore. The Phase-1 shims at ``<name>.py`` in the original flat layout import
11
+ #: these names directly, CONSTANTS INCLUDED -- omitting a constant here would not
12
+ #: break them, but omitting one from a shim does, which is why they are listed.
13
+ __all__ = [
14
+ "lwc_calc",
15
+ ]
16
+
17
+ import math
18
+ from collections.abc import Iterable
19
+
20
+
21
+ def lwc_calc(conc: Iterable[Iterable[float]], bins: Iterable[float]) -> list[float]:
22
+ """Liquid water content (g/m^3) from concentration and bin diameters.
23
+
24
+ Direct port of lwc_calc.m.
25
+
26
+ conc: sequence of rows (one per time step), each a sequence of
27
+ concentrations (cm^-3) per bin.
28
+ bins: sequence of bin (mid-point) diameters, in microns.
29
+
30
+ Returns a list of LWC values, one per row of `conc`.
31
+
32
+ Note: unlike single_vt.m, the original lwc_calc.m does NOT
33
+ override MATLAB's built-in `pi`, so it gets full double-precision
34
+ pi -- this port uses math.pi accordingly (not the 3.1415926
35
+ literal used elsewhere in the source).
36
+ """
37
+ bins = list(bins)
38
+ volume_cm3 = [(math.pi / 6) * (b * 1e-4) ** 3 for b in bins]
39
+
40
+ lwc = []
41
+ for row in conc:
42
+ # ``strict=False`` is stated explicitly, and it is NOT a formality.
43
+ #
44
+ # ``row`` and ``volume_cm3`` are not provably the same length here:
45
+ # ``conc`` and ``bins`` are both caller-supplied and this function is
46
+ # public API (re-exported by the Phase-1 ``lwc`` shim). The port's only
47
+ # internal caller -- ``sizedist.py:1379``, ``sizeDist.m:1627`` -- does
48
+ # pass matched lengths, but the zip cannot see that.
49
+ #
50
+ # What MATLAB does on a mismatch is a *third* thing, neither truncation
51
+ # nor a Python exception. ``lwc_calc.m:6`` reads
52
+ #
53
+ # sum(conc(:,:) .* pi/6 * (bins(:)*(1e-4)) .^3, 2)
54
+ #
55
+ # and ``.*`` / ``*`` share precedence left-to-right, so the last operator
56
+ # is a *matrix* product ``(T,N) * (N,1)``, not an element-wise one; the
57
+ # trailing ``sum(...,2)`` is then a no-op on the resulting column. A
58
+ # length mismatch is therefore MATLAB's "Inner matrix dimensions must
59
+ # agree" error, i.e. it is outside the original's contract entirely.
60
+ #
61
+ # Turning this into ``strict=True`` would convert today's silent
62
+ # truncation into a Python exception. That is a behaviour change on an
63
+ # input the original refuses to process at all, so it is a fidelity
64
+ # decision (what should the port do where MATLAB dies?) and not a lint
65
+ # autofix: any behavior-changing deviation must be an
66
+ # opt-in flag. Left as-is deliberately; the explicit ``False`` records
67
+ # that the default was chosen rather than overlooked.
68
+ total = sum(c * v for c, v in zip(row, volume_cm3, strict=False))
69
+ lwc.append(total * 1e6)
70
+ return lwc