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.
- arrayprobe/__init__.py +219 -0
- arrayprobe/__main__.py +19 -0
- arrayprobe/_v314_lazy.py +48 -0
- arrayprobe/ai_ready.py +212 -0
- arrayprobe/attributed_export.py +1333 -0
- arrayprobe/authordefaults.py +267 -0
- arrayprobe/cli.py +3510 -0
- arrayprobe/combine.py +12 -0
- arrayprobe/compare.py +950 -0
- arrayprobe/config.py +1239 -0
- arrayprobe/constants.py +12 -0
- arrayprobe/count_closure.py +204 -0
- arrayprobe/diagnostic_views.py +769 -0
- arrayprobe/diode_report.py +265 -0
- arrayprobe/driver/__init__.py +5 -0
- arrayprobe/driver/_load_record.py +331 -0
- arrayprobe/driver/preflight_inputs.py +250 -0
- arrayprobe/driver/reprocess.py +553 -0
- arrayprobe/driver/run_flight.py +8166 -0
- arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
- arrayprobe/dropsize.py +519 -0
- arrayprobe/friendly.py +206 -0
- arrayprobe/geometry/__init__.py +77 -0
- arrayprobe/geometry/min_rectangle.py +92 -0
- arrayprobe/intarr.py +12 -0
- arrayprobe/intarr_analysis.py +16 -0
- arrayprobe/intarr_plots.py +12 -0
- arrayprobe/inventory.py +129 -0
- arrayprobe/jit_kernels.py +344 -0
- arrayprobe/lwc.py +44 -0
- arrayprobe/masks.py +349 -0
- arrayprobe/matio.py +410 -0
- arrayprobe/matlab_compat.py +13 -0
- arrayprobe/ncio.py +26 -0
- arrayprobe/particle.py +55 -0
- arrayprobe/particle_perimeter.py +12 -0
- arrayprobe/products.py +78 -0
- arrayprobe/profiles.py +179 -0
- arrayprobe/provenance.py +21 -0
- arrayprobe/py.typed +11 -0
- arrayprobe/readers/__init__.py +9 -0
- arrayprobe/readers/dmt.py +603 -0
- arrayprobe/readers/mask_csv.py +12 -0
- arrayprobe/readers/pms.py +12 -0
- arrayprobe/readers/sea.py +433 -0
- arrayprobe/readers/tasinfo.py +12 -0
- arrayprobe/regimes.py +507 -0
- arrayprobe/render.py +728 -0
- arrayprobe/reproduce_report.py +149 -0
- arrayprobe/review_agreement.py +135 -0
- arrayprobe/review_sampling.py +327 -0
- arrayprobe/run_page.py +624 -0
- arrayprobe/sample_area.py +12 -0
- arrayprobe/selector.py +206 -0
- arrayprobe/sizing.py +151 -0
- arrayprobe/time_convert.py +12 -0
- arrayprobe/timing_closure.py +141 -0
- arrayprobe/tools/__init__.py +27 -0
- arrayprobe/tools/make_demo_flight.py +1089 -0
- arrayprobe/tools/make_tas_file.py +760 -0
- arrayprobe/tools/probe_comparison.py +569 -0
- arrayprobe/tools/synthetic_truth.py +698 -0
- arrayprobe/tools/tas_sources.py +705 -0
- arrayprobe/triage_context.py +488 -0
- arrayprobe/triage_server.py +5215 -0
- arrayprobe/tune/__init__.py +15 -0
- arrayprobe/tune/diodes.py +400 -0
- arrayprobe/tune/distributions.py +300 -0
- arrayprobe/tune/sample.py +243 -0
- arrayprobe/tune/score.py +230 -0
- arrayprobe/tune/settings.py +354 -0
- arrayprobe/validate_by_condition.py +208 -0
- arrayprobe/validation_report.py +166 -0
- arrayprobe-0.1.0.dist-info/METADATA +260 -0
- arrayprobe-0.1.0.dist-info/RECORD +189 -0
- arrayprobe-0.1.0.dist-info/WHEEL +5 -0
- arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
- arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
- arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
- arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
- arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
- arrayprobe_soda2/__init__.py +131 -0
- arrayprobe_soda2/angles.py +143 -0
- arrayprobe_soda2/aspect_ratio.py +541 -0
- arrayprobe_soda2/backfill.py +100 -0
- arrayprobe_soda2/binary_dof.py +181 -0
- arrayprobe_soda2/buildindex.py +113 -0
- arrayprobe_soda2/decompress_dmt.py +285 -0
- arrayprobe_soda2/enhancement_hooks.py +275 -0
- arrayprobe_soda2/export_ascii.py +732 -0
- arrayprobe_soda2/export_ncdf.py +683 -0
- arrayprobe_soda2/export_ncdf_raf.py +396 -0
- arrayprobe_soda2/fillholes.py +161 -0
- arrayprobe_soda2/find_radius.py +105 -0
- arrayprobe_soda2/findsize.py +407 -0
- arrayprobe_soda2/fit_poisson.py +170 -0
- arrayprobe_soda2/fix2dimage.py +63 -0
- arrayprobe_soda2/fixraking.py +162 -0
- arrayprobe_soda2/fixstuckbits.py +146 -0
- arrayprobe_soda2/hvps4_read_frame.py +121 -0
- arrayprobe_soda2/jit_kernels.py +152 -0
- arrayprobe_soda2/label_blobs.py +177 -0
- arrayprobe_soda2/min_circle_fast.py +320 -0
- arrayprobe_soda2/particlesort.py +703 -0
- arrayprobe_soda2/pbp_writer.py +558 -0
- arrayprobe_soda2/poisson_spot_correct.py +183 -0
- arrayprobe_soda2/princomp.py +107 -0
- arrayprobe_soda2/probespecs.py +361 -0
- arrayprobe_soda2/process_2d.py +1364 -0
- arrayprobe_soda2/process_2d_parallel.py +626 -0
- arrayprobe_soda2/process_hk.py +512 -0
- arrayprobe_soda2/processbuffer_2dc.py +155 -0
- arrayprobe_soda2/processbuffer_cip.py +213 -0
- arrayprobe_soda2/processbuffer_f2dc.py +139 -0
- arrayprobe_soda2/processbuffer_spec.py +441 -0
- arrayprobe_soda2/processbuffer_tail.py +350 -0
- arrayprobe_soda2/pth_readers.py +245 -0
- arrayprobe_soda2/py.typed +11 -0
- arrayprobe_soda2/read2dbuffer.py +371 -0
- arrayprobe_soda2/reject.py +246 -0
- arrayprobe_soda2/reprocess_pbp.py +156 -0
- arrayprobe_soda2/sample_area.py +264 -0
- arrayprobe_soda2/save_writer.py +480 -0
- arrayprobe_soda2/sea.py +324 -0
- arrayprobe_soda2/spec_absolutepointers.py +109 -0
- arrayprobe_soda2/spec_decompress.py +203 -0
- arrayprobe_soda2/spec_index.py +476 -0
- arrayprobe_soda2/spec_read_frame.py +286 -0
- arrayprobe_soda2/spec_read_hk.py +301 -0
- arrayprobe_soda2/spec_readint.py +127 -0
- arrayprobe_soda2/timeconv.py +77 -0
- arrayprobe_soda2/update_op.py +101 -0
- arrayprobe_uiops/__init__.py +45 -0
- arrayprobe_uiops/combine.py +192 -0
- arrayprobe_uiops/combine_fork.py +359 -0
- arrayprobe_uiops/constants.py +830 -0
- arrayprobe_uiops/decode_naming.py +113 -0
- arrayprobe_uiops/diode_mask.py +250 -0
- arrayprobe_uiops/engine_absence.py +41 -0
- arrayprobe_uiops/export_oap.py +325 -0
- arrayprobe_uiops/geometry_core.py +366 -0
- arrayprobe_uiops/habit.py +749 -0
- arrayprobe_uiops/habit_core.py +248 -0
- arrayprobe_uiops/hollow_size_rule.py +376 -0
- arrayprobe_uiops/imgproc.py +2081 -0
- arrayprobe_uiops/imgproc_core.py +275 -0
- arrayprobe_uiops/intarr.py +167 -0
- arrayprobe_uiops/intarr_analysis.py +569 -0
- arrayprobe_uiops/intarr_plots.py +119 -0
- arrayprobe_uiops/jit_kernels.py +430 -0
- arrayprobe_uiops/lwc.py +70 -0
- arrayprobe_uiops/matlab_compat.py +860 -0
- arrayprobe_uiops/measure.py +346 -0
- arrayprobe_uiops/min_circle.py +204 -0
- arrayprobe_uiops/min_ellipse.py +161 -0
- arrayprobe_uiops/min_rectangle.py +200 -0
- arrayprobe_uiops/ncar_2dc_timing.py +100 -0
- arrayprobe_uiops/ncio.py +810 -0
- arrayprobe_uiops/oap_read.py +228 -0
- arrayprobe_uiops/particle.py +51 -0
- arrayprobe_uiops/particle_perimeter.py +94 -0
- arrayprobe_uiops/particle_physics.py +199 -0
- arrayprobe_uiops/pecan_params.py +134 -0
- arrayprobe_uiops/probe_cases.py +298 -0
- arrayprobe_uiops/product_sanity.py +337 -0
- arrayprobe_uiops/profile.py +71 -0
- arrayprobe_uiops/profiles.py +756 -0
- arrayprobe_uiops/provenance.py +804 -0
- arrayprobe_uiops/py.typed +11 -0
- arrayprobe_uiops/qc.py +169 -0
- arrayprobe_uiops/readers/__init__.py +8 -0
- arrayprobe_uiops/readers/mask_csv.py +74 -0
- arrayprobe_uiops/readers/pms.py +239 -0
- arrayprobe_uiops/readers/tasinfo.py +57 -0
- arrayprobe_uiops/rect_ellipse.py +129 -0
- arrayprobe_uiops/register_image_assisted.py +25 -0
- arrayprobe_uiops/reject.py +501 -0
- arrayprobe_uiops/reject_core.py +220 -0
- arrayprobe_uiops/sample_area.py +93 -0
- arrayprobe_uiops/sizedist.py +1923 -0
- arrayprobe_uiops/sizedist_core.py +814 -0
- arrayprobe_uiops/sizedist_tables.py +642 -0
- arrayprobe_uiops/spec.py +1094 -0
- arrayprobe_uiops/spec_core.py +703 -0
- arrayprobe_uiops/stray_pixel.py +103 -0
- arrayprobe_uiops/tas.py +191 -0
- arrayprobe_uiops/time_convert.py +41 -0
- uiops/__init__.py +402 -0
- uiops/py.typed +11 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Reproduces SODA-2, Copyright (c) 2016 UCAR; see LICENSES/BSD-3-Clause.txt and NOTICE.md.
|
|
3
|
+
"""SODA-2 ``fixraking.pro:1-67`` -- reconstruct raked images (every other
|
|
4
|
+
diode undersampled; written for the PIP), bug-for-bug.
|
|
5
|
+
|
|
6
|
+
Layout as in ``fixstuckbits``: diodes on axis 0, slices on axis 1 (IDL's
|
|
7
|
+
``[diode, slice]``); ``(size(image,/dim))[0]`` is the diode count (``:18``).
|
|
8
|
+
MATLAB/IDL index conventions are kept visible: IDL indices here are 0-based
|
|
9
|
+
already, so ``ieven``/``iodd`` are used as written.
|
|
10
|
+
|
|
11
|
+
Behaviour reproduced (established by **reading**, then confirmed on all 31
|
|
12
|
+
cases of the GDL oracle bank ``gdl_oracle/run_soda2_fixraking_bank.py``,
|
|
13
|
+
golden ``tests/data/gdl_soda2_fixraking_golden.json``: 27 run, 4 halt;
|
|
14
|
+
item 5's border rule was measured there):
|
|
15
|
+
|
|
16
|
+
1. ``:10`` ``modetype eq 0`` returns the image unchanged.
|
|
17
|
+
2. ``:12`` sets ``mode`` to the truncated ``modetype`` modulo 2: 1 for odd and 0 for even, never
|
|
18
|
+
2, so ``:38`` and ``:60`` (``mode eq 2``) are dead: an even ``modetype``
|
|
19
|
+
copies nothing (2) and masks no diodes before the threshold (4, 6). The
|
|
20
|
+
header comment (``:6``) says even numbers fix even diodes. Preserved.
|
|
21
|
+
3. ``:13`` ``type = fix(modetype+1)/2``: 1,2 -> copy; 3,4 -> kernel ``:48``;
|
|
22
|
+
5,6 -> kernel ``:53``; 7 and above reach ``:57`` with ``kernel``
|
|
23
|
+
undefined and IDL halts (``Variable is undefined: KERNEL``) --
|
|
24
|
+
:class:`FixrakingUndefinedKernel`; measured under GDL (modetype 7, 8).
|
|
25
|
+
Negative and non-integer ``modetype`` truncate (-1, -3 -> type 0, no
|
|
26
|
+
fix; 2.5 -> copy with mode 0, no fix; 3.5 -> type 2), measured.
|
|
27
|
+
A 1-D image (IDL ``bytarr(n, 1)`` collapses to 1-D) runs the copy
|
|
28
|
+
branch but halts at ``:57`` in convolution mode (``CONVOL: Incompatible
|
|
29
|
+
dimensions for Array and Kernel``), measured --
|
|
30
|
+
:class:`FixrakingIncompatibleDimensions`.
|
|
31
|
+
4. ``:19`` builds the even-diode indices from ``ndiodes/2``, integer division: an odd diode
|
|
32
|
+
count leaves the last diode in neither set.
|
|
33
|
+
5. ``:57`` ``convol(float(newimage), kernel, /edge_mirror)``: kernels are
|
|
34
|
+
symmetric, so IDL's no-flip convention is immaterial. The border rule is
|
|
35
|
+
measured under GDL (bank): asymmetric -- the low edge of
|
|
36
|
+
each axis mirrors without repeating (virtual pixel -1 is ``A[1]``, numpy
|
|
37
|
+
``reflect``), the high edge repeats (virtual pixel n is ``A[n-1]``, numpy
|
|
38
|
+
``symmetric``), on both axes; the two ``slice_high_edge`` cases pin the
|
|
39
|
+
slice axis's high edge (``reflect`` would set pixel [3, 4]; GDL does not).
|
|
40
|
+
Computed in float32, as IDL's ``float`` and the float32 ``0.7`` literal.
|
|
41
|
+
6. ``:62-63`` finds the pixels of ``cimage`` at or above ``thresh``; when nothing crosses,
|
|
42
|
+
``good`` is the scalar ``-1`` and ``newimage[-1] = 1`` sets the **last
|
|
43
|
+
element** (column-major, i.e. ``[ndiodes-1, nslices-1]``). Derived from
|
|
44
|
+
the measured S4-x precedent (``fixstuckbits.py``: GDL treats a scalar
|
|
45
|
+
negative index as counting from the end); measured under GDL for this
|
|
46
|
+
file by the ``nothing_crosses`` bank cases
|
|
47
|
+
(``tests/test_soda2_fixraking_gdl.py``,
|
|
48
|
+
``test_nothing_crosses_sets_the_last_element_in_gdl``).
|
|
49
|
+
7. Output keeps the input dtype (``newimage = image``, ``:17``).
|
|
50
|
+
"""
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import numpy as np
|
|
54
|
+
|
|
55
|
+
__all__ = ["FixrakingIncompatibleDimensions", "FixrakingUndefinedKernel", "fixraking"]
|
|
56
|
+
|
|
57
|
+
# `:48` -- float32 because IDL's 0.7 literal is single precision.
|
|
58
|
+
_KERNEL_TYPE2 = np.array([[0.7, 1, 0.7], [1, 0, 1], [0.7, 1, 0.7]],
|
|
59
|
+
dtype=np.float32)
|
|
60
|
+
_THRESH_TYPE2 = 2
|
|
61
|
+
# `:53`
|
|
62
|
+
_KERNEL_TYPE3 = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]], dtype=np.float32)
|
|
63
|
+
_THRESH_TYPE3 = 4
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class FixrakingUndefinedKernel(RuntimeError):
|
|
67
|
+
"""``fixraking.pro:43-57``: ``type >= 4`` (``modetype >= 7``) enters the
|
|
68
|
+
convolution block with ``kernel`` never assigned; IDL halts at ``:57``."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class FixrakingIncompatibleDimensions(ValueError):
|
|
72
|
+
"""``fixraking.pro:57``: ``convol`` of a 1-D image with the 3x3 kernel;
|
|
73
|
+
GDL halts with ``CONVOL: Incompatible dimensions for Array and Kernel``."""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _idl_fix(x: float) -> int:
|
|
77
|
+
"""IDL ``fix``: truncation toward zero."""
|
|
78
|
+
return int(x)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _idl_mod(a: int, b: int) -> int:
|
|
82
|
+
"""IDL ``mod`` takes the sign of the dividend (C remainder)."""
|
|
83
|
+
r = abs(a) % abs(b)
|
|
84
|
+
return -r if a < 0 else r
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _convol_edge_mirror(a: np.ndarray, kernel: np.ndarray) -> np.ndarray:
|
|
88
|
+
"""``convol(a, kernel, /edge_mirror)`` for a 3x3 symmetric kernel,
|
|
89
|
+
no ``/normalize`` (scale 1). See module docstring item 5."""
|
|
90
|
+
# GDL bank (golden gdl_soda2_fixraking_golden.json): the low edge
|
|
91
|
+
# mirrors without repeating (A[-1] = A[1]), the high edge repeats (A[n] = A[n-1]).
|
|
92
|
+
padded = np.pad(a, ((0, 1), (0, 1)), mode="symmetric")
|
|
93
|
+
padded = np.pad(padded, ((1, 0), (1, 0)), mode="reflect")
|
|
94
|
+
out = np.zeros(a.shape, dtype=np.float32)
|
|
95
|
+
n0, n1 = a.shape
|
|
96
|
+
for i in range(3):
|
|
97
|
+
for j in range(3):
|
|
98
|
+
k = kernel[i, j]
|
|
99
|
+
if k == 0:
|
|
100
|
+
continue
|
|
101
|
+
out += k * padded[i:i + n0, j:j + n1]
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def fixraking(image: np.ndarray, modetype: int) -> np.ndarray:
|
|
106
|
+
"""``fixraking.pro:1-67``. ``image`` is ``[diode, slice]``."""
|
|
107
|
+
# `:10`
|
|
108
|
+
if modetype == 0:
|
|
109
|
+
# IDL returns the value, and the one caller
|
|
110
|
+
# (soda2_processbuffer.pro:616) calls only when rakefix gt 0 and
|
|
111
|
+
# reassigns bitimage from the result, so aliasing is never visible
|
|
112
|
+
# there; a copy keeps the IDL value semantics for any other caller.
|
|
113
|
+
return np.asarray(image).copy()
|
|
114
|
+
# `:12-13`
|
|
115
|
+
mode = _idl_mod(_idl_fix(modetype), 2)
|
|
116
|
+
type_ = _idl_fix(modetype + 1) // 2 if modetype + 1 >= 0 else \
|
|
117
|
+
-(abs(_idl_fix(modetype + 1)) // 2)
|
|
118
|
+
|
|
119
|
+
image = np.asarray(image)
|
|
120
|
+
newimage = image.copy() # `:17`
|
|
121
|
+
ndiodes = image.shape[0] # `:18`
|
|
122
|
+
ieven = np.arange(ndiodes // 2) * 2 # `:19`
|
|
123
|
+
iodd = ieven + 1 # `:20`
|
|
124
|
+
|
|
125
|
+
# `:36-40` copy mode
|
|
126
|
+
if type_ == 1:
|
|
127
|
+
if mode == 1:
|
|
128
|
+
newimage[iodd, ...] = image[ieven, ...]
|
|
129
|
+
if mode == 2: # dead: mode is 0 or 1
|
|
130
|
+
newimage[ieven, ...] = image[iodd, ...]
|
|
131
|
+
|
|
132
|
+
# `:43-64` convolution mode
|
|
133
|
+
if type_ >= 2:
|
|
134
|
+
if type_ == 2:
|
|
135
|
+
kernel, thresh = _KERNEL_TYPE2, _THRESH_TYPE2
|
|
136
|
+
elif type_ == 3:
|
|
137
|
+
kernel, thresh = _KERNEL_TYPE3, _THRESH_TYPE3
|
|
138
|
+
else:
|
|
139
|
+
raise FixrakingUndefinedKernel(
|
|
140
|
+
f"fixraking.pro:57: modetype={modetype} gives type={type_}; "
|
|
141
|
+
"kernel is undefined (IDL: Variable is undefined: KERNEL)")
|
|
142
|
+
a = newimage.astype(np.float32)
|
|
143
|
+
if a.ndim != 2:
|
|
144
|
+
raise FixrakingIncompatibleDimensions(
|
|
145
|
+
f"fixraking.pro:57: image has {a.ndim} dimension(s); "
|
|
146
|
+
"IDL: CONVOL: Incompatible dimensions for Array and Kernel")
|
|
147
|
+
cimage = _convol_edge_mirror(a, kernel).reshape(newimage.shape)
|
|
148
|
+
if mode == 1: # `:59`
|
|
149
|
+
cimage[ieven, ...] = 0
|
|
150
|
+
if mode == 2: # `:60`, dead
|
|
151
|
+
cimage[iodd, ...] = 0
|
|
152
|
+
# `:62-63`, column-major flat order as IDL's where().
|
|
153
|
+
flat_c = cimage.ravel(order="F")
|
|
154
|
+
good = np.nonzero(flat_c >= thresh)[0]
|
|
155
|
+
flat_new = newimage.ravel(order="F").copy()
|
|
156
|
+
if good.size == 0:
|
|
157
|
+
flat_new[-1] = 1 # where() sentinel -1
|
|
158
|
+
else:
|
|
159
|
+
flat_new[good] = 1
|
|
160
|
+
newimage = flat_new.reshape(newimage.shape, order="F")
|
|
161
|
+
|
|
162
|
+
return newimage
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Reproduces SODA-2, Copyright (c) 2016 UCAR; see LICENSES/BSD-3-Clause.txt and NOTICE.md.
|
|
3
|
+
"""``fixstuckbits.pro`` -- work around bits stuck 'on' in an OAP image
|
|
4
|
+
buffer.
|
|
5
|
+
|
|
6
|
+
30 lines of IDL. Signature ``fixstuckbits(image, h=h)``. Callers:
|
|
7
|
+
``soda2_processbuffer.pro:615`` (all probes, gated by
|
|
8
|
+
``(*pop).stuckbits``, default 0 at ``soda2_update_op.pro:23``) and
|
|
9
|
+
``soda2_bitimage.pro:43``. Neither caller passes ``h``.
|
|
10
|
+
|
|
11
|
+
**Line-by-line** (IDL 1-based diode indexing kept visible; converted to
|
|
12
|
+
0-based only where NumPy requires it):
|
|
13
|
+
|
|
14
|
+
- ``:8`` -- ``h=total(image,2)`` when omitted: a per-diode-column total
|
|
15
|
+
across slices, FLOAT (IDL's ``total`` promotes).
|
|
16
|
+
- ``:11-13`` -- ``pad=7``; ``h2`` is a **LONG** (``lonarr``) array of
|
|
17
|
+
``len(h)+14`` with ``h`` written into the middle -- assigning a FLOAT
|
|
18
|
+
``h`` into a LONG array **truncates toward zero** (totals are
|
|
19
|
+
non-negative, so this is ``floor``).
|
|
20
|
+
- ``:14`` -- ``hf=median(h2,7)``, IDL's width-7 median filter, returns
|
|
21
|
+
FLOAT. Implemented here as the plain interior 7-window median (see
|
|
22
|
+
:func:`_median_filter_7`); the padded region's own value never crosses
|
|
23
|
+
the threshold below (the 7-element pad on each side is wider than the
|
|
24
|
+
filter's half-width 3), so this port does not reproduce IDL's edge rule
|
|
25
|
+
for a shortened window -- pinned by ``test_pad_region_never_crosses_threshold``.
|
|
26
|
+
- ``:15`` -- ``diff=abs(h2-hf)``.
|
|
27
|
+
- ``:17`` -- the stuck diodes are those whose ``diff`` exceeds ten times the
|
|
28
|
+
root of the median of ``h``, offset by ``pad``. IDL's
|
|
29
|
+
scalar ``median`` **without ``/EVEN`` takes the upper of the two middle
|
|
30
|
+
values** for an even count (measured: ``median([1,2,3,4]) = 3``):
|
|
31
|
+
``np.sort(h)[n // 2]``.
|
|
32
|
+
- **``:19`` -- the no-match case is S4-x, and GDL measurement overturned
|
|
33
|
+
the first-pass reading (a halt) below.** IDL's ``where`` with no match
|
|
34
|
+
returns the scalar ``-1``; ``- pad`` makes it the scalar ``-8``; ``:19``
|
|
35
|
+
tests ``stuck[0] eq -1``, the *pre-subtraction* sentinel, so it is
|
|
36
|
+
always false; ``:20`` then subscripts ``image`` with the scalar ``-8``.
|
|
37
|
+
**Measured under GDL (this bank): a scalar index of ``-8`` is a normal
|
|
38
|
+
IDL negative index -- it counts from the end of the array -- so for any
|
|
39
|
+
image with 8 or more diodes, ``:20`` silently zeroes diode column
|
|
40
|
+
``n - 8`` (not a real stuck diode) and reconstructs it from its own
|
|
41
|
+
neighbour at ``n - 9``, exactly as if that column had been flagged.**
|
|
42
|
+
Only when the diode count is *under* 8 does ``-8`` fall outside the
|
|
43
|
+
array and GDL actually halt: ``% FIXSTUCKBITS: Subscript out of range
|
|
44
|
+
[-i]`` (measured on a 5-diode image). This port reproduces the silent
|
|
45
|
+
corruption for ``n >= 8`` by using the same negative-index arithmetic
|
|
46
|
+
NumPy already applies, and raises :class:`NoStuckBitsHalt` only for
|
|
47
|
+
``n < 8``, matching the genuine halt.
|
|
48
|
+
- ``:20-27`` -- for each stuck column: zero it, then copy the **left**
|
|
49
|
+
neighbour (or the right one for column 0), reading from the
|
|
50
|
+
already-zeroed ``image`` -- two adjacent stuck columns leave the
|
|
51
|
+
*second* one blank. IDL mutates the caller's array in place at ``:20``
|
|
52
|
+
(both call sites immediately reassign their own variable to the
|
|
53
|
+
return value, so the mutation is unobservable there); this port
|
|
54
|
+
**copies** ``image`` first and never mutates the caller's array.
|
|
55
|
+
"""
|
|
56
|
+
from __future__ import annotations
|
|
57
|
+
|
|
58
|
+
import numpy as np
|
|
59
|
+
|
|
60
|
+
__all__ = ["NoStuckBitsHalt", "fixstuckbits"]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class NoStuckBitsHalt(RuntimeError):
|
|
64
|
+
"""``fixstuckbits.pro:17-20`` -- when no diode crosses the threshold
|
|
65
|
+
and the image has **fewer than 8 diodes**, IDL's scalar index ``-8``
|
|
66
|
+
(the where() sentinel ``-1`` minus ``pad=7``) falls outside the array
|
|
67
|
+
and GDL halts: ``% FIXSTUCKBITS: Subscript out of range [-i]``
|
|
68
|
+
(measured on a 5-diode image). This is the genuine-halt half of SODA-2 register entry S4-x;
|
|
69
|
+
for 8 or more diodes, ``-8`` is a valid negative index and the
|
|
70
|
+
routine silently corrupts diode column ``n - 8`` instead -- see the
|
|
71
|
+
module docstring and the non-halting half of that entry."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _median_filter_7(h2: np.ndarray) -> np.ndarray:
|
|
75
|
+
"""Plain width-7 median over the interior of ``h2`` (indices
|
|
76
|
+
``3..len-4``); the 3 outermost positions on each end are never read by
|
|
77
|
+
``:15`` because the pad is wider than the filter half-width -- see the
|
|
78
|
+
module docstring and ``test_pad_region_never_crosses_threshold``."""
|
|
79
|
+
n = len(h2)
|
|
80
|
+
out = np.zeros(n, dtype=np.float32)
|
|
81
|
+
for i in range(3, n - 3):
|
|
82
|
+
window = h2[i - 3:i + 4]
|
|
83
|
+
out[i] = np.sort(window)[3].astype(np.float32)
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def fixstuckbits(image: np.ndarray, h: np.ndarray | None = None) -> np.ndarray:
|
|
88
|
+
"""``fixstuckbits(image, h=h)`` (``fixstuckbits.pro:8-29``).
|
|
89
|
+
|
|
90
|
+
``image`` is a 2-D array, diode axis first (axis 0), matching
|
|
91
|
+
``findsize.py`` / ``processbuffer_spec.py``'s ``[x, y]`` convention.
|
|
92
|
+
``h`` is an ``intarr`` (``(*pmisc).lastdhist``) at the one call site
|
|
93
|
+
that supplies it; when omitted, ``h = total(image, 2)`` (a per-column
|
|
94
|
+
sum over slices).
|
|
95
|
+
|
|
96
|
+
Raises :class:`NoStuckBitsHalt` where IDL itself would halt (SODA-2 register entry S4-x),
|
|
97
|
+
rather than silently returning ``image`` unchanged.
|
|
98
|
+
|
|
99
|
+
The input is never mutated; the return is always a fresh array.
|
|
100
|
+
"""
|
|
101
|
+
image = np.asarray(image)
|
|
102
|
+
n = image.shape[0]
|
|
103
|
+
|
|
104
|
+
if h is None:
|
|
105
|
+
h_float = image.sum(axis=1).astype(np.float64)
|
|
106
|
+
else:
|
|
107
|
+
h_float = np.asarray(h, dtype=np.float64)
|
|
108
|
+
|
|
109
|
+
pad = 7
|
|
110
|
+
h2 = np.zeros(n + 2 * pad, dtype=np.int32)
|
|
111
|
+
h2[pad:pad + n] = h_float.astype(np.int32) # LONG truncation, :12-13
|
|
112
|
+
|
|
113
|
+
hf = _median_filter_7(h2)
|
|
114
|
+
diff = np.abs(h2.astype(np.float32) - hf)
|
|
115
|
+
|
|
116
|
+
med_h = np.sort(h_float)[len(h_float) // 2] # IDL scalar median, upper-middle
|
|
117
|
+
threshold = np.float32(10) * np.float32(np.sqrt(med_h))
|
|
118
|
+
|
|
119
|
+
stuck_idx = np.where(diff > threshold)[0]
|
|
120
|
+
if stuck_idx.size == 0:
|
|
121
|
+
# `:17-20`, S4-x: IDL's where() sentinel -1 minus pad(7) = -8, a
|
|
122
|
+
# scalar negative index. For n < 8 diodes that is genuinely out
|
|
123
|
+
# of range and GDL halts (measured); for n >= 8 it silently
|
|
124
|
+
# corrupts diode column n-8 instead of returning the image
|
|
125
|
+
# unchanged. NumPy's own negative indexing reproduces the n >= 8
|
|
126
|
+
# branch exactly, so only the n < 8 branch needs an explicit guard.
|
|
127
|
+
if n < 8:
|
|
128
|
+
raise NoStuckBitsHalt(
|
|
129
|
+
"fixstuckbits.pro:17-20: no diode crossed the threshold "
|
|
130
|
+
"and the image has fewer than 8 diodes, so IDL's scalar "
|
|
131
|
+
"index -8 falls outside the array -- GDL halts with "
|
|
132
|
+
"'Subscript out of range [-i]' (measured); SODA-2 "
|
|
133
|
+
"finding S4-x")
|
|
134
|
+
stuck = np.array([-8])
|
|
135
|
+
else:
|
|
136
|
+
stuck = stuck_idx - pad # :17, back into diode-column space
|
|
137
|
+
|
|
138
|
+
out = image.copy()
|
|
139
|
+
out[stuck, :] = 0
|
|
140
|
+
newimage = out.copy()
|
|
141
|
+
for s in stuck:
|
|
142
|
+
if s == 0:
|
|
143
|
+
newimage[0, :] = out[1, :]
|
|
144
|
+
else:
|
|
145
|
+
newimage[s, :] = out[s - 1, :]
|
|
146
|
+
return newimage
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Reproduces SODA-2, Copyright (c) 2016 UCAR; see LICENSES/BSD-3-Clause.txt and NOTICE.md.
|
|
3
|
+
"""``hvps4_read_frame.pro`` -- read one HVPS-4 frame (SPEC subformat 2).
|
|
4
|
+
|
|
5
|
+
67 lines of IDL, Aaron Bansemer, NCAR, 8/2022. Copyright (C) 2016 UCAR,
|
|
6
|
+
3-clause BSD. Provenance: ``SODA2/abansemer-soda2-afcea15/hvps4_read_frame.pro``.
|
|
7
|
+
Validated against GDL by ``tests/test_soda2_hvps4_read_frame.py``; bank at
|
|
8
|
+
``gdl_oracle/run_soda2_hvps4_read_frame_bank.py`` (synthetic fixture). GDL
|
|
9
|
+
cannot run ``:39-40``'s IDL string methods, so the bank runs an oracle-path
|
|
10
|
+
shim of those two lines (``gdl_oracle/shims/hvps4_read_frame.pro``); which
|
|
11
|
+
block runs (``array``/``res``) is shim-derived.
|
|
12
|
+
|
|
13
|
+
**Line-by-line** (IDL 0-based indexing; every slice below is the source's):
|
|
14
|
+
|
|
15
|
+
- `:11-14` -- seek, ``x = spec_readint(lun, 3)``; ``nh``/``nv`` low 12 bits.
|
|
16
|
+
- `:17-22` -- bit 12 missing time word, **bit 14 the array resolution**
|
|
17
|
+
(1 = 50 um, 0 = 150 um; 2D-S reads it as the empty-FIFO flag), bit 15 overload.
|
|
18
|
+
- `:25` -- reads ``2+nh+nv`` words with ``spec_readint``, with the undecremented counts.
|
|
19
|
+
- `:31-36` -- defaults: one blank slice, ``time = 0L`` (LONG), ``error = 1``,
|
|
20
|
+
``overload = 0`` (INT).
|
|
21
|
+
- `:39-42` -- ``array`` is ``id``'s first letter, ``res`` its integer tail;
|
|
22
|
+
the frame is decoded only when the letter **and** the bit-14 resolution
|
|
23
|
+
match. ``'h50'`` matches nothing (``eq`` is case-sensitive).
|
|
24
|
+
- `:44-53` -- H block, ``nh gt 3``: ``nh = nh-1``; image ``buff[2:nh-1]``;
|
|
25
|
+
counter ``ulong(buff[nh:nh+2])``; ``time = ishft(c[2],32) + ishft(c[1],16)
|
|
26
|
+
+ c[0]`` in ULONG. **Measured under GDL: ``ishft(ULONG, 32)`` returns its
|
|
27
|
+
operand unshifted** (the shift count is taken mod 32, as x86 does), so
|
|
28
|
+
``c[2]`` is *added* to the time, and the sum wraps mod 2**32 (bank case
|
|
29
|
+
``high_counter``; whether IDL agrees is an open oracle question, flagged, not measured).
|
|
30
|
+
``error = missingtwh`` -- a split particle is dropped, never stitched.
|
|
31
|
+
- `:55-64` -- V block, same shape, image ``buff[2:nv-1]`` and counter
|
|
32
|
+
``buff[nv:nv+2]`` with **no** ``nh`` offset (a SODA-2 finding, preserved: on a frame with
|
|
33
|
+
both arrays the V block reads the H words; bank case ``dual_v50``).
|
|
34
|
+
- `:66` -- ``{image, time, error, overload, particlecount}``; no ``imageraw``,
|
|
35
|
+
no ``timetrunc``, no ``nn eq 2`` check.
|
|
36
|
+
"""
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
from dataclasses import dataclass
|
|
40
|
+
from typing import BinaryIO
|
|
41
|
+
|
|
42
|
+
import numpy as np
|
|
43
|
+
|
|
44
|
+
from .spec_decompress import spec_decompress
|
|
45
|
+
from .spec_readint import spec_readint
|
|
46
|
+
|
|
47
|
+
__all__ = ["Hvps4Frame", "hvps4_read_frame"]
|
|
48
|
+
|
|
49
|
+
_MASK_12BIT = 0xFFF
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Hvps4Frame:
|
|
54
|
+
"""``hvps4_read_frame``'s return struct (`:66`), IDL types carried as
|
|
55
|
+
NumPy scalar dtypes as GDL reports them (bank ``TN`` field)."""
|
|
56
|
+
|
|
57
|
+
#: ``(numslices, 128)`` uint8 (the package's transpose of ``bytarr(128,n)``).
|
|
58
|
+
image: np.ndarray
|
|
59
|
+
#: ULONG (``np.uint32``) when a block ran; LONG ``0`` (``np.int32``) otherwise.
|
|
60
|
+
time: np.uint32 | np.int32
|
|
61
|
+
#: INT.
|
|
62
|
+
error: np.int16
|
|
63
|
+
#: LONG when a block ran (``ishft`` of ``x and '8000'x``); INT ``0`` otherwise.
|
|
64
|
+
overload: np.int32 | np.int16
|
|
65
|
+
#: UINT, ``buff[0]``.
|
|
66
|
+
particlecount: np.uint16
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _ishft_ulong(value: int, shift: int) -> int:
|
|
70
|
+
"""GDL's measured ``ishft`` on a ULONG: count taken mod 32, result mod 2**32."""
|
|
71
|
+
return (value << (shift % 32)) & 0xFFFFFFFF
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def hvps4_read_frame(f: BinaryIO, bpoint: int, id: str) -> Hvps4Frame:
|
|
75
|
+
"""``q = hvps4_read_frame(lun, bpoint, id)``; ``id`` is e.g. ``'H50'``.
|
|
76
|
+
|
|
77
|
+
Source: ``hvps4_read_frame.pro`` (SODA-2)."""
|
|
78
|
+
f.seek(bpoint) # `:11`
|
|
79
|
+
x = spec_readint(f, 3) # `:12`
|
|
80
|
+
nh = int(x[1]) & _MASK_12BIT
|
|
81
|
+
nv = int(x[2]) & _MASK_12BIT
|
|
82
|
+
missingtwh = (int(x[1]) & 0x1000) >> 12
|
|
83
|
+
missingtwv = (int(x[2]) & 0x1000) >> 12
|
|
84
|
+
arrayhid = (int(x[1]) & 0x4000) >> 14
|
|
85
|
+
arrayvid = (int(x[2]) & 0x4000) >> 14
|
|
86
|
+
overloadh = (int(x[1]) & 0x8000) >> 15
|
|
87
|
+
overloadv = (int(x[2]) & 0x8000) >> 15
|
|
88
|
+
|
|
89
|
+
buff = spec_readint(f, 2 + nh + nv) # `:25`
|
|
90
|
+
particlecount = np.uint16(buff[0])
|
|
91
|
+
|
|
92
|
+
image = np.zeros((1, 128), dtype=np.uint8)
|
|
93
|
+
time: np.uint32 | np.int32 = np.int32(0)
|
|
94
|
+
error = np.int16(1)
|
|
95
|
+
overload: np.int32 | np.int16 = np.int16(0)
|
|
96
|
+
|
|
97
|
+
# `:39-40`, IDL ``substring(0,0)`` / ``fix(substring(1,3))``.
|
|
98
|
+
array = id[0:1]
|
|
99
|
+
res = int(id[1:4])
|
|
100
|
+
arrayhres = 50 if arrayhid == 1 else 150
|
|
101
|
+
arrayvres = 50 if arrayvid == 1 else 150
|
|
102
|
+
|
|
103
|
+
def _block(n: int, overload_bit: int, missingtw: int) -> None:
|
|
104
|
+
nonlocal image, time, error, overload
|
|
105
|
+
n -= 1 # `:45` / `:56`
|
|
106
|
+
imageraw = buff[2:n].copy() # IDL [2:n-1] inclusive
|
|
107
|
+
c = buff[n:n + 3].astype(np.uint32) # IDL [n:n+2]
|
|
108
|
+
t = (_ishft_ulong(int(c[2]), 32) + _ishft_ulong(int(c[1]), 16)
|
|
109
|
+
+ int(c[0])) & 0xFFFFFFFF
|
|
110
|
+
time = np.uint32(t)
|
|
111
|
+
image = spec_decompress(imageraw, overload_bit, version=1)
|
|
112
|
+
error = np.int16(1 if missingtw else 0)
|
|
113
|
+
overload = np.int32(overload_bit)
|
|
114
|
+
|
|
115
|
+
if nh > 3 and array == "H" and arrayhres == res: # `:44`
|
|
116
|
+
_block(nh, overloadh, missingtwh)
|
|
117
|
+
if nv > 3 and array == "V" and arrayvres == res: # `:55`, no nh offset (preserved)
|
|
118
|
+
_block(nv, overloadv, missingtwv)
|
|
119
|
+
|
|
120
|
+
return Hvps4Frame(image=image, time=time, error=error, overload=overload,
|
|
121
|
+
particlecount=particlecount)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Reproduces SODA-2, Copyright (c) 2016 UCAR; see LICENSES/BSD-3-Clause.txt and NOTICE.md.
|
|
3
|
+
"""SODA-2's opt-in accelerated kernel -- ``label_blobs(..., jit=True)``.
|
|
4
|
+
|
|
5
|
+
**Space: the port.** The kernel here returns the same value as the function
|
|
6
|
+
it replaces, bit for bit, so a call with ``jit=True`` returns the same array
|
|
7
|
+
as one without (``tests/test_soda2_label_region_jit_identity.py`` runs both
|
|
8
|
+
and compares with ``np.array_equal``/``tobytes()``, never ``allclose``). It
|
|
9
|
+
is opt-in and defaults off, and numba -- already an optional dependency of
|
|
10
|
+
the two UIOOPS-engine JIT paths (``arrayprobe.jit_kernels``,
|
|
11
|
+
``arrayprobe_uiops.jit_kernels``) -- is imported only when a caller asks for
|
|
12
|
+
it, never by ``import arrayprobe_soda2``, matching that same posture.
|
|
13
|
+
|
|
14
|
+
Which kernel, and why only this one: the function-level profile of a real
|
|
15
|
+
UND CIP run (profiled 2026-09-18) found
|
|
16
|
+
:func:`arrayprobe_soda2.label_blobs._label_region` -- the 4-/8-connected
|
|
17
|
+
flood fill ``label_blobs`` uses to work around IDL ``label_region``'s own
|
|
18
|
+
border-zeroing -- to be the single hottest **leaf** by self-time in the
|
|
19
|
+
profiled tail, ~24 % of it measured (305-particle dense window) and ~28 % of
|
|
20
|
+
a real run once combined with the established 97.3 %-of-a-run tail share.
|
|
21
|
+
It is two nested ``for`` loops over a small
|
|
22
|
+
2-D integer array plus a flood-fill stack: integer comparisons and array
|
|
23
|
+
indexing only, zero floating-point trig. Structurally almost identical to
|
|
24
|
+
the UIOOPS engine's own ``particle_perimeter`` kernel
|
|
25
|
+
(:mod:`arrayprobe.jit_kernels`), which was accelerated on exactly this
|
|
26
|
+
precedent -- pure integer double loop, numba-compiled, proven byte-identical
|
|
27
|
+
-- so no new exactness argument is needed here, only the same kind of
|
|
28
|
+
rewrite ``particle_perimeter``/``cgal_min_r`` already needed to become numba
|
|
29
|
+
kernels in the first place.
|
|
30
|
+
|
|
31
|
+
:func:`_label_region_kernel` is :func:`arrayprobe_soda2.label_blobs._label_region`
|
|
32
|
+
with its Python ``list`` of ``(y, x)`` tuples (numba's nopython mode does not
|
|
33
|
+
accept a growing reflected list of tuples) replaced by a pre-sized ``int64``
|
|
34
|
+
array stack with an explicit top pointer -- the same shape of rewrite
|
|
35
|
+
``cgal_min_r``'s Welzl pass needed for its own Python structures
|
|
36
|
+
(:mod:`arrayprobe.jit_kernels`'s module docstring). ``ny * nx`` rows is
|
|
37
|
+
always enough: a pixel is pushed at most once, immediately after its label
|
|
38
|
+
is set, and the ``labels[...] == 0`` guard then excludes it from ever being
|
|
39
|
+
pushed again. The stack's LIFO push/pop matches Python's
|
|
40
|
+
``list.append``/``list.pop()`` exactly, but this is provable overkill: the
|
|
41
|
+
*order* pixels are visited inside one flood fill cannot change the array
|
|
42
|
+
returned, because every pixel reached from a seed receives that seed's
|
|
43
|
+
``next_label`` regardless of the order the fill reaches it in -- only the
|
|
44
|
+
outer raster scan's y-then-x order (unchanged here, and the only place
|
|
45
|
+
``next_label`` is assigned) decides which id a blob receives. Connectivity
|
|
46
|
+
(4- vs 8-neighbour) is threaded through as a plain ``(k, 2)`` int64 offset
|
|
47
|
+
array rather than compiling two kernels, since neither array shape nor
|
|
48
|
+
values are part of a numba array type signature -- one compilation serves
|
|
49
|
+
both :func:`arrayprobe_soda2.label_blobs.label_blobs`'s ``all_neighbors``
|
|
50
|
+
states.
|
|
51
|
+
|
|
52
|
+
What stays out, on purpose (the profile's own "Ranked candidates" section):
|
|
53
|
+
``findsize``'s ``aspect_ratio``/``min_circle_fast_traced`` complex, ~61 % of
|
|
54
|
+
a real run. It routes through ``angles.find_angle_array``'s law-of-cosines,
|
|
55
|
+
the same floating-point-trig shape the UIOOPS profile excluded ``holroyd``
|
|
56
|
+
for ("rotates particle pixels with arctan, cos and sin ... one ULP could
|
|
57
|
+
move" -- ``arrayprobe/jit_kernels.py``'s own module docstring). Porting it
|
|
58
|
+
needs a trig-exactness proof this module does not attempt.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
from __future__ import annotations
|
|
62
|
+
|
|
63
|
+
from typing import Any
|
|
64
|
+
|
|
65
|
+
import numpy as np
|
|
66
|
+
|
|
67
|
+
__all__ = ["JitKernels", "load"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
#: 4-connected and 8-connected neighbour offsets, ``(dy, dx)`` -- passed as
|
|
71
|
+
#: data, not baked into two separate compiled kernels (see module docstring).
|
|
72
|
+
_NEIGH4 = np.array([(-1, 0), (1, 0), (0, -1), (0, 1)], dtype=np.int64)
|
|
73
|
+
_NEIGH8 = np.array([(-1, -1), (-1, 0), (-1, 1), (0, -1),
|
|
74
|
+
(0, 1), (1, -1), (1, 0), (1, 1)], dtype=np.int64)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _label_region_kernel(temp: np.ndarray, neighbours: np.ndarray) -> np.ndarray:
|
|
78
|
+
"""``label_blobs._label_region``'s body, numba-shaped: raster-order
|
|
79
|
+
(y then x) flood fill of ``temp`` (2-D, 0/nonzero) using ``neighbours``
|
|
80
|
+
(an ``(k, 2)`` int64 array of ``(dy, dx)`` offsets, ``k`` = 4 or 8).
|
|
81
|
+
Returns ``uint32`` labels, same shape as ``temp``. See module docstring
|
|
82
|
+
for why an array-backed stack replacing the reference's Python list
|
|
83
|
+
cannot change the result.
|
|
84
|
+
"""
|
|
85
|
+
ny, nx = temp.shape
|
|
86
|
+
labels = np.zeros((ny, nx), dtype=np.uint32)
|
|
87
|
+
next_label = 1
|
|
88
|
+
n_nb = neighbours.shape[0]
|
|
89
|
+
stack = np.empty((ny * nx, 2), dtype=np.int64)
|
|
90
|
+
for y in range(ny):
|
|
91
|
+
for x in range(nx):
|
|
92
|
+
if temp[y, x] == 0 or labels[y, x] != 0:
|
|
93
|
+
continue
|
|
94
|
+
# New blob found at raster position (x fastest): flood fill.
|
|
95
|
+
top = 0
|
|
96
|
+
stack[top, 0] = y
|
|
97
|
+
stack[top, 1] = x
|
|
98
|
+
top += 1
|
|
99
|
+
labels[y, x] = next_label
|
|
100
|
+
while top > 0:
|
|
101
|
+
top -= 1
|
|
102
|
+
cy = stack[top, 0]
|
|
103
|
+
cx = stack[top, 1]
|
|
104
|
+
for k in range(n_nb):
|
|
105
|
+
ny_ = cy + neighbours[k, 0]
|
|
106
|
+
nx_ = cx + neighbours[k, 1]
|
|
107
|
+
if (0 <= ny_ < ny and 0 <= nx_ < nx
|
|
108
|
+
and temp[ny_, nx_] != 0 and labels[ny_, nx_] == 0):
|
|
109
|
+
labels[ny_, nx_] = next_label
|
|
110
|
+
stack[top, 0] = ny_
|
|
111
|
+
stack[top, 1] = nx_
|
|
112
|
+
top += 1
|
|
113
|
+
next_label += 1
|
|
114
|
+
return labels
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class JitKernels:
|
|
118
|
+
"""The compiled kernel, and the drop-in function ``label_blobs`` calls
|
|
119
|
+
through."""
|
|
120
|
+
|
|
121
|
+
def __init__(self, njit: Any) -> None:
|
|
122
|
+
opts = {"cache": True, "boundscheck": True} # fastmath stays OFF
|
|
123
|
+
self._label_region = njit(**opts)(_label_region_kernel)
|
|
124
|
+
|
|
125
|
+
def label_region(self, temp: np.ndarray, all_neighbors: bool) -> np.ndarray:
|
|
126
|
+
"""Drop-in for :func:`arrayprobe_soda2.label_blobs._label_region`."""
|
|
127
|
+
a = np.asarray(temp)
|
|
128
|
+
if a.ndim != 2 or a.dtype.kind not in "iu":
|
|
129
|
+
from .label_blobs import _label_region
|
|
130
|
+
return _label_region(temp, all_neighbors)
|
|
131
|
+
neighbours = _NEIGH8 if all_neighbors else _NEIGH4
|
|
132
|
+
return self._label_region(np.ascontiguousarray(a), neighbours)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
_LOADED: JitKernels | None = None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def load() -> JitKernels:
|
|
139
|
+
"""Import numba and compile (or load from cache) the kernel, once per
|
|
140
|
+
process."""
|
|
141
|
+
global _LOADED
|
|
142
|
+
if _LOADED is None:
|
|
143
|
+
try:
|
|
144
|
+
from numba import njit
|
|
145
|
+
except ImportError as exc: # pragma: no cover - exercised only without the extra
|
|
146
|
+
raise ModuleNotFoundError(
|
|
147
|
+
"label_blobs(jit=True) needs numba, an optional extra: "
|
|
148
|
+
"pip install \"arrayprobe[jit]\". The default "
|
|
149
|
+
"(jit=False) returns the same array without it."
|
|
150
|
+
) from exc
|
|
151
|
+
_LOADED = JitKernels(njit)
|
|
152
|
+
return _LOADED
|