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,113 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """The one place that names a stage-2 decode: engine and reader decide the extension together.
3
+
4
+ v3.5's own SPEC decoder (probetype 2: 2D-S, HVPS, 3VCPI; channels ``H`` and ``V``) writes
5
+ ``<flight>.<channel>.nc`` (``arrayprobe_uiops/spec.py:655``, ``:896``). Every other decode writes
6
+ ``.cdf``: v3.1.4's readers, and the SEA / PMS / DMT readers both engines share
7
+ (``readers/sea.py:259``, ``:280``; ``readers/pms.py:191-193``), so a v3.5 CIP decode is
8
+ ``<flight>.CIP.cdf``.
9
+
10
+ Five instance fixes (2026-09-14 to 2026-09-30) each re-derived part of this rule in one
11
+ place; two of them keyed it on the engine alone and missed the channel term (``bed81c7``). This
12
+ module is the single source, and ``tests/test_decode_suffix_single_source.py`` refuses a new
13
+ hard-coded decode spelling anywhere under ``src`` or ``tools``.
14
+
15
+ The engine comes from the product's own ``.call`` stamp, never from which file exists: a stale
16
+ v3.1.4 decode beside a v3.5 proc must not be drawn under it (``46368b2``). It lives in the v3.5
17
+ engine because code both engines share lives there.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from pathlib import Path
24
+
25
+ from arrayprobe_uiops import provenance
26
+
27
+ #: Every extension a stage-2 decode can carry.
28
+ DECODE_SUFFIXES = (".nc", ".cdf")
29
+
30
+ #: Channels v3.5's own SPEC decoder writes (probetype 2); ``arrayprobe_uiops/spec.py:655``,
31
+ #: ``:896``.
32
+ V35_OWN_DECODER_CHANNELS = frozenset({"H", "V"})
33
+
34
+ #: ``proc.<flight>.<channel>[.diodecorrected].nc`` -> flight stem and channel token.
35
+ _PROC_RE = re.compile(r"^proc\.(?P<flight>.+?)\.(?P<channel>[^.]+)(?:\.diodecorrected)?\.nc$")
36
+
37
+
38
+ def decode_suffix(engine: str | None, channel: str) -> str:
39
+ """``".nc"`` iff ``engine == "3.5"`` and ``channel`` is ``H`` or ``V``; ``".cdf"`` otherwise.
40
+
41
+ ``.cdf`` covers v3.1.4 on every probe and the SEA / PMS / DMT readers both engines share
42
+ (CIP, PIP, 2DC, 2dc, f2dc, 2dp), which write ``.cdf`` whichever engine ran them.
43
+ """
44
+ return ".nc" if engine == "3.5" and channel in V35_OWN_DECODER_CHANNELS else ".cdf"
45
+
46
+
47
+ def decode_name(stem: str, channel: str, engine: str) -> str:
48
+ """``<stem>.<channel><suffix>``, for a caller that knows the engine before any stamp exists."""
49
+ return f"{stem}.{channel}{decode_suffix(engine, channel)}"
50
+
51
+
52
+ def combined_suffix(engine: str) -> str:
53
+ """``"_2"`` iff ``engine == "3.1.4"`` (``combine_sizedist.m:199``'s own naming, kept so a
54
+ port-validation product matches the archived ORACLES product by name); ``""`` for every
55
+ other engine."""
56
+ return "_2" if engine == "3.1.4" else ""
57
+
58
+
59
+ def combined_name(stem: str, orientation: str, probe: str, engine: str) -> str:
60
+ """``<stem>.combined.<orientation>.<probe><suffix>.cdf``.
61
+
62
+ The suffix is :func:`combined_suffix`'s."""
63
+ return f"{stem}.combined.{orientation}.{probe}{combined_suffix(engine)}.cdf"
64
+
65
+
66
+ def existing_combined_path(directory: Path | str, stem: str, orientation: str = "H",
67
+ probe: str = "2DS", *, legacy_if_missing: bool = False) -> Path:
68
+ """A v3.5 / SODA-2 combined product in ``directory``: the current (no ``_2``) name if that
69
+ file exists, else the pre-2026-10-15 ``_2`` name if that one does. When neither exists it
70
+ returns the current name, or the ``_2`` name with ``legacy_if_missing`` (for a caller naming
71
+ an archived product written before the rename). The ``_2`` name is read only to reach
72
+ products written before the rename."""
73
+ directory = Path(directory)
74
+ names = [directory / combined_name(stem, orientation, probe, e) for e in ("3.5", "3.1.4")]
75
+ return next((p for p in names if p.is_file()), names[1] if legacy_if_missing else names[0])
76
+
77
+
78
+ def strip_combined_suffix(name: str, orientation: str = "H", probe: str = "2DS") -> str:
79
+ """The flight stem of a combined product's file name, under either naming."""
80
+ for engine in ("3.5", "3.1.4"):
81
+ tail = combined_name("", orientation, probe, engine)
82
+ if name.endswith(tail):
83
+ return name.removesuffix(tail)
84
+ return name
85
+
86
+
87
+ def engine_from_stamp(product: Path | str, *, assume_engine: str | None = None) -> str:
88
+ """The engine recorded in ``product``'s ``.call`` stamp.
89
+
90
+ A stamp with no ``engine=`` key is a pre-2026-09-15 v3.1.4 stamp and reads as ``"3.1.4"``
91
+ (``run_flight._stamps_equivalent``). No stamp returns ``assume_engine`` when the caller passed
92
+ one, and otherwise raises :class:`arrayprobe.provenance.Unstamped`: nothing here defaults
93
+ silently.
94
+ """
95
+ stamp = provenance.read(product)
96
+ if stamp is None:
97
+ if assume_engine is None:
98
+ raise provenance.Unstamped(product)
99
+ return assume_engine
100
+ return stamp.engine if stamp.engine is not None else "3.1.4"
101
+
102
+
103
+ def decode_path(proc_path: Path | str, *, assume_engine: str | None = None) -> Path:
104
+ """The decode beside ``proc.<flight>.<channel>[.diodecorrected].nc``, named from its stamp.
105
+
106
+ The engine is :func:`engine_from_stamp`'s, never chosen by which file exists.
107
+ """
108
+ proc_path = Path(proc_path)
109
+ m = _PROC_RE.match(proc_path.name)
110
+ if m is None:
111
+ raise ValueError(f"{proc_path.name} is not a proc.<flight>.<channel>.nc file")
112
+ engine = engine_from_stamp(proc_path, assume_engine=assume_engine)
113
+ return proc_path.with_name(decode_name(m.group("flight"), m.group("channel"), engine))
@@ -0,0 +1,250 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Stuck-diode masking shared by both engines: the fork's rule and its re-illumination.
3
+
4
+ The ORACLES production chain found stuck diodes with ``find_shadow_diodes.m`` (a
5
+ dissertation Appendix-B extraction) and re-illuminated them in the nine-argument
6
+ ``imgProc_sm`` (extraction ``:286-292``)::
7
+
8
+ c(:,shadow_diode)='1';
9
+
10
+ This module holds the parts both engines use: the stuck-diode rule
11
+ (:func:`stuck_diodes`, ``find_shadow_diodes.m:66-97``), the mask record
12
+ (:class:`ShadowDiodeMask`) and the re-illumination (:func:`reilluminate`).
13
+ The earlier translation's ``arrayprobe.masks`` imports them and keeps the file-level
14
+ wrapper (``bin_stats`` reading, ``.mat`` I/O, the nine-argument lookup).
15
+
16
+ It imports only the standard library and NumPy, because ``import arrayprobe``
17
+ loads it (``tests/test_lazy_numba_and_v35_import.py``'s ``V35_SHARED``) and the
18
+ v3.5 engine must not import the v3.1.4 package (``tests/test_no_dependence_on_v314.py``).
19
+ The two MATLAB integer semantics the rule needs -- ``int32`` of a double and
20
+ ``find`` -- are therefore written here for the non-negative operands the rule
21
+ produces, and the rule is asserted against the fork's file run under Octave
22
+ (``tests/test_find_shadow_diodes.py``, golden
23
+ ``tests/data/find_shadow_diodes_octave_golden.json``).
24
+
25
+ Line numbers are those of the promoted ``find_shadow_diodes.m`` (raw extraction
26
+ ``archive/staging_variant_raw/find_shadow_diodes.m.raw.txt`` = promoted + 1).
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from collections.abc import Callable, Sequence
32
+ from dataclasses import dataclass
33
+ from pathlib import Path
34
+ from typing import NamedTuple
35
+
36
+ import numpy as np
37
+ import numpy.typing as npt
38
+
39
+ __all__ = [
40
+ "STUCK_FRACTION",
41
+ "HIGH_FRACTION",
42
+ "ShadowDiodeMask",
43
+ "StuckDiodeRule",
44
+ "stuck_diodes",
45
+ "reilluminate",
46
+ ]
47
+
48
+ #: ``:94`` and ``:97`` -- a diode is stuck below this fraction of the mean or max.
49
+ #: (The recovered ORACLES masks also exist at 75%, ``S3o`` §3; the code says 0.80.)
50
+ STUCK_FRACTION = 0.80
51
+
52
+ #: ``:66`` -- a diode above this fraction of the mean was masked in flight.
53
+ HIGH_FRACTION = 1.2
54
+
55
+ #: ``'1'`` marks a lit diode in the char image (``imgProc_sm.m:266`` inverts
56
+ #: through ``65535 - data``); the same character as ``arrayprobe.particle.LIT``.
57
+ _LIT_ORD = ord("1")
58
+
59
+ #: What MATLAB pads a widened char array with (``char(0)``), measured in Octave:
60
+ #: ``c=['0101';'1010']; c(:,[2 6])='1'`` gives column 5 the value 0.
61
+ _CHAR_PAD = 0
62
+
63
+ _INT32 = np.iinfo(np.int32)
64
+
65
+
66
+ def _int32(x: npt.ArrayLike) -> np.ndarray:
67
+ """MATLAB ``int32(x)`` for a double: half away from zero, NaN to 0, saturating.
68
+
69
+ ``x - floor(x)`` is exact for every finite double, so the half is tested
70
+ without a rounding of its own (the defect ``floor(x + 0.5)`` carries).
71
+ """
72
+ a = np.asarray(x, dtype=np.float64)
73
+ m = np.abs(a)
74
+ f = np.floor(m)
75
+ with np.errstate(invalid="ignore"):
76
+ r = np.sign(a) * (f + (m - f >= 0.5))
77
+ r = np.where(np.isnan(r), 0.0, r)
78
+ return np.clip(r, _INT32.min, _INT32.max).astype(np.int32)
79
+
80
+
81
+ def _find(condition: np.ndarray) -> np.ndarray:
82
+ """MATLAB ``find`` on a vector: 1-based indices, float64 (the class MATLAB stores)."""
83
+ return (np.flatnonzero(np.asarray(condition).reshape(-1)) + 1).astype(np.float64)
84
+
85
+
86
+ def _mean(x: np.ndarray) -> float:
87
+ """MATLAB ``mean`` of an integer array: double, ``sum(double(x))/n``, summed in
88
+ order as MATLAB does (``np.cumsum``; NumPy's ``sum`` is pairwise)."""
89
+ if not x.size:
90
+ return float("nan")
91
+ return float(np.cumsum(x.astype(np.float64))[-1]) / x.size
92
+
93
+
94
+ def _replace_high_counts(a: np.ndarray, idx: np.ndarray,
95
+ mean: Callable[[np.ndarray], float]) -> np.ndarray:
96
+ """``:68-69``: ``a(ill_diode)=NaN; a(ill_diode)=nanmean(a);`` on int32 ``a``.
97
+
98
+ int32(NaN) is 0, so the first line stores zeros and ``nanmean`` then has no
99
+ NaN to skip: the replacement is the mean *including* those zeros.
100
+ """
101
+ a = a.copy()
102
+ a[idx] = _int32(np.nan) # :68 -- stores 0
103
+ a[idx] = _int32(mean(a)) # :69 -- nanmean == mean here
104
+ return a
105
+
106
+
107
+ class StuckDiodeRule(NamedTuple):
108
+ """What ``find_shadow_diodes.m:66-97`` computes from one ``bin_stats`` vector."""
109
+
110
+ shadow_diode: np.ndarray
111
+ """1-based stuck diodes, float64, sorted (``sort(find(...))``, ``:94-98``)."""
112
+
113
+ a: np.ndarray
114
+ """The counts as saved: int32, after ``:66-69``'s high-count replacement."""
115
+
116
+ ill_diode: np.ndarray
117
+ """1-based diodes over ``1.2*mean(a)`` (``:66``), float64; usually empty."""
118
+
119
+ branch: str
120
+ """``"mean"`` when ``ill_diode`` was non-empty (``:94``), else ``"max"`` (``:97``)."""
121
+
122
+ threshold: float
123
+ """``0.80*mean(a)`` (double) or ``0.80*max(a)`` (int32, as a float)."""
124
+
125
+
126
+ def stuck_diodes(bin_stats: npt.ArrayLike) -> StuckDiodeRule:
127
+ """The fork's stuck-diode rule on **lit** counts, ``find_shadow_diodes.m:66-97``.
128
+
129
+ * ``:66`` -- diodes above ``1.2 x mean`` (masked in flight: lit on every
130
+ slice) are replaced by ``nanmean(a)`` (``:68-69``), and a diode is stuck
131
+ below ``0.80 x mean`` of the replaced array (``:94``);
132
+ * otherwise a diode is stuck below ``0.80 x max`` (``:97``), int32.
133
+
134
+ ``a(ill_diode)=NaN`` stores 0 on int32 ``a``, so ``nanmean`` averages those
135
+ zeros in: the replacement is diluted by ``len(ill_diode)/n``. Reproduced.
136
+
137
+ ``bin_stats`` must count lit slices (the production fork's ``imgProc_sm.m:387-388``);
138
+ a shadow count turns the rule upside down. A non-positive mean raises
139
+ ``ValueError``: ``:55``'s ``ylim([0 1.5*nanmean(a)])`` stops MATLAB first.
140
+ """
141
+ a = np.asarray(bin_stats).astype(np.int32).reshape(-1)
142
+ if not 1.5 * _mean(a) > 0:
143
+ raise ValueError(
144
+ "find_shadow_diodes.m:55 ylim([0 1.5*nanmean(a)]) is not increasing: "
145
+ f"bin_stats is all zero or empty (n={a.size}); MATLAB saves nothing")
146
+
147
+ ill = _find(a.astype(np.float64) > HIGH_FRACTION * _mean(a)) # :66
148
+ if ill.size:
149
+ a = _replace_high_counts(a, ill.astype(np.int64) - 1, _mean)
150
+ threshold = STUCK_FRACTION * _mean(a) # :94
151
+ diode = _find(a.astype(np.float64) < threshold)
152
+ branch = "mean"
153
+ else:
154
+ threshold_i = _int32(STUCK_FRACTION * float(a.max())) # :97, int32
155
+ threshold = float(threshold_i)
156
+ diode = _find(a < threshold_i)
157
+ branch = "max"
158
+ return StuckDiodeRule(shadow_diode=np.sort(diode), a=a, ill_diode=ill,
159
+ branch=branch, threshold=threshold)
160
+
161
+
162
+ @dataclass(frozen=True)
163
+ class ShadowDiodeMask:
164
+ """The ``shadow_diode`` list from one ``diode.<date><time>[.<or>].mat``."""
165
+
166
+ diodes: np.ndarray
167
+ """1-based diode numbers, in file order, as float64 -- the class MATLAB
168
+ stores them in. Kept unrounded so that a non-integer entry is caught at use
169
+ rather than silently floored here."""
170
+
171
+ date: str | None
172
+ """The ``date`` variable, ``'YYMMDD'``. ``None`` if the file lacks it."""
173
+
174
+ time: str | None
175
+ """The ``time`` variable, ``'HHMMSS'``."""
176
+
177
+ source: Path | None
178
+ """Where it was read from, for provenance in error messages."""
179
+
180
+ header: str = ""
181
+ """The MAT-file's own creation stamp. For the ORACLES masks this is what
182
+ distinguishes 2017 Linux output of record from a later regeneration."""
183
+
184
+ def __len__(self) -> int:
185
+ return int(self.diodes.size)
186
+
187
+ def __bool__(self) -> bool:
188
+ # Deliberately mirrors MATLAB's `isempty(shadow_diode)==0` test rather
189
+ # than "a mask object exists": an empty mask is a real, common outcome
190
+ # and must behave as no masking at all.
191
+ return bool(self.diodes.size)
192
+
193
+ def matches(self, date: str, time: str) -> bool:
194
+ """Whether the file's own stamp agrees with the flight it is being used for.
195
+
196
+ MATLAB never checks this -- it locates the file by name and trusts it.
197
+ The check is available so a caller can refuse a mask from the wrong
198
+ file, which is worth having given the ORACLES masks were kept in
199
+ threshold-named directories with several vintages side by side.
200
+ """
201
+ return self.date == date and self.time == time
202
+
203
+
204
+ def reilluminate(c: np.ndarray, diodes: Sequence[int] | np.ndarray | ShadowDiodeMask, *,
205
+ index_error: type[Exception] = IndexError
206
+ ) -> np.ndarray:
207
+ """``c(:,shadow_diode)='1'`` -- set whole diode columns to lit.
208
+
209
+ ``c`` is the ``(nslices, ndiodes)`` uint8 ASCII image. ``diodes`` is a
210
+ sequence of 1-based diode numbers, or a :class:`ShadowDiodeMask`.
211
+
212
+ Two MATLAB behaviours are reproduced rather than tidied:
213
+
214
+ * **An empty list is a no-op.** ``c(:,[])='1'`` changes nothing, which is
215
+ what makes the empty-mask case identical to no mask at all.
216
+ * **An index past the last diode WIDENS the image.** MATLAB grows the array
217
+ and pads the new columns with ``char(0)``; measured in Octave,
218
+ ``c=['0101';'1010']; c(:,[2 6])='1'`` returns a 2x6 char array whose fifth
219
+ column is 0. It does *not* error. ``imgProc_sm.m:272-276`` then finds
220
+ ``size(c,2) ~= diodenum``, prints ``Not equal to doide number`` and
221
+ ``return``\\ s from the whole function -- so a mask with one bad diode
222
+ number ends the run part-way through, leaving a short proc file and no
223
+ error status. Reproducing the widening is what lets that guard fire here
224
+ too, instead of being pre-empted by an IndexError of our own invention.
225
+
226
+ A zero, negative or fractional entry raises ``index_error`` (the earlier
227
+ translation passes its ``MatlabIndexError``), as MATLAB does: *"subscripts must
228
+ be either integers 1 to (2^63)-1 or logicals"*.
229
+ """
230
+ if isinstance(diodes, ShadowDiodeMask):
231
+ diodes = diodes.diodes
232
+ idx = np.asarray(diodes, dtype=np.float64).ravel(order="F")
233
+ if idx.size == 0:
234
+ return c
235
+
236
+ bad = idx[(idx < 1) | (idx != np.floor(idx))]
237
+ if bad.size:
238
+ raise index_error(
239
+ f"c(_,{bad[0]:g}): subscripts must be either integers 1 to (2^63)-1 "
240
+ "or logicals -- shadow_diode carries a non-positive or fractional "
241
+ "diode number, which stops MATLAB at imgProc_sm.m:290"
242
+ )
243
+
244
+ idx = idx.astype(np.int64)
245
+ need = int(idx.max())
246
+ if need > c.shape[1]:
247
+ pad = np.full((c.shape[0], need - c.shape[1]), _CHAR_PAD, dtype=c.dtype)
248
+ c = np.hstack([c, pad])
249
+ c[:, idx - 1] = _LIT_ORD
250
+ return c
@@ -0,0 +1,41 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Whether the earlier translation is installed, and the error raised when it is asked for and
3
+ this distribution lacks it.
4
+
5
+ Here, in the v3.5 engine, because both the earlier translation's lazy loader and the ``uiops``
6
+ selector use them, and code both share lives in the v3.5 engine (neither the selector nor the
7
+ engines import the earlier translation).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib.util
13
+ import os
14
+
15
+ #: The module whose presence stands for the earlier translation's engine.
16
+ _PROBE = "arrayprobe.reject"
17
+
18
+
19
+ def engine_present() -> bool:
20
+ """True when the earlier translation's engine modules are importable here.
21
+
22
+ ``ARRAYPROBE_FORCE_V314_ABSENT=1`` makes this return False even where the modules are
23
+ installed. It is a test hook, so a subprocess can see the surface a distribution without
24
+ the engine shows; users never set it.
25
+ """
26
+ if os.environ.get("ARRAYPROBE_FORCE_V314_ABSENT") == "1":
27
+ return False
28
+ try:
29
+ return importlib.util.find_spec(_PROBE) is not None
30
+ except (ImportError, ValueError):
31
+ return False
32
+
33
+
34
+ ABSENT_MESSAGE = (
35
+ "This package processes data with UIOOPS v3.5 (--engine 3.5; in Python, "
36
+ "arrayprobe.engine(\"3.5\")). The engine named here is not part of this package."
37
+ )
38
+
39
+
40
+ class V314EngineAbsent(ImportError):
41
+ """Raised when the earlier translation's module is asked for and this distribution lacks it."""