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,769 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""Two diagnostic views: the record strip and the one-second comparison.
|
|
3
|
+
|
|
4
|
+
Visualisation, so core rather than ``enhancements_uiops/`` -- nothing here computes a pipeline
|
|
5
|
+
number
|
|
6
|
+
or writes one; every function reads files the port already wrote and says what is in them.
|
|
7
|
+
Both views are standard library + numpy + netCDF4 only (the PNG is written by hand with
|
|
8
|
+
``zlib``, like :func:`arrayprobe.render._png_bytes`), so neither needs the ``viz`` extra.
|
|
9
|
+
|
|
10
|
+
**The record strip** (:func:`record_strip`, :func:`record_strip_png`, :func:`record_strip_html`).
|
|
11
|
+
HydroViewer's view, and the gap
|
|
12
|
+
that had been missing from this package:
|
|
13
|
+
whole 1700-slice image records stacked one above the next, every particle in place, the
|
|
14
|
+
boundary slices between particles marked, and each particle's shadow coloured by its reject code
|
|
15
|
+
or its habit. The triage server shows one particle, cropped; this shows the *buffer* -- the
|
|
16
|
+
spacing between particles, the particles a record-boundary reset put side by side, and a
|
|
17
|
+
shadow that no particle window claims (a slice ``imgProc_sm`` never framed). Every fifth particle
|
|
18
|
+
gets a red tick above its first slice, HydroViewer's ``annotate`` aid for lining a strip up
|
|
19
|
+
against the per-particle file.
|
|
20
|
+
|
|
21
|
+
**The one-second comparison** (:func:`compare_second`, :func:`second_comparison_html`). For
|
|
22
|
+
validation work: one second of two size-distribution files -- the port's and the archive's --
|
|
23
|
+
bin by bin, with the differing cells marked and the particles of that second whose diameter falls
|
|
24
|
+
in a differing bin listed beside them, each with its reject code and centre-in flag. It is the
|
|
25
|
+
tool a residual root-cause did by hand with ``compare_nc.py`` and a notebook.
|
|
26
|
+
|
|
27
|
+
**What each view claims, and where a test checks it** (``tests/test_diagnostic_views.py``):
|
|
28
|
+
|
|
29
|
+
* the strip's shadow inside each particle window is the particle's own silhouette -- asserted
|
|
30
|
+
against :func:`arrayprobe.render.reconstruct_particle_image`, the gallery's path, which decodes
|
|
31
|
+
with ``dec2bin_concat`` where this module unpacks bits; two mechanisms, one answer;
|
|
32
|
+
* the strip lists exactly the proc rows whose ``parent_rec_num`` falls in the records shown;
|
|
33
|
+
* the PNG decodes back to the index image, and each category's pixel count equals the summed
|
|
34
|
+
shadow of the particles in it;
|
|
35
|
+
* the comparison's per-bin values are the files' own, its differing cells are exactly the
|
|
36
|
+
cells that differ, and a particle is listed only if its second and its diameter put it there.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import html
|
|
42
|
+
import os
|
|
43
|
+
import struct
|
|
44
|
+
import threading
|
|
45
|
+
import zlib
|
|
46
|
+
from dataclasses import dataclass, field
|
|
47
|
+
|
|
48
|
+
import numpy as np
|
|
49
|
+
|
|
50
|
+
from .matlab_compat import HOLROYD_HABITS, REJECT_CODES
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"BOUNDARY_WORD",
|
|
54
|
+
"SLICES_PER_RECORD",
|
|
55
|
+
"StripParticle",
|
|
56
|
+
"RecordStrip",
|
|
57
|
+
"record_strip",
|
|
58
|
+
"strip_index_image",
|
|
59
|
+
"record_strip_png",
|
|
60
|
+
"record_strip_html",
|
|
61
|
+
"SecondComparison",
|
|
62
|
+
"compare_second",
|
|
63
|
+
"second_comparison_html",
|
|
64
|
+
"per_second_counts",
|
|
65
|
+
"HOLLOW_ACCEPTED_CODES",
|
|
66
|
+
"HOLLOW_VERDICT_MIN_FRACTION",
|
|
67
|
+
"HollowShare",
|
|
68
|
+
"hollow_share",
|
|
69
|
+
"hollow_share_text",
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
#: The 2D-S/HVPS particle-boundary word: a slice in which every word is ``0xAAAA`` separates two
|
|
73
|
+
#: particles (``imgProc_sm.m``'s boundary for probetype 2; ``imgproc.py``'s ``cfg.boundary``).
|
|
74
|
+
#: Other probe types pass their own to :func:`record_strip`.
|
|
75
|
+
BOUNDARY_WORD = 0xAAAA
|
|
76
|
+
|
|
77
|
+
#: ``ImgBlocklen`` -- every decoded image record is 1700 slices.
|
|
78
|
+
SLICES_PER_RECORD = 1700
|
|
79
|
+
|
|
80
|
+
_ACCEPTED = REJECT_CODES["0"]
|
|
81
|
+
_REJECT_BY_VALUE = {v: k for k, v in REJECT_CODES.items()}
|
|
82
|
+
_HABIT_BY_VALUE = {v: k for k, v in HOLROYD_HABITS.items()}
|
|
83
|
+
|
|
84
|
+
# Palette indices below _FIRST_CATEGORY are fixed roles; categories follow in a fixed order.
|
|
85
|
+
_BACKGROUND, _SEPARATOR, _BOUNDARY, _UNCLAIMED, _TICK = range(5)
|
|
86
|
+
_FIRST_CATEGORY = 5
|
|
87
|
+
_ROLE_COLOURS = [
|
|
88
|
+
(255, 255, 255), # background: an unshadowed diode
|
|
89
|
+
(232, 232, 232), # separator band between records (and the tick row)
|
|
90
|
+
(0, 190, 200), # boundary slice: every word is the boundary word
|
|
91
|
+
(150, 150, 150), # shadow inside no particle window
|
|
92
|
+
(220, 0, 0), # every-fifth-particle tick
|
|
93
|
+
]
|
|
94
|
+
#: Category colours in order; the accepted class is always black, so it reads as the particle
|
|
95
|
+
#: silhouette every other view here draws.
|
|
96
|
+
_CATEGORY_COLOURS = [
|
|
97
|
+
(31, 119, 180), (255, 127, 14), (44, 160, 44), (148, 103, 189), (140, 86, 75),
|
|
98
|
+
(227, 119, 194), (188, 189, 34), (23, 190, 207), (214, 39, 40), (127, 127, 127),
|
|
99
|
+
(174, 199, 232), (255, 187, 120), (152, 223, 138), (197, 176, 213), (196, 156, 148),
|
|
100
|
+
]
|
|
101
|
+
_ACCEPTED_COLOUR = (0, 0, 0)
|
|
102
|
+
_SEPARATOR_ROWS = 4
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class StripParticle:
|
|
107
|
+
"""One proc row, placed in its record. Slices are 1-based and inclusive, as ``position`` is."""
|
|
108
|
+
|
|
109
|
+
index: int # 0-based row in the proc file
|
|
110
|
+
record: int # 1-based ``parent_rec_num``
|
|
111
|
+
first_slice: int
|
|
112
|
+
last_slice: int
|
|
113
|
+
reject: str | None # ``image_auto_reject`` as its character; ``'0'`` is accepted
|
|
114
|
+
habit: str | None # ``holroyd_habit`` as its character
|
|
115
|
+
|
|
116
|
+
def category(self, colour_by: str) -> str:
|
|
117
|
+
"""The class this particle is coloured by: ``'accepted'``, a reject code, or a habit."""
|
|
118
|
+
if colour_by == "reject":
|
|
119
|
+
if self.reject and self.reject in "0HhuR": # sizeDist.m:1209's accepted set
|
|
120
|
+
return "accepted"
|
|
121
|
+
return f"reject {self.reject or '?'}"
|
|
122
|
+
return f"habit {self.habit or '?'}"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class RecordStrip:
|
|
127
|
+
"""``n`` consecutive image records with their particles in place.
|
|
128
|
+
|
|
129
|
+
``shadow`` is ``(n_records, 1700, n_diodes)``, ``True`` where a diode was shadowed -- the
|
|
130
|
+
same convention as :func:`arrayprobe.render.reconstruct_particle_image`. ``boundary`` is
|
|
131
|
+
``(n_records, 1700)``, ``True`` on a slice whose every word is the boundary word.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
records: tuple[int, ...]
|
|
135
|
+
shadow: np.ndarray
|
|
136
|
+
boundary: np.ndarray
|
|
137
|
+
particles: tuple[StripParticle, ...]
|
|
138
|
+
colour_by: str = "reject"
|
|
139
|
+
categories: tuple[str, ...] = field(default=())
|
|
140
|
+
|
|
141
|
+
def particles_in(self, record: int) -> list[StripParticle]:
|
|
142
|
+
"""The particles whose ``parent_rec_num`` is ``record`` (1-based), in proc order."""
|
|
143
|
+
return [p for p in self.particles if p.record == record]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _shadow_of_block(block: np.ndarray) -> np.ndarray:
|
|
147
|
+
"""``(slices, n_words)`` raw words -> ``(slices, 16 * n_words)`` shadow, MSB first.
|
|
148
|
+
|
|
149
|
+
``imgProc_sm.m:266-268`` inverts (``65535 - data``) and reads a ``'0'`` character as shadow;
|
|
150
|
+
that is the same as reading a set bit of the raw word as shadow, which is what this does with
|
|
151
|
+
``unpackbits`` -- deliberately not ``dec2bin_concat``, so the test that compares the two is
|
|
152
|
+
comparing two mechanisms rather than one.
|
|
153
|
+
"""
|
|
154
|
+
words = np.asarray(block).astype(np.int64) & 0xFFFF
|
|
155
|
+
as_bytes = words.astype(">u2").view(np.uint8).reshape(words.shape[0], -1)
|
|
156
|
+
return np.unpackbits(as_bytes, axis=1).astype(bool)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _char(value, table) -> str | None:
|
|
160
|
+
if value is None:
|
|
161
|
+
return None
|
|
162
|
+
v = float(value)
|
|
163
|
+
if not np.isfinite(v):
|
|
164
|
+
return None
|
|
165
|
+
return table.get(int(v), chr(int(v)) if 32 <= int(v) < 127 else None)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _first_at_least(var, n: int, value: float) -> int:
|
|
169
|
+
"""The first row of the 1-D, non-decreasing ``var`` (length ``n``) whose value is at least
|
|
170
|
+
``value``, or ``n``: a binary search that reads one element per step, as a one-element slice
|
|
171
|
+
so a stored value reaches the comparison exactly as a whole read would deliver it."""
|
|
172
|
+
lo, hi = 0, n
|
|
173
|
+
while lo < hi:
|
|
174
|
+
mid = (lo + hi) // 2
|
|
175
|
+
if float(np.asarray(var[mid:mid + 1]).reshape(-1)[0]) < value:
|
|
176
|
+
lo = mid + 1
|
|
177
|
+
else:
|
|
178
|
+
hi = mid
|
|
179
|
+
return lo
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
#: ``{(proc path, size, mtime_ns): parent_rec_num is finite and non-decreasing}`` -- one bool per
|
|
183
|
+
#: proc file, so the scan below runs once per file per process, not once per request.
|
|
184
|
+
_RECORD_ORDER_CACHE: dict[tuple, bool] = {}
|
|
185
|
+
_RECORD_ORDER_LOCK = threading.Lock()
|
|
186
|
+
_ORDER_SCAN_CHUNK = 1 << 20
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _in_record_order(proc_ds, pvar, n: int) -> bool:
|
|
190
|
+
"""Whether ``parent_rec_num`` is finite and non-decreasing over the whole file.
|
|
191
|
+
|
|
192
|
+
The binary search in :func:`_strip_rows` is only correct on such a file, and a local check of
|
|
193
|
+
the block it finds cannot see disorder elsewhere (a shuffled file can bisect to an empty
|
|
194
|
+
block). So the whole variable is scanned once, in chunks of ``_ORDER_SCAN_CHUNK`` elements --
|
|
195
|
+
bounded memory -- and the answer is cached per file (path, size and mtime), so a server pays
|
|
196
|
+
it once per flight rather than per request.
|
|
197
|
+
"""
|
|
198
|
+
key = None
|
|
199
|
+
try:
|
|
200
|
+
path = proc_ds.filepath()
|
|
201
|
+
st = os.stat(path)
|
|
202
|
+
key = (str(path), st.st_size, st.st_mtime_ns)
|
|
203
|
+
except (AttributeError, OSError, ValueError):
|
|
204
|
+
pass
|
|
205
|
+
if key is not None:
|
|
206
|
+
with _RECORD_ORDER_LOCK:
|
|
207
|
+
hit = _RECORD_ORDER_CACHE.get(key)
|
|
208
|
+
if hit is not None:
|
|
209
|
+
return hit
|
|
210
|
+
ordered, prev = True, -np.inf
|
|
211
|
+
for start in range(0, n, _ORDER_SCAN_CHUNK):
|
|
212
|
+
part = np.asarray(pvar[start:start + _ORDER_SCAN_CHUNK]).reshape(-1)
|
|
213
|
+
if part.size and (not np.all(np.isfinite(part)) or part[0] < prev
|
|
214
|
+
or np.any(np.diff(part) < 0)):
|
|
215
|
+
ordered = False
|
|
216
|
+
break
|
|
217
|
+
if part.size:
|
|
218
|
+
prev = part[-1]
|
|
219
|
+
if key is not None:
|
|
220
|
+
with _RECORD_ORDER_LOCK:
|
|
221
|
+
_RECORD_ORDER_CACHE[key] = ordered
|
|
222
|
+
return ordered
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _strip_rows(proc_ds, first_record: int, last: int):
|
|
226
|
+
"""``(lo, hi, parent, position, reject, habit)`` for the proc rows a strip of records
|
|
227
|
+
``first_record``..``last`` needs, each array starting at proc row ``lo``.
|
|
228
|
+
|
|
229
|
+
``parent_rec_num`` is written in record order, so the rows of a run of records are one
|
|
230
|
+
contiguous block: its bounds are found by binary search (O(log n) one-element reads) and only
|
|
231
|
+
that block of each variable is read. Reading the four variables whole on every request is what
|
|
232
|
+
took the triage server to 44 GB on a 17.8M-particle flight (2026-10-01). A file this does not
|
|
233
|
+
recognise -- ``parent_rec_num`` not 1-D, ``position`` not ``(particles, 2)``, or
|
|
234
|
+
``parent_rec_num`` not finite and non-decreasing (:func:`_in_record_order`) -- is read whole,
|
|
235
|
+
exactly as before, so the shown content never depends on which path ran.
|
|
236
|
+
"""
|
|
237
|
+
pvar = proc_ds.variables["parent_rec_num"]
|
|
238
|
+
posvar = proc_ds.variables["position"]
|
|
239
|
+
rvar = proc_ds.variables.get("image_auto_reject")
|
|
240
|
+
hvar = proc_ds.variables.get("holroyd_habit")
|
|
241
|
+
n = int(pvar.shape[0]) if pvar.ndim == 1 else -1
|
|
242
|
+
sliceable = (n >= 0 and posvar.ndim == 2 and int(posvar.shape[0]) == n
|
|
243
|
+
and int(posvar.shape[1]) == 2
|
|
244
|
+
and all(v is None or (v.ndim == 1 and int(v.shape[0]) == n)
|
|
245
|
+
for v in (rvar, hvar)))
|
|
246
|
+
if sliceable and _in_record_order(proc_ds, pvar, n):
|
|
247
|
+
lo = _first_at_least(pvar, n, first_record)
|
|
248
|
+
hi = _first_at_least(pvar, n, last + 1)
|
|
249
|
+
return (lo, hi, np.asarray(pvar[lo:hi]).reshape(-1),
|
|
250
|
+
np.asarray(posvar[lo:hi, :]).reshape(-1, 2),
|
|
251
|
+
np.asarray(rvar[lo:hi]).reshape(-1) if rvar is not None else None,
|
|
252
|
+
np.asarray(hvar[lo:hi]).reshape(-1) if hvar is not None else None)
|
|
253
|
+
parent = np.asarray(pvar[:]).reshape(-1)
|
|
254
|
+
return (0, parent.size, parent,
|
|
255
|
+
np.asarray(posvar[:]).reshape(-1, 2),
|
|
256
|
+
np.asarray(rvar[:]).reshape(-1) if rvar is not None else None,
|
|
257
|
+
np.asarray(hvar[:]).reshape(-1) if hvar is not None else None)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def record_strip(image_ds, proc_ds, first_record: int, n_records: int = 6, *,
|
|
261
|
+
colour_by: str = "reject", boundary_word: int = BOUNDARY_WORD) -> RecordStrip:
|
|
262
|
+
"""Records ``first_record`` .. ``first_record + n_records - 1`` (1-based) with their particles.
|
|
263
|
+
|
|
264
|
+
``image_ds``/``proc_ds`` are open ``netCDF4.Dataset`` handles on one flight's decoded image
|
|
265
|
+
file and its proc file. The last record shown is clipped to the file's own length, and a
|
|
266
|
+
``first_record`` outside the file raises, naming the file's range -- a strip of nothing would
|
|
267
|
+
look like an empty buffer, which is a different finding.
|
|
268
|
+
"""
|
|
269
|
+
if colour_by not in ("reject", "habit"):
|
|
270
|
+
raise ValueError(f"colour_by must be 'reject' or 'habit', not {colour_by!r}")
|
|
271
|
+
data = image_ds.variables["data"]
|
|
272
|
+
total = int(data.shape[0])
|
|
273
|
+
if not 1 <= first_record <= total:
|
|
274
|
+
raise ValueError(f"record {first_record} is outside this file's 1..{total}")
|
|
275
|
+
if n_records < 1:
|
|
276
|
+
raise ValueError("n_records must be at least 1")
|
|
277
|
+
last = min(total, first_record + n_records - 1)
|
|
278
|
+
records = tuple(range(first_record, last + 1))
|
|
279
|
+
|
|
280
|
+
blocks = [np.asarray(data[r - 1, :, :]) for r in records]
|
|
281
|
+
shadow = np.stack([_shadow_of_block(b) for b in blocks])
|
|
282
|
+
boundary = np.stack([np.all((b.astype(np.int64) & 0xFFFF) == boundary_word, axis=1)
|
|
283
|
+
for b in blocks])
|
|
284
|
+
|
|
285
|
+
lo, hi, parent, position, reject, habit = _strip_rows(proc_ds, first_record, last)
|
|
286
|
+
rows = np.nonzero((parent >= first_record) & (parent <= last))[0]
|
|
287
|
+
particles = tuple(
|
|
288
|
+
StripParticle(
|
|
289
|
+
index=int(lo + i), record=int(parent[i]),
|
|
290
|
+
first_slice=int(position[i, 0]), last_slice=int(position[i, 1]),
|
|
291
|
+
reject=_char(reject[i], _REJECT_BY_VALUE) if reject is not None else None,
|
|
292
|
+
habit=_char(habit[i], _HABIT_BY_VALUE) if habit is not None else None)
|
|
293
|
+
for i in rows)
|
|
294
|
+
categories = tuple(sorted({p.category(colour_by) for p in particles},
|
|
295
|
+
key=lambda c: (c != "accepted", c)))
|
|
296
|
+
return RecordStrip(records, shadow, boundary, particles, colour_by, categories)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def strip_index_image(strip: RecordStrip) -> tuple[np.ndarray, list[tuple[int, int, int]]]:
|
|
300
|
+
"""The strip as a palette-index image and its palette -- what :func:`record_strip_png` encodes.
|
|
301
|
+
|
|
302
|
+
Layout: for each record, a band of ``_SEPARATOR_ROWS`` rows (the tick row: red at the first
|
|
303
|
+
slice of every fifth particle, counted across the whole strip from 1) then one row per diode;
|
|
304
|
+
one column per slice. Pixel roles: background, boundary slice, shadow inside no particle
|
|
305
|
+
window, and one colour per category (``strip.categories``, accepted always black).
|
|
306
|
+
"""
|
|
307
|
+
n_rec, n_slices, n_diodes = strip.shadow.shape
|
|
308
|
+
band = _SEPARATOR_ROWS + n_diodes
|
|
309
|
+
img = np.full((n_rec * band, n_slices), _BACKGROUND, dtype=np.uint8)
|
|
310
|
+
palette = list(_ROLE_COLOURS)
|
|
311
|
+
colour_of = {}
|
|
312
|
+
others = iter(_CATEGORY_COLOURS * (1 + len(strip.categories) // len(_CATEGORY_COLOURS)))
|
|
313
|
+
for k, cat in enumerate(strip.categories):
|
|
314
|
+
colour_of[cat] = _FIRST_CATEGORY + k
|
|
315
|
+
palette.append(_ACCEPTED_COLOUR if cat == "accepted" else next(others))
|
|
316
|
+
|
|
317
|
+
for k, rec in enumerate(strip.records):
|
|
318
|
+
top = k * band
|
|
319
|
+
img[top:top + _SEPARATOR_ROWS, :] = _SEPARATOR
|
|
320
|
+
body = img[top + _SEPARATOR_ROWS: top + band, :] # (diodes, slices) view
|
|
321
|
+
sh = strip.shadow[k].T # (diodes, slices)
|
|
322
|
+
body[:, strip.boundary[k]] = _BOUNDARY
|
|
323
|
+
body[sh & ~strip.boundary[k][None, :]] = _UNCLAIMED
|
|
324
|
+
for p in strip.particles_in(rec):
|
|
325
|
+
lo, hi = max(p.first_slice, 1) - 1, min(p.last_slice, n_slices)
|
|
326
|
+
window = body[:, lo:hi]
|
|
327
|
+
window[sh[:, lo:hi]] = colour_of[p.category(strip.colour_by)]
|
|
328
|
+
for n, p in enumerate(strip.particles, start=1):
|
|
329
|
+
if n % 5 == 0:
|
|
330
|
+
k = strip.records.index(p.record)
|
|
331
|
+
col = max(p.first_slice, 1) - 1
|
|
332
|
+
img[k * band: k * band + _SEPARATOR_ROWS, col] = _TICK
|
|
333
|
+
return img, palette
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _palette_png(img: np.ndarray, palette) -> bytes:
|
|
337
|
+
"""An 8-bit palette PNG (colour type 3) of ``img``; standard library only."""
|
|
338
|
+
height, width = img.shape
|
|
339
|
+
raw = b"".join(b"\x00" + img[row].tobytes() for row in range(height))
|
|
340
|
+
|
|
341
|
+
def chunk(tag: bytes, payload: bytes) -> bytes:
|
|
342
|
+
return (struct.pack(">I", len(payload)) + tag + payload
|
|
343
|
+
+ struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF))
|
|
344
|
+
|
|
345
|
+
plte = b"".join(bytes(c) for c in palette)
|
|
346
|
+
return (b"\x89PNG\r\n\x1a\n"
|
|
347
|
+
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 3, 0, 0, 0))
|
|
348
|
+
+ chunk(b"PLTE", plte)
|
|
349
|
+
+ chunk(b"IDAT", zlib.compress(raw, 6))
|
|
350
|
+
+ chunk(b"IEND", b""))
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def record_strip_png(strip: RecordStrip) -> bytes:
|
|
354
|
+
"""The strip as PNG bytes. Deterministic: the same strip always gives the same bytes."""
|
|
355
|
+
img, palette = strip_index_image(strip)
|
|
356
|
+
return _palette_png(img, palette)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _hex(rgb) -> str:
|
|
360
|
+
r, g, b = rgb
|
|
361
|
+
return f"#{r:02x}{g:02x}{b:02x}"
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def record_strip_html(strip: RecordStrip, *, title: str = "", link_particle=None) -> str:
|
|
365
|
+
"""An HTML fragment: the PNG inline, a legend with counts, and the particle table.
|
|
366
|
+
|
|
367
|
+
``link_particle`` (``index -> href``) makes each particle row a link; the triage server passes
|
|
368
|
+
its own particle page, a file written by the CLI passes nothing.
|
|
369
|
+
"""
|
|
370
|
+
import base64
|
|
371
|
+
|
|
372
|
+
img, palette = strip_index_image(strip)
|
|
373
|
+
png = _palette_png(img, palette)
|
|
374
|
+
counts = {c: 0 for c in strip.categories}
|
|
375
|
+
for p in strip.particles:
|
|
376
|
+
counts[p.category(strip.colour_by)] += 1
|
|
377
|
+
legend = "".join(
|
|
378
|
+
f"<span style='display:inline-block;margin-right:1em'>"
|
|
379
|
+
f"<span style='display:inline-block;width:.9em;height:.9em;vertical-align:middle;"
|
|
380
|
+
f"background:{_hex(palette[_FIRST_CATEGORY + k])};border:1px solid #888'></span> "
|
|
381
|
+
f"{html.escape(c)} ({counts[c]})</span>"
|
|
382
|
+
for k, c in enumerate(strip.categories))
|
|
383
|
+
roles = (f"<span style='color:{_hex(_ROLE_COLOURS[_BOUNDARY])}'>■</span> boundary slice"
|
|
384
|
+
f" · <span style='color:{_hex(_ROLE_COLOURS[_UNCLAIMED])}'>■</span> "
|
|
385
|
+
f"shadow in no particle window · <span style='color:"
|
|
386
|
+
f"{_hex(_ROLE_COLOURS[_TICK])}'>■</span> every fifth particle")
|
|
387
|
+
rows = []
|
|
388
|
+
for n, p in enumerate(strip.particles, start=1):
|
|
389
|
+
label = str(p.index)
|
|
390
|
+
if link_particle is not None:
|
|
391
|
+
label = f"<a href='{html.escape(link_particle(p.index))}'>{p.index}</a>"
|
|
392
|
+
rows.append(f"<tr><td>{n}{' *' if n % 5 == 0 else ''}</td><td>{label}</td>"
|
|
393
|
+
f"<td>{p.record}</td><td>{p.first_slice}-{p.last_slice}</td>"
|
|
394
|
+
f"<td>{html.escape(p.reject or '?')}</td>"
|
|
395
|
+
f"<td>{html.escape(p.habit or '?')}</td></tr>")
|
|
396
|
+
first, last = strip.records[0], strip.records[-1]
|
|
397
|
+
n_boundary = int(strip.boundary.sum())
|
|
398
|
+
return (
|
|
399
|
+
(f"<h2>{html.escape(title)}</h2>" if title else "")
|
|
400
|
+
+ f"<p class='muted'>records {first}-{last}, one band each (1700 slices across, one row "
|
|
401
|
+
f"per diode); {len(strip.particles)} particle(s); {n_boundary} boundary slice(s); "
|
|
402
|
+
f"coloured by {html.escape(strip.colour_by)}</p>"
|
|
403
|
+
+ f"<img alt='record strip' style='width:100%;image-rendering:pixelated' "
|
|
404
|
+
f"src='data:image/png;base64,{base64.b64encode(png).decode()}'>"
|
|
405
|
+
+ f"<p>{legend}</p><p class='muted'>{roles}</p>"
|
|
406
|
+
+ "<table><tr><th>#</th><th>proc row</th><th>record</th><th>slices</th>"
|
|
407
|
+
"<th>reject</th><th>habit</th></tr>" + "".join(rows) + "</table>")
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
# ---------------------------------------------------------------------------------------------
|
|
411
|
+
# The one-second comparison
|
|
412
|
+
# ---------------------------------------------------------------------------------------------
|
|
413
|
+
|
|
414
|
+
@dataclass(frozen=True)
|
|
415
|
+
class SecondComparison:
|
|
416
|
+
"""One second of two size-distribution files, bin by bin.
|
|
417
|
+
|
|
418
|
+
``ours``/``theirs`` are the named variable's per-bin values at that second, read from each
|
|
419
|
+
file unscaled. ``differing`` marks the bins where they are not equal within ``rtol`` (exact
|
|
420
|
+
by default; NaN equals NaN). ``particles`` are the proc rows of that second whose
|
|
421
|
+
``diameter_var`` falls in a differing bin, ``[bin_min, bin_max)`` -- a guide to where to look,
|
|
422
|
+
not the binning itself: ``count`` additionally requires the particle's codes, centre-in flag
|
|
423
|
+
and time window to pass,
|
|
424
|
+
which is why each listed particle carries its reject code and centre-in flag.
|
|
425
|
+
"""
|
|
426
|
+
|
|
427
|
+
second: int
|
|
428
|
+
variable: str
|
|
429
|
+
bin_min: np.ndarray
|
|
430
|
+
bin_max: np.ndarray
|
|
431
|
+
ours: np.ndarray
|
|
432
|
+
theirs: np.ndarray
|
|
433
|
+
differing: np.ndarray
|
|
434
|
+
rtol: float
|
|
435
|
+
diameter_var: str | None = None
|
|
436
|
+
particles: tuple[dict, ...] = ()
|
|
437
|
+
|
|
438
|
+
@property
|
|
439
|
+
def n_differing(self) -> int:
|
|
440
|
+
"""How many bins differ at this second."""
|
|
441
|
+
return int(self.differing.sum())
|
|
442
|
+
|
|
443
|
+
def summary(self) -> str:
|
|
444
|
+
"""Plain text: the differing bins with both values, then the particles behind them."""
|
|
445
|
+
lines =[f"second {self.second:06d}, variable {self.variable!r}: "
|
|
446
|
+
f"{self.n_differing} of {self.differing.size} bin(s) differ"
|
|
447
|
+
f" ({'exact' if self.rtol == 0 else f'rtol {self.rtol:g}'})"]
|
|
448
|
+
for i in np.nonzero(self.differing)[0]:
|
|
449
|
+
lines.append(f" bin {i + 1:3d} [{self.bin_min[i]:.4g}, {self.bin_max[i]:.4g}): "
|
|
450
|
+
f"ours {self.ours[i]:.6g} theirs {self.theirs[i]:.6g} "
|
|
451
|
+
f"diff {self.ours[i] - self.theirs[i]:+.6g}")
|
|
452
|
+
if self.diameter_var is not None:
|
|
453
|
+
lines.append(f" {len(self.particles)} particle(s) of this second fall in a "
|
|
454
|
+
f"differing bin by {self.diameter_var}")
|
|
455
|
+
for p in self.particles:
|
|
456
|
+
lines.append(f" proc row {p['index']}: bin {p['bin']}, "
|
|
457
|
+
f"{self.diameter_var} {p['diameter']:.4g}, reject "
|
|
458
|
+
f"{p['reject'] or '?'}, centre-in {p['center_in']}")
|
|
459
|
+
return "\n".join(lines)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _sd_second(ds, second: int, variable: str, label: str):
|
|
463
|
+
times = np.asarray(ds.variables["time"][:]).reshape(-1).astype(float)
|
|
464
|
+
hits = np.nonzero(np.floor(times) == second)[0]
|
|
465
|
+
if hits.size == 0:
|
|
466
|
+
near = times[np.argsort(np.abs(times - second))[:3]]
|
|
467
|
+
raise KeyError(f"{label} has no second {second:06d}; nearest "
|
|
468
|
+
f"{', '.join(f'{int(t):06d}' for t in near)}")
|
|
469
|
+
if variable not in ds.variables:
|
|
470
|
+
raise KeyError(f"{label} has no variable {variable!r}")
|
|
471
|
+
var = ds.variables[variable]
|
|
472
|
+
if var.dimensions[0] != ds.variables["time"].dimensions[0] or var.ndim != 2:
|
|
473
|
+
raise ValueError(f"{variable!r} is not a (time, bin) variable in {label}")
|
|
474
|
+
return np.asarray(var[hits[0], :], dtype=float).reshape(-1)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def compare_second(ours_sd, theirs_sd, second: int, *, variable: str = "count",
|
|
478
|
+
proc=None, diameter_var: str = "image_diam_minR",
|
|
479
|
+
rtol: float = 0.0) -> SecondComparison:
|
|
480
|
+
"""Compare one second (``HHMMSS``) of two ``sd`` files; list the particles behind the cells.
|
|
481
|
+
|
|
482
|
+
``ours_sd``/``theirs_sd`` and ``proc`` are paths. ``proc``, when given, is the per-particle
|
|
483
|
+
file behind ``ours_sd``; without it no particles are listed. The two files must share a bin
|
|
484
|
+
ladder, or the comparison raises rather than setting two different bins side by side.
|
|
485
|
+
``diameter_var`` is stated in every rendering because the ``sd`` file does not record which
|
|
486
|
+
size definition its run chose -- the ``.call`` sidecar does.
|
|
487
|
+
"""
|
|
488
|
+
import netCDF4
|
|
489
|
+
|
|
490
|
+
with netCDF4.Dataset(str(ours_sd)) as a, netCDF4.Dataset(str(theirs_sd)) as b:
|
|
491
|
+
a.set_auto_maskandscale(False)
|
|
492
|
+
b.set_auto_maskandscale(False)
|
|
493
|
+
bin_min = np.asarray(a.variables["bin_min"][:], dtype=float)
|
|
494
|
+
bin_max = np.asarray(a.variables["bin_max"][:], dtype=float)
|
|
495
|
+
if not (np.array_equal(bin_min, np.asarray(b.variables["bin_min"][:], dtype=float))
|
|
496
|
+
and np.array_equal(bin_max, np.asarray(b.variables["bin_max"][:], dtype=float))):
|
|
497
|
+
raise ValueError("the two files have different bin ladders; compare them "
|
|
498
|
+
"with `arrayprobe compare` rather than bin by bin")
|
|
499
|
+
ours = _sd_second(a, second, variable, str(ours_sd))
|
|
500
|
+
theirs = _sd_second(b, second, variable, str(theirs_sd))
|
|
501
|
+
equal = np.isclose(ours, theirs, rtol=rtol, atol=0.0, equal_nan=True)
|
|
502
|
+
differing = ~equal
|
|
503
|
+
|
|
504
|
+
particles: tuple[dict, ...] = ()
|
|
505
|
+
if proc is not None:
|
|
506
|
+
with netCDF4.Dataset(str(proc)) as p:
|
|
507
|
+
p.set_auto_maskandscale(False)
|
|
508
|
+
t = np.asarray(p.variables["Time"][:]).reshape(-1).astype(float)
|
|
509
|
+
d = np.asarray(p.variables[diameter_var][:]).reshape(-1).astype(float)
|
|
510
|
+
rej = (np.asarray(p.variables["image_auto_reject"][:]).reshape(-1)
|
|
511
|
+
if "image_auto_reject" in p.variables else None)
|
|
512
|
+
cin = (np.asarray(p.variables["image_center_in"][:]).reshape(-1)
|
|
513
|
+
if "image_center_in" in p.variables else None)
|
|
514
|
+
rows = []
|
|
515
|
+
for i in np.nonzero(np.floor(t) == second)[0]:
|
|
516
|
+
inside = np.nonzero((bin_min <= d[i]) & (d[i] < bin_max))[0]
|
|
517
|
+
if inside.size and differing[inside[0]]:
|
|
518
|
+
rows.append({
|
|
519
|
+
"index": int(i), "bin": int(inside[0]) + 1, "diameter": float(d[i]),
|
|
520
|
+
"reject": _char(rej[i], _REJECT_BY_VALUE) if rej is not None else None,
|
|
521
|
+
"center_in": int(cin[i]) if cin is not None else None,
|
|
522
|
+
})
|
|
523
|
+
particles = tuple(rows)
|
|
524
|
+
return SecondComparison(second, variable, bin_min, bin_max, ours, theirs, differing,
|
|
525
|
+
rtol, diameter_var if proc is not None else None, particles)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def second_comparison_html(cmp: SecondComparison, *, ours_label: str = "ours",
|
|
529
|
+
theirs_label: str = "theirs") -> str:
|
|
530
|
+
"""An HTML fragment: every bin where either file is non-zero, differing rows marked."""
|
|
531
|
+
shown = np.nonzero(cmp.differing | (np.nan_to_num(cmp.ours) != 0)
|
|
532
|
+
| (np.nan_to_num(cmp.theirs) != 0))[0]
|
|
533
|
+
rows = []
|
|
534
|
+
for i in shown:
|
|
535
|
+
mark = " style='background:#fde2e2'" if cmp.differing[i] else ""
|
|
536
|
+
rows.append(f"<tr{mark}><td>{i + 1}</td><td>{cmp.bin_min[i]:.4g}</td>"
|
|
537
|
+
f"<td>{cmp.bin_max[i]:.4g}</td><td>{cmp.ours[i]:.6g}</td>"
|
|
538
|
+
f"<td>{cmp.theirs[i]:.6g}</td>"
|
|
539
|
+
f"<td>{cmp.ours[i] - cmp.theirs[i]:+.6g}</td>"
|
|
540
|
+
f"<td>{'differs' if cmp.differing[i] else ''}</td></tr>")
|
|
541
|
+
head = (f"<h2>Second {cmp.second:06d}: {html.escape(cmp.variable)}</h2>"
|
|
542
|
+
f"<p>{cmp.n_differing} of {cmp.differing.size} bin(s) differ "
|
|
543
|
+
f"({'exact comparison' if cmp.rtol == 0 else f'rtol {cmp.rtol:g}'}); "
|
|
544
|
+
f"{len(shown)} bin(s) shown -- every bin where either file is non-zero or the two "
|
|
545
|
+
f"differ</p>")
|
|
546
|
+
table = (f"<table><tr><th>bin</th><th>min</th><th>max</th><th>{html.escape(ours_label)}"
|
|
547
|
+
f"</th><th>{html.escape(theirs_label)}</th><th>diff</th><th></th></tr>"
|
|
548
|
+
+ "".join(rows) + "</table>")
|
|
549
|
+
if cmp.diameter_var is None:
|
|
550
|
+
parts = "<p class='muted'>no proc file given, so no particles are listed</p>"
|
|
551
|
+
else:
|
|
552
|
+
prow = "".join(
|
|
553
|
+
f"<tr><td>{p['index']}</td><td>{p['bin']}</td><td>{p['diameter']:.4g}</td>"
|
|
554
|
+
f"<td>{html.escape(p['reject'] or '?')}</td><td>{p['center_in']}</td></tr>"
|
|
555
|
+
for p in cmp.particles)
|
|
556
|
+
parts = (f"<h3>Particles of this second in a differing bin</h3>"
|
|
557
|
+
f"<p class='muted'>by <code>{html.escape(cmp.diameter_var)}</code>, "
|
|
558
|
+
f"[bin_min, bin_max). The sd file does not record which size definition its "
|
|
559
|
+
f"run binned by (its <code>.call</code> sidecar does), and <code>count</code> "
|
|
560
|
+
f"also requires the reject codes, centre-in and time window to pass -- so "
|
|
561
|
+
f"this list is where to look, not what was counted.</p>"
|
|
562
|
+
f"<table><tr><th>proc row</th><th>bin</th><th>diameter</th><th>reject</th>"
|
|
563
|
+
f"<th>centre-in</th></tr>{prow}</table>")
|
|
564
|
+
return head + table + parts
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def per_second_counts(hhmmss) -> tuple[np.ndarray, np.ndarray]:
|
|
568
|
+
"""Particles per second from a proc file's ``Time`` (``HHMMSS``): ``(seconds, counts)``.
|
|
569
|
+
|
|
570
|
+
``seconds`` are seconds of day, floored; non-finite times are dropped. The counts sum to the
|
|
571
|
+
number of finite particle times -- the triage server's rate panel draws exactly this.
|
|
572
|
+
"""
|
|
573
|
+
from arrayprobe_uiops.sizedist_core import _hhmmss_to_insec
|
|
574
|
+
|
|
575
|
+
insec = np.floor(_hhmmss_to_insec(np.asarray(hhmmss, dtype=float).reshape(-1)))
|
|
576
|
+
finite = insec[np.isfinite(insec)]
|
|
577
|
+
seconds, counts = np.unique(finite, return_counts=True)
|
|
578
|
+
return seconds, counts
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
# ---------------------------------------------------------------------------------------------
|
|
582
|
+
# How much of a between-engine difference hollow ('H') particles can make.
|
|
583
|
+
#
|
|
584
|
+
# UIOOPS v3.5 divides a hollow ('H', Poisson-spot) particle's `image_diam_minR` by its Korolev
|
|
585
|
+
# `size_factor` (1.07-1.9; `arrayprobe_uiops/measure.py:318-319`) before sizeDist bins it. SODA-2
|
|
586
|
+
# bins the uncorrected circle unless `apply_psc` is set. So wherever 'H' particles are common,
|
|
587
|
+
# the two engines put the same particles in different bins. `hollow_share` reads ONE v3.5 proc
|
|
588
|
+
# file and says, per size bin, how many particles that division moves, in which direction. It
|
|
589
|
+
# reads the file and writes nothing: no product changes.
|
|
590
|
+
|
|
591
|
+
#: Codes the v3.5 product counts in `image_auto_reject` (accepted, 'H' hollow, 'h', 'u', 'R'),
|
|
592
|
+
#: the same set the 'H'-undivided side of the ARM three-way comparison counts.
|
|
593
|
+
HOLLOW_ACCEPTED_CODES = "0HhuR"
|
|
594
|
+
|
|
595
|
+
#: The verdict fires when the division changes the range's accepted count by at least this
|
|
596
|
+
#: fraction of the count as written AND by more than twice that count's Poisson standard error.
|
|
597
|
+
#: 5 % is the counting noise of a range holding 400 particles (1/sqrt(400)); the two measured
|
|
598
|
+
#: cases where hollow sizing drove a between-engine difference sit far above it (ARM 2D-S,
|
|
599
|
+
#: 55-115 um: 07-07 a 75 % shift, 07-08 a 24 % shift), and the Poisson clause keeps a sparse
|
|
600
|
+
#: range from firing on a handful of particles.
|
|
601
|
+
HOLLOW_VERDICT_MIN_FRACTION = 0.05
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
@dataclass
|
|
605
|
+
class HollowShare:
|
|
606
|
+
"""Per-bin hollow census of one v3.5 proc file. Every array has one entry per bin.
|
|
607
|
+
|
|
608
|
+
``moved_out[b]``: accepted 'H' particles whose undivided size is in bin ``b`` and whose
|
|
609
|
+
written (divided) size is not -- the correction takes them out of ``b``.
|
|
610
|
+
``moved_in[b]``: accepted 'H' particles whose written size is in ``b`` and whose undivided
|
|
611
|
+
size is not -- the correction brings them into ``b``.
|
|
612
|
+
So ``accepted = accepted_undivided - moved_out + moved_in`` in every bin.
|
|
613
|
+
"""
|
|
614
|
+
|
|
615
|
+
edges_um: np.ndarray
|
|
616
|
+
accepted: np.ndarray # accepted particles at their written sizes
|
|
617
|
+
accepted_h: np.ndarray # of which 'H'
|
|
618
|
+
moved_out: np.ndarray
|
|
619
|
+
moved_in: np.ndarray
|
|
620
|
+
accepted_undivided: np.ndarray # the same particles with each 'H' at size x size_factor
|
|
621
|
+
min_fraction: float = HOLLOW_VERDICT_MIN_FRACTION
|
|
622
|
+
source: str = ""
|
|
623
|
+
|
|
624
|
+
@property
|
|
625
|
+
def h_share(self) -> np.ndarray:
|
|
626
|
+
"""Accepted 'H' / accepted, per bin (NaN in an empty bin)."""
|
|
627
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
628
|
+
return np.where(self.accepted > 0, self.accepted_h / self.accepted, np.nan)
|
|
629
|
+
|
|
630
|
+
@property
|
|
631
|
+
def ratio_undivided_to_written(self) -> np.ndarray:
|
|
632
|
+
"""Count without the correction / count with it, per bin: what an engine that does not
|
|
633
|
+
divide (SODA-2 with ``apply_psc = 0``) would count against what v3.5 counts, from the
|
|
634
|
+
sizing alone."""
|
|
635
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
636
|
+
return np.where(self.accepted > 0, self.accepted_undivided / self.accepted, np.nan)
|
|
637
|
+
|
|
638
|
+
@property
|
|
639
|
+
def net_shift(self) -> int:
|
|
640
|
+
"""Change in the range's accepted count caused by the division (written - undivided)."""
|
|
641
|
+
return int(self.accepted.sum() - self.accepted_undivided.sum())
|
|
642
|
+
|
|
643
|
+
@property
|
|
644
|
+
def fires(self) -> bool:
|
|
645
|
+
"""The verdict rule: see :data:`HOLLOW_VERDICT_MIN_FRACTION`."""
|
|
646
|
+
n = max(int(self.accepted.sum()), 1)
|
|
647
|
+
shift = abs(self.net_shift)
|
|
648
|
+
return shift > 0 and shift >= self.min_fraction * n and shift > 2.0 * np.sqrt(n)
|
|
649
|
+
|
|
650
|
+
def verdict(self) -> str:
|
|
651
|
+
"""One line, ``YES: ...`` when :attr:`fires` and ``NO: ...`` otherwise: the range, the
|
|
652
|
+
count undivided and as written, the fractional shift and the rule applied. Computes
|
|
653
|
+
nothing beyond the census."""
|
|
654
|
+
lo, hi = self.edges_um[0], self.edges_um[-1]
|
|
655
|
+
n, nu = int(self.accepted.sum()), int(self.accepted_undivided.sum())
|
|
656
|
+
frac = self.net_shift / n if n else float("nan")
|
|
657
|
+
rule = f"rule: |shift| >= {self.min_fraction:.0%} of the count and > 2 sqrt(count)"
|
|
658
|
+
if self.fires:
|
|
659
|
+
return (f"YES: hollow sizing can explain a between-engine difference in "
|
|
660
|
+
f"{lo:g}-{hi:g} um: the 'H' division changes the accepted count from "
|
|
661
|
+
f"{nu} (undivided) to {n} (as written), {frac:+.1%} ({rule}).")
|
|
662
|
+
return (f"NO: hollow sizing moves too little to explain a between-engine difference in "
|
|
663
|
+
f"{lo:g}-{hi:g} um: {nu} undivided against {n} as written, {frac:+.1%} ({rule}).")
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _codes(var) -> np.ndarray:
|
|
667
|
+
raw = np.asarray(var[:])
|
|
668
|
+
if raw.dtype.kind in "SU":
|
|
669
|
+
flat = raw.astype("S1").reshape(-1)
|
|
670
|
+
return np.array([c[0] if len(c) else -1 for c in flat], dtype=np.int64)
|
|
671
|
+
return np.ma.filled(np.ma.asarray(raw), -1).astype(np.int64).reshape(-1)
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def hollow_share(proc_path, bin_edges_um, *,
|
|
675
|
+
min_fraction: float = HOLLOW_VERDICT_MIN_FRACTION) -> HollowShare:
|
|
676
|
+
"""Per-bin hollow census of one v3.5 proc file (see :class:`HollowShare`).
|
|
677
|
+
|
|
678
|
+
``bin_edges_um`` are ascending edges in micrometres; a bin is ``[lo, hi)``, sizeDist's
|
|
679
|
+
``bin_index`` rule. Accepted means ``image_auto_reject`` in :data:`HOLLOW_ACCEPTED_CODES`
|
|
680
|
+
with ``image_center_in == 1``. The written size is ``image_diam_minR`` (mm) and the undivided
|
|
681
|
+
size of an 'H' particle is ``image_diam_minR * size_factor``, the rebin
|
|
682
|
+
``compare_ena_threeway.py --uiops-h-undivided`` uses. sizeDist's own reject stage (area
|
|
683
|
+
ratio, interarrival) is not applied, so the counts are the proc file's accepted particles,
|
|
684
|
+
not the product's ``Counts``. Reads the file; writes nothing.
|
|
685
|
+
"""
|
|
686
|
+
import netCDF4
|
|
687
|
+
|
|
688
|
+
edges = np.asarray(bin_edges_um, dtype=np.float64).reshape(-1)
|
|
689
|
+
if edges.size < 2 or np.any(np.diff(edges) <= 0):
|
|
690
|
+
raise ValueError("bin_edges_um must be at least two strictly ascending edges")
|
|
691
|
+
with netCDF4.Dataset(str(proc_path)) as d:
|
|
692
|
+
for name in ("image_auto_reject", "image_center_in", "image_diam_minR", "size_factor"):
|
|
693
|
+
if name not in d.variables:
|
|
694
|
+
raise ValueError(f"{proc_path}: no {name!r}; hollow_share reads a UIOPS v3.5 "
|
|
695
|
+
"proc file")
|
|
696
|
+
code = _codes(d.variables["image_auto_reject"])
|
|
697
|
+
cin = np.ma.filled(np.ma.asarray(d.variables["image_center_in"][:]), -1).reshape(-1)
|
|
698
|
+
diam = np.ma.filled(np.ma.asarray(d.variables["image_diam_minR"][:],
|
|
699
|
+
dtype=np.float64), np.nan).reshape(-1)
|
|
700
|
+
sf = np.ma.filled(np.ma.asarray(d.variables["size_factor"][:], dtype=np.float64),
|
|
701
|
+
np.nan).reshape(-1)
|
|
702
|
+
accepted = np.isin(code, [ord(c) for c in HOLLOW_ACCEPTED_CODES]) & (cin == 1)
|
|
703
|
+
is_h = accepted & (code == ord("H"))
|
|
704
|
+
written_um = diam * 1000.0
|
|
705
|
+
undiv_um = np.where(is_h, diam * sf, diam) * 1000.0
|
|
706
|
+
nb = edges.size - 1
|
|
707
|
+
|
|
708
|
+
def bin_of(x: np.ndarray) -> np.ndarray:
|
|
709
|
+
b = np.searchsorted(edges, x, side="right") - 1
|
|
710
|
+
b[~np.isfinite(x) | (x < edges[0]) | (x >= edges[-1])] = -1
|
|
711
|
+
return b
|
|
712
|
+
|
|
713
|
+
bw, bu = bin_of(written_um), bin_of(undiv_um)
|
|
714
|
+
|
|
715
|
+
def count(mask: np.ndarray, b: np.ndarray) -> np.ndarray:
|
|
716
|
+
sel = mask & (b >= 0)
|
|
717
|
+
return np.bincount(b[sel], minlength=nb)[:nb].astype(np.int64)
|
|
718
|
+
|
|
719
|
+
moved = is_h & (bw != bu)
|
|
720
|
+
return HollowShare(
|
|
721
|
+
edges_um=edges,
|
|
722
|
+
accepted=count(accepted, bw),
|
|
723
|
+
accepted_h=count(is_h, bw),
|
|
724
|
+
moved_out=count(moved, bu),
|
|
725
|
+
moved_in=count(moved, bw),
|
|
726
|
+
accepted_undivided=count(accepted, bu),
|
|
727
|
+
min_fraction=min_fraction,
|
|
728
|
+
source=str(proc_path),
|
|
729
|
+
)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def hollow_share_text(share: HollowShare) -> str:
|
|
733
|
+
"""The census as a plain-text table, one row per bin, ending with the verdict."""
|
|
734
|
+
rows = [f"hollow ('H') census of {share.source}",
|
|
735
|
+
f"{'bin (um)':>15} {'accepted':>9} {'H':>7} {'H share':>8} {'out':>6} {'in':>6} "
|
|
736
|
+
f"{'undivided':>10} {'undiv/written':>14}"]
|
|
737
|
+
share_h, ratio = share.h_share, share.ratio_undivided_to_written
|
|
738
|
+
for b in range(share.accepted.size):
|
|
739
|
+
span = f"{share.edges_um[b]:g}-{share.edges_um[b + 1]:g}"
|
|
740
|
+
rows.append(f"{span:>15} {share.accepted[b]:>9d} {share.accepted_h[b]:>7d} "
|
|
741
|
+
f"{share_h[b]:>8.3f} {share.moved_out[b]:>6d} {share.moved_in[b]:>6d} "
|
|
742
|
+
f"{share.accepted_undivided[b]:>10d} {ratio[b]:>14.3f}")
|
|
743
|
+
rows.append("out: 'H' the correction moves out of the bin; in: 'H' it moves into the bin; "
|
|
744
|
+
"undivided = accepted - in + out")
|
|
745
|
+
rows.append(share.verdict())
|
|
746
|
+
return "\n".join(rows)
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def hollow_share_at_or_above(proc_path, threshold_um: float) -> dict:
|
|
750
|
+
"""Hollow summary of one v3.5 proc file at or above one size: :func:`hollow_share` over the
|
|
751
|
+
open range ``[threshold_um, inf)``, as a dict.
|
|
752
|
+
|
|
753
|
+
``accepted`` and ``accepted_h`` count accepted particles (and the 'H' among them) whose
|
|
754
|
+
written size is at or above the threshold; ``h_share`` is their ratio; ``accepted_undivided``
|
|
755
|
+
counts with each 'H' at ``size x size_factor``; ``ratio_undivided_to_written`` is
|
|
756
|
+
``accepted_undivided / accepted``, the factor by which an engine that does not divide (SODA-2
|
|
757
|
+
with ``apply_psc = 0``) would count more above the threshold from sizing alone. Divide a
|
|
758
|
+
measured between-engine N ratio by it to see what hollow sizing leaves unexplained.
|
|
759
|
+
"""
|
|
760
|
+
share = hollow_share(proc_path, [float(threshold_um), np.inf])
|
|
761
|
+
n, nh = int(share.accepted[0]), int(share.accepted_h[0])
|
|
762
|
+
nu = int(share.accepted_undivided[0])
|
|
763
|
+
return {
|
|
764
|
+
"source": share.source, "threshold_um": float(threshold_um),
|
|
765
|
+
"accepted": n, "accepted_h": nh, "h_share": nh / n if n else float("nan"),
|
|
766
|
+
"accepted_undivided": nu,
|
|
767
|
+
"ratio_undivided_to_written": nu / n if n else float("nan"),
|
|
768
|
+
"verdict": share.verdict(),
|
|
769
|
+
}
|