arrayprobe 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. arrayprobe/__init__.py +219 -0
  2. arrayprobe/__main__.py +19 -0
  3. arrayprobe/_v314_lazy.py +48 -0
  4. arrayprobe/ai_ready.py +212 -0
  5. arrayprobe/attributed_export.py +1333 -0
  6. arrayprobe/authordefaults.py +267 -0
  7. arrayprobe/cli.py +3510 -0
  8. arrayprobe/combine.py +12 -0
  9. arrayprobe/compare.py +950 -0
  10. arrayprobe/config.py +1239 -0
  11. arrayprobe/constants.py +12 -0
  12. arrayprobe/count_closure.py +204 -0
  13. arrayprobe/diagnostic_views.py +769 -0
  14. arrayprobe/diode_report.py +265 -0
  15. arrayprobe/driver/__init__.py +5 -0
  16. arrayprobe/driver/_load_record.py +331 -0
  17. arrayprobe/driver/preflight_inputs.py +250 -0
  18. arrayprobe/driver/reprocess.py +553 -0
  19. arrayprobe/driver/run_flight.py +8166 -0
  20. arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
  21. arrayprobe/dropsize.py +519 -0
  22. arrayprobe/friendly.py +206 -0
  23. arrayprobe/geometry/__init__.py +77 -0
  24. arrayprobe/geometry/min_rectangle.py +92 -0
  25. arrayprobe/intarr.py +12 -0
  26. arrayprobe/intarr_analysis.py +16 -0
  27. arrayprobe/intarr_plots.py +12 -0
  28. arrayprobe/inventory.py +129 -0
  29. arrayprobe/jit_kernels.py +344 -0
  30. arrayprobe/lwc.py +44 -0
  31. arrayprobe/masks.py +349 -0
  32. arrayprobe/matio.py +410 -0
  33. arrayprobe/matlab_compat.py +13 -0
  34. arrayprobe/ncio.py +26 -0
  35. arrayprobe/particle.py +55 -0
  36. arrayprobe/particle_perimeter.py +12 -0
  37. arrayprobe/products.py +78 -0
  38. arrayprobe/profiles.py +179 -0
  39. arrayprobe/provenance.py +21 -0
  40. arrayprobe/py.typed +11 -0
  41. arrayprobe/readers/__init__.py +9 -0
  42. arrayprobe/readers/dmt.py +603 -0
  43. arrayprobe/readers/mask_csv.py +12 -0
  44. arrayprobe/readers/pms.py +12 -0
  45. arrayprobe/readers/sea.py +433 -0
  46. arrayprobe/readers/tasinfo.py +12 -0
  47. arrayprobe/regimes.py +507 -0
  48. arrayprobe/render.py +728 -0
  49. arrayprobe/reproduce_report.py +149 -0
  50. arrayprobe/review_agreement.py +135 -0
  51. arrayprobe/review_sampling.py +327 -0
  52. arrayprobe/run_page.py +624 -0
  53. arrayprobe/sample_area.py +12 -0
  54. arrayprobe/selector.py +206 -0
  55. arrayprobe/sizing.py +151 -0
  56. arrayprobe/time_convert.py +12 -0
  57. arrayprobe/timing_closure.py +141 -0
  58. arrayprobe/tools/__init__.py +27 -0
  59. arrayprobe/tools/make_demo_flight.py +1089 -0
  60. arrayprobe/tools/make_tas_file.py +760 -0
  61. arrayprobe/tools/probe_comparison.py +569 -0
  62. arrayprobe/tools/synthetic_truth.py +698 -0
  63. arrayprobe/tools/tas_sources.py +705 -0
  64. arrayprobe/triage_context.py +488 -0
  65. arrayprobe/triage_server.py +5215 -0
  66. arrayprobe/tune/__init__.py +15 -0
  67. arrayprobe/tune/diodes.py +400 -0
  68. arrayprobe/tune/distributions.py +300 -0
  69. arrayprobe/tune/sample.py +243 -0
  70. arrayprobe/tune/score.py +230 -0
  71. arrayprobe/tune/settings.py +354 -0
  72. arrayprobe/validate_by_condition.py +208 -0
  73. arrayprobe/validation_report.py +166 -0
  74. arrayprobe-0.1.0.dist-info/METADATA +260 -0
  75. arrayprobe-0.1.0.dist-info/RECORD +189 -0
  76. arrayprobe-0.1.0.dist-info/WHEEL +5 -0
  77. arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
  78. arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
  79. arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
  80. arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
  81. arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
  82. arrayprobe_soda2/__init__.py +131 -0
  83. arrayprobe_soda2/angles.py +143 -0
  84. arrayprobe_soda2/aspect_ratio.py +541 -0
  85. arrayprobe_soda2/backfill.py +100 -0
  86. arrayprobe_soda2/binary_dof.py +181 -0
  87. arrayprobe_soda2/buildindex.py +113 -0
  88. arrayprobe_soda2/decompress_dmt.py +285 -0
  89. arrayprobe_soda2/enhancement_hooks.py +275 -0
  90. arrayprobe_soda2/export_ascii.py +732 -0
  91. arrayprobe_soda2/export_ncdf.py +683 -0
  92. arrayprobe_soda2/export_ncdf_raf.py +396 -0
  93. arrayprobe_soda2/fillholes.py +161 -0
  94. arrayprobe_soda2/find_radius.py +105 -0
  95. arrayprobe_soda2/findsize.py +407 -0
  96. arrayprobe_soda2/fit_poisson.py +170 -0
  97. arrayprobe_soda2/fix2dimage.py +63 -0
  98. arrayprobe_soda2/fixraking.py +162 -0
  99. arrayprobe_soda2/fixstuckbits.py +146 -0
  100. arrayprobe_soda2/hvps4_read_frame.py +121 -0
  101. arrayprobe_soda2/jit_kernels.py +152 -0
  102. arrayprobe_soda2/label_blobs.py +177 -0
  103. arrayprobe_soda2/min_circle_fast.py +320 -0
  104. arrayprobe_soda2/particlesort.py +703 -0
  105. arrayprobe_soda2/pbp_writer.py +558 -0
  106. arrayprobe_soda2/poisson_spot_correct.py +183 -0
  107. arrayprobe_soda2/princomp.py +107 -0
  108. arrayprobe_soda2/probespecs.py +361 -0
  109. arrayprobe_soda2/process_2d.py +1364 -0
  110. arrayprobe_soda2/process_2d_parallel.py +626 -0
  111. arrayprobe_soda2/process_hk.py +512 -0
  112. arrayprobe_soda2/processbuffer_2dc.py +155 -0
  113. arrayprobe_soda2/processbuffer_cip.py +213 -0
  114. arrayprobe_soda2/processbuffer_f2dc.py +139 -0
  115. arrayprobe_soda2/processbuffer_spec.py +441 -0
  116. arrayprobe_soda2/processbuffer_tail.py +350 -0
  117. arrayprobe_soda2/pth_readers.py +245 -0
  118. arrayprobe_soda2/py.typed +11 -0
  119. arrayprobe_soda2/read2dbuffer.py +371 -0
  120. arrayprobe_soda2/reject.py +246 -0
  121. arrayprobe_soda2/reprocess_pbp.py +156 -0
  122. arrayprobe_soda2/sample_area.py +264 -0
  123. arrayprobe_soda2/save_writer.py +480 -0
  124. arrayprobe_soda2/sea.py +324 -0
  125. arrayprobe_soda2/spec_absolutepointers.py +109 -0
  126. arrayprobe_soda2/spec_decompress.py +203 -0
  127. arrayprobe_soda2/spec_index.py +476 -0
  128. arrayprobe_soda2/spec_read_frame.py +286 -0
  129. arrayprobe_soda2/spec_read_hk.py +301 -0
  130. arrayprobe_soda2/spec_readint.py +127 -0
  131. arrayprobe_soda2/timeconv.py +77 -0
  132. arrayprobe_soda2/update_op.py +101 -0
  133. arrayprobe_uiops/__init__.py +45 -0
  134. arrayprobe_uiops/combine.py +192 -0
  135. arrayprobe_uiops/combine_fork.py +359 -0
  136. arrayprobe_uiops/constants.py +830 -0
  137. arrayprobe_uiops/decode_naming.py +113 -0
  138. arrayprobe_uiops/diode_mask.py +250 -0
  139. arrayprobe_uiops/engine_absence.py +41 -0
  140. arrayprobe_uiops/export_oap.py +325 -0
  141. arrayprobe_uiops/geometry_core.py +366 -0
  142. arrayprobe_uiops/habit.py +749 -0
  143. arrayprobe_uiops/habit_core.py +248 -0
  144. arrayprobe_uiops/hollow_size_rule.py +376 -0
  145. arrayprobe_uiops/imgproc.py +2081 -0
  146. arrayprobe_uiops/imgproc_core.py +275 -0
  147. arrayprobe_uiops/intarr.py +167 -0
  148. arrayprobe_uiops/intarr_analysis.py +569 -0
  149. arrayprobe_uiops/intarr_plots.py +119 -0
  150. arrayprobe_uiops/jit_kernels.py +430 -0
  151. arrayprobe_uiops/lwc.py +70 -0
  152. arrayprobe_uiops/matlab_compat.py +860 -0
  153. arrayprobe_uiops/measure.py +346 -0
  154. arrayprobe_uiops/min_circle.py +204 -0
  155. arrayprobe_uiops/min_ellipse.py +161 -0
  156. arrayprobe_uiops/min_rectangle.py +200 -0
  157. arrayprobe_uiops/ncar_2dc_timing.py +100 -0
  158. arrayprobe_uiops/ncio.py +810 -0
  159. arrayprobe_uiops/oap_read.py +228 -0
  160. arrayprobe_uiops/particle.py +51 -0
  161. arrayprobe_uiops/particle_perimeter.py +94 -0
  162. arrayprobe_uiops/particle_physics.py +199 -0
  163. arrayprobe_uiops/pecan_params.py +134 -0
  164. arrayprobe_uiops/probe_cases.py +298 -0
  165. arrayprobe_uiops/product_sanity.py +337 -0
  166. arrayprobe_uiops/profile.py +71 -0
  167. arrayprobe_uiops/profiles.py +756 -0
  168. arrayprobe_uiops/provenance.py +804 -0
  169. arrayprobe_uiops/py.typed +11 -0
  170. arrayprobe_uiops/qc.py +169 -0
  171. arrayprobe_uiops/readers/__init__.py +8 -0
  172. arrayprobe_uiops/readers/mask_csv.py +74 -0
  173. arrayprobe_uiops/readers/pms.py +239 -0
  174. arrayprobe_uiops/readers/tasinfo.py +57 -0
  175. arrayprobe_uiops/rect_ellipse.py +129 -0
  176. arrayprobe_uiops/register_image_assisted.py +25 -0
  177. arrayprobe_uiops/reject.py +501 -0
  178. arrayprobe_uiops/reject_core.py +220 -0
  179. arrayprobe_uiops/sample_area.py +93 -0
  180. arrayprobe_uiops/sizedist.py +1923 -0
  181. arrayprobe_uiops/sizedist_core.py +814 -0
  182. arrayprobe_uiops/sizedist_tables.py +642 -0
  183. arrayprobe_uiops/spec.py +1094 -0
  184. arrayprobe_uiops/spec_core.py +703 -0
  185. arrayprobe_uiops/stray_pixel.py +103 -0
  186. arrayprobe_uiops/tas.py +191 -0
  187. arrayprobe_uiops/time_convert.py +41 -0
  188. uiops/__init__.py +402 -0
  189. uiops/py.typed +11 -0
