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
arrayprobe/masks.py ADDED
@@ -0,0 +1,349 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Stuck-diode masks: an archived production chain's diode re-illumination.
3
+
4
+ The ORACLES products were not made by either MATLAB tree this port had on disk
5
+ when S3 was written. They were made by a **nine-argument** ``imgProc_sm`` that
6
+ exists here only as a dissertation Appendix-B extraction, and the whole
7
+ substantive difference between it and the six-argument variant tree file is one
8
+ guarded block (extraction ``:286-292``)::
9
+
10
+ if exist([path '/' 'diode.' flight file '.' infile(end-4) '.mat'],'file')==2;
11
+ load([path '/' 'diode.' flight file '.' infile(end-4) '.mat'],'shadow_diode');
12
+ c(:,shadow_diode)='1';
13
+ else
14
+ end
15
+
16
+ ``c`` is the particle's char image with ``'1'`` marking a **lit** diode
17
+ (``imgProc_sm.m:266`` inverts through ``65535 - data``), so the assignment
18
+ declares the listed photodiodes illuminated no matter what the probe recorded.
19
+ It runs *before* habit classification, rejection, sizing and the smallest
20
+ enclosing circle, so it reaches every one of the 41 written variables -- the
21
+ widest blast radius of any divergence found in this port.
22
+
23
+ The masks come from ``find_shadow_diodes.m``, ported here as
24
+ :func:`find_shadow_diodes`, which reads ``bin_stats`` back out of a first-pass
25
+ proc file, calls a diode "stuck" when it is lit for less than 80% of the array
26
+ **max** -- or of the **mean**, when some diode reads above 1.2 x mean (the
27
+ inconsistent shadow-diode selection rule) -- and saves the list. Processing is therefore a
28
+ two-pass affair: process, find the stuck diodes, process again with them re-illuminated
29
+ (``examples/5_data_quality/01_find_stuck_diodes.ipynb``).
30
+
31
+ Three behaviours of the MATLAB are reproduced here deliberately, because each
32
+ can decide whether a product is reproducible:
33
+
34
+ 1. **A missing or differently-named file is silent.** ``exist(...)==2`` simply
35
+ fails and the run proceeds unmasked, with nothing in the output recording
36
+ that masking did not happen -- and the ORACLES variant writes no netCDF
37
+ attributes at all, so the product cannot be interrogated afterwards either.
38
+ 2. **An empty result is given a name the loader cannot find.**
39
+ ``find_shadow_diodes.m:103-107`` writes ``diode.<date><time>.<or>.mat`` when
40
+ the mask is non-empty and ``diode.<date><time>.<or>empty.mat`` when it is
41
+ empty. ``empty`` is glued straight onto the orientation letter, so the file
42
+ the loader looks for does not exist, and the branch is skipped. Equivalent
43
+ in effect to an empty mask, and much harder to notice.
44
+ 3. **An out-of-range diode number widens the image instead of erroring.** See
45
+ :func:`reilluminate`.
46
+
47
+ For the 09/06/2016 2D-S flight the recovered masks are empty, so this block is
48
+ inert for that product.
49
+ It is *not* inert in general: the 09/06 HVPS mask names
50
+ diodes 2 and 128, and later flights name others.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ from dataclasses import dataclass
56
+ from pathlib import Path
57
+
58
+ import numpy as np
59
+
60
+ from arrayprobe_uiops.diode_mask import (
61
+ HIGH_FRACTION,
62
+ STUCK_FRACTION,
63
+ ShadowDiodeMask,
64
+ stuck_diodes,
65
+ )
66
+ from arrayprobe_uiops.diode_mask import reilluminate as _reilluminate
67
+
68
+ from .matio import loadmat
69
+ from .matlab_compat import MatlabIndexError
70
+
71
+ __all__ = [
72
+ "STUCK_FRACTION",
73
+ "HIGH_FRACTION",
74
+ "ShadowDiodeMask",
75
+ "MaskFileError",
76
+ "load_shadow_diode_mask",
77
+ "matlab_mask_filename",
78
+ "orientation_from_infile",
79
+ "find_shadow_diode_mask",
80
+ "reilluminate",
81
+ "ShadowDiodeSearch",
82
+ "ShadowDiodeSearchError",
83
+ "find_shadow_diodes",
84
+ ]
85
+
86
+ class MaskFileError(ValueError):
87
+ """A ``diode.*.mat`` file that cannot be used as a shadow-diode mask."""
88
+
89
+
90
+ def load_shadow_diode_mask(path) -> ShadowDiodeMask:
91
+ """Read a ``diode.*.mat`` written by ``find_shadow_diodes.m:104``."""
92
+ path = Path(path)
93
+ mat = loadmat(path)
94
+ if "shadow_diode" not in mat:
95
+ raise MaskFileError(
96
+ f"{path} has no 'shadow_diode' variable (found: "
97
+ f"{', '.join(sorted(mat.keys())) or 'nothing'}). "
98
+ "imgProc_sm.m loads that name specifically."
99
+ )
100
+ raw = mat["shadow_diode"]
101
+ if isinstance(raw, str):
102
+ raise MaskFileError(f"{path}: 'shadow_diode' is char data, expected numeric")
103
+ diodes = np.asarray(raw, dtype=np.float64).ravel(order="F")
104
+
105
+ def _text(name):
106
+ v = mat.variables.get(name)
107
+ return v if isinstance(v, str) else None
108
+
109
+ return ShadowDiodeMask(
110
+ diodes=diodes,
111
+ date=_text("date"),
112
+ time=_text("time"),
113
+ source=path,
114
+ header=mat.header,
115
+ )
116
+
117
+
118
+ def orientation_from_infile(infile) -> str:
119
+ """``infile(end-4)`` -- the orientation letter in ``...<H|V>.cdf``.
120
+
121
+ MATLAB indexes the *fifth character from the end*, which for
122
+ ``base160906064403.V.cdf`` is ``'V'``. It is a positional index, not a
123
+ parse: on any name whose last five characters are not ``X.cdf`` it returns
124
+ whatever sits there, and the lookup then quietly finds no file.
125
+ """
126
+ name = Path(infile).name if not isinstance(infile, str) else infile
127
+ name = Path(name).name
128
+ if len(name) < 5:
129
+ raise MaskFileError(
130
+ f"{name!r} is shorter than five characters, so MATLAB's "
131
+ "infile(end-4) would be an index error"
132
+ )
133
+ return name[-5]
134
+
135
+
136
+ def matlab_mask_filename(flight: str, file: str, orientation: str) -> str:
137
+ """``['diode.' flight file '.' orientation '.mat']`` -- imgProc_sm ``:288``."""
138
+ return f"diode.{flight}{file}.{orientation}.mat"
139
+
140
+
141
+ def find_shadow_diode_mask(path, flight: str, file: str, infile) -> ShadowDiodeMask | None:
142
+ """Reproduce ``if exist([...],'file')==2`` -- returning ``None`` when absent.
143
+
144
+ ``None`` is the honest result: MATLAB's ``else`` branch is empty, so a
145
+ missing file means the image is used exactly as decoded and **nothing is
146
+ recorded anywhere** to say masking was skipped. Callers that care must
147
+ check for themselves; the archived products cannot be interrogated after the
148
+ fact, because the variant writes no attributes.
149
+ """
150
+ orientation = orientation_from_infile(infile)
151
+ candidate = Path(path) / matlab_mask_filename(flight, file, orientation)
152
+ if not candidate.is_file():
153
+ return None
154
+ return load_shadow_diode_mask(candidate)
155
+
156
+
157
+ #: Where the source of :func:`find_shadow_diodes` lives: a dissertation
158
+ #: Appendix-B extraction, promoted to a runnable ``.m`` by
159
+ #: ``octave_oracle/recover_dissertation_sources.py`` (PDF artifacts only).
160
+ FIND_SHADOW_DIODES_SOURCE = "archive/staging_variant_raw/find_shadow_diodes.m.raw.txt"
161
+
162
+ #: ``find_shadow_diodes.m:30-31`` -- the directory is hard-coded, not an input.
163
+ MATLAB_FIND_SHADOW_DIODES_PATH = "/condo/mcfarq/sid/b/{campaign}/{campaign}_20{date}/"
164
+
165
+
166
+ #: ``STUCK_FRACTION`` (0.80, ``:94``/``:97``) and ``HIGH_FRACTION`` (1.2, ``:66``) live in
167
+ #: :mod:`arrayprobe_uiops.diode_mask` with the rule; imported above.
168
+
169
+
170
+ def _saved_mask_filename(date: str, time: str, orientation: str, empty: bool) -> str:
171
+ """``:103-107``: ``diode.<date><time>.<or>.mat``, or ``...<or>empty.mat``.
172
+
173
+ Upstream quirk: ``empty`` is glued onto the orientation
174
+ letter, so :func:`find_shadow_diode_mask` -- ``imgProc_sm.m:288`` -- never
175
+ finds an empty mask. Preserved.
176
+ """
177
+ return f"diode.{date}{time}.{orientation}{'empty' if empty else ''}.mat"
178
+
179
+
180
+ class ShadowDiodeSearchError(RuntimeError):
181
+ """A ``bin_stats`` input on which ``find_shadow_diodes.m`` dies before saving."""
182
+
183
+
184
+ @dataclass(frozen=True)
185
+ class ShadowDiodeSearch:
186
+ """What one ``find_shadow_diodes(date,time,orientation)`` call computed."""
187
+
188
+ shadow_diode: np.ndarray
189
+ """1-based diode numbers, float64, sorted -- ``sort(find(...))`` (``:94-98``)."""
190
+
191
+ a: np.ndarray
192
+ """``bin_stats`` as saved: int32, after ``:66-69``'s high-count replacement."""
193
+
194
+ bin_stats: np.ndarray
195
+ """``bin_stats`` as read at ``:41``, before any replacement (int32)."""
196
+
197
+ ill_diode: np.ndarray
198
+ """1-based diodes over ``1.2*mean(a)`` (``:66``), float64; usually empty."""
199
+
200
+ branch: str
201
+ """``"mean"`` when ``ill_diode`` was non-empty (``:94``), else ``"max"`` (``:97``)."""
202
+
203
+ threshold: float
204
+ """The value ``a`` was compared against: ``0.80*mean(a)`` (double) or
205
+ ``0.80*max(a)`` (int32, returned here as a float)."""
206
+
207
+ written: Path | None
208
+ """The ``.mat`` written, or ``None`` when the caller asked for no write."""
209
+
210
+
211
+ def _read_bin_stats(infile) -> np.ndarray:
212
+ """``a=ncread(infile,'bin_stats')`` (``:41``): an int32 column vector.
213
+
214
+ Read raw. ``bin_stats`` is defined ``'int'`` with no ``_FillValue`` or
215
+ scale attributes (``imgProc_sm.m:438``), so MATLAB's ``ncread`` returns the
216
+ stored values unconverted, as int32 -- and the class matters below.
217
+ netCDF4-python would mask a value equal to the library's *default* fill
218
+ even without the attribute, which MATLAB does not do.
219
+ """
220
+ import netCDF4
221
+
222
+ with netCDF4.Dataset(str(infile)) as ds:
223
+ var = ds.variables["bin_stats"]
224
+ var.set_auto_maskandscale(False)
225
+ raw = np.asarray(var[...])
226
+ return raw.astype(np.int32).reshape(-1)
227
+
228
+
229
+ def find_shadow_diodes(date: str, time: str, orientation: str, *, path,
230
+ infile=None, write: bool = True, counts: str = "lit",
231
+ slice_total: int | None = None) -> ShadowDiodeSearch:
232
+ """Port of ``find_shadow_diodes.m``: find stuck diodes from a first-pass proc.
233
+
234
+ MATLAB-order arguments -- ``date`` ``'YYMMDD'``, ``time`` ``'HHMMSS'``,
235
+ ``orientation`` ``'H'``/``'V'`` -- and the MATLAB-order result: 1-based
236
+ diode numbers in :attr:`ShadowDiodeSearch.shadow_diode`, ready for
237
+ ``[run].diode_masks`` and :func:`reilluminate`.
238
+
239
+ ``path`` stands in for ``:31``'s hard-coded
240
+ ``/condo/mcfarq/sid/b/oracles/oracles_20<date>/`` (see
241
+ :data:`MATLAB_FIND_SHADOW_DIODES_PATH`), and is used exactly as MATLAB uses
242
+ it: glued by string concatenation, so it should end in a separator. The
243
+ input defaults to ``[path 'base' date time '.' orientation '_1.cdf']``
244
+ (``:40``); ``infile`` overrides it, for this port's ``proc.*.nc`` names.
245
+
246
+ **The rule is not the one the file's own header states.** The header says
247
+ "<80% of max count"; the 06/20/2018 note says "<80% of mean count". The
248
+ code does both, depending on a third test:
249
+
250
+ * ``:66`` -- if any diode reads **above 1.2 x mean** (a diode masked
251
+ in-flight, which reads lit on every slice), those diodes are replaced by
252
+ the array's ``nanmean`` (``:68-69``) and a diode is stuck when it is
253
+ below **0.80 x mean** of the replaced array (``:94``);
254
+ * otherwise a diode is stuck when it is below **0.80 x max** (``:97``).
255
+
256
+ **Polarity.** The rule is written for **lit** counts (``counts="lit"``, the
257
+ default and the production fork's ``bin_stats``). Stock UIOOPS (v3.1.4 stock
258
+ and every v3.5 proc file) writes **shadowed** counts instead
259
+ (``imgProc_sm.m`` v3.5 ``:1208,1210``); a caller holding such a file passes
260
+ ``counts="shadowed"`` and ``slice_total`` (the slice total ``S`` every
261
+ diode saw, ``tune.diodes.position_slice_total``) and the counts are
262
+ converted as ``lit = S - shadowed`` before the rule runs. Fed unconverted,
263
+ the rule reads the stuck diode as the busiest one and flags nearly
264
+ everything else. ``counts="shadowed"`` without ``slice_total`` raises.
265
+
266
+ Quirks reproduced, each pinned by a test:
267
+
268
+ 1. **The NaN does not survive.** ``a`` is int32 (``bin_stats`` is
269
+ ``'int'``), and ``a(ill_diode)=NaN`` stores 0 -- MATLAB's int32(NaN).
270
+ ``nanmean`` therefore sees no NaN and averages the zeros in: the
271
+ replacement value is diluted by ``len(ill_diode)/n`` rather than being
272
+ the mean of the other diodes the comment promises. Octave does the same.
273
+ 2. **``0.80*max(a)`` is int32**, rounded half away from zero (integer
274
+ dominance). For integer ``a`` this can never change a comparison, but
275
+ it is kept as MATLAB computes it.
276
+ 3. **An empty result is saved as ``diode.<date><time>.<or>empty.mat``**
277
+ (``:105-106``), a name ``imgProc_sm.m:288`` never constructs.
278
+ 4. **A non-positive array mean kills the run before any save.** ``:55``'s
279
+ ``ylim([0 1.5*nanmean(a)])`` needs increasing limits, so a proc whose
280
+ ``bin_stats`` is all zero (no particles) or never written ends in an
281
+ error, not an empty mask. Raised here as
282
+ :class:`ShadowDiodeSearchError`.
283
+
284
+ Not reproduced: the two ``.jpeg`` figures (``:44-63``, ``:72-91``) -- a
285
+ picture is not a computed number; ``arrayprobe diode-masks`` and
286
+ ``examples/5_data_quality/01_find_stuck_diodes.ipynb`` draw the same counts.
287
+
288
+ The ``.mat`` holds the whole workspace left by ``:100``'s ``clearvars
289
+ -except path orientation shadow_diode date time a``, in MATLAB's ``who``
290
+ (alphabetical) order. ``path`` is saved as the string passed here.
291
+ """
292
+ from .matio import savemat
293
+ from .matlab_compat import msum
294
+
295
+ path_s = str(path)
296
+ if infile is None:
297
+ infile = f"{path_s}base{date}{time}.{orientation}_1.cdf"
298
+ if counts not in ("lit", "shadowed"):
299
+ raise ValueError(f"counts must be 'lit' or 'shadowed', not {counts!r}")
300
+ bin_stats = _read_bin_stats(infile)
301
+ if counts == "shadowed":
302
+ if slice_total is None:
303
+ raise ValueError("counts='shadowed' needs slice_total, the slice total S "
304
+ "(lit = S - shadowed)")
305
+ if bin_stats.size and int(bin_stats.max()) > int(slice_total):
306
+ raise ValueError(f"a shadow count ({int(bin_stats.max())}) exceeds "
307
+ f"slice_total={int(slice_total)}")
308
+ bin_stats = (int(slice_total) - bin_stats.astype(np.int64)).astype(bin_stats.dtype)
309
+ a = bin_stats.copy()
310
+ n = a.size
311
+
312
+ def mean(x):
313
+ # MATLAB `mean` of an integer array: double, sum(double(x))/n. Exact
314
+ # here -- integer counts sum exactly in double below 2^53.
315
+ return float(msum(x.astype(np.float64))) / x.size if x.size else float("nan")
316
+
317
+ first_ylim = 1.5 * mean(a) # :55, nanmean of a NaN-free array
318
+ if not first_ylim > 0:
319
+ raise ShadowDiodeSearchError(
320
+ f"{infile}: find_shadow_diodes.m:55 ylim([0 1.5*nanmean(a)]) = "
321
+ f"[0 {first_ylim:g}] is not increasing -- MATLAB stops here and saves "
322
+ "nothing. bin_stats is all zero, empty or unwritten "
323
+ f"(n={n}, sum={int(a.astype(np.int64).sum()) if n else 0}).")
324
+
325
+ rule = stuck_diodes(a) # :66-97, shared with the v3.5 engine
326
+ a, ill, branch, threshold = rule.a, rule.ill_diode, rule.branch, rule.threshold
327
+ shadow_diode = rule.shadow_diode
328
+
329
+ written = None
330
+ if write:
331
+ written = Path(path_s + _saved_mask_filename(date, time, orientation,
332
+ not shadow_diode.size))
333
+ savemat(written, {"a": a, "date": date, "orientation": orientation,
334
+ "path": path_s, "shadow_diode": shadow_diode,
335
+ "time": time})
336
+ return ShadowDiodeSearch(shadow_diode=shadow_diode, a=a, bin_stats=bin_stats,
337
+ ill_diode=ill, branch=branch, threshold=threshold,
338
+ written=written)
339
+
340
+
341
+ def reilluminate(c: np.ndarray, diodes) -> np.ndarray:
342
+ """``c(:,shadow_diode)='1'`` (extraction ``:290``), through
343
+ :func:`arrayprobe_uiops.diode_mask.reilluminate`.
344
+
345
+ A zero, negative or fractional entry raises :class:`MatlabIndexError`, as
346
+ MATLAB does; an index past the last diode widens the image, so
347
+ ``imgProc_sm.m:272-276``'s width guard fires as in MATLAB.
348
+ """
349
+ return _reilluminate(c, diodes, index_error=MatlabIndexError)