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,1094 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """``read_binary_SPEC.m``'s record-walking driver (UIOOPS v3.5).
3
+
4
+ An earlier stage took this file's **pure** half -- `interp_tas`, the TAS-update gate and the
5
+ probe/aircraft TAS ratio -- into :mod:`arrayprobe_uiops.tas` and validated it on a
6
+ case grid. This module is the other half: the record loop, ``readRecord``,
7
+ ``get_img``'s packet walk, the three ``.csv`` sidecars and the netCDF writer.
8
+ It needs a real binary file and a real netCDF writer, so it was validated the
9
+ way the earlier translation's reader was -- by running **the whole vendored v3.5 program,
10
+ unmodified**, under Octave 11.3.0 on a synthetic raw fixture and comparing what
11
+ each program wrote (``octave_oracle/run_v35_spec_bank.py``,
12
+ ``tests/test_v35_spec.py``).
13
+
14
+ **Oracle layer 2 only.** No archived product was ever written by v3.5 -- v3.5
15
+ postdates every campaign this project holds -- so nothing here has the
16
+ archived-product (layer 1) validation the earlier translation's reader has.
17
+
18
+ Reuse
19
+ -----
20
+
21
+ Everything the two releases share is imported from
22
+ :mod:`arrayprobe.readers.spec` rather than re-translated: the record iterator,
23
+ the image canvas, the run-length decoders, the header-slice writer and the
24
+ packed-image conversion. Only what the diff actually changed is written again
25
+ here. ``tests/test_v35_spec.py::TestReuseIsNotAccidental`` names each borrowed
26
+ helper, so a rename in the earlier translation fails here loudly instead of silently
27
+ falling back to a local copy.
28
+
29
+ What v3.5 changed, and what this module does about each
30
+ ------------------------------------------------------
31
+
32
+ 1. **The scan bound**, ``while iii<=2048`` -> ``while iii+4<=2048``
33
+ (``:297``, Finlon 04/17/20, "Watch for index outside of image buffer"). It
34
+ is a safety fix *and* a behaviour change: words 2045-2048 are no longer
35
+ examined at all, so a packet whose marker lands there is silently dropped.
36
+ Measured against both vendored trees on the same bytes -- see
37
+ :data:`LATE_MARKER_FIRST_SKIPPED`.
38
+ 2. **The TAS output and its gate** (``:294``, ``:407-413``). ``get_img`` now
39
+ returns the record's TAS, carried forward from the previous record when the
40
+ current reading is missing or suspect. The gate itself is
41
+ :func:`arrayprobe_uiops.tas.update_tas`; this module supplies the housekeeping
42
+ values it judges.
43
+ 3. **The 15-column ``.tas.csv``** (``:400-405``, ``:416-418``): six end-diode
44
+ voltages joined the nine v3.1.4 columns, each word scaled by
45
+ ``0.00244140625``. The column that was already there changed meaning -- see
46
+ :class:`SidecarWriterV35`.
47
+ 4. **NETCDF4 output**, ``.H.cdf``/``.V.cdf`` -> ``.H.nc``/``.V.nc``, with two
48
+ new variables (``tas``, ``tasRatio``), three new global attributes, per-
49
+ variable deflate and a ``_FillValue`` on ``tas``. See
50
+ :data:`WRITER_GAPS` for the two parts of that this port does **not**
51
+ reproduce and why.
52
+ 5. **The day-rollover clamp** (``:224-226``), applied inside the V-channel
53
+ write block only. Preserved exactly, asymmetry included.
54
+ 6. **An optional whole-record time offset** (``:148-151``). Implemented from
55
+ documented semantics, not from an Octave run -- see :data:`WRITER_GAPS`.
56
+
57
+ Preserved defects
58
+ -----------------
59
+
60
+ Every one of these was measured on the v3.5 source, not carried over on the
61
+ assumption that "the diff did not touch it":
62
+
63
+ * **The last record of a file is never a primary.** Unchanged from v3.1.4:
64
+ ``iter_record_windows`` yields *n-1* windows -- *n* when a partial record
65
+ follows the last whole one, which keeps the EOF probe from failing once more.
66
+ * **``.MK.csv`` has no line terminators.** ``:429-431`` still declares twenty
67
+ ``%d`` conversions for nineteen values, so ``fprintf`` drops the trailing
68
+ ``' \n'``. This was first inferred from the
69
+ diff's *silence*; the oracle then ran the v3.5 program and measured it.
70
+ * **The housekeeping walk advances by 53 for a 53-word packet** (``:421``),
71
+ one short, so the final word is re-examined. Unchanged.
72
+ * **``nStereo`` is read and never used** (``:393``), in both releases.
73
+ * **``daystart`` is dead machinery.** ``:140`` sets ``daystart = 99999999`` and
74
+ nothing ever reads it; ``readRecord`` declares it as both an input and an
75
+ eleventh output (``:269``) and assigns it nowhere, and both call sites pass
76
+ one argument and request ten outputs. The day handling that reached
77
+ production is the V-only ``hour>=24`` clamp, nothing more.
78
+ """
79
+
80
+ from __future__ import annotations
81
+
82
+ import dataclasses
83
+ import datetime as dt
84
+ import os
85
+ import struct
86
+ import time as _time
87
+ import warnings
88
+ from collections.abc import Sequence
89
+ from typing import Any
90
+
91
+ import numpy as np
92
+
93
+ from arrayprobe_uiops.spec_core import (
94
+ _MASK_COUNT,
95
+ _MASK_TIMING,
96
+ DATA_WORDS,
97
+ DIODES,
98
+ IMG_BLOCKLEN,
99
+ IMG_ROWLEN,
100
+ MARKER_2S,
101
+ MARKER_HK,
102
+ MARKER_MK,
103
+ RECORD_BYTES,
104
+ RECORD_WORDS,
105
+ RecordHeader,
106
+ SidecarWriter,
107
+ SpawnRetryWarning,
108
+ _at,
109
+ _decode_runs_auto,
110
+ _decode_runs_scalar,
111
+ _ImageCanvas,
112
+ _marker_positions,
113
+ _merge_sidecars,
114
+ _next_marker,
115
+ _pack_image,
116
+ _report_part_progress,
117
+ _write_header_slice,
118
+ iter_record_windows,
119
+ record_window_count,
120
+ sixteen2int,
121
+ )
122
+ from arrayprobe_uiops.tas import Series, TasValue, interp_tas, tas_ratio, update_tas
123
+
124
+ from . import ncio, provenance
125
+
126
+ #: Names re-exported from the v3.1.4 port unchanged, so a v3.5 caller does not
127
+ #: have to reach into the other package for the pieces the two releases share.
128
+ #: ``tests/test_v35_spec.py::TestReuseIsNotAccidental`` asserts each is the SAME
129
+ #: object as the v3.1.4 port's, so this stays a re-export and never drifts into
130
+ #: a second copy.
131
+ SHARED_WITH_V314 = (
132
+ "DATA_WORDS",
133
+ "DIODES",
134
+ "IMG_BLOCKLEN",
135
+ "IMG_ROWLEN",
136
+ "MARKER_2S",
137
+ "MARKER_HK",
138
+ "MARKER_MK",
139
+ "RECORD_BYTES",
140
+ "RECORD_WORDS",
141
+ "RecordHeader",
142
+ "iter_record_windows",
143
+ "sixteen2int",
144
+ )
145
+
146
+ __all__ = [
147
+ # This module's own surface.
148
+ "DIODE_VOLTAGE_SCALE",
149
+ "INITIAL_TAS",
150
+ "LATE_MARKER_FIRST_SKIPPED",
151
+ "SCAN_LIMIT",
152
+ "SHARED_WITH_V314",
153
+ "SeamRerunWarning",
154
+ "WRITER_GAPS",
155
+ "SidecarWriterV35",
156
+ "apply_time_offset",
157
+ "get_img_v35",
158
+ "hk_readings_v35",
159
+ "read_binary_spec_v35",
160
+ "read_binary_spec_v35_parallel",
161
+ # Re-exports, listed literally so a linter can see they are deliberate;
162
+ # SHARED_WITH_V314 above is the same list in a form a test can iterate.
163
+ "DATA_WORDS",
164
+ "DIODES",
165
+ "IMG_BLOCKLEN",
166
+ "IMG_ROWLEN",
167
+ "MARKER_2S",
168
+ "MARKER_HK",
169
+ "MARKER_MK",
170
+ "RECORD_BYTES",
171
+ "RECORD_WORDS",
172
+ "RecordHeader",
173
+ "iter_record_windows",
174
+ "sixteen2int",
175
+ ]
176
+
177
+ #: ``read_binary_SPEC.m:297``. The scan visits ``iii`` while ``iii + 4 <= 2048``,
178
+ #: so the last position examined is 2044 -- four short of v3.1.4's 2048.
179
+ SCAN_LIMIT = DATA_WORDS - 4
180
+
181
+ #: The first word position v3.5 declines to examine and v3.1.4 does examine.
182
+ #: A marker here is decoded by v3.1.4 and dropped by v3.5, measured on the same
183
+ #: bytes by ``octave_oracle/run_v35_spec_bank.py``'s ``bound_*`` cases.
184
+ LATE_MARKER_FIRST_SKIPPED = SCAN_LIMIT + 1 # 2045
185
+
186
+ #: ``:137``. ``previousTAS`` before any housekeeping packet has been seen. It is
187
+ #: written to the netCDF as-is for every record up to the first accepted
188
+ #: reading, and ``:185-186`` reads it back as "uncorrectable" when forming the
189
+ #: TAS ratio.
190
+ INITIAL_TAS = -999.0
191
+
192
+ #: ``:400-405``. Each end-diode voltage word is scaled by this. The literal is
193
+ #: exactly ``10 / 4096`` -- a 12-bit converter over a 10 V full scale -- which
194
+ #: upstream writes as the decimal 0.00244140625 with no comment saying so.
195
+ #: Derived, then checked: the decimal is exact in binary, so the two are the
196
+ #: same number and not merely close.
197
+ DIODE_VOLTAGE_SCALE = 0.00244140625
198
+
199
+ #: What this port does NOT reproduce about v3.5's output file, stated rather
200
+ #: than left to be discovered. Both are properties of the netCDF *encoding*,
201
+ #: not of any value the file carries.
202
+ #:
203
+ #: ``deflate``
204
+ #: ``:96-106`` calls ``netcdf.defVarDeflate(f, varid, true, true, 9)`` on
205
+ #: every variable. This port's files are NETCDF4 and uncompressed. The
206
+ #: project's single netCDF encoder, ``arrayprobe_uiops.ncio``, owns the MATLAB
207
+ #: dimension reversal and the MATLAB type map and exposes no deflate
208
+ #: parameter, and forking it -- or hand-rolling the transpose beside it --
209
+ #: is what the project's NetCDF-axis convention forbids. Deflate is lossless and
210
+ #: invisible to every reader: the arrays read back are identical either way,
211
+ #: which ``tests/test_v35_spec.py::TestWriterGaps`` measures rather than
212
+ #: asserts. Closing it properly is a ``deflate=`` keyword on
213
+ #: ``ncio.def_var``.
214
+ #: ``tas_fill_value``
215
+ #: ``:105`` calls ``netcdf.defVarFill(f, varid9, false, -999.)``, giving the
216
+ #: ``tas`` variable a ``_FillValue`` of -999. netCDF4-python can only set
217
+ #: ``_FillValue`` at variable-creation time, which ``ncio.def_var`` does not
218
+ #: expose either. The attribute is never *exercised* by this program --
219
+ #: ``tas`` is written for every record on both channels, measured in the
220
+ #: oracle -- so no value differs; the attribute is simply absent.
221
+ #: ``time_offset``
222
+ #: ``:148-151``'s ``varargin{3}`` path builds a MATLAB ``datetime`` and adds
223
+ #: ``seconds(timeOffset)``. Octave 11.3.0's ``datatypes`` package supplies
224
+ #: ``datetime`` but **not** ``plus`` for it ("plus method not defined for
225
+ #: datetime class", measured 2026-09-11), so this one path has no Octave
226
+ #: oracle. It is implemented from documented calendar semantics and pinned
227
+ #: by tests, doctrine layer 3.
228
+ WRITER_GAPS = ("deflate", "tas_fill_value", "time_offset")
229
+
230
+
231
+ class SidecarWriterV35(SidecarWriter):
232
+ """The v3.1.4 sidecar writer with v3.5's 15-column ``.tas.csv``.
233
+
234
+ Source: the appends of ``get_img`` in ``read_binary_SPEC.m:283-443`` (UIOOPS v3.5).
235
+
236
+ ``.NV.csv`` and ``.MK.csv`` are untouched by the v3.5 diff and are inherited
237
+ unchanged, **including** the mask file's missing line terminators -- which
238
+ the Octave oracle of the SPEC reader re-measured against the v3.5 source
239
+ rather than inheriting on the strength of the diff not mentioning it.
240
+
241
+ Three things changed about ``.tas.csv`` and only one of them is visible in the
242
+ format string. The third is that ``tas`` is in the row, and its class
243
+ sets the row's: from the first accepted reading on it is a single, and
244
+ every ``%f`` column is printed at single precision (see :meth:`tas`). The
245
+ other two:
246
+
247
+ * six columns were appended (``:416``), the H and V end-diode voltages, each
248
+ word times :data:`DIODE_VOLTAGE_SCALE`; and
249
+ * **the second column stopped being the probe's reading.** v3.1.4 wrote the
250
+ value it had just bit-cast out of the packet. v3.5 writes ``tas``, the
251
+ value that survived the update gate (``:407-413``) -- so a record whose
252
+ probe TAS was rejected as suspect is logged with the *previous* record's
253
+ TAS, and the rejected reading is not recorded anywhere. Measured: the
254
+ oracle's ``tasTemp = 170`` and ``nHOL = 1`` records both log ``50.0``,
255
+ the last accepted value. Preserved, not corrected.
256
+ """
257
+
258
+ def tas( # type: ignore[override] # v3.5 widens the row; see the docstring
259
+ self,
260
+ timehhmmss: Any,
261
+ tas: Any,
262
+ time: Any,
263
+ n_twm: Any,
264
+ n_scm: Any,
265
+ n_hol: Any,
266
+ n_vol: Any,
267
+ n_vpd: Any,
268
+ n_hpd: Any,
269
+ v_he1: Any = 0.0,
270
+ v_he2: Any = 0.0,
271
+ v_he3: Any = 0.0,
272
+ v_ve1: Any = 0.0,
273
+ v_ve2: Any = 0.0,
274
+ v_ve3: Any = 0.0,
275
+ ) -> None:
276
+ """``:416-418`` -- fifteen fields, nine ``%f`` and six ``%d``... almost.
277
+
278
+ The real format is
279
+ ``'%f, %f, %f, %d, %d, %d, %d, %d, %d, %f, %f, %f, %f, %f, %f\\n'``:
280
+ three ``%f``, six ``%d``, six ``%f``. Fifteen conversions for fifteen
281
+ values, so -- unlike ``.MK.csv`` -- this writer is well formed and the
282
+ line terminator is written.
283
+ """
284
+ if not self.enabled:
285
+ return
286
+ # :418 builds the row as ONE array, [timehhmmss tas time ...]. Once
287
+ # `tas` is a single -- from the first accepted probe reading on -- that
288
+ # concatenation is single, so every %f column is printed after
289
+ # rounding to float32: 123454.999 prints as 123455.000000 and a
290
+ # 32-bit `time` counter above 2^24 loses its low bits. Before any
291
+ # reading is accepted `tas` is the double -999 and nothing is rounded.
292
+ # Measured under Octave on the vendored v3.5 tree
293
+ # (tests/test_reader_edge_octave.py::SpecAgainstOctave). The %d columns are
294
+ # 16-bit words, exact in either class.
295
+ cast = _as_single if isinstance(tas, np.float32) else float
296
+ self._tas.append(
297
+ f"{_matlab_f(cast(timehhmmss))}, {_matlab_f(float(tas))}, "
298
+ f"{_matlab_f(cast(time))}, "
299
+ f"{int(n_twm):d}, {int(n_scm):d}, {int(n_hol):d}, "
300
+ f"{int(n_vol):d}, {int(n_vpd):d}, {int(n_hpd):d}, "
301
+ + ", ".join(_matlab_f(cast(v)) for v in (v_he1, v_he2, v_he3, v_ve1, v_ve2, v_ve3))
302
+ + "\n"
303
+ )
304
+
305
+
306
+ def _as_single(value: Any) -> float:
307
+ """``single(value)``, returned as the exactly equal Python float."""
308
+ return float(np.float32(value))
309
+
310
+
311
+ def _matlab_f(value: float) -> str:
312
+ """MATLAB's ``%f``: C's for finite values, ``NaN``/``Inf``/``-Inf`` otherwise.
313
+
314
+ A housekeeping TAS is a bit-cast of two raw words, so a corrupt packet can
315
+ carry a NaN or infinite single; MATLAB prints those capitalised, where
316
+ Python's ``%f`` prints ``nan``/``inf``.
317
+ """
318
+ if value != value:
319
+ return "NaN"
320
+ if value in (float("inf"), float("-inf")):
321
+ return "Inf" if value > 0 else "-Inf"
322
+ return f"{value:f}"
323
+
324
+
325
+ def get_img_v35(buf: Any, timehhmmss: Any, sidecar: Any = None, tas_prev: TasValue = INITIAL_TAS, *,
326
+ fast: bool = True) -> Any:
327
+ """``read_binary_SPEC.m:283-442``. Returns ``(imgH, imgV, nNext, tas, tasPrev)``.
328
+
329
+ Two outputs more than v3.1.4's ``get_img``, and one fewer argument: there is
330
+ no ``FidelityProfile`` here, because **v3.5 has no profile axis for this
331
+ function**. ``spec_buffer_guard`` exists in the earlier translation to choose
332
+ between stock's 2017-03-08 bounds guards and the production variant tree that
333
+ predates them; v3.5 carries those guards unconditionally (``:322``,
334
+ ``:326``, ``:333``, ``:356``, ``:360``, ``:367``), and the production variant
335
+ is a v3.1.4-era fork that was never rebased onto any later release
336
+ (see the two-engines note). There is nothing to select, so nothing is
337
+ offered; inventing a switch here would imply a v3.5 variant that does not
338
+ exist.
339
+
340
+ ``buf`` is the **two-record** window (4096 words for a complete pair); only
341
+ ``iii + 4 <= 2048`` is scanned. ``tas`` comes back as the value for this
342
+ record and ``tasPrev`` as the value the *next* record starts from; the
343
+ MATLAB writes ``tasPrev = tas`` only inside the accept branch, where the two
344
+ are equal by construction, so returning both is faithful rather than
345
+ redundant.
346
+ """
347
+ buf = np.asarray(buf)
348
+ decode = _decode_runs_auto if fast else _decode_runs_scalar
349
+ markers = _marker_positions(buf) if fast else None
350
+
351
+ img_h = _ImageCanvas()
352
+ img_v = _ImageCanvas()
353
+ i_slice = 0
354
+ iii = 1
355
+ # :294 -- the record's TAS is the previous record's until a packet in THIS
356
+ # record replaces it. A record with no housekeeping packet at all therefore
357
+ # still reports a TAS, and it is the carried one.
358
+ tas = tas_prev
359
+ while iii + 4 <= DATA_WORDS:
360
+ if _at(buf, iii) == MARKER_2S:
361
+ n_h = _at(buf, iii + 1) & _MASK_COUNT
362
+ b_h_timing = _at(buf, iii + 1) & _MASK_TIMING
363
+ n_v = _at(buf, iii + 2) & _MASK_COUNT
364
+ b_v_timing = _at(buf, iii + 2) & _MASK_TIMING
365
+ pc = _at(buf, iii + 3)
366
+ n_s = _at(buf, iii + 4)
367
+ nh_word = _at(buf, iii + 1)
368
+ nv_word = _at(buf, iii + 2)
369
+
370
+ if sidecar is not None:
371
+ sidecar.nv(timehhmmss, _at(buf, iii + 2))
372
+ if n_h != 0 and n_v != 0:
373
+ sidecar.output_txt(n_h, n_v)
374
+
375
+ iii += 5
376
+ if b_h_timing != 0 or b_v_timing != 0:
377
+ iii += n_h + n_v
378
+ elif n_h != 0 and iii + n_h - 1 <= buf.size:
379
+ decode(buf, iii, n_h, n_s, img_h, i_slice, True)
380
+ i_slice += n_s + 2
381
+ t_particle = _at(buf, iii + n_h - 2) * 65536 + _at(buf, iii + n_h - 1)
382
+ _write_header_slice(
383
+ img_h, i_slice, t_particle, nh_word, pc, n_s, with_metadata=True
384
+ )
385
+ iii += n_h
386
+ elif n_v != 0 and iii + n_v - 1 <= buf.size:
387
+ decode(buf, iii, n_v, n_s, img_v, i_slice, True)
388
+ i_slice += n_s + 2
389
+ t_particle = _at(buf, iii + n_v - 2) * 65536 + _at(buf, iii + n_v - 1)
390
+ _write_header_slice(
391
+ img_v, i_slice, t_particle, nv_word, pc, n_s, with_metadata=True
392
+ )
393
+ iii += n_v
394
+
395
+ elif _at(buf, iii) == MARKER_HK:
396
+ # :389 -- two words concatenated MSB-first and reinterpreted as an
397
+ # IEEE single. The result stays float32 all the way to the netCDF
398
+ # and to the TAS ratio; see read_binary_spec_v35.
399
+ raw = (_at(buf, iii - 1 + 50) << 16) | _at(buf, iii - 1 + 51)
400
+ tas_temp = np.uint32(raw).view(np.float32)
401
+ time = _at(buf, iii - 1 + 52) * 65536 + _at(buf, iii - 1 + 53)
402
+ n_hol = _at(buf, iii - 1 + 44)
403
+ n_vol = _at(buf, iii - 1 + 45)
404
+ # :407-413, the TAS gate. `tasPrev` follows `tas` because the MATLAB
405
+ # updates it only where the two already agree.
406
+ # tas_temp stays a numpy float32 and the gate returns whichever of
407
+ # its two inputs it keeps, so `tas` carries MATLAB's CLASS as well
408
+ # as its value: single from the first accepted reading on (and
409
+ # through every later record, via tasPrev), double -999 before
410
+ # that. The class is observable -- :418 concatenates `tas` with
411
+ # doubles, which makes the whole .tas.csv row single (see
412
+ # SidecarWriterV35). The comparisons are unaffected: every value
413
+ # here is exactly representable as a float32.
414
+ tas = update_tas(tas_temp, tas_prev, n_hol, n_vol)
415
+ tas_prev = tas
416
+ if sidecar is not None:
417
+ sidecar.tas(
418
+ timehhmmss,
419
+ tas, # the GATED value, not tas_temp -- see SidecarWriterV35
420
+ time,
421
+ _at(buf, iii - 1 + 42), # nTWM
422
+ _at(buf, iii - 1 + 43), # nSCM
423
+ n_hol,
424
+ n_vol,
425
+ _at(buf, iii - 1 + 34), # nVPD
426
+ _at(buf, iii - 1 + 35), # nHPD
427
+ *(_at(buf, iii - 1 + k) * DIODE_VOLTAGE_SCALE for k in range(2, 8)),
428
+ )
429
+ # :421 advances by 53 for a 53-word packet, one short, so the final
430
+ # word is re-examined on the next pass. Unchanged from v3.1.4.
431
+ iii += 53
432
+
433
+ elif _at(buf, iii) == MARKER_MK:
434
+ time_word = _at(buf, iii - 1 + 2) * 65536 + _at(buf, iii - 1 + 3)
435
+ mask_bits = [_at(buf, k) for k in range(iii - 1 + 4, iii - 1 + 19 + 1)]
436
+ time_start = _at(buf, iii - 1 + 20) * 65536 + _at(buf, iii - 1 + 21)
437
+ time_end = _at(buf, iii - 1 + 22) * 65536 + _at(buf, iii - 1 + 23)
438
+ if sidecar is not None:
439
+ sidecar.mask(time_word, mask_bits, time_start, time_end)
440
+ iii += 23
441
+
442
+ else:
443
+ iii = _next_marker(markers, iii, buf.size)
444
+
445
+ # :441. nNext is measured from 2048 whatever the scan bound is, so the v3.5
446
+ # bound makes it smaller by up to four as well.
447
+ return img_h.result(), img_v.result(), iii - DATA_WORDS, tas, tas_prev
448
+
449
+
450
+ def apply_time_offset(header: RecordHeader, offset_seconds: float) -> RecordHeader:
451
+ """``:148-151`` -- shift one record's whole timestamp by ``timeOffset``.
452
+
453
+ Source: ``read_binary_SPEC.m:148-152`` (UIOOPS v3.5).
454
+
455
+ ``wkday`` and ``millisec`` are **not** touched, because the MATLAB does not
456
+ touch them: it rebuilds only ``[year, month, day]`` from ``ymd`` and
457
+ ``[hour, minute, second]`` from ``hms`` of a ``datetime`` constructed
458
+ *without* the milliseconds. A negative offset that crosses midnight
459
+ therefore leaves ``wkday`` naming the wrong day, and a fractional offset is
460
+ lost against a ``millisec`` field that stays where it was. Preserved.
461
+
462
+ **No Octave oracle** (doctrine layer 3): Octave 11.3.0's ``datatypes``
463
+ package has ``datetime`` but no ``plus`` for it (measured). This
464
+ is calendar arithmetic from documented semantics, pinned by tests.
465
+ """
466
+ base = dt.datetime(
467
+ header.year, header.month, header.day,
468
+ header.hour % 24, header.minute, header.second,
469
+ ) + dt.timedelta(days=header.hour // 24, seconds=float(offset_seconds))
470
+ return RecordHeader(
471
+ year=base.year, month=base.month, wkday=header.wkday, day=base.day,
472
+ hour=base.hour, minute=base.minute, second=base.second,
473
+ millisec=header.millisec,
474
+ )
475
+
476
+
477
+ _TIME_VARS = (
478
+ ("year", "short"),
479
+ ("month", "byte"),
480
+ ("day", "byte"),
481
+ ("hour", "byte"),
482
+ ("minute", "byte"),
483
+ ("second", "byte"),
484
+ ("millisec", "short"),
485
+ ("wkday", "byte"),
486
+ )
487
+ _TIME_FIELDS = ("year", "month", "day", "hour", "minute", "second", "millisec", "wkday")
488
+
489
+
490
+ class _ImageFileV35:
491
+ """One v3.5 output file: ``.H.nc`` / ``.V.nc``.
492
+
493
+ Differs from the earlier translation's ``_ImageFile`` in four ways, all read off the
494
+ diff: the NETCDF4 format, the ``.nc`` extension, three global attributes,
495
+ and the two new record variables ``tas`` and ``tasRatio``. See
496
+ :data:`WRITER_GAPS` for the two encoding details it does not carry.
497
+
498
+ ``tasRatio`` is written **only** when the caller supplied an aircraft TAS
499
+ series (``:208-211``, ``:236-239``), exactly as the MATLAB gates it -- so a
500
+ run without one leaves the variable defined and entirely unwritten, and a
501
+ reader gets netCDF's default double fill, ``9.969209968386869e+36``, with
502
+ nothing in the file to say it was never populated. Measured in the oracle's
503
+ ``main_no_tas`` case; preserved rather than papered over with a real value.
504
+ """
505
+
506
+ def __init__(self, filename: Any, orientation: str, software: str, *,
507
+ write_tas_ratio: bool, creation_time: str, block: int = 256,
508
+ stamp_profile: str | None = None) -> None:
509
+ self.ncid = ncio.create(filename, "clobber", format="NETCDF4")
510
+ dim_time = self.ncid.def_dim("time", ncio.NC_UNLIMITED)
511
+ dim_row = self.ncid.def_dim("ImgRowlen", IMG_ROWLEN)
512
+ dim_block = self.ncid.def_dim("ImgBlocklen", IMG_BLOCKLEN)
513
+ # :90-93 / :116-119. The attribute name carries BOTH a space and an
514
+ # underscore ('Probe Channel_Orientation'); written verbatim, as the
515
+ # output contract requires.
516
+ self.ncid.put_att(ncio.NC_GLOBAL, "Software", software)
517
+ self.ncid.put_att(ncio.NC_GLOBAL, "Creation Time", creation_time)
518
+ self.ncid.put_att(ncio.NC_GLOBAL, "Probe Channel_Orientation", orientation)
519
+ # In-file provenance: arrayprobe_engine / arrayprobe_profile, not MATLAB output.
520
+ for name, value in provenance.engine_attrs(engine="3.5", profile=stamp_profile).items():
521
+ self.ncid.put_att(ncio.NC_GLOBAL, name, value)
522
+ self.varids = [self.ncid.def_var(n, t, dim_time) for n, t in _TIME_VARS]
523
+ self.varid_data = self.ncid.def_var("data", "int", [dim_row, dim_block, dim_time])
524
+ self.varid_tas = self.ncid.def_var("tas", "double", dim_time)
525
+ self.varid_tas_ratio = self.ncid.def_var("tasRatio", "double", dim_time)
526
+ self.ncid.end_def()
527
+ self.count = 0
528
+ self._write_tas_ratio = write_tas_ratio
529
+ self._block = block
530
+ self._times: list[tuple[int, ...]] = []
531
+ self._images: list[np.ndarray] = []
532
+ self._tas: list[float] = []
533
+ self._ratios: list[float] = []
534
+
535
+ def append(self, header: RecordHeader, packed: np.ndarray,
536
+ tas: float, tas_ratio_value: float) -> None:
537
+ self._times.append(tuple(getattr(header, f) for f in _TIME_FIELDS))
538
+ self._images.append(packed)
539
+ self._tas.append(float(tas))
540
+ self._ratios.append(float(tas_ratio_value))
541
+ self.count += 1
542
+ if len(self._images) >= self._block:
543
+ self.flush()
544
+
545
+ def flush(self) -> None:
546
+ if not self._images:
547
+ return
548
+ start = self.count - len(self._images)
549
+ times = np.asarray(self._times, dtype=np.int64)
550
+ for k, varid in enumerate(self.varids):
551
+ self.ncid.put_var(varid, start, times.shape[0], times[:, k])
552
+ block = np.stack(self._images).transpose(0, 2, 1) # (n, 1700, 8), on-disk order
553
+ ncio.write_record_block(self.ncid, self.varid_data, start, block)
554
+ self.ncid.put_var(self.varid_tas, start, len(self._tas),
555
+ np.asarray(self._tas, dtype=np.float64))
556
+ if self._write_tas_ratio:
557
+ self.ncid.put_var(self.varid_tas_ratio, start, len(self._ratios),
558
+ np.asarray(self._ratios, dtype=np.float64))
559
+ self._times.clear()
560
+ self._images.clear()
561
+ self._tas.clear()
562
+ self._ratios.clear()
563
+
564
+ def close(self) -> None:
565
+ self.flush()
566
+ self.ncid.close()
567
+
568
+
569
+ class _CountingSinkV35:
570
+ """A channel counted but not written; see the earlier translation's ``_CountingSink``."""
571
+
572
+ def __init__(self) -> None:
573
+ self.count = 0
574
+
575
+ def append(self, header: Any, packed: Any, tas: Any, tas_ratio_value: Any) -> None: # noqa: ARG002
576
+ """Count the record and discard it. The arguments exist only so this
577
+ class is substitutable for :class:`_ImageFileV35` at the call site."""
578
+ self.count += 1
579
+
580
+ def flush(self) -> None:
581
+ """Nothing is buffered, so nothing is written."""
582
+
583
+ def close(self) -> None:
584
+ """No file was opened; present so the caller can close both channels."""
585
+
586
+
587
+ def read_binary_spec_v35(
588
+ infilename: Any,
589
+ outfilename: Any,
590
+ *,
591
+ software: str,
592
+ flt_time: Sequence[float] | None = None,
593
+ flt_tas: Sequence[float] | None = None,
594
+ time_offset: float | None = None,
595
+ creation_time: str,
596
+ sidecars: bool = True,
597
+ output_txt: bool = False,
598
+ fast: bool = True,
599
+ channels: str = "HV",
600
+ progress: Any = None,
601
+ stamp_profile: str | None = None,
602
+ ) -> Any:
603
+ """``read_binary_SPEC.m`` (v3.5) -- raw ``.2DS``/``.HVPS`` to ``.H.nc`` + ``.V.nc``.
604
+
605
+ Returns ``(n_h, n_v)``, MATLAB's ``kk1-1`` and ``kk2-1``.
606
+
607
+ ``software`` is **required and has no default**, and that is the point.
608
+ ``:79-81`` opens ``version.txt`` with a bare relative path and writes its
609
+ contents as the ``Software`` global attribute, so upstream's value is a
610
+ property of the *process's working directory* -- a run launched from
611
+ somewhere else gets a different attribute, or dies, since ``fopen``'s
612
+ failure is unchecked and ``fscanf`` then receives a handle of ``-1``.
613
+ Reproducing a cwd-dependent file read would make this function's output
614
+ depend on where Python happened to be started; naming the string instead
615
+ makes the same fact explicit and recordable. The vendored v3.5 tree's own
616
+ ``version.txt`` reads ``UIOOPS_v3.5``.
617
+
618
+ ``creation_time`` is likewise required: ``:91`` (and ``:117`` for the V file) stamps
619
+ ``datestr(now, 'yyyy/mm/dd HH:MM:SS')``, which every byte
620
+ comparison already excludes. Passing it in keeps the function
621
+ deterministic and keeps the caller honest about what it wrote.
622
+
623
+ ``flt_time``/``flt_tas`` are ``varargin{1}``/``{2}``, the 1-Hz aircraft
624
+ series. Supplying them is what turns the ``tasRatio`` variable from
625
+ fill-valued into written -- see :class:`_ImageFileV35`. They go through
626
+ :func:`arrayprobe_uiops.tas.interp_tas` exactly once, at the top, as ``:40``
627
+ does; a TAS series with fewer than two usable nodes therefore **aborts the
628
+ decode before a single record is read**, which is the TAS port's measured behaviour
629
+ and is preserved.
630
+
631
+ ``time_offset`` is ``varargin{3}``. See :func:`apply_time_offset` and
632
+ :data:`WRITER_GAPS` -- it is the one path with no Octave oracle.
633
+
634
+ ``channels`` selects which channel files are *written*; the skipped channel
635
+ is still decoded and still counted, so the return value and every sidecar
636
+ are unchanged. Same storage rationale as the earlier translation's: on the archived
637
+ 2016 2D-S the V channel is a recording of a soot-fouled mirror and is by far the
638
+ larger file.
639
+ """
640
+ if channels not in ("HV", "H", "V"):
641
+ raise ValueError(f"channels must be 'HV', 'H' or 'V'; got {channels!r}")
642
+ if (flt_time is None) != (flt_tas is None):
643
+ # :37-39 reads varargin{1} and varargin{2} together; one without the
644
+ # other is an index error there, not a partial mode.
645
+ raise ValueError(
646
+ "flt_time and flt_tas are varargin{1} and varargin{2} of "
647
+ "read_binary_SPEC.m and are supplied together or not at all"
648
+ )
649
+ # :40 -- interpolated once for the whole flight, before any record is read.
650
+ flight: tuple[Series, np.ndarray] | None = (
651
+ None if flt_time is None or flt_tas is None
652
+ else (flt_time, interp_tas(flt_tas))
653
+ )
654
+
655
+ def make(suffix: Any, orientation: Any) -> Any:
656
+ return _ImageFileV35(
657
+ f"{outfilename}.{suffix}.nc", orientation, software,
658
+ write_tas_ratio=flight is not None, creation_time=creation_time,
659
+ stamp_profile=stamp_profile,
660
+ )
661
+
662
+ out_h = make("H", "Horizontal") if "H" in channels else _CountingSinkV35()
663
+ out_v = make("V", "Vertical") if "V" in channels else _CountingSinkV35()
664
+ sidecar = SidecarWriterV35(outfilename, enabled=sidecars, output_txt=output_txt)
665
+ tas_prev: TasValue = INITIAL_TAS
666
+ try:
667
+ for i, (raw_header, buf) in enumerate(iter_record_windows(infilename)):
668
+ header = (apply_time_offset(raw_header, time_offset)
669
+ if time_offset is not None else raw_header)
670
+ img_h, img_v, _, tas, tas_prev = get_img_v35(
671
+ buf, header.timehhmmss, sidecar, tas_prev, fast=fast
672
+ )
673
+ ratio = 1.0
674
+ if flight is not None:
675
+ # :176-193. `tas` is a float32 all the way from the packet's
676
+ # `typecast(...,'single')`, and MATLAB's single/double division
677
+ # is computed in single -- measured: 50/120 comes back as
678
+ # 0.4166666567325592. `tas_ratio` already divides in float32
679
+ # (pass 6), so this outer np.float32 is a no-op kept as a guard.
680
+ ratio = float(np.float32(tas_ratio(
681
+ float(tas), flight[0], flight[1],
682
+ header.hour, header.minute, header.second,
683
+ )))
684
+ if img_h[:, :IMG_BLOCKLEN].any():
685
+ out_h.append(header, _pack_image(img_h), tas, ratio)
686
+ if img_v[:, :IMG_BLOCKLEN].any():
687
+ # :224-226. The clamp lives INSIDE the V write block and mutates
688
+ # `hour`, so the same physical record is stamped 25:mm:ss in
689
+ # .H.nc and 01:mm:ss in .V.nc. Preserved, asymmetry and all.
690
+ v_header = (header if header.hour < 24
691
+ else dataclasses.replace(header, hour=header.hour - 24))
692
+ out_v.append(v_header, _pack_image(img_v), tas, ratio)
693
+ if progress is not None:
694
+ progress(i, out_h.count, out_v.count)
695
+ finally:
696
+ sidecar.flush()
697
+ out_h.close()
698
+ out_v.close()
699
+ return out_h.count, out_v.count
700
+
701
+
702
+ # --------------------------------------------------------------------------
703
+ # Parallel decode
704
+ # --------------------------------------------------------------------------
705
+ #
706
+ # The v3.5 record loop carries exactly one value from one window to the next:
707
+ # ``tas_prev``, the running airspeed the update gate judges each housekeeping
708
+ # reading against. Everything else ``get_img_v35`` touches is reset per window,
709
+ # the aircraft series is a pure function computed once, and the outputs are
710
+ # append-only in window order. So the file can be decoded in ranges, each range
711
+ # started from the airspeed the serial loop would have carried into it.
712
+ #
713
+ # Those start values come from a cheap first pass (:func:`hk_readings_v35`,
714
+ # which walks each window's packets without decoding images) replayed through
715
+ # the serial gate itself. The first pass is a second copy of the packet walk,
716
+ # so it is never trusted on its own: every part reports the airspeed it ended
717
+ # on, and a part whose start value does not equal its predecessor's end value,
718
+ # bit for bit, is decoded again from the correct one before anything is
719
+ # merged. Part 0 starts from INITIAL_TAS, as the serial loop does, and each
720
+ # part runs the serial code, so agreement at every seam means the merged output
721
+ # is the serial output; a wrong first pass costs time, never bytes.
722
+
723
+
724
+ class SeamRerunWarning(RuntimeWarning):
725
+ """A part of a parallel v3.5 decode started from an airspeed that did not
726
+ equal the previous part's final airspeed, and was decoded again from the
727
+ correct one. The output is unaffected; only time was lost. It means the
728
+ cheap housekeeping pass disagreed with the decoder, which is a defect in
729
+ that pass and worth reporting."""
730
+
731
+
732
+ def _tas_bits(value: float) -> tuple[bool, bytes]:
733
+ """The IEEE bit pattern of an airspeed, and whether it is MATLAB single.
734
+ Seams are compared by bits, not ``==``, because ``+0.0 == -0.0`` and
735
+ ``nan != nan``, and the update gate can keep either sign of zero. The class
736
+ is compared too: a part started from a double where the serial loop carries
737
+ a single would write different ``.tas.csv`` rows (see
738
+ :class:`SidecarWriterV35`)."""
739
+ return isinstance(value, np.float32), struct.pack("<d", float(value))
740
+
741
+
742
+ def hk_readings_v35(buf: Any) -> list[tuple[TasValue, int, int]]:
743
+ """Every housekeeping reading :func:`get_img_v35` would judge, in order.
744
+
745
+ Source: walks ``get_img`` in ``read_binary_SPEC.m:283-443`` (UIOOPS v3.5).
746
+
747
+ Each item is ``(tas_temp, n_hol, n_vol)``, exactly the first, third and
748
+ fourth arguments ``get_img_v35`` passes to :func:`update_tas`. The walk
749
+ repeats ``get_img_v35``'s advance of ``iii`` packet for packet -- the
750
+ image-packet skip under the same two conditions, 53 words for a
751
+ housekeeping packet, 23 for a mask packet, the next marker otherwise --
752
+ but decodes no image and writes no sidecar, so it costs a small fraction
753
+ of a decode. Feeding the readings through :func:`update_tas` from a
754
+ window's incoming airspeed gives the airspeed the next window starts from.
755
+ """
756
+ buf = np.asarray(buf)
757
+ markers = _marker_positions(buf)
758
+ readings: list[tuple[TasValue, int, int]] = []
759
+ iii = 1
760
+ while iii + 4 <= DATA_WORDS:
761
+ word = _at(buf, iii)
762
+ if word == MARKER_2S:
763
+ n_h = _at(buf, iii + 1) & _MASK_COUNT
764
+ b_h_timing = _at(buf, iii + 1) & _MASK_TIMING
765
+ n_v = _at(buf, iii + 2) & _MASK_COUNT
766
+ b_v_timing = _at(buf, iii + 2) & _MASK_TIMING
767
+ iii += 5
768
+ if b_h_timing != 0 or b_v_timing != 0:
769
+ iii += n_h + n_v
770
+ elif n_h != 0 and iii + n_h - 1 <= buf.size:
771
+ iii += n_h
772
+ elif n_v != 0 and iii + n_v - 1 <= buf.size:
773
+ iii += n_v
774
+ elif word == MARKER_HK:
775
+ raw = (_at(buf, iii - 1 + 50) << 16) | _at(buf, iii - 1 + 51)
776
+ tas_temp = np.uint32(raw).view(np.float32)
777
+ # Kept float32, as get_img_v35 keeps it: the class the gate carries
778
+ # forward is part of the state a part must start from.
779
+ readings.append((tas_temp, _at(buf, iii - 1 + 44), _at(buf, iii - 1 + 45)))
780
+ iii += 53
781
+ elif word == MARKER_MK:
782
+ iii += 23
783
+ else:
784
+ iii = _next_marker(markers, iii, buf.size)
785
+ return readings
786
+
787
+
788
+ def _hk_range_v35(args: Any) -> list[tuple[TasValue, int, int]]:
789
+ """The housekeeping readings of windows ``[lo, hi)``, flattened in window
790
+ order. Runs in a worker process; module level for pickling."""
791
+ infilename, lo, hi = args
792
+ out: list[tuple[TasValue, int, int]] = []
793
+ for _header, buf in iter_record_windows(infilename, lo, hi):
794
+ out.extend(hk_readings_v35(buf))
795
+ return out
796
+
797
+
798
+ def _replay_incoming(readings_by_part: Any) -> list[TasValue]:
799
+ """Each part's incoming airspeed, by running the serial gate over every
800
+ earlier part's readings from :data:`INITIAL_TAS`."""
801
+ incoming: list[TasValue] = []
802
+ tas: TasValue = INITIAL_TAS
803
+ for readings in readings_by_part:
804
+ incoming.append(tas)
805
+ for tas_temp, n_hol, n_vol in readings:
806
+ tas = update_tas(tas_temp, tas, n_hol, n_vol)
807
+ return incoming
808
+
809
+
810
+ def _decode_range_v35(args: Any) -> dict:
811
+ """Decode windows ``[lo, hi)`` into part files, starting from ``tas_in``.
812
+
813
+ Runs in a worker process. The loop body is :func:`read_binary_spec_v35`'s,
814
+ unchanged, with the netCDF writer replaced by flat part files the parent
815
+ merges: per written record and channel, the packed image (int32, lossless
816
+ because each packed word holds sixteen bits), the eight time fields with
817
+ the V-channel clamp already applied, the airspeed and the ratio.
818
+ """
819
+ (infilename, prefix, lo, hi, tas_in, flight, time_offset, sidecars, output_txt,
820
+ fast, channels, report_every) = args
821
+ label = os.path.basename(prefix)
822
+ span = hi - lo
823
+ sidecar = SidecarWriterV35(prefix + ".sc", enabled=sidecars, output_txt=output_txt,
824
+ output_txt_path=prefix + ".sc.txt")
825
+ counts = {"H": 0, "V": 0}
826
+ handles: dict = {}
827
+ times: dict = {"H": [], "V": []}
828
+ tas_rows: dict = {"H": [], "V": []}
829
+ ratio_rows: dict = {"H": [], "V": []}
830
+ dtypes: dict = {}
831
+ tas_prev: TasValue = tas_in
832
+ try:
833
+ for channel in ("H", "V"):
834
+ if channel in channels:
835
+ handles[channel] = open(prefix + "." + channel + ".img", "wb")
836
+ windows = iter_record_windows(infilename, lo, hi)
837
+ for n, (raw_header, buf) in enumerate(windows, start=1):
838
+ header = (apply_time_offset(raw_header, time_offset)
839
+ if time_offset is not None else raw_header)
840
+ img_h, img_v, _, tas, tas_prev = get_img_v35(
841
+ buf, header.timehhmmss, sidecar, tas_prev, fast=fast
842
+ )
843
+ ratio = 1.0
844
+ if flight is not None:
845
+ ratio = float(np.float32(tas_ratio(
846
+ float(tas), flight[0], flight[1],
847
+ header.hour, header.minute, header.second,
848
+ )))
849
+ for channel, img in (("H", img_h), ("V", img_v)):
850
+ if not img[:, :IMG_BLOCKLEN].any():
851
+ continue
852
+ counts[channel] += 1
853
+ if channel not in handles:
854
+ continue
855
+ stamped = header
856
+ if channel == "V" and header.hour >= 24:
857
+ # The serial loop's V-only day-rollover clamp.
858
+ stamped = dataclasses.replace(header, hour=header.hour - 24)
859
+ packed = _pack_image(img)
860
+ dtypes[channel] = packed.dtype.str
861
+ packed.astype(np.int32).tofile(handles[channel])
862
+ times[channel].append(tuple(getattr(stamped, f) for f in _TIME_FIELDS))
863
+ tas_rows[channel].append(float(tas))
864
+ ratio_rows[channel].append(float(ratio))
865
+ if report_every > 0 and n % report_every == 0:
866
+ _report_part_progress(label, n, span)
867
+ finally:
868
+ for fh in handles.values():
869
+ fh.close()
870
+ sidecar.flush()
871
+
872
+ for channel in handles:
873
+ np.save(prefix + "." + channel + ".times.npy",
874
+ np.asarray(times[channel], dtype=np.int64).reshape(-1, len(_TIME_FIELDS)))
875
+ np.save(prefix + "." + channel + ".tas.npy",
876
+ np.asarray(tas_rows[channel], dtype=np.float64))
877
+ np.save(prefix + "." + channel + ".ratio.npy",
878
+ np.asarray(ratio_rows[channel], dtype=np.float64))
879
+ return {"lo": lo, "hi": hi, "prefix": prefix, "counts": counts, "dtypes": dtypes,
880
+ "tas_in": tas_in, "tas_out": tas_prev}
881
+
882
+
883
+ def _merge_parts_v35(parts: Any, outfilename: Any, channels: Any, *, software: str,
884
+ creation_time: str,
885
+ write_tas_ratio: bool, stamp_profile: str | None) -> Any:
886
+ """Write the real ``.H.nc``/``.V.nc`` from the parts, in range order.
887
+
888
+ NETCDF4 is HDF5, whose on-disk layout can depend on the sizes of the
889
+ writes that built it, so the parts are not block-written. Every record goes
890
+ through :meth:`_ImageFileV35.append`, one at a time, into files made by the
891
+ same constructor in the same order as the serial path: the library sees the
892
+ serial path's call sequence, including its 256-record flushes.
893
+ """
894
+ parts = sorted(parts, key=lambda p: p["lo"])
895
+
896
+ def make(suffix: Any, orientation: Any) -> Any:
897
+ return _ImageFileV35(
898
+ f"{outfilename}.{suffix}.nc", orientation, software,
899
+ write_tas_ratio=write_tas_ratio, creation_time=creation_time,
900
+ stamp_profile=stamp_profile,
901
+ )
902
+
903
+ out = {
904
+ "H": make("H", "Horizontal") if "H" in channels else _CountingSinkV35(),
905
+ "V": make("V", "Vertical") if "V" in channels else _CountingSinkV35(),
906
+ }
907
+ try:
908
+ for part in parts:
909
+ for channel in ("H", "V"):
910
+ n = part["counts"][channel]
911
+ handle = out[channel]
912
+ if channel not in channels:
913
+ handle.count += n
914
+ continue
915
+ if n == 0:
916
+ continue
917
+ prefix = part["prefix"] + "." + channel
918
+ images = np.memmap(prefix + ".img", dtype=np.int32, mode="r",
919
+ shape=(n, IMG_ROWLEN, IMG_BLOCKLEN))
920
+ stamps = np.load(prefix + ".times.npy")
921
+ tas = np.load(prefix + ".tas.npy")
922
+ ratio = np.load(prefix + ".ratio.npy")
923
+ dtype = np.dtype(part["dtypes"][channel])
924
+ for i in range(n):
925
+ header = RecordHeader(**{f: int(stamps[i, k])
926
+ for k, f in enumerate(_TIME_FIELDS)})
927
+ handle.append(header, np.array(images[i], dtype=dtype),
928
+ float(tas[i]), float(ratio[i]))
929
+ # Release the map before the part directory is removed (Windows
930
+ # refuses to delete a mapped file).
931
+ del images
932
+ finally:
933
+ for handle in out.values():
934
+ handle.close()
935
+ return out["H"].count, out["V"].count
936
+
937
+
938
+ def _split_decode_v35(infilename: Any, outfilename: Any, edges: Any, mapper: Any, tmp: Any, *,
939
+ flight: Any, time_offset: Any,
940
+ software: str, creation_time: str, sidecars: bool, output_txt: bool,
941
+ fast: bool, channels: str, report_every: int,
942
+ stamp_profile: str | None, progress: Any = None, stats: Any = None) -> Any:
943
+ """Both rounds, the seam check and the merge, for one set of ``edges``.
944
+
945
+ ``mapper`` is a pool's ``map`` or the builtin ``map``; the tests drive every
946
+ split of a small fixture through the builtin one, in process.
947
+ """
948
+ infilename = os.fspath(infilename)
949
+ spans = [(edges[k], edges[k + 1]) for k in range(len(edges) - 1)
950
+ if edges[k + 1] > edges[k]]
951
+ readings = list(mapper(_hk_range_v35, [(infilename, lo, hi) for lo, hi in spans]))
952
+ incoming = _replay_incoming(readings)
953
+ tasks = [
954
+ (infilename, os.path.join(tmp, f"p{k:03d}"), lo, hi, incoming[k], flight,
955
+ time_offset, sidecars, output_txt, fast, channels, report_every)
956
+ for k, (lo, hi) in enumerate(spans)
957
+ ]
958
+ parts = []
959
+ for done, part in enumerate(mapper(_decode_range_v35, tasks), start=1):
960
+ parts.append(part)
961
+ if progress is not None:
962
+ progress(done, len(tasks), part["counts"])
963
+ parts.sort(key=lambda p: p["lo"])
964
+
965
+ if parts and _tas_bits(parts[0]["tas_in"]) != _tas_bits(INITIAL_TAS):
966
+ raise AssertionError("the first part of a parallel v3.5 decode did not start "
967
+ "from INITIAL_TAS")
968
+ reruns = 0
969
+ for k in range(1, len(parts)):
970
+ want = parts[k - 1]["tas_out"]
971
+ if _tas_bits(want) == _tas_bits(parts[k]["tas_in"]):
972
+ continue
973
+ warnings.warn(
974
+ f"parallel v3.5 decode: part {k} started from airspeed "
975
+ f"{parts[k]['tas_in']!r} but part {k - 1} ended on {want!r}; decoding part "
976
+ f"{k} again from the correct value",
977
+ SeamRerunWarning, stacklevel=3)
978
+ task = list(tasks[k])
979
+ task[1] = os.path.join(tmp, f"p{k:03d}_rerun{reruns}")
980
+ task[4] = want
981
+ parts[k] = _decode_range_v35(tuple(task))
982
+ reruns += 1
983
+ if stats is not None:
984
+ stats["parts"] = len(parts)
985
+ stats["reruns"] = reruns
986
+
987
+ n_h, n_v = _merge_parts_v35(
988
+ parts, os.fspath(outfilename), channels, software=software,
989
+ creation_time=creation_time, write_tas_ratio=flight is not None,
990
+ stamp_profile=stamp_profile)
991
+ _merge_sidecars(parts, os.fspath(outfilename), output_txt=output_txt)
992
+ return n_h, n_v
993
+
994
+
995
+ def read_binary_spec_v35_parallel(
996
+ infilename: Any,
997
+ outfilename: Any,
998
+ *,
999
+ jobs: int,
1000
+ software: str,
1001
+ creation_time: str,
1002
+ flt_time: Sequence[float] | None = None,
1003
+ flt_tas: Sequence[float] | None = None,
1004
+ time_offset: float | None = None,
1005
+ sidecars: bool = True,
1006
+ output_txt: bool = False,
1007
+ fast: bool = True,
1008
+ channels: str = "HV",
1009
+ workdir: Any = None,
1010
+ progress: Any = None,
1011
+ spawn_retries: int = 2,
1012
+ report_every: int = 0,
1013
+ stamp_profile: str | None = None,
1014
+ stats: dict | None = None,
1015
+ ) -> Any:
1016
+ """:func:`read_binary_spec_v35` across ``jobs`` processes, byte-identical output.
1017
+
1018
+ Returns the same ``(n_h, n_v)``. ``jobs <= 1``, or a file with no decode
1019
+ window, delegates to the serial function. Every other keyword means what it
1020
+ means there, and the checks run in the same order: ``channels``, then the
1021
+ flight pair, then :func:`interp_tas`, all before any record is read.
1022
+
1023
+ Two pool rounds share one pool: a cheap housekeeping pass per part, whose
1024
+ readings the parent replays through the serial airspeed gate to give every
1025
+ part its exact starting airspeed, then the decode. Each part's final
1026
+ airspeed is compared bit for bit with the next part's starting one, and a
1027
+ part that disagrees is decoded again before the merge (see
1028
+ :class:`SeamRerunWarning`). ``stats``, when given a dict, receives
1029
+ ``parts`` and ``reruns``.
1030
+
1031
+ ``workdir``, ``spawn_retries`` and ``report_every`` behave as in the earlier
1032
+ translation's ``read_binary_SPEC_parallel``: a fresh
1033
+ temporary directory per attempt, the whole pool restarted with a
1034
+ :class:`arrayprobe_uiops.spec_core.SpawnRetryWarning` when it dies before
1035
+ finishing, and one liveness line per ``report_every`` windows per part.
1036
+
1037
+ Byte identity with the serial function, whole files with the same
1038
+ ``creation_time``, is asserted in ``tests/test_v35_spec_parallel.py``.
1039
+ """
1040
+ import concurrent.futures
1041
+ import concurrent.futures.process
1042
+ import shutil
1043
+ import tempfile
1044
+
1045
+ if channels not in ("HV", "H", "V"):
1046
+ raise ValueError(f"channels must be 'HV', 'H' or 'V'; got {channels!r}")
1047
+ if (flt_time is None) != (flt_tas is None):
1048
+ raise ValueError(
1049
+ "flt_time and flt_tas are varargin{1} and varargin{2} of "
1050
+ "read_binary_SPEC.m and are supplied together or not at all"
1051
+ )
1052
+ outfilename = os.fspath(outfilename)
1053
+ n_windows = record_window_count(infilename)
1054
+ if jobs <= 1 or n_windows <= 1:
1055
+ return read_binary_spec_v35(
1056
+ infilename, outfilename, software=software, flt_time=flt_time,
1057
+ flt_tas=flt_tas, time_offset=time_offset, creation_time=creation_time,
1058
+ sidecars=sidecars, output_txt=output_txt, fast=fast, channels=channels,
1059
+ progress=progress, stamp_profile=stamp_profile)
1060
+ flight: tuple[Series, np.ndarray] | None = (
1061
+ None if flt_time is None or flt_tas is None
1062
+ else (flt_time, interp_tas(flt_tas))
1063
+ )
1064
+
1065
+ jobs = min(jobs, n_windows)
1066
+ edges = [round(k * n_windows / jobs) for k in range(jobs + 1)]
1067
+ n_tasks = sum(1 for k in range(jobs) if edges[k + 1] > edges[k])
1068
+ for attempt in range(spawn_retries + 1):
1069
+ tmp = tempfile.mkdtemp(prefix="s2parallel_v35_", dir=workdir)
1070
+ try:
1071
+ try:
1072
+ with concurrent.futures.ProcessPoolExecutor(max_workers=n_tasks) as pool:
1073
+ return _split_decode_v35(
1074
+ infilename, outfilename, edges, pool.map, tmp, flight=flight,
1075
+ time_offset=time_offset, software=software,
1076
+ creation_time=creation_time, sidecars=sidecars,
1077
+ output_txt=output_txt, fast=fast, channels=channels,
1078
+ report_every=report_every, stamp_profile=stamp_profile,
1079
+ progress=progress, stats=stats)
1080
+ except concurrent.futures.process.BrokenProcessPool:
1081
+ # Only a pool that died is retried; an exception raised inside a
1082
+ # part comes back through the result queue and propagates. A
1083
+ # fresh directory each attempt, because part sidecars append.
1084
+ if attempt >= spawn_retries:
1085
+ raise
1086
+ warnings.warn(
1087
+ f"parallel v3.5 decode of {os.path.basename(os.fspath(infilename))}: "
1088
+ f"the worker pool died before completing (attempt {attempt + 1} of "
1089
+ f"{spawn_retries + 1}); restarting it from a fresh temporary directory",
1090
+ SpawnRetryWarning, stacklevel=2)
1091
+ _time.sleep(2.0 * (attempt + 1))
1092
+ finally:
1093
+ shutil.rmtree(tmp, ignore_errors=True)
1094
+ raise AssertionError("unreachable") # pragma: no cover