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,15 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""Tune loop: what a user can change, and whether a change reaches the output.
|
|
3
|
+
|
|
4
|
+
:mod:`arrayprobe.tune.settings` lists every setting a run on the v3.5 engine (the default engine)
|
|
5
|
+
can change, where each is set, and whether it has any effect on a given probe case.
|
|
6
|
+
:mod:`arrayprobe.tune.sample` draws review queues from a proc file (particles inside time windows,
|
|
7
|
+
per size bin) for the triage server.
|
|
8
|
+
:mod:`arrayprobe.tune.distributions` reports the per-particle distributions inside time
|
|
9
|
+
windows of a proc file, with each active threshold marked where it cuts.
|
|
10
|
+
:mod:`arrayprobe.tune.score` crosses a reviewer's triage labels with each queued particle's
|
|
11
|
+
reject code and size bin. :mod:`arrayprobe.tune.diodes` reads a proc file's ``bin_stats`` as
|
|
12
|
+
lit counts and flags stuck diodes with the ORACLES fork's rule. Nothing here runs the pipeline
|
|
13
|
+
or changes a computed number; ``sample`` writes only a queue file, and ``distributions``,
|
|
14
|
+
``score`` and ``diodes`` only a JSON report.
|
|
15
|
+
"""
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""Stuck diodes in one proc file: ``bin_stats`` as lit counts, run through the fork's rule.
|
|
3
|
+
|
|
4
|
+
The ORACLES chain's ``find_shadow_diodes.m`` reads ``bin_stats`` from an imgProc output and flags
|
|
5
|
+
a diode that reads lit on fewer slices than the others
|
|
6
|
+
(:func:`arrayprobe_uiops.diode_mask.stuck_diodes`, ``find_shadow_diodes.m:66-97``). The rule is
|
|
7
|
+
written for **lit** counts, and which slices a proc file's ``bin_stats`` counts depends on what
|
|
8
|
+
wrote it:
|
|
9
|
+
|
|
10
|
+
* the ORACLES fork's ``imgProc_sm.m:387-388`` sums ``c=='1'`` (lit) -- a v3.1.4 profile with
|
|
11
|
+
``diode_stats_counts_shadowed=False``;
|
|
12
|
+
* stock v3.1.4 (``imgProc_sm.m:804-805``) and the v3.5 engine (``arrayprobe_uiops/measure.py``,
|
|
13
|
+
v3.5 ``imgProc_sm.m:1207-1211``) sum ``c=='0'`` (shadowed).
|
|
14
|
+
|
|
15
|
+
A shadow count is converted as ``lit_i = S - shadow_i``: every diode sees every slice of every
|
|
16
|
+
particle, so ``S``, the total slice count of the particles that fed ``bin_stats``, is common to
|
|
17
|
+
all diodes. ``S`` is read from the proc file's ``position`` (start and end slice of each
|
|
18
|
+
particle within its image record, v3.5 ``imgProc_sm.m:856``) as
|
|
19
|
+
``sum(end - start + 1 - image_slice_offset)``, the offset being the probe's
|
|
20
|
+
(``arrayprobe_uiops.imgproc.PROBES_V35``, ``:764-795``). Feeding the rule an unconverted shadow
|
|
21
|
+
count flags the healthiest diodes instead of the stuck ones.
|
|
22
|
+
|
|
23
|
+
**Provenance.** The engine and profile come from the file's own provenance attributes or its
|
|
24
|
+
``.call`` sidecar (:mod:`arrayprobe_uiops.provenance`); the two carriers must agree. A stamp with
|
|
25
|
+
no
|
|
26
|
+
``engine=`` key, or no stamp at all, is read as v3.1.4 (the repository's rule for products
|
|
27
|
+
stamped before 2026-09-15 and for MATLAB-written products). v3.1.4 has profiles of both
|
|
28
|
+
conventions, so where the stamp names no profile the caller must name one (``profile=``); the
|
|
29
|
+
convention is never defaulted. SODA-2 products carry no ``bin_stats`` and are refused.
|
|
30
|
+
|
|
31
|
+
Read-only: nothing here writes a product or changes a computed number.
|
|
32
|
+
"""
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import logging
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Any
|
|
38
|
+
|
|
39
|
+
import numpy as np
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"RULE_SOURCE",
|
|
43
|
+
"DiodeReportError",
|
|
44
|
+
"counting_convention",
|
|
45
|
+
"slice_offset",
|
|
46
|
+
"lit_counts",
|
|
47
|
+
"position_slice_total",
|
|
48
|
+
"report",
|
|
49
|
+
"report_from_counts",
|
|
50
|
+
"toml_line",
|
|
51
|
+
"summary_lines",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
#: Where the rule's two branches and its high-count test live (promoted ``.m`` line numbers).
|
|
55
|
+
RULE_SOURCE = {
|
|
56
|
+
"max": "find_shadow_diodes.m:97 (a < int32(STUCK_FRACTION*max(a)))",
|
|
57
|
+
"mean": "find_shadow_diodes.m:94 (a < STUCK_FRACTION*mean(a), after :66-69)",
|
|
58
|
+
"high": "find_shadow_diodes.m:66 (a > HIGH_FRACTION*mean(a))",
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
_LIT_SOURCE = "ORACLES fork imgProc_sm.m:387-388 (sum(c=='1'))"
|
|
62
|
+
_SHADOW_SOURCE = {
|
|
63
|
+
"3.5": "arrayprobe_uiops/measure.py (v3.5 imgProc_sm.m:1207-1211, sum(c=='0'))",
|
|
64
|
+
"3.1.4": "stock v3.1.4 imgProc_sm.m:804-805 (sum(c=='0'))",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class DiodeReportError(ValueError):
|
|
69
|
+
"""A proc file whose ``bin_stats`` convention or slice total cannot be established."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _stamp_of(path: Path):
|
|
73
|
+
"""The file's stamp from either carrier, refusing when both exist and disagree."""
|
|
74
|
+
from arrayprobe_uiops import provenance
|
|
75
|
+
|
|
76
|
+
sidecar = provenance.read(path)
|
|
77
|
+
try:
|
|
78
|
+
inside = provenance.read_in_file_stamp(path)
|
|
79
|
+
except (OSError, RuntimeError, ValueError):
|
|
80
|
+
inside = None
|
|
81
|
+
diffs = provenance.disagreements(sidecar, inside)
|
|
82
|
+
if diffs:
|
|
83
|
+
raise provenance.ProvenanceDisagreement(path, diffs)
|
|
84
|
+
if sidecar is not None and sidecar.format == "unparseable":
|
|
85
|
+
raise DiodeReportError(f"{path.name}: its .call sidecar cannot be parsed: {sidecar.raw!r}")
|
|
86
|
+
return sidecar if sidecar is not None else inside
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def counting_convention(path: Path | str, profile: str | None = None) -> dict[str, Any]:
|
|
90
|
+
"""Which slices ``path``'s ``bin_stats`` counts, and how that was established.
|
|
91
|
+
|
|
92
|
+
Returns ``{"engine", "engine_source", "profile", "shadowed", "convention_source"}``.
|
|
93
|
+
``profile`` names the v3.1.4 profile when the stamp names none; when the stamp names one,
|
|
94
|
+
a different ``profile`` is refused.
|
|
95
|
+
"""
|
|
96
|
+
from arrayprobe import profiles
|
|
97
|
+
|
|
98
|
+
path = Path(path)
|
|
99
|
+
stamp = _stamp_of(path)
|
|
100
|
+
if stamp is None:
|
|
101
|
+
engine, engine_source = "3.1.4", "no stamp: read as v3.1.4"
|
|
102
|
+
stamped_profile = None
|
|
103
|
+
else:
|
|
104
|
+
stamped_profile = stamp.profile
|
|
105
|
+
if stamp.engine is not None:
|
|
106
|
+
engine, engine_source = stamp.engine, f"stamp ({stamp.format})"
|
|
107
|
+
else:
|
|
108
|
+
engine, engine_source = "3.1.4", "stamp names no engine: read as v3.1.4"
|
|
109
|
+
if engine == "soda2":
|
|
110
|
+
raise DiodeReportError(f"{path.name}: a SODA-2 product carries no bin_stats")
|
|
111
|
+
if stamped_profile and profile and stamped_profile != profile:
|
|
112
|
+
raise DiodeReportError(
|
|
113
|
+
f"{path.name}: the stamp names profile {stamped_profile!r}, not {profile!r}")
|
|
114
|
+
chosen = stamped_profile or profile
|
|
115
|
+
|
|
116
|
+
if engine == "3.5":
|
|
117
|
+
return {"engine": engine, "engine_source": engine_source, "profile": chosen,
|
|
118
|
+
"shadowed": True, "convention_source": _SHADOW_SOURCE["3.5"]}
|
|
119
|
+
if not chosen:
|
|
120
|
+
raise DiodeReportError(
|
|
121
|
+
f"{path.name}: engine 3.1.4 ({engine_source}) and no profile named; v3.1.4 profiles "
|
|
122
|
+
"count lit slices (the ORACLES fork) or shadowed ones (stock), so name the profile")
|
|
123
|
+
try:
|
|
124
|
+
prof = profiles.profile(chosen)
|
|
125
|
+
except KeyError as exc:
|
|
126
|
+
raise DiodeReportError(f"{path.name}: {exc.args[0]}") from None
|
|
127
|
+
shadowed = bool(prof.diode_stats_counts_shadowed)
|
|
128
|
+
return {"engine": engine, "engine_source": engine_source, "profile": chosen,
|
|
129
|
+
"shadowed": shadowed,
|
|
130
|
+
"convention_source": (_SHADOW_SOURCE["3.1.4"] if shadowed else _LIT_SOURCE)
|
|
131
|
+
+ f"; profile {chosen}.diode_stats_counts_shadowed={shadowed}"}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def slice_offset(n_diodes: int, probe: str | None = None) -> tuple[int, str]:
|
|
135
|
+
"""The probe's ``image_slice_offset`` and where it came from.
|
|
136
|
+
|
|
137
|
+
With ``probe`` given, its :data:`~arrayprobe_uiops.imgproc.PROBES_V35` entry. Without, the
|
|
138
|
+
offset shared by every probe of ``n_diodes`` diodes; refused when those probes differ.
|
|
139
|
+
"""
|
|
140
|
+
from arrayprobe_uiops.imgproc import PROBES_V35
|
|
141
|
+
|
|
142
|
+
if probe is not None:
|
|
143
|
+
if probe not in PROBES_V35:
|
|
144
|
+
raise DiodeReportError(f"unknown probe {probe!r}; known: {', '.join(PROBES_V35)}")
|
|
145
|
+
return int(PROBES_V35[probe].image_slice_offset), f"PROBES_V35[{probe!r}]"
|
|
146
|
+
same = {name: int(p.image_slice_offset) for name, p in PROBES_V35.items()
|
|
147
|
+
if int(p.diodenum) == n_diodes}
|
|
148
|
+
offsets = set(same.values())
|
|
149
|
+
if len(offsets) != 1:
|
|
150
|
+
raise DiodeReportError(
|
|
151
|
+
f"{n_diodes} diodes: the probes of that width ({', '.join(same) or 'none'}) do not "
|
|
152
|
+
"share one image_slice_offset; name the probe")
|
|
153
|
+
return offsets.pop(), f"every {n_diodes}-diode probe in PROBES_V35 ({', '.join(same)})"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
#: Rows of ``position`` read per block when ``S`` is computed from a file.
|
|
157
|
+
POSITION_BLOCK_ROWS = 1_000_000
|
|
158
|
+
#: Below this many rows ``S`` is computed in this process; above it, across worker processes.
|
|
159
|
+
PARALLEL_MIN_ROWS = 2_000_000
|
|
160
|
+
|
|
161
|
+
#: The parallel read's wall-clock allowance per row a worker reads: 10x the ~20 us a row
|
|
162
|
+
#: measured on the unchunked layout (2026-10-01), so a slow disk is not mistaken for a hang.
|
|
163
|
+
PARALLEL_ROW_ALLOWANCE_S = 200e-6
|
|
164
|
+
|
|
165
|
+
#: The parallel read's timeout never falls below this, so worker spawn and import are covered.
|
|
166
|
+
PARALLEL_TIMEOUT_FLOOR_S = 120.0
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _read(path: Path) -> tuple[np.ndarray, tuple[int, int] | None]:
|
|
170
|
+
"""``bin_stats`` (raw), and ``(n_rows, pos_axis)`` for ``position`` or ``None`` if absent.
|
|
171
|
+
|
|
172
|
+
``position`` itself is not read here: :func:`position_slice_total` reads it in blocks.
|
|
173
|
+
"""
|
|
174
|
+
from netCDF4 import Dataset
|
|
175
|
+
|
|
176
|
+
with Dataset(path, "r") as ds:
|
|
177
|
+
if "bin_stats" not in ds.variables:
|
|
178
|
+
raise DiodeReportError(f"{path.name}: no bin_stats variable")
|
|
179
|
+
var = ds.variables["bin_stats"]
|
|
180
|
+
var.set_auto_maskandscale(False)
|
|
181
|
+
bin_stats = np.asarray(var[:]).reshape(-1)
|
|
182
|
+
position = None
|
|
183
|
+
if "position" in ds.variables:
|
|
184
|
+
pv = ds.variables["position"]
|
|
185
|
+
if len(pv.dimensions) == 2 and "pos_count" in pv.dimensions:
|
|
186
|
+
axis = pv.dimensions.index("pos_count")
|
|
187
|
+
position = (int(pv.shape[1 - axis]), axis)
|
|
188
|
+
return bin_stats, position
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _block_total(block, offset: int) -> int:
|
|
192
|
+
"""``sum(end - start + 1 - offset)`` over one ``(n, 2)`` block, in int64."""
|
|
193
|
+
pos = np.asarray(block, dtype=np.int64).reshape(-1, 2)
|
|
194
|
+
return int(np.sum(pos[:, 1] - pos[:, 0] + 1 - offset, dtype=np.int64))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _range_total(path: str, axis: int, offset: int, lo: int, hi: int, block_rows: int) -> int:
|
|
198
|
+
"""``S`` over rows ``[lo, hi)`` of ``path``'s ``position``, read ``block_rows`` at a time."""
|
|
199
|
+
from netCDF4 import Dataset
|
|
200
|
+
|
|
201
|
+
total = 0
|
|
202
|
+
with Dataset(path, "r") as ds:
|
|
203
|
+
pv = ds.variables["position"]
|
|
204
|
+
pv.set_auto_maskandscale(False)
|
|
205
|
+
for a in range(lo, hi, block_rows):
|
|
206
|
+
b = min(a + block_rows, hi)
|
|
207
|
+
block = np.asarray(pv[a:b, :] if axis == 1 else pv[:, a:b].T)
|
|
208
|
+
total += _block_total(block, offset)
|
|
209
|
+
return total
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def position_slice_total(path: Path | str, offset: int, *, block_rows: int = POSITION_BLOCK_ROWS,
|
|
213
|
+
jobs: int | None = None) -> int | None:
|
|
214
|
+
"""``S = sum(end - start + 1 - offset)`` over ``path``'s ``position``, ``None`` if absent.
|
|
215
|
+
|
|
216
|
+
Read in contiguous blocks of ``block_rows`` rows and summed in int64, so the result equals
|
|
217
|
+
the whole-array sum exactly. A proc file written before the v3.5 writer chunked
|
|
218
|
+
``position`` in ``[1024, 2]`` blocks stores it one particle per HDF5 chunk, and reading
|
|
219
|
+
it costs ~20 us a row (measured on a 17.8 M-particle file), so
|
|
220
|
+
``jobs`` worker processes each read a share of the rows; ``None`` picks
|
|
221
|
+
``min(cpu_count, 8)`` above :data:`PARALLEL_MIN_ROWS` rows and one process below.
|
|
222
|
+
"""
|
|
223
|
+
import os
|
|
224
|
+
|
|
225
|
+
path = Path(path)
|
|
226
|
+
_, position = _read(path)
|
|
227
|
+
if position is None:
|
|
228
|
+
return None
|
|
229
|
+
n, axis = position
|
|
230
|
+
if block_rows < 1:
|
|
231
|
+
raise ValueError(f"block_rows must be positive, not {block_rows}")
|
|
232
|
+
if jobs is None:
|
|
233
|
+
jobs = min(os.cpu_count() or 1, 8) if n >= PARALLEL_MIN_ROWS else 1
|
|
234
|
+
jobs = max(1, min(int(jobs), -(-n // block_rows) if n else 1))
|
|
235
|
+
if jobs == 1:
|
|
236
|
+
return _range_total(str(path), axis, offset, 0, n, block_rows)
|
|
237
|
+
total, why = _parallel_total(str(path), axis, offset, n, jobs, block_rows)
|
|
238
|
+
if total is None:
|
|
239
|
+
logging.getLogger(__name__).warning(
|
|
240
|
+
"arrayprobe tune diodes: the parallel read of %s's position failed (%s); "
|
|
241
|
+
"reading it serially", path.name, why)
|
|
242
|
+
return _range_total(str(path), axis, offset, 0, n, block_rows)
|
|
243
|
+
return total
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _parallel_timeout(n: int, jobs: int, block_rows: int) -> float:
|
|
247
|
+
"""Seconds the parallel read may take before it is abandoned for the serial one.
|
|
248
|
+
|
|
249
|
+
``max(PARALLEL_TIMEOUT_FLOOR_S, blocks * rows_per_block * PARALLEL_ROW_ALLOWANCE_S)``, where
|
|
250
|
+
``blocks = ceil(share / block_rows)`` is the block count of the largest worker's share
|
|
251
|
+
``share = ceil(n / jobs)`` and ``rows_per_block = min(block_rows, share)``. For 17.8 M rows
|
|
252
|
+
over 8 workers in 1 M-row blocks: 3 blocks x 1 M rows x 200 us = 600 s.
|
|
253
|
+
"""
|
|
254
|
+
share = -(-n // jobs)
|
|
255
|
+
blocks = -(-share // block_rows)
|
|
256
|
+
return max(PARALLEL_TIMEOUT_FLOOR_S, blocks * min(block_rows, share) * PARALLEL_ROW_ALLOWANCE_S)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _parallel_total(path: str, axis: int, offset: int, n: int, jobs: int,
|
|
260
|
+
block_rows: int) -> tuple[int | None, str]:
|
|
261
|
+
"""``S`` across ``jobs`` worker processes, or ``(None, why)`` when the pool fails.
|
|
262
|
+
|
|
263
|
+
Bounded: the results are awaited for :func:`_parallel_timeout` seconds at most, because
|
|
264
|
+
Windows workers that die at spawn (``OSError: [WinError 6] The handle is invalid``) leave
|
|
265
|
+
``ProcessPoolExecutor`` waiting forever. A timeout, a ``BrokenProcessPool`` or an
|
|
266
|
+
``OSError`` returns ``None`` and the caller reads serially; any other worker exception
|
|
267
|
+
propagates. A failed pool is shut down without waiting and its workers terminated.
|
|
268
|
+
"""
|
|
269
|
+
import concurrent.futures as cf
|
|
270
|
+
from concurrent.futures.process import BrokenProcessPool
|
|
271
|
+
|
|
272
|
+
edges = [n * k // jobs for k in range(jobs + 1)]
|
|
273
|
+
timeout = _parallel_timeout(n, jobs, block_rows)
|
|
274
|
+
pool = None
|
|
275
|
+
ok = False
|
|
276
|
+
try:
|
|
277
|
+
pool = cf.ProcessPoolExecutor(max_workers=jobs)
|
|
278
|
+
parts = [pool.submit(_range_total, path, axis, offset, edges[k], edges[k + 1],
|
|
279
|
+
block_rows) for k in range(jobs)]
|
|
280
|
+
done, pending = cf.wait(parts, timeout=timeout, return_when=cf.FIRST_EXCEPTION)
|
|
281
|
+
for f in done:
|
|
282
|
+
f.result() # re-raises a worker's exception
|
|
283
|
+
if pending:
|
|
284
|
+
return None, f"no result within {timeout:.0f} s"
|
|
285
|
+
total = sum(f.result() for f in parts)
|
|
286
|
+
ok = True
|
|
287
|
+
return total, ""
|
|
288
|
+
except (BrokenProcessPool, OSError) as exc:
|
|
289
|
+
return None, f"{type(exc).__name__}: {exc}"
|
|
290
|
+
finally:
|
|
291
|
+
if pool is not None:
|
|
292
|
+
if ok:
|
|
293
|
+
pool.shutdown(wait=True)
|
|
294
|
+
else:
|
|
295
|
+
pool.shutdown(wait=False, cancel_futures=True)
|
|
296
|
+
# Python 3.12 has no public way to stop a running worker (3.14 adds
|
|
297
|
+
# kill_workers); without this, interpreter exit joins a stalled worker.
|
|
298
|
+
for proc in list((getattr(pool, "_processes", None) or {}).values()):
|
|
299
|
+
try:
|
|
300
|
+
proc.terminate()
|
|
301
|
+
except Exception: # noqa: BLE001 - best effort on a pool already failed
|
|
302
|
+
pass
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def lit_counts(bin_stats, *, shadowed: bool, position=None, offset: int = 0,
|
|
306
|
+
total: int | None = None) -> tuple[np.ndarray, int | None]:
|
|
307
|
+
"""``bin_stats`` as lit counts, and ``S`` (``None`` when the counts were already lit).
|
|
308
|
+
|
|
309
|
+
``S`` comes from ``position`` (an ``(n, 2)`` start/end array) or, already summed, ``total``.
|
|
310
|
+
"""
|
|
311
|
+
counts = np.asarray(bin_stats, dtype=np.int64).reshape(-1)
|
|
312
|
+
if not shadowed:
|
|
313
|
+
return counts, None
|
|
314
|
+
if total is None:
|
|
315
|
+
if position is None:
|
|
316
|
+
raise DiodeReportError("a shadow count needs the proc file's position to compute S")
|
|
317
|
+
total = _block_total(position, offset)
|
|
318
|
+
total = int(total)
|
|
319
|
+
if counts.size and int(counts.max()) > total:
|
|
320
|
+
raise DiodeReportError(
|
|
321
|
+
f"a shadow count ({int(counts.max())}) exceeds the slice total S={total}: "
|
|
322
|
+
"position does not describe the particles that fed bin_stats")
|
|
323
|
+
return total - counts, total
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def report_from_counts(lit) -> dict[str, Any]:
|
|
327
|
+
"""The rule's verdict on lit counts, per diode and overall."""
|
|
328
|
+
from arrayprobe_uiops import diode_mask
|
|
329
|
+
|
|
330
|
+
lit = np.asarray(lit, dtype=np.int64).reshape(-1)
|
|
331
|
+
rule = diode_mask.stuck_diodes(lit)
|
|
332
|
+
flagged = [int(d) for d in rule.shadow_diode]
|
|
333
|
+
mean = float(np.mean(lit.astype(np.float64)))
|
|
334
|
+
peak = float(lit.max())
|
|
335
|
+
per_diode = [
|
|
336
|
+
{"diode": i + 1, "lit": int(v), "saved": int(rule.a[i]),
|
|
337
|
+
"fraction_of_max": float(v) / peak if peak else None,
|
|
338
|
+
"fraction_of_mean": float(v) / mean if mean else None,
|
|
339
|
+
"flagged": (i + 1) in flagged}
|
|
340
|
+
for i, v in enumerate(lit)
|
|
341
|
+
]
|
|
342
|
+
return {
|
|
343
|
+
"n_diodes": int(lit.size),
|
|
344
|
+
"flagged": flagged,
|
|
345
|
+
"ill_diode": [int(d) for d in rule.ill_diode],
|
|
346
|
+
"branch": rule.branch,
|
|
347
|
+
"threshold": rule.threshold,
|
|
348
|
+
"stuck_fraction": diode_mask.STUCK_FRACTION,
|
|
349
|
+
"high_fraction": diode_mask.HIGH_FRACTION,
|
|
350
|
+
"rule_source": RULE_SOURCE[rule.branch],
|
|
351
|
+
"high_source": RULE_SOURCE["high"],
|
|
352
|
+
"per_diode": per_diode,
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def report(path: Path | str, *, profile: str | None = None, probe: str | None = None,
|
|
357
|
+
jobs: int | None = None) -> dict[str, Any]:
|
|
358
|
+
"""The stuck-diode report for one proc file (see the module docstring)."""
|
|
359
|
+
path = Path(path)
|
|
360
|
+
conv = counting_convention(path, profile)
|
|
361
|
+
bin_stats, _ = _read(path)
|
|
362
|
+
offset, offset_source, total = (None, None, None)
|
|
363
|
+
if conv["shadowed"]:
|
|
364
|
+
offset, offset_source = slice_offset(bin_stats.size, probe)
|
|
365
|
+
total = position_slice_total(path, offset, jobs=jobs)
|
|
366
|
+
lit, total = lit_counts(bin_stats, shadowed=conv["shadowed"], offset=offset or 0,
|
|
367
|
+
total=total)
|
|
368
|
+
out = {"proc": str(path), **conv,
|
|
369
|
+
"counts": "shadowed, converted lit = S - shadow" if conv["shadowed"] else "lit",
|
|
370
|
+
"S": total, "image_slice_offset": offset, "offset_source": offset_source}
|
|
371
|
+
out.update(report_from_counts(lit))
|
|
372
|
+
return out
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def toml_line(stem: str, flagged) -> str:
|
|
376
|
+
"""The run-file entry declaring ``flagged`` for raw stem ``stem``: a ``[masking.diodes]``
|
|
377
|
+
table row, which ``arrayprobe.config`` loads into ``RunConfig.diode_masks`` and a run
|
|
378
|
+
applies under ``--diode-corrected``."""
|
|
379
|
+
diodes = ", ".join(str(int(d)) for d in flagged)
|
|
380
|
+
return f'[masking.diodes]\n"{stem}" = [{diodes}]'
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def summary_lines(rep: dict[str, Any]) -> list[str]:
|
|
384
|
+
"""A short printed form of :func:`report`'s output."""
|
|
385
|
+
lines = [
|
|
386
|
+
f"{Path(rep['proc']).name}: engine {rep['engine']} ({rep['engine_source']}), "
|
|
387
|
+
f"profile {rep['profile'] or 'unstated'}",
|
|
388
|
+
f" bin_stats counts: {rep['counts']}"
|
|
389
|
+
+ (f", S={rep['S']} (offset {rep['image_slice_offset']}, {rep['offset_source']})"
|
|
390
|
+
if rep["S"] is not None else ""),
|
|
391
|
+
f" rule: branch {rep['branch']}, threshold {rep['threshold']:g} ({rep['rule_source']})",
|
|
392
|
+
f" diodes over {rep['high_fraction']:g} x mean: {rep['ill_diode'] or 'none'}",
|
|
393
|
+
f" flagged: {rep['flagged'] or 'none'}",
|
|
394
|
+
" diode lit of max of mean",
|
|
395
|
+
]
|
|
396
|
+
for d in rep["per_diode"]:
|
|
397
|
+
if d["flagged"] or d["diode"] in rep["ill_diode"]:
|
|
398
|
+
lines.append(f" {d['diode']:5d} {d['lit']:8d} {d['fraction_of_max']:8.3f} "
|
|
399
|
+
f"{d['fraction_of_mean']:8.3f}" + (" flagged" if d["flagged"] else ""))
|
|
400
|
+
return lines
|