arrayprobe-soda2-enhancements 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 (31) hide show
  1. arrayprobe_soda2_enhancements/__init__.py +36 -0
  2. arrayprobe_soda2_enhancements/_adapter.py +175 -0
  3. arrayprobe_soda2_enhancements/_aspect_ratio_recompute.py +124 -0
  4. arrayprobe_soda2_enhancements/aspr_nan_fix.py +56 -0
  5. arrayprobe_soda2_enhancements/blank_roi_dof_fix.py +49 -0
  6. arrayprobe_soda2_enhancements/den_clamp_fix.py +55 -0
  7. arrayprobe_soda2_enhancements/dilation_clamp_fix.py +89 -0
  8. arrayprobe_soda2_enhancements/double_pi_fix.py +222 -0
  9. arrayprobe_soda2_enhancements/empty_roi_diodegaps_fix.py +59 -0
  10. arrayprobe_soda2_enhancements/fillholes_int_labels.py +98 -0
  11. arrayprobe_soda2_enhancements/hk_probeid_columns.py +80 -0
  12. arrayprobe_soda2_enhancements/label_blobs_int_count.py +51 -0
  13. arrayprobe_soda2_enhancements/last_buffer_index_fix.py +246 -0
  14. arrayprobe_soda2_enhancements/no_stuck_diode_fix.py +84 -0
  15. arrayprobe_soda2_enhancements/pbp_inttime_consistent.py +78 -0
  16. arrayprobe_soda2_enhancements/pbp_rejectionflag_ubyte.py +132 -0
  17. arrayprobe_soda2_enhancements/poisson_fill_guard.py +58 -0
  18. arrayprobe_soda2_enhancements/py.typed +0 -0
  19. arrayprobe_soda2_enhancements/registry.py +249 -0
  20. arrayprobe_soda2_enhancements/rejection_tally_fix.py +94 -0
  21. arrayprobe_soda2_enhancements/rollover_modulus_fix.py +104 -0
  22. arrayprobe_soda2_enhancements/run_diagnostics.py +278 -0
  23. arrayprobe_soda2_enhancements/same_time_buffer_fix.py +78 -0
  24. arrayprobe_soda2_enhancements/zero_area_return_fix.py +68 -0
  25. arrayprobe_soda2_enhancements-0.1.0.dist-info/METADATA +80 -0
  26. arrayprobe_soda2_enhancements-0.1.0.dist-info/RECORD +31 -0
  27. arrayprobe_soda2_enhancements-0.1.0.dist-info/WHEEL +5 -0
  28. arrayprobe_soda2_enhancements-0.1.0.dist-info/licenses/LICENSE +31 -0
  29. arrayprobe_soda2_enhancements-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
  30. arrayprobe_soda2_enhancements-0.1.0.dist-info/licenses/NOTICE.md +160 -0
  31. arrayprobe_soda2_enhancements-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,36 @@
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
+ """``arrayprobe-soda2-enhancements`` -- opt-in corrections for findings against
4
+ ``arrayprobe_soda2``, NCAR SODA-2's Python port.
5
+
6
+ Requested 2026-09-14: *"same for soda - address any findings and start to create
7
+ its own enhancements 'version' that users could use. so we essentially create two packages -
8
+ v3.5 and soda with opt in enhancements."* This is the "soda" package that quote asks for,
9
+ built the same way ``arrayprobe_enhancements`` was built for UIOOPS: a separate distribution
10
+ that imports ``arrayprobe_soda2`` and never the reverse, so installing it is the opt-in and
11
+ the port stays importable, tested and byte-faithful with this package deleted.
12
+
13
+ Which findings are correctable here (Tier A)
14
+ and which are deferred is ``enhancements_soda2/BACKLOG_STATUS.md``.
15
+
16
+ **Dependency direction.** This package imports ``arrayprobe_soda2`` (packaged inside the
17
+ ``arrayprobe`` distribution) and nothing else from this repository -- never ``arrayprobe``
18
+ (the UIOOPS v3.1.4 port), ``arrayprobe_uiops``, or ``arrayprobe_enhancements``. Two lineages,
19
+ never sharing a correction: ``arrayprobe_enhancements.applicability``'s ``ENGINES`` excludes
20
+ SODA-2 on the same grounds. Enforced by
21
+ ``enhancements_soda2/tests/test_lineage_isolation.py`` (this package, an AST sweep for those
22
+ imports) and ``tests/test_no_enhancement_coupling.py`` (the port, an AST
23
+ sweep for any unconditional reference to this package).
24
+
25
+ **Opt-in, default OFF, same as ``arrayprobe_enhancements``** --
26
+ the port (``arrayprobe_soda2``) never applies a correction by itself, and every registered
27
+ module here is opt-in by name through :mod:`arrayprobe_soda2_enhancements.registry`, **except**
28
+ the five in ``registry.PROTECTIVE`` (corrections for data-destroying upstream defects), which
29
+ run by default on every SODA-2 probe -- SODA-2 has never written an archived product
30
+ for any probe, so the protective-corrections rule's "default-off on the lineage with an archived product" carve-out
31
+ excludes nothing here. See ``registry``'s own docstring.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ __all__: list[str] = []
@@ -0,0 +1,175 @@
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
+ """The driver adapter: resolved corrections -> ``arrayprobe_soda2.enhancement_hooks`` substitutions.
4
+
5
+ Before this, ``arrayprobe soda2 run`` recorded the resolved ``[enhancements]``
6
+ table and applied nothing (``"skipped": {name: "no driver adapter"}``). This module turns a
7
+ resolved table into one replacement per hook point and installs them for the duration of a
8
+ ``with`` block around ``soda2_process_2d``; the public entry is
9
+ :func:`arrayprobe_soda2_enhancements.registry.apply`.
10
+
11
+ Every registered correction is classified here as exactly one of:
12
+
13
+ * **routed** -- its entry point is a drop-in for one port binding (same call signature, same
14
+ return type), listed in :data:`ROUTES`;
15
+ * **not driver-applicable**, with the reason, in :data:`NOT_ROUTED` -- a diagnostic that
16
+ reports rather than corrects, a correction whose defect is inline arithmetic with no function
17
+ boundary to substitute, or one whose signature needs a value the driver's call does not pass.
18
+
19
+ ``test_adapter.py`` checks the two tables partition the registry, so a new correction cannot be
20
+ registered without a decision here.
21
+
22
+ **Composition.** Two corrections that act on one binding are composed into one callable rather
23
+ than stacked (the hooks module refuses stacking): ``aspr_nan_fix`` + ``den_clamp_fix`` share
24
+ ``axis_and_ratio`` and compose through ``_aspect_ratio_recompute.recompute``'s two flags;
25
+ ``label_blobs_int_count`` + ``dilation_clamp_fix`` share ``label_blobs`` and compose as "the
26
+ dilation branch with the clamp corrected, returning ``uint32`` labels when S4-y is also on".
27
+ ``double_pi_fix`` replaces ``aspect_ratio`` and reads ``axis_and_ratio`` through the port module
28
+ at call time, so it composes with the first pair.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from collections.abc import Callable, Iterator, Mapping
34
+ from contextlib import contextmanager
35
+ from typing import Any
36
+
37
+ from arrayprobe_soda2 import enhancement_hooks
38
+
39
+ #: correction name -> hook point it is routed through.
40
+ ROUTES: dict[str, str] = {
41
+ "last_buffer_index_fix": "spec_index",
42
+ "pbp_rejectionflag_ubyte": "open_pbp_ncdf",
43
+ "hk_probeid_columns": "process_hk",
44
+ "same_time_buffer_fix": "process_spec_buffer",
45
+ "blank_roi_dof_fix": "binary_dof",
46
+ "no_stuck_diode_fix": "fixstuckbits",
47
+ "label_blobs_int_count": "label_blobs",
48
+ "dilation_clamp_fix": "label_blobs",
49
+ "fillholes_int_labels": "fillholes",
50
+ "poisson_fill_guard": "poisson_spot_correct",
51
+ "zero_area_return_fix": "soda2_findsize",
52
+ "double_pi_fix": "aspect_ratio",
53
+ "aspr_nan_fix": "axis_and_ratio",
54
+ "den_clamp_fix": "axis_and_ratio",
55
+ }
56
+
57
+ #: correction name -> why the driver adapter does not apply it.
58
+ NOT_ROUTED: dict[str, str] = {
59
+ "rollover_modulus_fix": "inline arithmetic inside process_spec_buffer "
60
+ "(processbuffer_spec.py:305); no function boundary to substitute",
61
+ "empty_roi_diodegaps_fix": "inline arithmetic inside process_buffer_tail "
62
+ "(processbuffer_tail.py:283); no function boundary to substitute",
63
+ "pbp_inttime_consistent": "its writer needs `interarrival`, which the driver's "
64
+ "write_pbp_csv_buffer call (process_2d.py:389) does not pass",
65
+ "rejection_tally_fix": "returns a separate corrected tally beside the port's own; "
66
+ "call it on the run's arrays, it substitutes no driver call",
67
+ "run_diagnostics": "a diagnostic: reports on a run and changes no output",
68
+ }
69
+
70
+
71
+ def _entry(name: str) -> Callable[..., Any]:
72
+ from arrayprobe_soda2_enhancements.registry import entry_point
73
+ return entry_point(name)
74
+
75
+
76
+ def _axis_and_ratio(nan_fix: bool, den_fix: bool) -> Callable[..., Any]:
77
+ from arrayprobe_soda2_enhancements._aspect_ratio_recompute import recompute
78
+
79
+ def axis_and_ratio(x_ind, y_ind_adjusted, circle):
80
+ r = recompute(x_ind, y_ind_adjusted, circle,
81
+ den_zero_guard=den_fix, aspr_nan_passthrough=nan_fix)
82
+ return r.aspr, r.orientation
83
+ return axis_and_ratio
84
+
85
+
86
+ def _label_blobs(int_fix: bool, dilation_fix: bool) -> Callable[..., Any]:
87
+ from arrayprobe_soda2.label_blobs import label_blobs as port_label_blobs
88
+
89
+ from arrayprobe_soda2_enhancements.dilation_clamp_fix import corrected_label_blobs_dilation
90
+
91
+ def label_blobs(img, dilatelength: int = 0, all_neighbors: bool = False,
92
+ integer: bool = False, jit: bool = False):
93
+ # `jit` is accepted here because this substitution stands in for the port's
94
+ # own label_blobs, which gained the keyword on 2026-09-18 (the SODA-2
95
+ # flood-fill kernel, 36.2x, byte-identical). A substitution that does not
96
+ # track its target's signature raises TypeError at the first particle --
97
+ # which is exactly what `corrected_fillholes` did the same day, and what
98
+ # this call site was one `keeplargest != 0` away from doing.
99
+ integer = integer or int_fix
100
+ if dilation_fix and dilatelength != 0:
101
+ # The dilation correction has no compiled path, so it takes the
102
+ # reference route and `jit` is deliberately dropped: speed only, no
103
+ # written byte moves either way.
104
+ return corrected_label_blobs_dilation(img, dilatelength,
105
+ all_neighbors=all_neighbors, integer=integer)
106
+ return port_label_blobs(img, dilatelength=dilatelength, all_neighbors=all_neighbors,
107
+ integer=integer, jit=jit)
108
+ return label_blobs
109
+
110
+
111
+ def replacements(resolved: Mapping[str, bool]) -> tuple[dict[str, Callable[..., Any]],
112
+ dict[str, str]]:
113
+ """``(hook point -> replacement, point -> the corrections composed into it)`` for every
114
+ resolved-ON correction that is routed."""
115
+ on = {n for n, v in resolved.items() if v and n in ROUTES}
116
+ by_point: dict[str, list[str]] = {}
117
+ for n in sorted(on):
118
+ by_point.setdefault(ROUTES[n], []).append(n)
119
+ repl: dict[str, Callable[..., Any]] = {}
120
+ for point, names in by_point.items():
121
+ if point == "axis_and_ratio":
122
+ repl[point] = _axis_and_ratio("aspr_nan_fix" in names, "den_clamp_fix" in names)
123
+ elif point == "label_blobs":
124
+ repl[point] = _label_blobs("label_blobs_int_count" in names,
125
+ "dilation_clamp_fix" in names)
126
+ else:
127
+ (only,) = names # every other point has exactly one correction routed to it
128
+ repl[point] = _entry(only)
129
+ return repl, {p: ", ".join(ns) for p, ns in by_point.items()}
130
+
131
+
132
+ #: Where :func:`worker_replacements` is found from a fresh interpreter. A string rather than a
133
+ #: reference, because that is the whole point: a ``spawn``-started worker imports it by name.
134
+ WORKER_FACTORY = "arrayprobe_soda2_enhancements._adapter:worker_replacements"
135
+
136
+
137
+ def worker_replacements(resolved: Mapping[str, bool]) -> dict[str, Callable[..., Any]]:
138
+ """:func:`replacements`' mapping, rebuilt in a process that has only ``resolved``.
139
+
140
+ The entire route from a resolved table to a set of substitutions is a pure function of
141
+ that table -- :func:`replacements` reads nothing else, and its two composed callables
142
+ (:func:`_axis_and_ratio`, :func:`_label_blobs`) close over booleans drawn from it and
143
+ over nothing from the caller. So the parent can ship the table, which is plain data and
144
+ pickles, and a worker rebuilds the same callables here.
145
+
146
+ ``load_all()`` first, and that is not a formality: registration is an import side effect,
147
+ so in a fresh interpreter :data:`registry.REGISTRY` is empty and every ``entry_point``
148
+ lookup below would raise ``UnknownEnhancement`` (stage 8 saw exactly this).
149
+ """
150
+ from arrayprobe_soda2_enhancements.registry import load_all
151
+ load_all()
152
+ return replacements(resolved)[0]
153
+
154
+
155
+ @contextmanager
156
+ def applied(resolved: Mapping[str, bool]) -> Iterator[dict[str, Any]]:
157
+ """Install the routed corrections for the ``with`` block; yield the sidecar record
158
+ ``{"applied": [...], "skipped": {name: reason}, "hook_points": {point: names}}``.
159
+ ``skipped`` lists only resolved-ON corrections that were not applied.
160
+
161
+ The substitution is installed **with a reconstruction plan**, so a split run
162
+ (``soda2_process_2d(..., jobs=N)``) can rebuild these same corrections inside each worker
163
+ instead of being refused. ``overridden`` calls the factory itself and checks it produces
164
+ the same hook points, so the plan cannot drift away from what is installed here.
165
+ """
166
+ repl, composed = replacements(resolved)
167
+ applied_names = sorted(n for n, v in resolved.items() if v and n in ROUTES)
168
+ skipped = {n: NOT_ROUTED.get(n, "no route recorded in arrayprobe_soda2_enhancements._adapter")
169
+ for n, v in sorted(resolved.items()) if v and n not in ROUTES}
170
+ plan = enhancement_hooks.Reconstruction(factory=WORKER_FACTORY,
171
+ payload={str(n): bool(v)
172
+ for n, v in sorted(resolved.items())})
173
+ with enhancement_hooks.overridden(repl, reconstruction=plan):
174
+ yield {"applied": applied_names, "skipped": skipped,
175
+ "hook_points": dict(sorted(composed.items()))}
@@ -0,0 +1,124 @@
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
+ """Shared re-derivation of ``aspect_ratio.axis_and_ratio`` for S2-d and S2-f.
4
+
5
+ Not registered itself (leading underscore -- ``test_registry.py`` excludes it from the
6
+ on-disk/registered comparison). Both :mod:`aspr_nan_fix` and :mod:`den_clamp_fix` correct one
7
+ clamp each inside the *same* port function
8
+ (``arrayprobe_soda2.aspect_ratio.axis_and_ratio``, ``aspect_ratio.pro:27-73,105``), so this
9
+ module reproduces that function's arithmetic once, parametrized by which clamp is corrected,
10
+ rather than duplicating it twice.
11
+
12
+ **Corner/vertex resolution (`:27-51`) is reproduced verbatim from the port**, using the port's
13
+ own primitives (``_field``, ``_op``, ``_sqrt_idl``, ``orientation_deg`` -- imported, not
14
+ copied, from ``arrayprobe_soda2.aspect_ratio``, the same reuse discipline
15
+ ``arrayprobe_enhancements.wide_hollow_fix`` uses for ``arrayprobe.reject``'s ``_pack``/
16
+ ``_popcount``) -- both S2-d and S2-f are entirely about the arithmetic that follows corner
17
+ selection, not about which corner gets picked, so nothing here can disagree with the port about
18
+ that step. With both clamps left uncorrected (the defaults), :func:`recompute` reproduces
19
+ ``axis_and_ratio`` bit for bit -- each module's own ``Equivalence`` test class checks this
20
+ directly against the real port function.
21
+
22
+ Does not touch ``arrayprobe_soda2`` -- ``aspect_ratio.py`` keeps both clamps exactly as
23
+ written (`den = sqrt(a^2+b^2) > 1` at `:66`, `return, aspr < 1.0` at `:105`), per the fidelity
24
+ doctrine.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from dataclasses import dataclass
30
+ from typing import Any
31
+
32
+ import numpy as np
33
+ from arrayprobe_soda2.aspect_ratio import _field, _op, _sqrt_idl, orientation_deg
34
+
35
+ __all__ = ["Recomputed", "recompute"]
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Recomputed:
40
+ """``axis_and_ratio``'s two return values, plus the two intermediates each correction
41
+ needs to know it actually changed something (``den`` for S2-f, ``aspr_raw`` -- the value
42
+ before the final clamp -- for S2-d)."""
43
+
44
+ aspr: np.float64
45
+ orientation: np.float32
46
+ den: Any
47
+ aspr_raw: np.float64
48
+
49
+
50
+ def recompute(x_ind, y_ind_adjusted, circle, *,
51
+ den_zero_guard: bool = False,
52
+ aspr_nan_passthrough: bool = False) -> Recomputed:
53
+ """Re-derive ``axis_and_ratio(x_ind, y_ind_adjusted, circle)`` with either or both
54
+ clamps corrected.
55
+
56
+ ``den_zero_guard=True``: S2-f's fix -- ``den`` is set to 1 only when it is exactly 0 (the
57
+ single-point-outline case the clamp was written for), instead of whenever it is merely
58
+ less than 1 (which also fires on a genuine sub-pixel-radius 3-point circle,
59
+ ``aspect_ratio.pro:66``'s ``> 1`` reading as MAX).
60
+
61
+ ``aspr_nan_passthrough=True``: S2-d's fix -- a non-finite ``aspr`` is returned as NaN
62
+ instead of being clamped to the ordinary value 1.0 (``aspect_ratio.pro:105``'s ``< 1.0``
63
+ reading as MIN, which IDL's ``<`` resolves to the *other*, finite operand on a NaN input).
64
+
65
+ Both ``False`` (the default) is exactly ``axis_and_ratio``'s own computation.
66
+ """
67
+ x_ind = np.asarray(x_ind)
68
+ y_ind = np.asarray(y_ind_adjusted)
69
+ corners = np.asarray(_field(circle, "corners")).ravel()
70
+
71
+ if corners.size == 3:
72
+ from arrayprobe_soda2.angles import find_angle
73
+
74
+ p_idx, q_idx, r_idx = (int(corners[0]), int(corners[1]), int(corners[2]))
75
+ ty_trig = np.float32 if y_ind.dtype != np.float64 else np.float64
76
+
77
+ def _trig_pt(idx: int) -> np.ndarray:
78
+ return np.array([x_ind[idx], y_ind[idx]], dtype=ty_trig)
79
+
80
+ p_pt, q_pt, r_pt = _trig_pt(p_idx), _trig_pt(q_idx), _trig_pt(r_idx)
81
+ ang_p = find_angle(p_pt, r_pt, q_pt)
82
+ ang_q = find_angle(q_pt, r_pt, p_pt)
83
+ ang_r = find_angle(r_pt, q_pt, p_pt)
84
+ vertex = int(np.argmin([ang_p, ang_q, ang_r]))
85
+ corner_idx = int(corners[vertex])
86
+ cx1, cy1 = x_ind[corner_idx], y_ind[corner_idx]
87
+ center = np.asarray(_field(circle, "center"), dtype=np.float64).ravel()
88
+ cx2, cy2 = np.float64(center[0]), np.float64(center[1])
89
+ else:
90
+ i0, i1 = int(corners[0]), int(corners[1])
91
+ cx1, cy1 = x_ind[i0], y_ind[i0]
92
+ cx2, cy2 = x_ind[i1], y_ind[i1]
93
+
94
+ orientation = orientation_deg(cx1, cy1, cx2, cy2)
95
+
96
+ with np.errstate(invalid="ignore", divide="ignore"):
97
+ a = _op(cy1, cy2, np.subtract)
98
+ b = _op(cx2, cx1, np.subtract)
99
+ c = _op(_op(cx1, cy2, np.multiply), _op(cx2, cy1, np.multiply), np.subtract)
100
+
101
+ den_raw = _sqrt_idl(_op(_op(a, a, np.multiply), _op(b, b, np.multiply), np.add))
102
+ den_dtype = den_raw.dtype
103
+ if den_zero_guard:
104
+ den = den_raw if float(den_raw) != 0.0 else den_dtype.type(1.0)
105
+ else:
106
+ den = den_raw if float(den_raw) > 1.0 else den_dtype.type(1.0)
107
+
108
+ term1 = _op(a, x_ind, np.multiply)
109
+ term2 = _op(b, y_ind, np.multiply)
110
+ numerator = _op(_op(term1, term2, np.add), c, np.add)
111
+ distmajor = _op(numerator, den, np.divide)
112
+
113
+ width = _op(_op(np.max(distmajor), np.min(distmajor), np.subtract), 1, np.add)
114
+ diam = np.float64(_field(circle, "diam"))
115
+ aspr_raw = _op(width, diam + 1.0, np.divide)
116
+
117
+ aspr64 = np.float64(aspr_raw)
118
+ if aspr_nan_passthrough and not np.isfinite(aspr64):
119
+ aspr = np.float64(np.nan)
120
+ else:
121
+ aspr = aspr64 if float(aspr64) < 1.0 else np.float64(1.0)
122
+
123
+ return Recomputed(aspr=np.float64(aspr), orientation=np.float32(orientation),
124
+ den=den, aspr_raw=aspr64)
@@ -0,0 +1,56 @@
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
+ """S2-d: a non-finite ``aspr`` stops being silently read as a perfectly round particle.
4
+
5
+ ``aspect_ratio.pro:105`` -- ``return, aspr < 1.0`` -- is IDL's MIN operator, and for a
6
+ non-finite ``aspr`` it returns the *other* (finite) operand: measured under GDL,
7
+ ``!values.d_nan < 1.0d`` is ``1.0``, not NaN (
8
+ ``tests/test_soda2_aspect_ratio.py::IdlSemanticsRecorded::
9
+ test_nan_lt_one_is_exactly_one`` pins the same IDL fact this port's
10
+ ``arrayprobe_soda2.aspect_ratio.axis_and_ratio`` faithfully reproduces). That makes
11
+ ``aspr == 1.0`` overloaded: it means indistinguishably a genuinely round particle, a
12
+ single-pixel particle, an empty outline, *or* a circle-fit that never converged and came back
13
+ non-finite.
14
+
15
+ **Correction**: a non-finite ``aspr`` stays non-finite (NaN) instead of being clamped to 1.0,
16
+ so a caller histogramming ``aspr`` can tell "round" from "the fit failed" -- exactly the
17
+ suggested edit in the finding (``IF finite(aspr) eq 0 THEN return, !values.f_nan``, applied
18
+ before the round-off clamp the line was actually written for, which this correction leaves
19
+ untouched).
20
+
21
+ ``src/arrayprobe_soda2/aspect_ratio.py`` is never imported for writing and never
22
+ modified -- ``axis_and_ratio`` keeps clamping every non-finite ``aspr`` to 1.0, per the
23
+ fidelity doctrine. Tests: ``tests/test_aspr_nan_fix.py``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import numpy as np
29
+
30
+ from arrayprobe_soda2_enhancements.registry import EnhancementSpec, register
31
+
32
+ from ._aspect_ratio_recompute import recompute
33
+
34
+ __all__ = ["corrected_aspr"]
35
+
36
+
37
+ def corrected_aspr(x_ind, y_ind_adjusted, circle) -> tuple[np.float64, np.float32]:
38
+ """``(aspr, orientation)`` with S2-d corrected: a non-finite ``aspr`` returns NaN
39
+ rather than being clamped to 1.0. S2-f's clamp (`den`, `:66`) is left exactly as the
40
+ port computes it -- this module corrects one finding only; see :mod:`den_clamp_fix` for
41
+ the other, and note the two compose (both flags can be set together via
42
+ :func:`arrayprobe_soda2_enhancements._aspect_ratio_recompute.recompute` directly, should a
43
+ caller ever want both S2-d and S2-f applied at once)."""
44
+ result = recompute(x_ind, y_ind_adjusted, circle, aspr_nan_passthrough=True)
45
+ return result.aspr, result.orientation
46
+
47
+
48
+ register(EnhancementSpec(
49
+ name="aspr_nan_fix",
50
+ summary="A non-finite aspect ratio returns NaN instead of being clamped to the "
51
+ "ordinary value 1.0 (aspect_ratio.pro:105's `<` is MIN, and IDL's `<` "
52
+ "resolves a NaN operand to the OTHER, finite side).",
53
+ finding="S2-d",
54
+ reachability="live",
55
+ entry_point="corrected_aspr",
56
+ ))
@@ -0,0 +1,49 @@
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
+ """S4-v: a blank ROI is accepted as within depth of field.
4
+
5
+ ``binary_dof.pro:21-31``: ``area = total(bitimage)`` is 0.0 for an
6
+ all-zero image, which matches none of the named ``CASE`` values (1
7
+ through 6) and falls to ``ELSE``; ``neighbor_count`` is also 0, and
8
+ ``0 ge 0`` is true in IDL, so ``dof`` is set to 1 -- a blank image is
9
+ accepted as within depth of field.
10
+
11
+ **Correction**: the register's own suggested edit -- ``IF area eq 0
12
+ THEN return, 0`` immediately after ``:21``, before the ``CASE``.
13
+
14
+ ``src/arrayprobe_soda2/binary_dof.py`` is never imported
15
+ for writing and never modified. This module calls the real,
16
+ unmodified ``binary_dof`` and overrides only the ``dof`` field when
17
+ ``area == 0``. Tests: ``tests/test_blank_roi_dof_fix.py``.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import replace
22
+ from typing import Any
23
+
24
+ import numpy as np
25
+ from arrayprobe_soda2.binary_dof import BinaryDof, binary_dof
26
+
27
+ from arrayprobe_soda2_enhancements.registry import EnhancementSpec, register
28
+
29
+ __all__ = ["corrected_binary_dof"]
30
+
31
+
32
+ def corrected_binary_dof(bitimage: Any) -> BinaryDof:
33
+ """``d = binary_dof(bitimage, neighbor_count=nc)`` with S4-v
34
+ corrected: a blank (all-zero) ``bitimage`` returns ``dof=0``, not
35
+ the ``ELSE`` branch's ``0 ge 0`` acceptance."""
36
+ result = binary_dof(bitimage)
37
+ if result.area == np.float32(0):
38
+ return replace(result, dof=0)
39
+ return result
40
+
41
+
42
+ register(EnhancementSpec(
43
+ name="blank_roi_dof_fix",
44
+ summary="binary_dof returns dof=0 for a blank (all-zero) image, "
45
+ "instead of falling to the ELSE branch's 0 ge 0 acceptance.",
46
+ finding="S4-v",
47
+ reachability="flagged",
48
+ entry_point="corrected_binary_dof",
49
+ ))
@@ -0,0 +1,55 @@
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
+ """S2-f: the `den` clamp guards a 0/0 that cannot happen, and bites a real, small circle.
4
+
5
+ ``aspect_ratio.pro:66`` -- ``den = sqrt(a^2+b^2) > 1`` -- is IDL's MAX, i.e. ``max(den, 1)``,
6
+ written to keep the perpendicular-distance formula at ``:68`` from dividing by zero for a
7
+ single-point outline (where ``a == b == 0``, so ``den`` is genuinely 0). It also fires whenever
8
+ ``sqrt(a^2+b^2)`` is merely *less than* 1 -- a real 3-point circle of radius below one pixel,
9
+ reachable once ``yres < xres`` compresses the y axis. There the clamp does not prevent a
10
+ division by zero; it inflates the divisor, and every perpendicular distance -- so ``aspr`` --
11
+ comes back too small, with no warning.
12
+
13
+ Measured on the tracked GDL golden (reproduced here against the
14
+ real port function rather than transcribed): the clamped and unclamped ``ASPR`` for the same
15
+ geometry are 0.6136363636363636 and 0.7272727272727273 -- a 16% understatement.
16
+
17
+ **Correction**: ``den`` is set to 1 only when it is exactly 0 (the case the clamp actually
18
+ guards against), never merely when it is less than 1 -- the finding's own suggested edit,
19
+ ``IF den eq 0 THEN den = 1``.
20
+
21
+ ``src/arrayprobe_soda2/aspect_ratio.py`` is never imported for writing and never
22
+ modified -- ``axis_and_ratio`` keeps the ``> 1`` clamp exactly as written, per the fidelity
23
+ doctrine. Tests: ``tests/test_den_clamp_fix.py``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import numpy as np
29
+
30
+ from arrayprobe_soda2_enhancements.registry import EnhancementSpec, register
31
+
32
+ from ._aspect_ratio_recompute import recompute
33
+
34
+ __all__ = ["corrected_aspr"]
35
+
36
+
37
+ def corrected_aspr(x_ind, y_ind_adjusted, circle) -> tuple[np.float64, np.float32]:
38
+ """``(aspr, orientation)`` with S2-f corrected: ``den`` is clamped to 1 only when it is
39
+ exactly 0, not whenever it is merely below 1. S2-d's clamp (the final ``aspr < 1.0``,
40
+ ``:105``) is left exactly as the port computes it -- see :mod:`aspr_nan_fix` for that
41
+ finding; the two compose via
42
+ :func:`arrayprobe_soda2_enhancements._aspect_ratio_recompute.recompute` directly."""
43
+ result = recompute(x_ind, y_ind_adjusted, circle, den_zero_guard=True)
44
+ return result.aspr, result.orientation
45
+
46
+
47
+ register(EnhancementSpec(
48
+ name="den_clamp_fix",
49
+ summary="`den` is clamped to 1 only when it is exactly 0 (a single-point outline), "
50
+ "not whenever sqrt(a^2+b^2) < 1 (a real, small 3-point circle, reachable "
51
+ "when yres < xres) -- aspect_ratio.pro:66's `>` is MAX.",
52
+ finding="S2-f",
53
+ reachability="live",
54
+ entry_point="corrected_aspr",
55
+ ))
@@ -0,0 +1,89 @@
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
+ """S4-z: the dilation kernel clamps against the roi's own slice count, not the padded
4
+ array it dilates.
5
+
6
+ ``label_blobs.pro:20`` -- ``kerneldim = (dilatelength*2+1) < (s[1]+2)`` -- reads as though it
7
+ protects against exceeding ``temp``'s own size (``s[1] + 2*pad``), but clamps against
8
+ ``s[1]+2`` instead, independent of ``pad``. For the production call
9
+ (``dilatelength=2``, ``soda2_processbuffer.pro:687-689``), a roi with 1 or 2 slices gets a
10
+ 3-wide kernel instead of the intended 5-wide one, changing which fragments
11
+ ``keeplargest`` merges.
12
+
13
+ **Correction**: re-derive ``label_blobs``'s dilation branch with the clamp corrected to
14
+ ``s1 + 2*pad`` (equivalently, since ``pad = max(1, dilatelength)``, the clamp never actually
15
+ binds for any real call site -- as the finding's own suggested edit notes, the padded array is
16
+ never exceeded, so dropping the clamp is equivalent to fixing it). Duplicates
17
+ ``label_blobs``'s orchestration (`:12-29`, ~20 lines) because the bug is inside the clamp
18
+ expression itself, not something a keyword can select -- but reuses the port's own
19
+ ``_label_region``/``_dilate_square`` primitives (the labelling flood-fill and the square
20
+ dilation, both already standalone functions in ``label_blobs.py``) rather than reimplementing
21
+ either, so only the kernel-size formula can differ from the port.
22
+
23
+ ``src/arrayprobe_soda2/label_blobs.py`` is never imported for writing and never
24
+ modified -- ``:20`` keeps the ``s[1]+2`` clamp exactly as written, per the fidelity doctrine.
25
+ Tests: ``tests/test_dilation_clamp_fix.py``.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import numpy as np
31
+ from arrayprobe_soda2.label_blobs import _dilate_square, _label_region
32
+
33
+ from arrayprobe_soda2_enhancements.registry import EnhancementSpec, register
34
+
35
+ __all__ = ["corrected_label_blobs_dilation"]
36
+
37
+
38
+ def corrected_label_blobs_dilation(img, dilatelength: int,
39
+ all_neighbors: bool = False,
40
+ integer: bool = False) -> np.ndarray:
41
+ """``label_blobs``'s dilation branch (`dilatelength != 0`) with S4-z's kernel clamp
42
+ corrected to the padded array's own dimension. Only meaningful for
43
+ ``dilatelength != 0`` -- the non-dilating branch never reaches the clamp at all, so
44
+ :mod:`label_blobs_int_count` (S4-y) or the port's own ``label_blobs`` covers that case
45
+ identically.
46
+ """
47
+ if dilatelength == 0:
48
+ raise ValueError(
49
+ "S4-z's clamp is inside the dilatelength != 0 branch; the port's own "
50
+ "label_blobs(img, dilatelength=0, ...) already reproduces the non-dilating "
51
+ "path exactly and needs no correction.")
52
+
53
+ img = np.asarray(img)
54
+ one_d = img.ndim == 1
55
+ img2d = img.reshape(1, -1) if one_d else img
56
+
57
+ img2 = np.minimum(1, img2d).astype(np.uint8)
58
+ s0, s1 = img2.shape[0], img2.shape[1]
59
+
60
+ pad = max(1, dilatelength)
61
+ temp = np.zeros((s0 + 2 * pad, s1 + 2 * pad), dtype=np.uint8)
62
+ temp[pad:pad + s0, pad:pad + s1] = img2
63
+ temp_yx = temp.T
64
+
65
+ # S4-z: clamp against the padded array's own dimension (s1 + 2*pad), not s1 + 2.
66
+ kerneldim = min(dilatelength * 2 + 1, s1 + 2 * pad)
67
+ dilated_yx = _dilate_square(temp_yx, kerneldim)
68
+ region_labels_yx = _label_region(dilated_yx, all_neighbors)
69
+ labels_yx = temp_yx.astype(np.uint32) * region_labels_yx
70
+
71
+ labels = labels_yx.T
72
+ cropped = labels[pad:pad + s0, pad:pad + s1]
73
+ if one_d:
74
+ cropped = cropped.reshape(-1)
75
+
76
+ if integer:
77
+ return cropped.astype(np.uint32)
78
+ return (cropped % 256).astype(np.uint8)
79
+
80
+
81
+ register(EnhancementSpec(
82
+ name="dilation_clamp_fix",
83
+ summary="label_blobs's dilation kernel clamps against the padded array's own "
84
+ "dimension (s1 + 2*pad), not s1 + 2 -- a 1- or 2-slice roi with "
85
+ "dilatelength=2 gets the intended 5-wide kernel instead of 3-wide.",
86
+ finding="S4-z",
87
+ reachability="live",
88
+ entry_point="corrected_label_blobs_dilation",
89
+ ))