@@ -0,0 +1,603 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """DMT probe raw decoder -- ``read_binary_DMT.m``.
3
+
4
+ The raw file is a flat sequence of **4112-byte records**: eight ``uint16`` of
5
+ timestamp (year, month, day, hour, minute, second, millisecond, weekday), then
6
+ 4096 bytes of a **byte-level run-length compressed** image block -- a
7
+ different compression scheme from the SPEC probes' own word-oriented one
8
+ (:mod:`arrayprobe.readers.spec`), even though the two share the same
9
+ downstream canvas convention (8 diode-words x 1700 slices, an 0xAA boundary
10
+ sentinel, ``-1`` padding beyond the last real slice) that ``imgProc_sm``
11
+ already expects.
12
+
13
+ **The compression scheme, read directly from ``:99-140`` since nothing else
14
+ documents it.** Each of the 4096 payload bytes is either a control byte or a
15
+ literal, walked left to right:
16
+
17
+ - **bit 5 set** (``byte & 0x20``) -- a marker. Consumes just this one byte;
18
+ nothing is decoded from it.
19
+ - **top two bits 00** -- a literal run: the next ``(byte & 0x1F) + 1`` bytes
20
+ are copied through unchanged.
21
+ - **top two bits 10** -- a zero run: ``(byte & 0x1F) + 1`` copies of ``0x00``,
22
+ with no further bytes consumed (the count is the whole payload).
23
+ - **top two bits 01** -- a fill run: ``(byte & 0x1F) + 1`` copies of ``0xFF``,
24
+ likewise self-contained.
25
+ - **top two bits 11** (and bit 5 clear) -- no-op; the byte is simply skipped.
26
+
27
+ **Two preserved quirks, both structural rather than incidental:**
28
+
29
+ 1. **The 4096th byte of every record is never read.** The control-byte scan
30
+ is bounded ``while i<4096`` (MATLAB, 1-based) -- the last payload byte can
31
+ only ever be a literal *inside* a run that was already truncated by the
32
+ ``i < length(bytes)`` guard in the literal-copy loop (:117), never a
33
+ control byte in its own right. This mirrors ``read_binary_SPEC.m``'s "last
34
+ record is never a primary" quirk in shape, though the mechanism differs.
35
+ 2. **The 8-byte reassembly is byte-reversed within each group.** ``:165-166``
36
+ builds each output word from ``decomp(dd+7), decomp(dd+6), ..., decomp(dd)``
37
+ -- descending, not ascending. Transcribed as read; a plausible-looking
38
+ ascending version would silently mirror every image horizontally.
39
+
40
+ After decompression, the code searches for the first run of **eight
41
+ consecutive sync bytes** and reassembles everything after it into 8-byte
42
+ groups -- the same canvas convention SPEC's ``get_img`` consumes, which is why
43
+ nothing downstream of this reader needs to know DMT and SPEC compress
44
+ differently. If a record decompresses to shorter than 1700 groups, row
45
+ ``len+1`` is set to the sentinel and rows beyond that to ``-1``, matching
46
+ :func:`arrayprobe.readers.spec._ImageCanvas`'s own tail convention.
47
+
48
+ **Four more preserved behaviours, each measured under Octave on the vendored
49
+ source** (``tests/test_reader_edge_octave.py::DmtAgainstOctave``):
50
+
51
+ 3. **A sync byte is any byte ``0xA0``-``0xAF``**, not only the sentinel
52
+ ``0xAA``: ``:148`` compares one hex digit of a char array (see
53
+ :func:`_sync_bytes`). ``exact_sync=True`` opts into the exact byte.
54
+ 4. **A record of 1700 groups or more writes the previous record's image.** The
55
+ canvas is rewritten only when the record is shorter (``:176``), so the
56
+ buffer goes out as the last shorter record left it (zeros before the first).
57
+ 5. **A record of 1-7 groups, or of none, stops the run** at ``:177``
58
+ (:class:`NonconformantAssignmentError`).
59
+ 6. **A truncated tail stops the run** unless it is under 20 bytes (the EOF
60
+ probe, ``:212-219``) or holds a 4095-byte payload (:func:`_tail_after`).
61
+ A record whose high hex digits hold no run of eight sync bytes stops it too
62
+ (:class:`DecompressionError`): the search then runs through the low digits
63
+ and indexes past the array.
64
+ """
65
+
66
+ from __future__ import annotations
67
+
68
+ import os
69
+
70
+ import numpy as np
71
+
72
+ from .. import ncio
73
+ from ..matlab_compat import MatlabIndexError
74
+
75
+ __all__ = ["DecompressionError", "NonconformantAssignmentError", "read_binary_DMT",
76
+ "read_binary_DMT_parallel"]
77
+
78
+ IMG_ROWLEN = 8
79
+ IMG_BLOCKLEN = 1700
80
+ _RECORD_BYTES = 4112
81
+ _PAYLOAD_BYTES = 4096
82
+ _SENTINEL = 0xAA
83
+
84
+ # :35-42. DMT's own header var types -- one field differs from SPEC's
85
+ # (`_TIME_VARS` in readers/spec.py): wkday is 'short' here, 'byte' there.
86
+ _TIME_VARS = (
87
+ ("year", "short"),
88
+ ("month", "byte"),
89
+ ("day", "byte"),
90
+ ("hour", "byte"),
91
+ ("minute", "byte"),
92
+ ("second", "byte"),
93
+ ("millisec", "short"),
94
+ ("wkday", "short"),
95
+ )
96
+ _TIME_FIELDS = tuple(name for name, _ in _TIME_VARS)
97
+ # :85-92's read order, which is also the write order above.
98
+ _HEADER_FIELDS = _TIME_FIELDS
99
+
100
+
101
+ class DecompressionError(ValueError):
102
+ """A record's decompressed stream has no run of eight sync bytes.
103
+
104
+ MATLAB's search (``:147-160``) has no exit for this case: it runs on
105
+ through the low hex digits of its char array and dies indexing past the
106
+ array, or, if it finds a run there, at ``:177`` (Octave-measured).
107
+ """
108
+
109
+
110
+ class NonconformantAssignmentError(ValueError):
111
+ """``read_binary_DMT.m:177`` dies: a record reassembles to 1-7 groups.
112
+
113
+ ``length`` of an *n*-by-8 matrix is ``max(n, 8)``, so for *n* < 8 the
114
+ assignment ``decomp_convert1(1:8,:) = decomp_convert`` puts *n* rows into
115
+ eight (Octave 11.3: ``=: nonconformant arguments (op1 is 8x8, op2 is 3x8)``).
116
+ Zero groups dies the same way under Octave, whose ``hex2dec`` of an empty
117
+ selection returns a scalar 0 and so makes a 1-by-8 row.
118
+ """
119
+
120
+
121
+ def _decompress_record(payload: np.ndarray) -> np.ndarray:
122
+ """``:94-140`` -- byte-level run-length expansion of one 4096-byte block.
123
+
124
+ ``payload`` is the raw ``uint8`` bytes (the ``bytes``/``data`` array in
125
+ the MATLAB, already as integer VALUES rather than the hex-string form the
126
+ MATLAB builds and re-parses -- an implementation difference with no
127
+ behavioural one, since ``dec2hex``/``hex2dec`` round-trip exactly).
128
+
129
+ Returns the decompressed byte values, a 1-D ``uint8`` array that may be
130
+ longer or shorter than 4096 depending on how many runs it contains.
131
+
132
+ The control scan's bound is the constant ``i<4096`` (``:108``), not the
133
+ payload's length, so a payload shorter than 4095 bytes -- the tail of a
134
+ truncated file -- is indexed past its end, and MATLAB dies at ``:109``'s
135
+ ``b1full(i,:)``. That raises :class:`~arrayprobe.matlab_compat.MatlabIndexError`
136
+ here. A 4095-byte payload decodes: its last control byte is at 4095.
137
+ """
138
+ n = len(payload)
139
+ out: list[int] = []
140
+ i = 0 # 0-based; MATLAB's `i` is 1-based, so this is MATLAB's i - 1.
141
+ while i < _PAYLOAD_BYTES - 1: # :108 -- MATLAB `while i<4096`, 1-based
142
+ if i >= n:
143
+ raise MatlabIndexError(
144
+ f"read_binary_DMT.m:109: b1full({i + 1},:) exceeds the {n}-byte payload "
145
+ "(a truncated record)")
146
+ b = int(payload[i])
147
+ i += 1
148
+ if b & 0x20: # :112 -- marker byte, consumes only itself
149
+ continue
150
+ count = (b & 0x1F) + 1 # :105, :116/:127/:133
151
+ top2 = b >> 6
152
+ if top2 == 0b00: # :114 -- literal run
153
+ for _ in range(count):
154
+ # :117 -- `if i < length(bytes)`, checked in MATLAB's 1-based
155
+ # `i` *after* it was advanced to the next byte to read. The
156
+ # 0-based equivalent excludes the payload's last byte: MATLAB
157
+ # never reads 1-based index n (Python 0-based n-1), so the
158
+ # guard here is `i >= n - 1`, not `i >= n`.
159
+ if i >= n - 1:
160
+ break
161
+ out.append(int(payload[i]))
162
+ i += 1
163
+ elif top2 == 0b10: # :125 -- zero run, no further bytes consumed
164
+ out.extend([0x00] * count)
165
+ elif top2 == 0b01: # :131 -- fill run, no further bytes consumed
166
+ out.extend([0xFF] * count)
167
+ # top2 == 0b11: :137 -- no-op, byte already consumed above
168
+ return np.asarray(out, dtype=np.uint8)
169
+
170
+
171
+ def _sync_bytes(decomp: np.ndarray, exact_sync: bool) -> np.ndarray:
172
+ """Which decompressed bytes the boundary search counts as ``'AA'``.
173
+
174
+ ``:148`` reads ``if decomp(i)=='AA'``, where ``decomp`` is an *N*-by-2
175
+ char array of hex-digit pairs. ``decomp(i)`` is a LINEAR index, so for
176
+ ``i <= N`` it is one character, the byte's high hex digit, and ``'A'=='AA'``
177
+ scalar-expands to ``[1 1]``, which ``if`` takes. The search therefore counts
178
+ every byte in ``0xA0``-``0xAF``, not only ``0xAA`` -- measured under Octave
179
+ (``tests/test_reader_edge_octave.py::DmtAgainstOctave``), the same predicate
180
+ ``read_binary_SEA.m:161`` has. ``exact_sync=True`` is the opt-in exact-byte
181
+ test, which is what the sentinel means and not what the MATLAB does.
182
+ """
183
+ if exact_sync:
184
+ return decomp == _SENTINEL
185
+ return (decomp & 0xF0) == 0xA0
186
+
187
+
188
+ def _find_boundary(decomp: np.ndarray, *, exact_sync: bool = False) -> int:
189
+ """``:144-160`` -- index (0-based) one past the first run of eight sync bytes.
190
+
191
+ See :func:`_sync_bytes` for which bytes count. MATLAB's search is bounded
192
+ only by its index: when the high digits hold no run it goes on through the
193
+ LOW hex digits (``decomp(N+1:2N)``) and then dies indexing past ``2N``;
194
+ a run it does find there leaves ``dd`` empty and dies at ``:177`` instead
195
+ (Octave-measured). Either way the record does not decode, so this raises
196
+ :class:`DecompressionError`.
197
+ """
198
+ accepted = _sync_bytes(decomp, exact_sync)
199
+ if len(accepted) >= 8:
200
+ # A run of >=8 True values starting at k is present when the
201
+ # 8-window sum at k equals 8 -- cheap, vectorized equivalent of the
202
+ # MATLAB's own running `count` scan.
203
+ window = np.convolve(accepted.astype(np.int64), np.ones(8, dtype=np.int64), mode="valid")
204
+ hit = np.flatnonzero(window == 8)
205
+ if hit.size:
206
+ return int(hit[0]) + 8 # one past the end of that 8-run
207
+ raise DecompressionError(
208
+ "no run of eight sync bytes in the decompressed record's high hex digits; "
209
+ "read_binary_DMT.m's search (:147-160) then runs through the low digits and "
210
+ "dies, at the index past the array or at :177"
211
+ )
212
+
213
+
214
+ def _reassemble(decomp: np.ndarray, start: int,
215
+ previous: np.ndarray | None = None) -> np.ndarray:
216
+ """``:162-180`` -- 8-byte groups from ``start`` to the end, byte-reversed
217
+ within each group, onto the 1700-row canvas ``decomp_convert1``.
218
+
219
+ ``decomp_convert1`` is allocated once (``:3``) and rewritten only inside
220
+ the branch taken when the decompressed record is shorter than 1700 groups
221
+ (``:176``). A record of 1700 groups or
222
+ more therefore writes the buffer as the previous record left it --
223
+ ``previous``, which is ``zeros(1700,8)`` before any record has filled it
224
+ -- and none of its own groups. A record of fewer than eight groups dies
225
+ at ``:177`` (:class:`NonconformantAssignmentError`). Both measured under
226
+ Octave.
227
+ """
228
+ n_groups = max(0, (len(decomp) - start) // 8)
229
+ if n_groups >= IMG_BLOCKLEN:
230
+ if previous is None:
231
+ return np.zeros((IMG_BLOCKLEN, IMG_ROWLEN), dtype=np.int64)
232
+ return previous
233
+ if n_groups < 8:
234
+ raise NonconformantAssignmentError(
235
+ f"read_binary_DMT.m:177: =: nonconformant arguments (op1 is 8x8, op2 is "
236
+ f"{max(n_groups, 1)}x8) -- the record reassembles to {n_groups} groups, and "
237
+ "length() of an n-by-8 matrix is 8 for n < 8")
238
+ canvas = np.full((IMG_BLOCKLEN, IMG_ROWLEN), -1, dtype=np.int64)
239
+ block = decomp[start : start + n_groups * 8].reshape(n_groups, 8)
240
+ canvas[:n_groups, :] = block[:, ::-1] # :165-166 -- descending within a group
241
+ canvas[n_groups, :] = _SENTINEL # :178
242
+ return canvas
243
+
244
+
245
+ def _decode_one(payload: np.ndarray, previous: np.ndarray | None = None, *,
246
+ exact_sync: bool = False) -> np.ndarray:
247
+ decomp = _decompress_record(payload)
248
+ start = _find_boundary(decomp, exact_sync=exact_sync)
249
+ return _reassemble(decomp, start, previous)
250
+
251
+
252
+ def _tail_after(pos: int, size: int) -> str:
253
+ """What ``:212-219``'s probe and the next pass make of the bytes after ``pos``.
254
+
255
+ The probe reads twenty bytes one at a time and stops the loop only when a
256
+ read fails, so fewer than 20 bytes end the file cleanly (``"end"``). With
257
+ 20 or more the loop reads another header and ``fread(fid,4096,'uchar')``:
258
+ a whole record decodes (``"record"``); a 4095-byte payload decodes too
259
+ (its last control byte is 4095); anything shorter dies at ``:109``
260
+ (``"die"``). Octave-measured (``tests/test_reader_edge_octave.py::DmtAgainstOctave``).
261
+ """
262
+ left = size - pos
263
+ if left < 20:
264
+ return "end"
265
+ if left - 16 >= _PAYLOAD_BYTES - 1:
266
+ return "record"
267
+ return "die"
268
+
269
+
270
+ class _ImageFile:
271
+ """One output file: the eight timestamp variables plus the packed image.
272
+
273
+ Structurally identical to ``readers.spec._ImageFile`` except for
274
+ ``wkday``'s type (see ``_TIME_VARS`` above) -- kept separate rather than
275
+ parametrizing the SPEC writer, since the two formats have no other reason
276
+ to share code and a shared writer would couple them for no benefit.
277
+ """
278
+
279
+ def __init__(self, filename, *, block: int = 256) -> None:
280
+ self.ncid = ncio.create(filename, "clobber")
281
+ dim_time = self.ncid.def_dim("time", ncio.NC_UNLIMITED)
282
+ dim_row = self.ncid.def_dim("ImgRowlen", IMG_ROWLEN)
283
+ dim_block = self.ncid.def_dim("ImgBlocklen", IMG_BLOCKLEN)
284
+ self.varids = [self.ncid.def_var(n, t, dim_time) for n, t in _TIME_VARS]
285
+ self.varid_data = self.ncid.def_var("data", "int", [dim_row, dim_block, dim_time])
286
+ self.ncid.end_def()
287
+ self.count = 0
288
+ self._block = block
289
+ self._times: list[tuple[int, ...]] = []
290
+ self._images: list[np.ndarray] = []
291
+
292
+ def append(self, header: dict, canvas: np.ndarray) -> None:
293
+ """Queue one decoded record, flushing once ``block`` have piled up.
294
+
295
+ ``count`` advances here, not at flush time: it is the record count
296
+ :func:`read_binary_DMT` returns, and that must describe what was
297
+ decoded rather than how the writes were batched.
298
+ """
299
+ self._times.append(tuple(header[f] for f in _TIME_FIELDS))
300
+ self._images.append(canvas)
301
+ self.count += 1
302
+ if len(self._images) >= self._block:
303
+ self.flush()
304
+
305
+ def flush(self) -> None:
306
+ """Write the queued records as one netCDF block, then empty the queue.
307
+
308
+ ``start`` is recovered from ``count`` rather than tracked separately,
309
+ so the record index stays a single fact. The comment below is the one
310
+ real difference from ``spec.py``'s otherwise identical writer, and it
311
+ is a difference in the *decoder's* output shape, not in this contract.
312
+ """
313
+ if not self._images:
314
+ return
315
+ start = self.count - len(self._images)
316
+ times = np.asarray(self._times, dtype=np.int64)
317
+ for k, varid in enumerate(self.varids):
318
+ self.ncid.put_var(varid, start, times.shape[0], times[:, k])
319
+ # canvas is already (1700, 8) = (ImgBlocklen, ImgRowlen); stacking
320
+ # records gives (n, 1700, 8) directly -- the on-disk order
321
+ # write_record_block wants, no transpose needed (unlike spec.py's
322
+ # writer, whose per-record images are (ImgRowlen, ImgBlocklen)).
323
+ block = np.stack(self._images)
324
+ ncio.write_record_block(self.ncid, self.varid_data, start, block)
325
+ self._times.clear()
326
+ self._images.clear()
327
+
328
+ def close(self) -> None:
329
+ """Flush whatever is still queued, then close the netCDF file.
330
+
331
+ Required, not tidying: an unflushed final partial batch would leave the
332
+ file short by up to ``block`` records with nothing downstream reporting
333
+ it -- ``imgProc_sm`` would just process a shorter flight.
334
+ """
335
+ self.flush()
336
+ self.ncid.close()
337
+
338
+
339
+ def _read_record(fh):
340
+ """``:85-94`` -- one header and up to 4096 payload bytes from ``fh``.
341
+
342
+ Returns ``(header, payload)``. A record too short to decode raises where
343
+ ``:109`` dies (see :func:`_decompress_record`); the check is made here,
344
+ before the header is unpacked, because a header cut short is only ever
345
+ followed by an empty payload.
346
+ """
347
+ chunk = fh.read(16) # :85-92, eight little-endian uint16
348
+ payload_bytes = fh.read(_PAYLOAD_BYTES) if len(chunk) == 16 else b"" # :94
349
+ if len(payload_bytes) < _PAYLOAD_BYTES - 1:
350
+ raise MatlabIndexError(
351
+ f"read_binary_DMT.m:109: b1full({len(payload_bytes) + 1},:) exceeds the "
352
+ f"{len(payload_bytes)}-byte payload (a truncated record)")
353
+ header = dict(zip(_HEADER_FIELDS, (int(v) for v in np.frombuffer(chunk, dtype="<u2")),
354
+ strict=True))
355
+ return header, np.frombuffer(payload_bytes, dtype=np.uint8)
356
+
357
+
358
+ def read_binary_DMT(infilename, outfilename, *, progress=None, # noqa: N802,N803
359
+ exact_sync: bool = False):
360
+ """``read_binary_DMT.m`` -- raw DMT probe file to ``<outfilename>``.
361
+
362
+ Unlike ``read_binary_SPEC`` in the earlier translation (not included in this package), DMT
363
+ writes one
364
+ output file (no H/V channel split -- the format has none) and the input
365
+ is a flat sequence of fixed 4112-byte records with no sliding window: the
366
+ MATLAB's ``while feof(fid)==0`` reads and decodes every record until end
367
+ of file, checked by trial-reading (and rewinding) the next 20 bytes
368
+ (``:212-219``) rather than by a record-count computed up front. The first
369
+ record is read unconditionally, so a file too short to hold one raises;
370
+ so does a tail of 20 bytes or more that is not a whole record (see
371
+ :func:`_tail_after`).
372
+
373
+ ``exact_sync`` (default ``False``, MATLAB's behaviour) makes the boundary
374
+ search count only the byte ``0xAA`` rather than every byte whose high hex
375
+ digit is ``A`` -- see :func:`_sync_bytes`.
376
+
377
+ Returns the number of records written.
378
+ """
379
+ out = _ImageFile(str(outfilename))
380
+ previous = None
381
+ try:
382
+ with open(infilename, "rb") as fh:
383
+ size = os.fstat(fh.fileno()).st_size
384
+ while True:
385
+ header, payload = _read_record(fh)
386
+ canvas = _decode_one(payload, previous, exact_sync=exact_sync)
387
+ previous = canvas
388
+ out.append(header, canvas)
389
+ if progress is not None:
390
+ progress(out.count)
391
+ # :211-219 -- trial-read the next 20 bytes to detect EOF.
392
+ if _tail_after(fh.tell(), size) == "end":
393
+ break
394
+ finally:
395
+ out.close()
396
+ return out.count
397
+
398
+
399
+ # ---------------------------------------------------------------------------
400
+ # Opt-in parallel decode. Port space: byte-identical, default serial, no new
401
+ # dependency. Byte identity: tests/test_dmt_parallel.py.
402
+ #
403
+ # ---------------------------------------------------------------------------
404
+
405
+
406
+ def _n_decodable_records(infilename) -> int:
407
+ """Whole records in the file, ``floor(size / 4112)``: the ones the parts
408
+ decode. What follows them -- nothing, a record's worth of 4111 bytes, or a
409
+ tail that stops the run -- is the parent's, after the merge
410
+ (:func:`_tail_after`).
411
+ """
412
+ return os.path.getsize(infilename) // _RECORD_BYTES
413
+
414
+
415
+ #: A canvas no record can produce (every real value is a byte or -1). A part
416
+ #: returns it for a record of 1700 groups or more whose image is the previous
417
+ #: record's, when that previous record belongs to an earlier part; the merge,
418
+ #: which sees the records in file order, substitutes it.
419
+ _STALE = np.full((IMG_BLOCKLEN, IMG_ROWLEN), -2, dtype=np.int64)
420
+
421
+
422
+ def _decode_dmt_range(args) -> dict:
423
+ """Worker: decode records ``[lo, hi)`` into ``.npy`` blocks under ``part``.
424
+
425
+ Spills every ``block`` records to disk, so a part never holds more than
426
+ ``block`` canvases. On the first exception at record ``k`` it stops and
427
+ returns the exception with ``k``, as the serial loop raises before
428
+ appending record ``k``.
429
+ """
430
+ infilename, part, lo, hi, block, report_every, *rest = args
431
+ exact_sync = bool(rest[0]) if rest else False
432
+ os.makedirs(part, exist_ok=True)
433
+ files: list[tuple[str, str]] = []
434
+ hdrs: list[np.ndarray] = []
435
+ imgs: list[np.ndarray] = []
436
+ fail_at = None
437
+ error = None
438
+ previous = _STALE # the image before this part's first record is not ours
439
+
440
+ def _spill() -> None:
441
+ j = len(files)
442
+ hp = os.path.join(part, f"h{j:06d}.npy")
443
+ ip = os.path.join(part, f"i{j:06d}.npy")
444
+ np.save(hp, np.stack(hdrs))
445
+ np.save(ip, np.stack(imgs))
446
+ files.append((hp, ip))
447
+ hdrs.clear()
448
+ imgs.clear()
449
+
450
+ with open(infilename, "rb") as fh:
451
+ fh.seek(lo * _RECORD_BYTES)
452
+ for k in range(lo, hi):
453
+ rec = fh.read(_RECORD_BYTES)
454
+ fields = np.frombuffer(rec[:16], dtype="<u2").astype(np.int64)
455
+ payload = np.frombuffer(rec[16:], dtype=np.uint8)
456
+ try:
457
+ canvas = _decode_one(payload, previous, exact_sync=exact_sync)
458
+ except Exception as exc: # noqa: BLE001 -- re-raised by the parent
459
+ fail_at, error = k, exc
460
+ break
461
+ previous = canvas
462
+ hdrs.append(fields)
463
+ imgs.append(canvas)
464
+ if len(imgs) >= block:
465
+ _spill()
466
+ done = k - lo + 1
467
+ if report_every and done % report_every == 0:
468
+ # The SPEC decoder's liveness helper (logging, flushed, fresh handler per
469
+ # call, no-op without a stdout), so the port keeps no bare print.
470
+ from arrayprobe_uiops.spec_core import _report_part_progress
471
+ _report_part_progress(os.path.basename(part), done, hi - lo, unit="records")
472
+ if imgs:
473
+ _spill()
474
+ return {"files": files, "fail_at": fail_at, "error": error}
475
+
476
+
477
+ def _merge_dmt_parts(parts, outfilename, progress, *, tail=None) -> int:
478
+ """Append every part's records, in file order, through one serial writer.
479
+
480
+ Reusing :class:`_ImageFile` with the serial append sequence keeps the
481
+ netCDF call sequence identical, not merely equivalent. A part's
482
+ :data:`_STALE` canvas becomes the image written before it, as the serial
483
+ loop's carried buffer would be. Stops at the lowest failing record, closes
484
+ the file (as the serial ``finally`` does) and re-raises that record's
485
+ exception.
486
+
487
+ ``tail``, ``(infilename, exact_sync)``, finishes the file after the whole
488
+ records the way the serial loop does: a 4111-byte record decodes, a
489
+ shorter tail of 20 bytes or more raises.
490
+ """
491
+ error = None
492
+ previous = None
493
+ out = _ImageFile(str(outfilename))
494
+ try:
495
+ for part in parts:
496
+ for hp, ip in part["files"]:
497
+ hdr = np.load(hp)
498
+ img = np.load(ip)
499
+ for row, canvas in zip(hdr, img, strict=True):
500
+ if canvas[0, 0] == _STALE[0, 0]:
501
+ canvas = (previous if previous is not None
502
+ else np.zeros((IMG_BLOCKLEN, IMG_ROWLEN), dtype=np.int64))
503
+ previous = canvas
504
+ header = dict(zip(_HEADER_FIELDS, (int(v) for v in row),
505
+ strict=True))
506
+ out.append(header, canvas)
507
+ if progress is not None:
508
+ progress(out.count)
509
+ if part["fail_at"] is not None:
510
+ error = part["error"]
511
+ break
512
+ if error is None and tail is not None:
513
+ infilename, exact_sync = tail
514
+ with open(infilename, "rb") as fh:
515
+ size = os.fstat(fh.fileno()).st_size
516
+ fh.seek(_n_decodable_records(infilename) * _RECORD_BYTES)
517
+ while _tail_after(fh.tell(), size) != "end":
518
+ header, payload = _read_record(fh)
519
+ canvas = _decode_one(payload, previous, exact_sync=exact_sync)
520
+ previous = canvas
521
+ out.append(header, canvas)
522
+ if progress is not None:
523
+ progress(out.count)
524
+ finally:
525
+ out.close()
526
+ if error is not None:
527
+ raise error
528
+ return out.count
529
+
530
+
531
+ def read_binary_DMT_parallel( # noqa: N802 -- matches the serial name
532
+ infilename,
533
+ outfilename,
534
+ *,
535
+ jobs: int,
536
+ workdir=None,
537
+ progress=None,
538
+ spawn_retries: int = 2,
539
+ report_every: int = 0,
540
+ block: int = 256,
541
+ exact_sync: bool = False,
542
+ ) -> int:
543
+ """:func:`read_binary_DMT` across ``jobs`` processes, byte-identical output.
544
+
545
+ Every DMT record decodes from its own 4112 bytes, so records split at any
546
+ multiple of 4112 with no priming; the one thing carried from record to
547
+ record, the image a record of 1700 groups or more repeats, is resolved in
548
+ the merge (:data:`_STALE`), and the bytes after the last whole record are
549
+ handled there too. ``jobs <= 1`` or a file of at most one
550
+ record delegates to the serial function. ``progress(count)`` is called
551
+ from the parent per record, the same sequence as serial. A decode failure
552
+ leaves the same partial file and raises the same exception as serial.
553
+ ``spawn_retries`` restarts a pool that died (``BrokenProcessPool``) from a
554
+ fresh temporary directory with ``spec.SpawnRetryWarning``, as
555
+ ``spec.read_binary_SPEC_parallel`` does. ``report_every`` (default 0,
556
+ silent) prints a liveness line per part every that many records.
557
+ """
558
+ import concurrent.futures
559
+ import concurrent.futures.process
560
+ import shutil
561
+ import tempfile
562
+ import time
563
+ import warnings
564
+
565
+ from arrayprobe_uiops.spec_core import SpawnRetryWarning
566
+
567
+ outfilename = os.fspath(outfilename)
568
+ n = _n_decodable_records(infilename)
569
+ if jobs <= 1 or n <= 1:
570
+ return read_binary_DMT(infilename, outfilename, progress=progress,
571
+ exact_sync=exact_sync)
572
+
573
+ jobs = min(jobs, n)
574
+ edges = [round(k * n / jobs) for k in range(jobs + 1)]
575
+ for attempt in range(spawn_retries + 1):
576
+ tmp = tempfile.mkdtemp(prefix="s2dmtparallel_", dir=workdir)
577
+ try:
578
+ tasks = [
579
+ (os.fspath(infilename), os.path.join(tmp, f"p{k:03d}"),
580
+ edges[k], edges[k + 1], block, report_every, exact_sync)
581
+ for k in range(jobs)
582
+ if edges[k + 1] > edges[k]
583
+ ]
584
+ try:
585
+ with concurrent.futures.ProcessPoolExecutor(
586
+ max_workers=len(tasks)) as pool:
587
+ parts = list(pool.map(_decode_dmt_range, tasks))
588
+ except concurrent.futures.process.BrokenProcessPool:
589
+ if attempt >= spawn_retries:
590
+ raise
591
+ warnings.warn(
592
+ f"parallel decode of {os.path.basename(os.fspath(infilename))}: "
593
+ f"the worker pool died before completing (attempt {attempt + 1} "
594
+ f"of {spawn_retries + 1}); restarting it from a fresh temporary "
595
+ "directory",
596
+ SpawnRetryWarning, stacklevel=2)
597
+ time.sleep(2.0 * (attempt + 1))
598
+ continue
599
+ return _merge_dmt_parts(parts, outfilename, progress,
600
+ tail=(os.fspath(infilename), exact_sync))
601
+ finally:
602
+ shutil.rmtree(tmp, ignore_errors=True)
603
+ raise AssertionError("unreachable") # pragma: no cover
@@ -0,0 +1,12 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ import sys as _sys
3
+ import typing as _typing
4
+
5
+ from arrayprobe_uiops.readers import mask_csv as _impl
6
+
7
+ # Static view for type checkers only: the alias below replaces this module at run time,
8
+ # so mypy would otherwise see an empty module. No run-time effect.
9
+ if _typing.TYPE_CHECKING:
10
+ from arrayprobe_uiops.readers.mask_csv import * # noqa: F403
11
+
12
+ _sys.modules[__name__] = _impl
@@ -0,0 +1,12 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ import sys as _sys
3
+ import typing as _typing
4
+
5
+ from arrayprobe_uiops.readers import pms as _impl
6
+
7
+ # Static view for type checkers only: the alias below replaces this module at run time,
8
+ # so mypy would otherwise see an empty module. No run-time effect.
9
+ if _typing.TYPE_CHECKING:
10
+ from arrayprobe_uiops.readers.pms import * # noqa: F403
11
+
12
+ _sys.modules[__name__] = _impl