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,703 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""Shared leaf: the SPEC record geometry, packet markers and marker scan both engines use.
|
|
3
|
+
|
|
4
|
+
Moved verbatim from ``arrayprobe.readers.spec``;
|
|
5
|
+
that module re-imports them, so its names still resolve. Constants and pure
|
|
6
|
+
functions: no module state, no numba, nothing a worker pickles.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from arrayprobe_uiops.matlab_compat import MatlabIndexError
|
|
20
|
+
|
|
21
|
+
# --------------------------------------------------------------------------
|
|
22
|
+
# Record geometry -- read_binary_SPEC.m:170-182, :150-156
|
|
23
|
+
# --------------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
HEADER_WORDS = 8
|
|
26
|
+
DATA_WORDS = 2048
|
|
27
|
+
RECORD_WORDS = HEADER_WORDS + DATA_WORDS + 1 # + the discarded trailing word
|
|
28
|
+
RECORD_BYTES = RECORD_WORDS * 2 # 4114
|
|
29
|
+
|
|
30
|
+
IMG_ROWLEN = 8 # read_binary_SPEC.m:45 -- 8 words of 16 diodes
|
|
31
|
+
IMG_BLOCKLEN = 1700 # read_binary_SPEC.m:46
|
|
32
|
+
DIODES = IMG_ROWLEN * 16 # 128
|
|
33
|
+
|
|
34
|
+
# Packet markers, as the little-endian uint16 the ASCII pair decodes to.
|
|
35
|
+
MARKER_2S = 12883 # 0x3253 -- 'S','2' on disk; image packet (:198)
|
|
36
|
+
MARKER_HK = 18507 # 0x484B -- 'K','H' on disk; housekeeping (:290)
|
|
37
|
+
MARKER_MK = 19787 # 0x4D4B -- 'K','M' on disk; mask (:307)
|
|
38
|
+
|
|
39
|
+
# The alternating '1010...' boundary slice (:244), as sixteen2int packs it.
|
|
40
|
+
BOUNDARY_WORD = 43690 # 0b1010101010101010
|
|
41
|
+
|
|
42
|
+
_MASK_COUNT = 4095 # 0b0000111111111111 -- nH / nV (:199)
|
|
43
|
+
_MASK_TIMING = 4096 # 0b0001000000000000 -- timing flag (:199)
|
|
44
|
+
_MASK_RUN = 16256 # 0b0011111110000000 -- shadowed run (:227)
|
|
45
|
+
_MASK_CLEAR = 127 # 0b0000000001111111 -- clear run (:228)
|
|
46
|
+
_MASK_NEWSLICE = 16384 # 0b0100000000000000 -- new-slice bit (:233)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _marker_positions(buf) -> np.ndarray:
|
|
50
|
+
"""1-based positions of every marker word in the scanned half of the window.
|
|
51
|
+
|
|
52
|
+
``read_binary_SPEC.m:320-322`` walks past a non-marker word one at a time and
|
|
53
|
+
does nothing else, and on real ORACLES data that is ~97% of the words: 99328
|
|
54
|
+
of the first 102400. Jumping straight to the next marker is the same walk
|
|
55
|
+
with the no-ops elided, and it is the difference between minutes and hours
|
|
56
|
+
over a 1 GB flight file.
|
|
57
|
+
"""
|
|
58
|
+
head = buf[:DATA_WORDS]
|
|
59
|
+
hit = (head == MARKER_2S) | (head == MARKER_HK) | (head == MARKER_MK)
|
|
60
|
+
return np.flatnonzero(hit) + 1
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _next_marker(markers, iii: int, size: int | None = None) -> int:
|
|
64
|
+
"""Where the ``else: iii=iii+1`` walk would next find something to do.
|
|
65
|
+
|
|
66
|
+
``size`` is the window's length. A window shorter than the scan (the lone
|
|
67
|
+
primary of a file holding less than one whole record) has no word at
|
|
68
|
+
``size + 1``, so the walk stops there and the next ``_at`` raises where
|
|
69
|
+
MATLAB's ``buf(iii)`` does, instead of jumping silently to the scan's end.
|
|
70
|
+
"""
|
|
71
|
+
if markers is None:
|
|
72
|
+
return iii + 1
|
|
73
|
+
k = int(np.searchsorted(markers, iii, side="left"))
|
|
74
|
+
if k < markers.size:
|
|
75
|
+
return int(markers[k])
|
|
76
|
+
if size is not None and size < DATA_WORDS:
|
|
77
|
+
return size + 1
|
|
78
|
+
return DATA_WORDS + 1
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# --------------------------------------------------------------------------
|
|
82
|
+
# Moved verbatim from arrayprobe.readers.spec (v3.1.4 cut S2, 2026-10-10); that
|
|
83
|
+
# module re-exports every name below, same objects.
|
|
84
|
+
# --------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class RecordHeader:
|
|
89
|
+
"""The eight timestamp words of one raw record (``readRecord``, :170-182).
|
|
90
|
+
|
|
91
|
+
Source: ``readRecord`` in ``read_binary_SPEC.m:170-182`` (UIOOPS v3.1.4)."""
|
|
92
|
+
|
|
93
|
+
year: int
|
|
94
|
+
month: int
|
|
95
|
+
wkday: int
|
|
96
|
+
day: int
|
|
97
|
+
hour: int
|
|
98
|
+
minute: int
|
|
99
|
+
second: int
|
|
100
|
+
millisec: int
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def timehhmmss(self) -> float:
|
|
104
|
+
"""``hour*10000 + minute*100 + second + millisec/1000`` (:94)."""
|
|
105
|
+
return self.hour * 10000 + self.minute * 100 + self.second + self.millisec / 1000
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# --------------------------------------------------------------------------
|
|
109
|
+
# Buffer access
|
|
110
|
+
# --------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _at(buf: np.ndarray, k: int) -> int:
|
|
114
|
+
"""``buf(k)`` with MATLAB's 1-based index and MATLAB's out-of-range error."""
|
|
115
|
+
if k < 1 or k > buf.size:
|
|
116
|
+
raise MatlabIndexError(
|
|
117
|
+
f"buf({k}) exceeds the {buf.size}-word decode window. MATLAB raises "
|
|
118
|
+
"'Index exceeds matrix dimensions' here; stock v3.1.4 guards against it "
|
|
119
|
+
"(read_binary_SPEC.m:222,226,233) but the ORACLES variant does not."
|
|
120
|
+
)
|
|
121
|
+
return int(buf[k - 1])
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class _ImageCanvas:
|
|
125
|
+
"""``zeros(128, 1700)`` that grows on assignment, as a MATLAB array does.
|
|
126
|
+
|
|
127
|
+
Columns are slices, rows are diodes, both 1-based on the public methods so the
|
|
128
|
+
transcription stays visually identical to the source.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
__slots__ = ("_a",)
|
|
132
|
+
|
|
133
|
+
def __init__(self, ncols: int = IMG_BLOCKLEN) -> None:
|
|
134
|
+
self._a = np.zeros((DIODES, ncols), dtype=np.uint8)
|
|
135
|
+
|
|
136
|
+
def _ensure(self, col: int) -> None:
|
|
137
|
+
if col > self._a.shape[1]:
|
|
138
|
+
grown = np.zeros((DIODES, max(col, 2 * self._a.shape[1])), dtype=np.uint8)
|
|
139
|
+
grown[:, : self._a.shape[1]] = self._a
|
|
140
|
+
self._a = grown
|
|
141
|
+
|
|
142
|
+
def set_run(self, lo: int, hi: int, col: int) -> None:
|
|
143
|
+
"""``img(lo:hi, col) = 1`` -- a no-op when ``hi < lo``, as in MATLAB."""
|
|
144
|
+
self._ensure(col)
|
|
145
|
+
if hi >= lo:
|
|
146
|
+
self._a[lo - 1 : hi, col - 1] = 1
|
|
147
|
+
|
|
148
|
+
def set_column(self, col: int, values: np.ndarray) -> None:
|
|
149
|
+
"""``img(:, col) = values`` for a full 128-element column."""
|
|
150
|
+
self._ensure(col)
|
|
151
|
+
self._a[:, col - 1] = values
|
|
152
|
+
|
|
153
|
+
def set_rows(self, lo: int, hi: int, col: int, values: np.ndarray) -> None:
|
|
154
|
+
"""``img(lo:hi, col) = values``."""
|
|
155
|
+
self._ensure(col)
|
|
156
|
+
self._a[lo - 1 : hi, col - 1] = values
|
|
157
|
+
|
|
158
|
+
def add_diff(self, diff: np.ndarray, first_col: int) -> None:
|
|
159
|
+
"""Union in a ``(129, n)`` difference array starting at ``first_col``.
|
|
160
|
+
|
|
161
|
+
The vectorized run fill accumulates ``+1`` at each run's first row and
|
|
162
|
+
``-1`` one past its last; a cumulative sum down the rows then marks every
|
|
163
|
+
covered diode. ``> 0`` rather than ``== 1`` because runs within a slice
|
|
164
|
+
overlap freely.
|
|
165
|
+
"""
|
|
166
|
+
n = diff.shape[1]
|
|
167
|
+
if n == 0:
|
|
168
|
+
return
|
|
169
|
+
self._ensure(first_col + n - 1)
|
|
170
|
+
covered = np.cumsum(diff[:DIODES, :], axis=0) > 0
|
|
171
|
+
self._a[:, first_col - 1 : first_col - 1 + n] |= covered.astype(np.uint8)
|
|
172
|
+
|
|
173
|
+
def result(self) -> np.ndarray:
|
|
174
|
+
"""The grown array, exactly as ``get_img`` returns it to its caller."""
|
|
175
|
+
return self._a
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# --------------------------------------------------------------------------
|
|
179
|
+
# Run-length image decompression
|
|
180
|
+
# --------------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _decode_runs_scalar(buf, iii, n_words, n_slices, canvas, i_slice, guard):
|
|
184
|
+
"""Literal transcription of ``read_binary_SPEC.m:223-241`` (H) / ``:257-275`` (V).
|
|
185
|
+
|
|
186
|
+
``iii`` has already been advanced past the five-word packet header, so word
|
|
187
|
+
``kkk`` of the particle is ``buf(iii+kkk)`` with ``kkk`` counting from 0.
|
|
188
|
+
Returns nothing; the canvas is mutated in place.
|
|
189
|
+
"""
|
|
190
|
+
jjj = 1
|
|
191
|
+
kkk = 0
|
|
192
|
+
limit = n_words - 2 # the last two words are the particle timestamp
|
|
193
|
+
while (not guard or iii + kkk <= buf.size) and jjj <= n_slices and kkk < limit:
|
|
194
|
+
word = _at(buf, iii + kkk)
|
|
195
|
+
aa = (word & _MASK_RUN) // 128
|
|
196
|
+
bb = word & _MASK_CLEAR
|
|
197
|
+
canvas.set_run(min(DIODES, bb + 1), min(aa + bb, DIODES), i_slice + jjj)
|
|
198
|
+
b_base = min(aa + bb, DIODES)
|
|
199
|
+
kkk += 1
|
|
200
|
+
while (
|
|
201
|
+
(not guard or iii + kkk <= buf.size)
|
|
202
|
+
and (_at(buf, iii + kkk) & _MASK_NEWSLICE) == 0
|
|
203
|
+
and kkk < limit
|
|
204
|
+
):
|
|
205
|
+
word = _at(buf, iii + kkk)
|
|
206
|
+
aa = (word & _MASK_RUN) // 128
|
|
207
|
+
bb = word & _MASK_CLEAR
|
|
208
|
+
canvas.set_run(
|
|
209
|
+
min(DIODES, b_base + bb + 1), min(b_base + aa + bb, DIODES), i_slice + jjj
|
|
210
|
+
)
|
|
211
|
+
b_base = min(b_base + aa + bb, DIODES)
|
|
212
|
+
kkk += 1
|
|
213
|
+
jjj += 1
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _decode_runs_fast(buf, iii, n_words, n_slices, canvas, i_slice, guard):
|
|
217
|
+
"""Vectorized equivalent of :func:`_decode_runs_scalar`.
|
|
218
|
+
|
|
219
|
+
Three observations make the sequential loop collapse:
|
|
220
|
+
|
|
221
|
+
* A slice ends at the first word whose bit 14 is set, so slice boundaries are
|
|
222
|
+
``flatnonzero`` of that bit -- no scan needed.
|
|
223
|
+
* ``bBase`` is a *saturating* running sum of non-negative increments, so
|
|
224
|
+
``min(cumsum, 128)`` at each word equals the clamped recurrence: once the
|
|
225
|
+
sum reaches 128 it can never come back down.
|
|
226
|
+
* Every write is ``= 1`` over a row range, which a difference array plus one
|
|
227
|
+
``cumsum`` turns into a single array operation.
|
|
228
|
+
|
|
229
|
+
Randomized equivalence against the scalar form is pinned in
|
|
230
|
+
``test_spec_reader.TestRunDecodeEquivalence``.
|
|
231
|
+
"""
|
|
232
|
+
limit = n_words - 2
|
|
233
|
+
if limit <= 0 or n_slices <= 0:
|
|
234
|
+
return
|
|
235
|
+
|
|
236
|
+
# How far the scalar loop may read. Under the guard it stops at the window
|
|
237
|
+
# edge; without it, an over-long packet must still raise from _at().
|
|
238
|
+
end = iii + limit - 1
|
|
239
|
+
if end > buf.size:
|
|
240
|
+
if not guard:
|
|
241
|
+
_at(buf, end) # raises MatlabIndexError, as MATLAB does
|
|
242
|
+
limit = max(0, buf.size - iii + 1)
|
|
243
|
+
if limit == 0:
|
|
244
|
+
return
|
|
245
|
+
|
|
246
|
+
words = buf[iii - 1 : iii - 1 + limit].astype(np.int64)
|
|
247
|
+
new_slice = (words & _MASK_NEWSLICE) != 0
|
|
248
|
+
|
|
249
|
+
# Slice starts: word 0 always, then every word that raises the new-slice bit.
|
|
250
|
+
starts = np.concatenate(([0], np.flatnonzero(new_slice[1:]) + 1))
|
|
251
|
+
if starts.size > n_slices:
|
|
252
|
+
starts = starts[:n_slices]
|
|
253
|
+
consumed = int(starts[-1])
|
|
254
|
+
# The final slice runs to the next start, or to the word budget.
|
|
255
|
+
tail = np.flatnonzero(new_slice[consumed + 1 :]) + consumed + 1
|
|
256
|
+
stop = int(tail[0]) if (starts.size == n_slices and tail.size) else limit
|
|
257
|
+
words = words[:stop]
|
|
258
|
+
|
|
259
|
+
aa = (words & _MASK_RUN) // 128
|
|
260
|
+
bb = words & _MASK_CLEAR
|
|
261
|
+
col = np.searchsorted(starts, np.arange(stop), side="right") - 1
|
|
262
|
+
|
|
263
|
+
cum = np.cumsum(aa + bb)
|
|
264
|
+
cum_before = np.concatenate(([0], cum[:-1]))
|
|
265
|
+
base_at_start = cum_before[starts] # cum just before each slice
|
|
266
|
+
prev = cum_before - base_at_start[col]
|
|
267
|
+
|
|
268
|
+
lo = np.minimum(DIODES, prev + bb + 1)
|
|
269
|
+
hi = np.minimum(cum - base_at_start[col], DIODES)
|
|
270
|
+
keep = hi >= lo
|
|
271
|
+
if not keep.any():
|
|
272
|
+
return
|
|
273
|
+
|
|
274
|
+
diff = np.zeros((DIODES + 1, int(col[-1]) + 1), dtype=np.int32)
|
|
275
|
+
np.add.at(diff, (lo[keep] - 1, col[keep]), 1)
|
|
276
|
+
np.add.at(diff, (hi[keep], col[keep]), -1)
|
|
277
|
+
canvas.add_diff(diff, i_slice + 1)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
#: Below this many run words the scalar loop beats the vectorized one: setting up
|
|
281
|
+
#: a dozen NumPy calls costs more than iterating a handful of Python ints. Real
|
|
282
|
+
#: ORACLES 2D-S data is dominated by 1-3 word particles (marine stratocumulus
|
|
283
|
+
#: drops shadow one or two diodes), so this branch carries most of the traffic --
|
|
284
|
+
#: and the two paths are pinned equivalent by
|
|
285
|
+
#: ``TestRunDecodeEquivalence.test_random_packets_agree``, which spans the
|
|
286
|
+
#: threshold in both directions.
|
|
287
|
+
_VECTOR_THRESHOLD = 12
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _decode_runs_auto(buf, iii, n_words, n_slices, canvas, i_slice, guard):
|
|
291
|
+
"""Pick whichever run decoder is cheaper for this particle. Same result either way."""
|
|
292
|
+
if n_words - 2 <= _VECTOR_THRESHOLD:
|
|
293
|
+
_decode_runs_scalar(buf, iii, n_words, n_slices, canvas, i_slice, guard)
|
|
294
|
+
else:
|
|
295
|
+
_decode_runs_fast(buf, iii, n_words, n_slices, canvas, i_slice, guard)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
_BIT_SHIFTS = {w: np.arange(w - 1, -1, -1, dtype=np.int64) for w in (16, 32, DIODES)}
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _bits(value: int, width: int) -> np.ndarray:
|
|
302
|
+
"""``dec2bin(value, width) - 48`` for the header slice's fixed widths.
|
|
303
|
+
|
|
304
|
+
:func:`~arrayprobe.matlab_compat.dec2bin` is the general transcription and stays
|
|
305
|
+
the reference; this is it specialized to the five calls per particle that
|
|
306
|
+
``_write_header_slice`` makes, which profiling put at 60% of decode time. The
|
|
307
|
+
two agree exactly whenever ``value < 2**width`` -- which every one of these does,
|
|
308
|
+
``tParticle`` being two 16-bit words -- and
|
|
309
|
+
``TestHeaderSlice.test_bit_helper_matches_dec2bin`` pins that.
|
|
310
|
+
"""
|
|
311
|
+
return ((value >> _BIT_SHIFTS[width]) & 1).astype(np.uint8)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _write_header_slice(canvas, i_slice, t_particle, n_word, pc, n_s, *, with_metadata):
|
|
315
|
+
"""``read_binary_SPEC.m:244-252`` -- the boundary slice and the header slice.
|
|
316
|
+
|
|
317
|
+
Line 246 (``img(:,iSlice)=1``) is a dead store: line 248 overwrites the whole
|
|
318
|
+
column. It is left out rather than transcribed, because reproducing a write
|
|
319
|
+
that is immediately and unconditionally discarded buys nothing and costs a
|
|
320
|
+
read of the reader's attention. Lines 248 and 249 are *also* redundant with
|
|
321
|
+
each other -- ``dec2bin(t,128)`` and ``dec2bin(t,32)`` agree on rows 97-128
|
|
322
|
+
for any ``t < 2^32``, which every particle timestamp is -- but the second is
|
|
323
|
+
kept, since it is what pins rows 97-128 if a timestamp ever overflows.
|
|
324
|
+
"""
|
|
325
|
+
# The alternating boundary pattern, which sixteen2int packs to eight 43690s.
|
|
326
|
+
boundary = np.zeros(DIODES, dtype=np.uint8)
|
|
327
|
+
boundary[0::2] = 1
|
|
328
|
+
canvas.set_column(i_slice - 1, boundary)
|
|
329
|
+
|
|
330
|
+
canvas.set_column(i_slice, _bits(t_particle, DIODES))
|
|
331
|
+
canvas.set_rows(97, 128, i_slice, _bits(t_particle, 32))
|
|
332
|
+
if with_metadata:
|
|
333
|
+
canvas.set_rows(49, 64, i_slice, _bits(n_word, 16))
|
|
334
|
+
canvas.set_rows(65, 80, i_slice, _bits(pc, 16))
|
|
335
|
+
canvas.set_rows(81, 96, i_slice, _bits(n_s, 16))
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
# --------------------------------------------------------------------------
|
|
339
|
+
# Packing
|
|
340
|
+
# --------------------------------------------------------------------------
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def sixteen2int(rows: np.ndarray) -> np.ndarray:
|
|
344
|
+
"""``read_binary_SPEC.m:328-335`` -- pack 16 diode rows MSB-first into a word.
|
|
345
|
+
|
|
346
|
+
``rows`` is ``(16, n)``; row 1 is bit 15. Returns ``(n,)`` int64. The
|
|
347
|
+
all-alternating boundary slice packs to :data:`BOUNDARY_WORD`, which is the
|
|
348
|
+
cheapest orientation check there is.
|
|
349
|
+
"""
|
|
350
|
+
a = np.asarray(rows, dtype=np.int64)
|
|
351
|
+
weights = (1 << np.arange(15, -1, -1, dtype=np.int64))[:, None]
|
|
352
|
+
return (a * weights).sum(axis=0)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _pack_image(img: np.ndarray) -> np.ndarray:
|
|
356
|
+
"""``:108-110`` -- the 8 x 1700 packed block MATLAB calls ``img1``."""
|
|
357
|
+
block = img[:, :IMG_BLOCKLEN]
|
|
358
|
+
return np.vstack([sixteen2int(block[m * 16 : (m + 1) * 16, :]) for m in range(IMG_ROWLEN)])
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# --------------------------------------------------------------------------
|
|
362
|
+
# Sidecar CSVs
|
|
363
|
+
# --------------------------------------------------------------------------
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _as_single(value) -> float:
|
|
367
|
+
"""``single(value)``, returned as the exactly equal Python float.
|
|
368
|
+
|
|
369
|
+
Same helper as ``arrayprobe_uiops.spec._as_single``, duplicated rather than
|
|
370
|
+
imported: the port and the v3.5 engine stay independently importable
|
|
371
|
+
(see the two-engines note), and this is two lines.
|
|
372
|
+
"""
|
|
373
|
+
return float(np.float32(value))
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _matlab_f(value: float) -> str:
|
|
377
|
+
"""MATLAB's ``%f``: C's for finite values, ``NaN``/``Inf``/``-Inf`` otherwise.
|
|
378
|
+
|
|
379
|
+
Same helper as ``arrayprobe_uiops.spec._matlab_f``; see its docstring.
|
|
380
|
+
"""
|
|
381
|
+
if value != value:
|
|
382
|
+
return "NaN"
|
|
383
|
+
if value in (float("inf"), float("-inf")):
|
|
384
|
+
return "Inf" if value > 0 else "-Inf"
|
|
385
|
+
return f"{value:f}"
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
class SidecarWriter:
|
|
389
|
+
"""The three ``.csv`` files ``get_img`` appends to, buffered.
|
|
390
|
+
|
|
391
|
+
Source: the appends of ``get_img`` in ``read_binary_SPEC.m:184-326`` (UIOOPS v3.1.4):
|
|
392
|
+
``.NV.csv`` at ``:210-211``, ``.tas.csv`` at ``:301-302``, ``.MK.csv`` at ``:314-315``.
|
|
393
|
+
|
|
394
|
+
MATLAB opens, appends and closes on every single event. Buffering changes
|
|
395
|
+
the syscall pattern and nothing else: the lines, their order and their
|
|
396
|
+
formatting are byte-identical -- including one formatting bug that is
|
|
397
|
+
preserved deliberately.
|
|
398
|
+
|
|
399
|
+
**The mask file has no line terminators.** ``:313`` declares twenty ``%d``
|
|
400
|
+
conversions but ``:315`` supplies nineteen values (``timeWord``, sixteen mask
|
|
401
|
+
bits, ``timeStart``, ``timeEnd``). MATLAB's ``fprintf`` stops as soon as the
|
|
402
|
+
data runs out, emitting the literal text up to the unfilled conversion and
|
|
403
|
+
dropping everything after it -- so each record ends ``..., `` and the trailing
|
|
404
|
+
``' \\n'`` is never written. Every mask record in a run therefore lands on one
|
|
405
|
+
single line. Reproduced; a file that suddenly gained newlines would not
|
|
406
|
+
compare against the reference.
|
|
407
|
+
|
|
408
|
+
Files are opened in append mode, as MATLAB's ``fopen(...,'a')`` does: a second
|
|
409
|
+
run over the same input adds to them rather than replacing them.
|
|
410
|
+
"""
|
|
411
|
+
|
|
412
|
+
def __init__(self, outfilename, *, enabled: bool = True, output_txt: bool = False,
|
|
413
|
+
output_txt_path: str | None = None) -> None:
|
|
414
|
+
self.outfilename = os.fspath(outfilename)
|
|
415
|
+
self.enabled = enabled
|
|
416
|
+
self.output_txt_enabled = output_txt
|
|
417
|
+
# ``:215`` redirects into ``output.txt`` relative to MATLAB's cwd, so the
|
|
418
|
+
# faithful default is the cwd. A parallel worker overrides it with its
|
|
419
|
+
# own part file so the lines can be merged in record order (found
|
|
420
|
+
# 2026-09-06: every worker was appending to the cwd file directly, in
|
|
421
|
+
# completion order, and the merge was looking for a part file nobody
|
|
422
|
+
# wrote -- see tests/test_spec_output_txt.py).
|
|
423
|
+
self.output_txt_path = output_txt_path or "output.txt"
|
|
424
|
+
self._nv: list[str] = []
|
|
425
|
+
self._tas: list[str] = []
|
|
426
|
+
self._mask: list[str] = []
|
|
427
|
+
self._output: list[str] = []
|
|
428
|
+
|
|
429
|
+
def nv(self, timehhmmss, nv_word) -> None:
|
|
430
|
+
"""``:209-212`` -- ``'%f, %d\\n'``."""
|
|
431
|
+
if self.enabled:
|
|
432
|
+
self._nv.append(f"{timehhmmss:f}, {int(nv_word):d}\n")
|
|
433
|
+
|
|
434
|
+
def tas(self, timehhmmss, tas, time, n_twm, n_scm, n_hol, n_vol, n_vpd, n_hpd) -> None:
|
|
435
|
+
"""``:300-303`` -- ``'%f, %f, %f, %d, %d, %d, %d, %d, %d\\n'``.
|
|
436
|
+
|
|
437
|
+
``:291`` reads ``tas`` as a MATLAB single with no accept/reject gate
|
|
438
|
+
(unlike v3.5's ``update_tas``), and ``:302`` builds the row as one array
|
|
439
|
+
``[timehhmmss tas time nTWM ...]``: once any element of a MATLAB array is
|
|
440
|
+
single, the whole array is, so ``timehhmmss`` and ``time`` are also
|
|
441
|
+
rounded to float32 here -- ``123454.999`` prints ``123455.000000`` and a
|
|
442
|
+
``time`` counter above 2**24 loses its low bits. Mirrors
|
|
443
|
+
``arrayprobe_uiops.spec.SidecarWriterV35.tas``, unconditionally rather than
|
|
444
|
+
gated, because v3.1.4 has no gate to be unconditional about.
|
|
445
|
+
"""
|
|
446
|
+
if self.enabled:
|
|
447
|
+
self._tas.append(
|
|
448
|
+
f"{_matlab_f(_as_single(timehhmmss))}, {_matlab_f(_as_single(tas))}, "
|
|
449
|
+
f"{_matlab_f(_as_single(time))}, "
|
|
450
|
+
f"{int(n_twm):d}, {int(n_scm):d}, {int(n_hol):d}, "
|
|
451
|
+
f"{int(n_vol):d}, {int(n_vpd):d}, {int(n_hpd):d}\n"
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
def mask(self, time_word, mask_bits, time_start, time_end) -> None:
|
|
455
|
+
"""``:313-316`` -- nineteen values into twenty conversions. See the class docstring."""
|
|
456
|
+
if self.enabled:
|
|
457
|
+
values = [int(time_word), *(int(b) for b in mask_bits), int(time_start), int(time_end)]
|
|
458
|
+
self._mask.append(", ".join(str(v) for v in values) + ", ")
|
|
459
|
+
|
|
460
|
+
def output_txt(self, n_h, n_v) -> None:
|
|
461
|
+
"""``:215`` -- ``system('echo nH nV >> output.txt')``, without the process spawn."""
|
|
462
|
+
if self.output_txt_enabled:
|
|
463
|
+
self._output.append(f"{int(n_h)} {int(n_v)}\n")
|
|
464
|
+
|
|
465
|
+
def flush(self) -> None:
|
|
466
|
+
"""Append the buffered lines to the three sidecars, then drop the buffers.
|
|
467
|
+
|
|
468
|
+
This is the only place the files are touched. MATLAB opens, writes and
|
|
469
|
+
closes per event (``:209-212``, ``:300-303``, ``:313-316``); buffering
|
|
470
|
+
and flushing produces the identical bytes in the identical order, and
|
|
471
|
+
the append mode is what makes that true across several flushes and
|
|
472
|
+
across a second run over the same input.
|
|
473
|
+
|
|
474
|
+
A sidecar with nothing buffered is not created, which matches MATLAB:
|
|
475
|
+
a run that never reaches an ``NV`` event writes no ``.NV.csv`` at all.
|
|
476
|
+
Idempotent -- calling it twice writes nothing the second time.
|
|
477
|
+
"""
|
|
478
|
+
for suffix, lines in (
|
|
479
|
+
(".NV.csv", self._nv),
|
|
480
|
+
(".tas.csv", self._tas),
|
|
481
|
+
(".MK.csv", self._mask),
|
|
482
|
+
):
|
|
483
|
+
if lines:
|
|
484
|
+
with open(self.outfilename + suffix, "a", newline="") as fh:
|
|
485
|
+
fh.writelines(lines)
|
|
486
|
+
lines.clear()
|
|
487
|
+
if self._output:
|
|
488
|
+
with open(self.output_txt_path, "a", newline="") as fh:
|
|
489
|
+
fh.writelines(self._output)
|
|
490
|
+
self._output.clear()
|
|
491
|
+
|
|
492
|
+
def __enter__(self) -> SidecarWriter:
|
|
493
|
+
return self
|
|
494
|
+
|
|
495
|
+
def __exit__(self, *exc) -> None:
|
|
496
|
+
self.flush()
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
# --------------------------------------------------------------------------
|
|
500
|
+
# Record iteration
|
|
501
|
+
# --------------------------------------------------------------------------
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def iter_record_windows(path, start: int = 0, stop: int | None = None):
|
|
505
|
+
"""Yield ``(RecordHeader, buf)`` for each primary record, MATLAB's way.
|
|
506
|
+
|
|
507
|
+
``start``/``stop`` select a half-open range of primary records without
|
|
508
|
+
building the ones before it. The default is the whole file, which is what
|
|
509
|
+
every existing caller gets. The range exists for the parallel decode: a
|
|
510
|
+
worker assigned windows ``[a, b)`` must be able to reach window *a* without
|
|
511
|
+
paying for the *a* windows before it, and with a memory map that costs
|
|
512
|
+
nothing -- record *i* is at a computable offset, so no scan is needed to
|
|
513
|
+
find it. **These are 0-based**, unlike the rest of this port's public
|
|
514
|
+
surface: they index this port's own window range, added for the parallel
|
|
515
|
+
decode, not a MATLAB array -- so the global "every public index is
|
|
516
|
+
MATLAB 1-based" convention (``docs/09-conventions.md``) does
|
|
517
|
+
not apply to them, and this is the one place that says so explicitly.
|
|
518
|
+
|
|
519
|
+
A worker reads one record **beyond** its last window, because window
|
|
520
|
+
``b-1`` is built from records ``b-1`` and ``b``. That overlap is what makes
|
|
521
|
+
the ranges independent rather than merely adjacent.
|
|
522
|
+
|
|
523
|
+
Reproduces ``read_binary_SPEC.m:83-160``: read records *N* and *N+1*,
|
|
524
|
+
concatenate their 2048-word image buffers into the 4096-word decode window,
|
|
525
|
+
then advance by one record. **The final record is never a primary** -- the
|
|
526
|
+
loop probes one byte past the pair and breaks -- so a file of *n* records
|
|
527
|
+
yields *n-1* windows. Preserved; see the module docstring, point 2.
|
|
528
|
+
|
|
529
|
+
**A trailing partial record changes that count, and the window is short, not
|
|
530
|
+
padded.** The EOF probe fails only when the byte it reads is past the end,
|
|
531
|
+
so bytes after the last whole record keep the loop going for one more pair:
|
|
532
|
+
the last whole record becomes a primary, continued by whatever
|
|
533
|
+
``fread(fid,2048,'uint16')`` returns from the partial one (none at all when
|
|
534
|
+
fewer than 18 bytes remain). A file of *n* whole records plus any tail
|
|
535
|
+
therefore yields *n* windows. A file shorter than one record yields a single
|
|
536
|
+
window whose primary is itself short; the scan then indexes past it, and
|
|
537
|
+
that raises from :func:`_at` where MATLAB's ``buf(iii)`` dies. An empty file,
|
|
538
|
+
or one too short to hold a data word, raises here: ``get_img`` receives an
|
|
539
|
+
empty ``buf`` and MATLAB dies at ``buf(1)``. All measured under Octave on
|
|
540
|
+
both vendored trees (a reader edge-case Octave test).
|
|
541
|
+
"""
|
|
542
|
+
size = os.path.getsize(path)
|
|
543
|
+
n_records, tail = divmod(size, RECORD_BYTES)
|
|
544
|
+
n_windows = record_window_count(path)
|
|
545
|
+
lo = max(0, start)
|
|
546
|
+
hi = n_windows if stop is None else min(stop, n_windows)
|
|
547
|
+
if hi <= lo:
|
|
548
|
+
return
|
|
549
|
+
if n_records == 0:
|
|
550
|
+
# The only window: a primary shorter than one record, nothing after it.
|
|
551
|
+
n_words = _data_words_in(size)
|
|
552
|
+
if n_words == 0:
|
|
553
|
+
raise MatlabIndexError(
|
|
554
|
+
f"buf(1) exceeds the 0-word decode window: a {size}-byte file holds no "
|
|
555
|
+
"image word, and read_binary_SPEC.m's get_img indexes buf(1) regardless.")
|
|
556
|
+
raw = np.fromfile(path, dtype="<u2", count=HEADER_WORDS + n_words)
|
|
557
|
+
header = RecordHeader(*(int(v) for v in raw[:HEADER_WORDS]))
|
|
558
|
+
yield header, raw[HEADER_WORDS:].astype(np.int64)
|
|
559
|
+
return
|
|
560
|
+
words = np.memmap(path, dtype="<u2", mode="r", shape=(n_records, RECORD_WORDS))
|
|
561
|
+
tail_words = None
|
|
562
|
+
if tail:
|
|
563
|
+
n_tail = _data_words_in(tail)
|
|
564
|
+
tail_words = np.fromfile(
|
|
565
|
+
path, dtype="<u2", count=n_tail,
|
|
566
|
+
offset=n_records * RECORD_BYTES + 2 * HEADER_WORDS) if n_tail else np.zeros(0, "<u2")
|
|
567
|
+
|
|
568
|
+
for i in range(lo, hi):
|
|
569
|
+
head = words[i, :HEADER_WORDS]
|
|
570
|
+
header = RecordHeader(*(int(v) for v in head))
|
|
571
|
+
primary = words[i, HEADER_WORDS : HEADER_WORDS + DATA_WORDS]
|
|
572
|
+
if i + 1 < n_records:
|
|
573
|
+
buf = np.concatenate(
|
|
574
|
+
(primary, words[i + 1, HEADER_WORDS : HEADER_WORDS + DATA_WORDS]))
|
|
575
|
+
elif tail_words is not None:
|
|
576
|
+
buf = np.concatenate((primary, tail_words))
|
|
577
|
+
else:
|
|
578
|
+
# A one-record file: that record still enters the loop once, with a
|
|
579
|
+
# short (2048-word) window.
|
|
580
|
+
buf = np.asarray(primary)
|
|
581
|
+
yield header, buf.astype(np.int64)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _data_words_in(n_bytes: int) -> int:
|
|
585
|
+
"""Image words ``readRecord`` gets from a record of ``n_bytes`` bytes: the
|
|
586
|
+
eight header ``fread`` calls take the first 16, ``fread(fid,2048,'uint16')``
|
|
587
|
+
takes whole words after that, and an odd byte is left over."""
|
|
588
|
+
return min(DATA_WORDS, max(0, (n_bytes - 2 * HEADER_WORDS) // 2))
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def record_window_count(path) -> int:
|
|
592
|
+
"""How many decode windows ``read_binary_SPEC.m``'s loop makes of this file.
|
|
593
|
+
|
|
594
|
+
*n* whole records give *n-1* (the last is never a primary), one whole record
|
|
595
|
+
gives 1, and *n* whole records followed by a partial one give *n*: the
|
|
596
|
+
partial record keeps the EOF probe from failing for one more pair. A file
|
|
597
|
+
with no whole record gives 1, the window MATLAB builds and then dies on
|
|
598
|
+
unless its primary holds enough words -- see :func:`iter_record_windows`.
|
|
599
|
+
"""
|
|
600
|
+
n_records, tail = divmod(os.path.getsize(path), RECORD_BYTES)
|
|
601
|
+
if n_records == 0:
|
|
602
|
+
return 1
|
|
603
|
+
if tail:
|
|
604
|
+
return n_records
|
|
605
|
+
return max(1, n_records - 1)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
# Since 2026-09-15 this heartbeat is the one library message that
|
|
609
|
+
# cannot simply move behind ``arrayprobe.cli``'s handler (see
|
|
610
|
+
# ``_report_part_progress`` below) -- it runs inside a ``ProcessPoolExecutor``
|
|
611
|
+
# worker, a fresh interpreter on Windows' ``spawn`` start method that never
|
|
612
|
+
# sees whatever ``arrayprobe.cli`` configured in the parent process. Its own
|
|
613
|
+
# logger is used only to build the :class:`logging.LogRecord` (never given a
|
|
614
|
+
# persistent handler, and ``propagate = False`` so nothing here can double
|
|
615
|
+
# into a caller-configured "arrayprobe" handler) -- a bare ``import
|
|
616
|
+
# arrayprobe`` still installs nothing (this only runs when
|
|
617
|
+
# ``report_every > 0`` is passed explicitly, unchanged from the old
|
|
618
|
+
# ``print``).
|
|
619
|
+
_progress_logger = logging.getLogger(f"{__name__}._report_part_progress")
|
|
620
|
+
_progress_logger.propagate = False
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _report_part_progress(label: str, done: int, span: int, unit: str = "windows") -> None:
|
|
624
|
+
"""One liveness line from a part process to the stdout it inherited.
|
|
625
|
+
|
|
626
|
+
A part runs in a ``ProcessPoolExecutor`` child, whose stdout is the parent's
|
|
627
|
+
fd 1 -- under ``scripts/run_flight.py`` that is the worker's own log, the file
|
|
628
|
+
``_await_workers`` watches for growth (measured 2026-09-13 through the same
|
|
629
|
+
``Popen(stdout=file)`` chain ``_spawn_worker`` uses). A fresh
|
|
630
|
+
:class:`logging.StreamHandler` bound to the *current* ``sys.stdout`` is
|
|
631
|
+
built on every call, deliberately never cached: the old ``print`` looked
|
|
632
|
+
up ``sys.stdout`` fresh on every call too (that is what let a test
|
|
633
|
+
redirect it mid-run), and a handler cached from the first call would keep
|
|
634
|
+
writing to whatever stream was current *then* -- exactly the bug a
|
|
635
|
+
resident handler would introduce and the tests catch. ``handler.emit``
|
|
636
|
+
flushes unconditionally, the same load-bearing property the old
|
|
637
|
+
``print(..., flush=True)`` had: a file-backed stdout is block-buffered,
|
|
638
|
+
and an unflushed line would sit in the buffer until the part exits, which
|
|
639
|
+
is exactly the silence this exists to end. ``print`` was a no-op when
|
|
640
|
+
``sys.stdout`` was ``None`` (a handle-less child) because ``print`` checks
|
|
641
|
+
that itself; ``StreamHandler`` does not -- passing ``None`` makes it fall
|
|
642
|
+
back to ``sys.stderr`` instead of doing nothing -- so that check is made
|
|
643
|
+
explicit here to keep the same no-op behaviour.
|
|
644
|
+
|
|
645
|
+
The shape ``[HH:MM:SS] ...part pNNN n/N windows`` matches the runner's own
|
|
646
|
+
``log()`` lines, and deliberately does NOT match the run monitor's
|
|
647
|
+
pattern for a cumulative count (``...<digits> records``).
|
|
648
|
+
"""
|
|
649
|
+
if sys.stdout is None:
|
|
650
|
+
return
|
|
651
|
+
record = _progress_logger.makeRecord(
|
|
652
|
+
_progress_logger.name, logging.INFO, __file__, 0,
|
|
653
|
+
"[%s] ...part %s %d/%d %s",
|
|
654
|
+
(f"{datetime.now():%H:%M:%S}", label, done, span, unit),
|
|
655
|
+
None,
|
|
656
|
+
)
|
|
657
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
658
|
+
handler.setFormatter(logging.Formatter("%(message)s"))
|
|
659
|
+
handler.emit(record)
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _merge_sidecars(parts, outfilename, *, output_txt: bool) -> None:
|
|
663
|
+
"""Concatenate the part sidecars in range order onto the real ones.
|
|
664
|
+
|
|
665
|
+
``SidecarWriter`` opens in append mode, matching MATLAB's
|
|
666
|
+
``fopen(..., 'a')``, so this appends rather than replaces -- the same
|
|
667
|
+
behaviour a second serial run over the same input would have.
|
|
668
|
+
"""
|
|
669
|
+
# (suffix of the part file, path the merged bytes are appended to). The
|
|
670
|
+
# ``output.txt`` lines go to the cwd, exactly where the serial writer and
|
|
671
|
+
# MATLAB's ``:215`` shell redirect put them -- not beside the output file.
|
|
672
|
+
targets = [(s, outfilename + "." + s) for s in ("tas.csv", "NV.csv", "MK.csv")]
|
|
673
|
+
if output_txt:
|
|
674
|
+
targets.append(("txt", "output.txt"))
|
|
675
|
+
for suffix, target in targets:
|
|
676
|
+
chunks = []
|
|
677
|
+
for part in sorted(parts, key=lambda p: p["lo"]):
|
|
678
|
+
path = part["prefix"] + ".sc." + suffix
|
|
679
|
+
if os.path.exists(path):
|
|
680
|
+
with open(path, "rb") as fh:
|
|
681
|
+
chunks.append(fh.read())
|
|
682
|
+
if chunks:
|
|
683
|
+
with open(target, "ab") as fh:
|
|
684
|
+
fh.write(b"".join(chunks))
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
class SpawnRetryWarning(RuntimeWarning):
|
|
688
|
+
"""A parallel decode's worker pool died before any task ran, and the whole
|
|
689
|
+
pool was started again from a fresh temporary directory.
|
|
690
|
+
|
|
691
|
+
Emitted once per retry so a log shows a degraded start even though the bytes
|
|
692
|
+
written are those of a first-attempt success. Nothing computed changes; only
|
|
693
|
+
whether the opt-in speed path completes or raises.
|
|
694
|
+
|
|
695
|
+
Background: on Windows, ``ProcessPoolExecutor``'s spawned workers have been
|
|
696
|
+
observed (2026-09-10/11) dying at their first call-queue semaphore acquire
|
|
697
|
+
with ``OSError: [WinError 6] The handle is invalid``, which
|
|
698
|
+
``concurrent.futures`` reports to the parent as ``BrokenProcessPool`` with no
|
|
699
|
+
informative ``__cause__``. The root cause is **not established** -- a probe that ran
|
|
700
|
+
48 workers under heavy load without reproducing it --
|
|
701
|
+
so this retry treats
|
|
702
|
+
the death as transient rather than claiming to diagnose it.
|
|
703
|
+
"""
|