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,286 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Reproduces SODA-2, Copyright (c) 2016 UCAR; see LICENSES/BSD-3-Clause.txt and NOTICE.md.
3
+ """``spec_read_frame.pro`` -- read and assemble one HVPS3/2DS frame, composing
4
+ ``spec_readint`` and `spec_decompress`.
5
+
6
+ 98 lines of IDL. This is the routine `soda2_processbuffer.pro` (out of scope,
7
+ 748 lines) calls once per particle pointer: given a byte offset into an open
8
+ SPEC raw file and which array (`'H'`/`'V'`) to read, it decodes the frame's
9
+ own tiny 3-word header, reads the rest of the frame with `spec_readint`
10
+ (already ported), assembles a 32-bit time word out of two 16-bit halves,
11
+ recurses up to two levels deep to stitch together a particle whose image was
12
+ split across "missing time word" fragments, and calls `spec_decompress`
13
+ (already ported) on the concatenated raw compressed words.
14
+
15
+ Provenance: ``SODA2/abansemer-soda2-afcea15/spec_read_frame.pro`` (whole
16
+ file), Aaron Bansemer, NCAR, 5/2011. Copyright (C) 2016 UCAR, 3-clause BSD.
17
+ Validated against GDL by ``tests/test_soda2_spec_read_frame.py``; bank at
18
+ ``gdl_oracle/run_soda2_spec_read_frame_bank.py``, 17 cases on a new
19
+ synthetic fixture, all matching. A third side -- a `struct`-only
20
+ recomputation of the whole routine's arithmetic, sharing no code with either
21
+ this module or NumPy -- is asserted against both the golden and the port in
22
+ the same test module (never a fixture compared with itself).
23
+
24
+ **Line-by-line** (IDL 0-based array indexing throughout; every index below
25
+ is exactly what the source writes, no MATLAB-style off-by-one to convert):
26
+
27
+ - `:8-9` -- ``version`` defaults to 0 ("original 2DS/HVPS"; a 2D-S with
28
+ ``subformat=0`` is always this value -- ``soda2_probespecs.pro``'s ``subformat=0``);
29
+ ``recursioncount`` defaults to 0, the recursion-depth counter below.
30
+ - `:11` -- ``point_lun, lun, fpoint`` -- seek to the frame's start.
31
+ - `:13-15` -- ``x = spec_readint(lun, 3)`` reads the frame's own 3-word
32
+ header (unsigned, default ``buffsize``); ``nh = x[1] and 0xFFF``,
33
+ ``nv = x[2] and 0xFFF`` are the H/V block lengths, each a 12-bit field.
34
+ - `:18-23` -- the top four bits of each of ``x[1]``/``x[2]`` are flags:
35
+ bit 12 ``missingtw*`` ("missing time words"), bit 14 ``fifo*`` ("empty
36
+ FIFO" -- decoded and never used downstream, S4-f), bit 15 ``overload*``
37
+ ("last 2 words are overload times"). IDL's ``and`` against a hex INT
38
+ literal like ``'8000'x`` (-32768 as a signed INT) promotes a UINT operand
39
+ to LONG, but every value here is a plain 16-bit field extracted by mask
40
+ and shift, so the promotion changes no bit this port needs to reproduce.
41
+ - `:26-28` -- ``spec_readint`` reads ``2+nh+nv`` words, the rest of the
42
+ frame using the **undecremented** ``nh``/``nv`` (the `version==1`
43
+ decrements at `:39`/`:50` happen only inside the H/V blocks below, after
44
+ this read has already used the original lengths) -- ``particlecount =
45
+ buff[0]``, ``numslices = buff[1]`` (**read and never used again** --
46
+ `spec_decompress` computes its own slice count from the startslice bits,
47
+ S4-f).
48
+ - `:29-35` -- defaults for a frame where neither block ends up running:
49
+ ``image`` a single blank slice, ``time``/``timetrunc`` 0, ``error=1``,
50
+ ``imageraw`` the IDL scalar ``0b`` (never an array), ``overload=0``,
51
+ ``gotframe=0``.
52
+ - `:38-46` -- **H block**, gated on ``nh > 3 and id == 'H'``. `version==1`
53
+ decrements ``nh`` by one first (`:39`) -- "for some reason nh and nv are
54
+ different for these instruments, dummy byte?", the source's own comment,
55
+ reproduced in the bank's `v1_h` case, which carries one literal unused
56
+ dummy word for exactly this reason. `:40`'s ``ELSE imageraw=0s`` is
57
+ unreachable here: it guards ``nh < 3``, but the block is only entered when
58
+ the *original* ``nh > 3``, and a `version==1` decrement of a value that
59
+ was already `> 3` leaves it `>= 3`. ``imageraw = buff[2:nh-1]`` inclusive
60
+ (`nh-2` elements); ``counter = buff[nh:nh+1]`` (2 elements, ``ulong``d).
61
+ - `:49-57` -- **V block**, the mirror image, gated on ``nv > 3 and id ==
62
+ 'V'``. Its slice is ``buff[nh+2:nh+nv-1]`` / ``buff[nh+nv:nh+nv+1]`` --
63
+ note the ``nh`` offset is the **undecremented** value even when the H
64
+ block never ran (``nh`` stays whatever `:14` set it to, 0 in every V-only
65
+ fixture case here, since this port's fixture convention is `nh =
66
+ len(hwords)`).
67
+ - `:63-71` -- assembled only if `gotframe` (either block ran). Version 0:
68
+ ``time = counter[0]<<16 + counter[1]``, ``timetrunc = counter[1]``.
69
+ Version 1: the halves are **reversed** -- ``time = counter[1]<<16 +
70
+ counter[0]``, ``timetrunc = counter[0]`` -- confirmed by the bank's
71
+ `v1_h` case (`TIME=2031646 = 31<<16+30`, matching Hwords' counter
72
+ `[30, 31]` read in reversed order) rather than assumed from the comment
73
+ alone.
74
+ - `:74-86` -- **the recursion**, gated on ``missingtw > 0 and
75
+ recursioncount < 2``. ``REPEAT ... UNTIL q.error eq 0`` calls this same
76
+ routine again at the *current* file position (after this frame's own
77
+ ``spec_readint`` calls have already advanced the pointer), skipping over
78
+ any intervening frame that itself comes back ``error=1`` (a "timeword-only"
79
+ frame the source's own comment names, or -- as the bank's
80
+ `mtw_then_v_then_h`/`v_in_chain` pair demonstrates -- simply a frame for
81
+ the *other* array, which errors here because its ``id`` does not match).
82
+ On success, ``imageraw`` is concatenated with the fragment's, and
83
+ ``time``/``timetrunc``/``overload`` are all **replaced** by the
84
+ fragment's own values (`:82-85`) -- ``particlecount`` alone survives
85
+ from the first fragment, because it is set once at `:27` and never
86
+ touched again. The recursion depth cap silently truncates a particle
87
+ spanning four or more fragments to its first three, and the values
88
+ returned then come from the *third* fragment even though that fragment's
89
+ own header still flags ``missingtw=1`` (finding S4-d, bank case
90
+ `chain_m1`: three ``missingtw``-flagged frames followed by a complete
91
+ one that is never read).
92
+ - `:89` -- the image is ``spec_decompress`` of the raw words with ``overload`` and ``version``,
93
+ the existing port.
94
+ - `:92-93` -- ``error = 0``, then ``IF (overload eq 0) and (nn eq 2) THEN
95
+ error = 1``. **Unreachable**, and kept verbatim: ``nn`` is assigned only
96
+ inside the H/V blocks (`:44`, `:55`), to ``nh``/``nv`` themselves -- both
97
+ are always `>= 3` wherever `nn` is set (the block's own gate is `> 3`,
98
+ and a `version==1` decrement of a value `> 3` cannot reach 2), so this
99
+ comparison against 2 can never be true (finding S4-e).
100
+ - `:96-97` -- the returned fields; ``overload`` is a GDL/IDL ``LONG`` when a
101
+ frame was found and the plain ``INT`` `:34` initialiser otherwise (the
102
+ bank's ``TN`` field distinguishes the two; this port always returns a
103
+ Python ``int``, so the distinction is a fact about IDL's own type system,
104
+ not something this port's callers can observe).
105
+
106
+ **Findings**: **S4-d** (the recursion
107
+ cap silently truncates and reports the truncated fragment's own time),
108
+ **S4-e** (`:93`'s error check is dead code), **S4-f** (`fifoh`/`fifov` and
109
+ the frame's own ``numslices`` are read and discarded).
110
+
111
+ **The GDL-oracle shim.** GDL 1.1.2's ``ISHFT`` returns a 1-element array for
112
+ a scalar operand where real IDL returns a scalar (measured:
113
+ ``size(ishft(0L,-15),/n_dim)`` is 1 under GDL). ``overload`` here is built
114
+ with ``ishft`` (`:22`-`:23`), so when it reaches `spec_decompress.pro`'s
115
+ ``skip=overload*2`` / ``FOR i=0,n-1-skip`` GDL halts. The bank supplies GDL
116
+ a **copy** of the vendored `spec_decompress.pro` with one line inserted
117
+ (``overload = overload[0]``, a no-op under real IDL) ahead of the vendored
118
+ tree on ``GDL_PATH`` -- never an edit to `SODA2/` itself
119
+ (`tests/test_upstream_tree_is_unmodified.py` sweeps it). This is an oracle
120
+ limitation, not a SODA-2 finding; see `gdl_oracle/run_soda2_spec_read_frame_bank.py`.
121
+ """
122
+ from __future__ import annotations
123
+
124
+ from dataclasses import dataclass
125
+ from typing import BinaryIO
126
+
127
+ import numpy as np
128
+
129
+ from .spec_decompress import spec_decompress
130
+ from .spec_readint import spec_readint
131
+
132
+ __all__ = ["SpecFrame", "spec_read_frame"]
133
+
134
+ _MASK_12BIT = 0xFFF
135
+ _MISSINGTW_MASK = 0x1000
136
+ _FIFO_MASK = 0x4000 # `:20-21` -- decoded, never used (S4-f).
137
+ _OVERLOAD_MASK = 0x8000
138
+
139
+
140
+ @dataclass
141
+ class SpecFrame:
142
+ """``q = spec_read_frame(...)``'s return struct (`:96-97`).
143
+
144
+ Source: ``spec_read_frame.pro:96-97`` (SODA-2)."""
145
+
146
+ #: ``(numslices, 128)`` uint8, the package's standing transpose of IDL's
147
+ #: ``bitarr(128, numslices)`` (`spec_decompress`'s own convention). A
148
+ #: single blank slice, ``(1, 128)``, when no frame for `id` was found.
149
+ image: np.ndarray
150
+ #: uint16 1-D when a frame was found; the IDL scalar ``0b`` (here
151
+ #: ``np.uint8(0)``) otherwise -- never a length-1 array. `:33`, `:81`.
152
+ imageraw: np.ndarray | np.uint8
153
+ #: `:64`/`:69` -- assembled from two 16-bit halves, never overflows.
154
+ time: int
155
+ timetrunc: int
156
+ #: 1 unless a frame for `id` was found and decoded (`:32`, `:92`); `:93`
157
+ #: is unreachable and never sets this to anything else (S4-e).
158
+ error: int
159
+ #: 0/1 (or, after the recursion, whatever the last fragment reported).
160
+ overload: int
161
+ #: ``buff[0]`` -- the FIRST fragment's, even after `:74-86`'s
162
+ #: concatenation replaces every other field with the last fragment's.
163
+ particlecount: int
164
+
165
+
166
+ def spec_read_frame(
167
+ f: BinaryIO,
168
+ fpoint: int,
169
+ id: str,
170
+ version: int = 0,
171
+ recursioncount: int = 0,
172
+ ) -> SpecFrame:
173
+ """``q = spec_read_frame(lun, fpoint, id, version=version,
174
+ recursioncount=recursioncount)``.
175
+
176
+ Source: ``spec_read_frame.pro`` (SODA-2).
177
+
178
+ ``f`` is an open binary SPEC raw file; ``fpoint`` the byte offset of the
179
+ frame's start (IDL's ``point_lun, lun, fpoint``, `:11`). ``id`` is
180
+ ``'H'`` or ``'V'`` and is matched **case-sensitively** (IDL's ``eq`` on
181
+ strings), exactly like the source -- ``'h'`` matches neither block and
182
+ comes back as a no-frame result even over a perfectly good H frame
183
+ (bank case ``h_plain_lowercase_id``).
184
+
185
+ No EOF guard: a recursion chain that runs off the end of the file
186
+ raises, exactly as the IDL would (an unhandled read failure), rather
187
+ than silently returning a short frame.
188
+ """
189
+ f.seek(fpoint)
190
+
191
+ # `:13-15` -- the frame's own 3-word header.
192
+ x = spec_readint(f, 3)
193
+ nh = int(x[1]) & _MASK_12BIT
194
+ nv = int(x[2]) & _MASK_12BIT
195
+
196
+ # `:18-23` -- flags packed into the top 4 bits of x[1]/x[2].
197
+ missingtwh = (int(x[1]) & _MISSINGTW_MASK) >> 12
198
+ missingtwv = (int(x[2]) & _MISSINGTW_MASK) >> 12
199
+ # fifoh/fifov (`:20-21`) are decoded for fidelity but never consumed --
200
+ # see the module docstring, S4-f.
201
+ overloadh = (int(x[1]) & _OVERLOAD_MASK) >> 15
202
+ overloadv = (int(x[2]) & _OVERLOAD_MASK) >> 15
203
+
204
+ # `:26-28` -- the rest of the frame, using the UNDECREMENTED nh/nv.
205
+ buff = spec_readint(f, 2 + nh + nv)
206
+ particlecount = int(buff[0])
207
+ # numslices = int(buff[1]) -- read (`:28`) and never used again (S4-f).
208
+
209
+ # `:29-35` -- defaults for "no block ran".
210
+ image = np.zeros((1, 128), dtype=np.uint8)
211
+ time = 0
212
+ timetrunc = 0
213
+ error = 1
214
+ imageraw: np.ndarray | np.uint8 = np.uint8(0)
215
+ overload = 0
216
+ gotframe = False
217
+ nn: int | None = None
218
+ counter: np.ndarray | None = None
219
+ missingtw = 0
220
+
221
+ # `:38-46` -- H block.
222
+ if nh > 3 and id == "H":
223
+ if version == 1:
224
+ nh -= 1 # `:39`
225
+ # `:40` -- `ELSE imageraw=0s` is unreachable here (nh stays >= 3);
226
+ # kept as a comment, not a guard, per the module docstring.
227
+ imageraw = buff[2:nh].copy() # IDL `[2:nh-1]` inclusive -> nh-2 elems
228
+ counter = buff[nh:nh + 2].astype(np.uint32)
229
+ overload = overloadh
230
+ missingtw = missingtwh
231
+ nn = nh
232
+ gotframe = True
233
+
234
+ # `:49-57` -- V block, undecremented `nh` as the offset even here.
235
+ if nv > 3 and id == "V":
236
+ if version == 1:
237
+ nv -= 1 # `:50`
238
+ imageraw = buff[nh + 2:nh + nv].copy()
239
+ counter = buff[nh + nv:nh + nv + 2].astype(np.uint32)
240
+ overload = overloadv
241
+ missingtw = missingtwv
242
+ nn = nv
243
+ gotframe = True
244
+
245
+ if gotframe:
246
+ assert counter is not None and nn is not None
247
+ # `:63-71` -- assemble the 32-bit time word.
248
+ if version == 0:
249
+ time = (int(counter[0]) << 16) + int(counter[1])
250
+ timetrunc = int(counter[1])
251
+ if version == 1:
252
+ time = (int(counter[1]) << 16) + int(counter[0])
253
+ timetrunc = int(counter[0])
254
+
255
+ # `:74-86` -- recursion, capped at depth 2 (three fragments total).
256
+ if missingtw > 0 and recursioncount < 2:
257
+ while True:
258
+ cpoint = f.tell()
259
+ q = spec_read_frame(f, cpoint, id, version=version,
260
+ recursioncount=recursioncount + 1)
261
+ if q.error == 0:
262
+ break
263
+ imageraw = np.concatenate(
264
+ [np.atleast_1d(imageraw), np.atleast_1d(q.imageraw)]
265
+ ).astype(np.uint16)
266
+ time = q.time
267
+ timetrunc = q.timetrunc
268
+ overload = q.overload
269
+
270
+ # `:89` -- decompress.
271
+ image = spec_decompress(imageraw, overload, version=version)
272
+
273
+ # `:92-93` -- unreachable (S4-e), kept verbatim.
274
+ error = 0
275
+ if overload == 0 and nn == 2:
276
+ error = 1
277
+
278
+ return SpecFrame(
279
+ image=image,
280
+ imageraw=imageraw,
281
+ time=time,
282
+ timetrunc=timetrunc,
283
+ error=error,
284
+ overload=overload,
285
+ particlecount=particlecount,
286
+ )
@@ -0,0 +1,301 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Reproduces SODA-2, Copyright (c) 2016 UCAR; see LICENSES/BSD-3-Clause.txt and NOTICE.md.
3
+ """``spec_read_hk.pro`` -- read one HVPS3/2DS housekeeping record: 48 diode
4
+ voltages, a custom-encoded TAS, and a 32-bit time word.
5
+
6
+ 68 lines of IDL. Signature `spec_read_hk(lun, bpoint, buffsize, version=version)`.
7
+ `bpoint` is the byte offset of the `'HK'` marker word itself
8
+ (`spec_index.pro:123-124` records it at the word whose value is 18507), so
9
+ `x[0]` is 18507 and `y[0]` (this module's `.x` field) is 18507.0 -- channel 0
10
+ of the returned array is the tag, not data. `buffsize` is an **optional
11
+ positional** in the IDL; both callers in the vendored tree omit it:
12
+ `soda2_processbuffer.pro:285` `hk=spec_read_hk(1,(*pmisc).hkpointers[i])` (no
13
+ buffsize, no version -- the original 2D-S path) and `spec_process_hk.pro:65`
14
+ `spec_read_hk(lun,hkindex.hkp[i],hkindex.buffsize,version=version)`. An
15
+ undefined `buffsize` reaches `spec_readint.pro:9` and defaults there to 4114
16
+ -- this port makes that default explicit as `buffsize=4114`.
17
+
18
+ Provenance: ``SODA2/abansemer-soda2-afcea15/spec_read_hk.pro`` (whole file),
19
+ Aaron Bansemer, NCAR, 5/2011. Copyright (C) 2016 UCAR, 3-clause BSD.
20
+ Validated against GDL by ``tests/test_soda2_spec_read_hk.py``; bank at
21
+ ``gdl_oracle/run_soda2_spec_read_hk_bank.py``, 12 cases (11 on a new
22
+ synthetic HK fixture, one -- ``s2_real`` -- on the pre-existing tracked
23
+ ``tests/data/s2_spec_raw_fixture``), all matching. A third side, a
24
+ ``struct``-only recomputation that derives ``tas`` from the IEEE bit fields
25
+ directly rather than by the source's own `dec2bin` loop, is asserted against
26
+ both the golden and the port in the same test module.
27
+
28
+ **Line-by-line** (IDL 0-based indexing; every index below is exactly what
29
+ the source writes):
30
+
31
+ - ``:8`` -- ``version`` defaults to **1** ("2DS/HVPS3") -- the *opposite*
32
+ numbering from `spec_read_frame`, where 0 is the 2DS. This module ports
33
+ both versions: ``version=1``, the original 2D-S call shape, here, and
34
+ ``version=2`` in ``_spec_read_hk_v2`` (``:43-65``, below), which
35
+ ``spec_process_hk.pro:65`` reaches through its ``version=version``.
36
+ - ``:10-11`` -- ``hklength=53`` for version 1, ``83`` for version 2; any
37
+ other version leaves ``hklength`` undefined and the IDL's own next line
38
+ would die. This port raises ``ValueError`` there instead.
39
+ - ``:13-14`` -- ``point_lun``; ``x = spec_readint(lun, hklength,
40
+ buffsize=buffsize, /signed)`` -- **signed** INT16, unlike `spec_read_frame`'s
41
+ unsigned reads. ``x`` is INT[53].
42
+ - ``:16`` -- ``f1 = 0.00244140625``, a FLOAT literal that is exactly
43
+ 5*2**-11, hence exact in float32; every coefficient built from it
44
+ (``f1*2``, ``f1*10``, ``f1/2``) is therefore also exact.
45
+ - ``:19-30`` -- ``c0 = fltarr(49)``; ``c0[9:21]=1.6``; ``c0[24]=-3.846``;
46
+ ``c1 = fltarr(49)+1.0``; ``c1[1:6]=f1``; ``c1[7:8]=f1*2``;
47
+ ``c1[9:21]=f1*10``; ``c1[22:23]=f1*2``; ``c1[24]=0.018356``;
48
+ ``c1[25:32]=f1``; ``c1[36:37]=f1/2``. IDL's ``a:b`` slice is **inclusive**;
49
+ the Python slices below add one to the upper bound accordingly. ``1.6``,
50
+ ``-3.846`` and ``0.018356`` are the three coefficients that are NOT exact
51
+ in float32 (measured bit patterns ``3FCCCCCD``, ``C07624DD``, ``3C965F52``).
52
+ - ``:32`` -- ``y = x[0:48]*c1 + c0`` -- INT times FLOAT promotes to FLOAT,
53
+ then a separate FLOAT addition: **two independent single-precision
54
+ roundings, no fused multiply-add**. Reproduced here as two explicit
55
+ float32 NumPy operations, never combined into one expression.
56
+ - ``:35`` -- ``exponent = ishft(x[49] and '3f80'x, -7) + 1`` -- bits 13..7 of
57
+ the high TAS word give the low 7 bits of an IEEE exponent byte; bit 15
58
+ (sign) and bit 14 (the exponent's own MSB) are excluded by the mask, so
59
+ they are silently ignored ("Only works for positive exponents", the
60
+ source's own comment).
61
+ - ``:36`` -- ``mantissabits = [dec2bin8(x[49] and '7f'x), dec2bin16(x[50] and
62
+ 'ffff'x)]`` -- 8 + 16 = 24 bits, **MSB first** (``dec2bin8.pro:9``,
63
+ ``dec2bin16.pro:9``); element 0 is always 0 (a 7-bit value packed into 8
64
+ bits). ``'ffff'x`` is LONG 65535 under GDL, so a negative signed
65
+ ``x[50]`` is masked to its unsigned low word before ``dec2bin16`` examines
66
+ bits 0-15 -- the result is the same as treating it as unsigned outright.
67
+ - ``:37`` -- ``mantissa = 1 + total(mantissabits/2^findgen(24))`` -- every
68
+ term is ``bit_i * 2**-i`` for ``i = 1..23`` (bit 0 is always the padding
69
+ zero), each exactly representable in float32, so the sum is the exact
70
+ IEEE significand ``1.f`` regardless of summation order.
71
+ - ``:38`` -- ``tas = mantissa * 2^exponent`` -- IDL's integer ``^`` on two
72
+ INT operands returns an **INT, wrapping at 16 bits**: measured under GDL,
73
+ ``2^15 = -32768``, ``2^16 = 0``, ``2^128 = 0``, ``2^7 = 128``. This is a
74
+ 16-bit-integer power of two, not a floating-point one -- reproduced here
75
+ with explicit modular arithmetic rather than ``2.0 ** exponent`` (S4-h;
76
+ see ``_wrapped_int_pow2``).
77
+ - ``:40`` -- ``time = ishft(ulong(x[51]),16) + x[52]`` -- the high word is
78
+ correctly widened to ULONG and shifted, but **the low word ``x[52]`` is
79
+ added as the signed INT `:14` already read it**, with no re-masking:
80
+ ULONG + INT promotes to ULONG (measured under GDL), so a low word
81
+ ``>= 0x8000`` is added as a *negative* number, making ``time`` 65536 too
82
+ small; with a zero high word this wraps to just under 2**32 (S4-g).
83
+ - ``:43-65`` -- version 2 (3VCPI/Hawkeye/HVPS-4, 83-word HK): **ported**
84
+ in ``_spec_read_hk_v2``, bit-exact against GDL on four
85
+ synthetic records (``test_soda2_spec_read_hk_v2.py``); the caller is
86
+ ``spec_process_hk.pro:65`` with ``buffsize=0`` from ``spec_index_hk``.
87
+ - ``:67`` -- returns ``{time, tas, x:y, raw:x}``; the struct's own field
88
+ named ``x`` is this port's ``x`` field (the float32[49] `y` array, per the
89
+ source's variable name inside the block) and ``raw`` is the signed
90
+ int16[53] read at `:14`. Measured tnames: ``ULONG, FLOAT, FLOAT[49],
91
+ INT[53]``.
92
+
93
+ **Who consumes what** (read, not measured): ``soda2_processbuffer.pro:288``
94
+ overrides ``hk.tas`` with ``probetas`` when ``subformat ne 0``; for the
95
+ original 2D-S (``subformat=0``) ``hk.tas`` reaches ``clocktas[c]`` (`:305`)
96
+ and the stretch factor (`:307-308`, gated ``hk.tas gt 0``).
97
+ ``spec_process_hk.pro:66-68`` sums ``h.x``, ``h.raw``, ``h.tas``. **No
98
+ caller in the vendored tree reads the ``time`` tag** -- confirmed with
99
+ ``grep -rn "\\.time" soda2_processbuffer.pro spec_process_hk.pro`` (no
100
+ ``hk.time``/``h.time`` hit; the many ``x.time``/``buffer.time`` hits belong
101
+ to unrelated structs).
102
+
103
+ **Findings**: **S4-g** (the signed
104
+ low time word makes `time` 65536 low whenever it is >= 0x8000, unconsumed
105
+ today), **S4-h** (the 16-bit-integer `2^exponent` turns a zero or sub-2 m/s
106
+ TAS into 2.0 or 0.0, and a >=2**15 TAS negative -- reachable through
107
+ `hk.tas` for the 2D-S).
108
+ """
109
+ from __future__ import annotations
110
+
111
+ from dataclasses import dataclass
112
+ from typing import BinaryIO
113
+
114
+ import numpy as np
115
+
116
+ from .spec_readint import spec_readint
117
+
118
+ __all__ = ["SpecHK", "spec_read_hk"]
119
+
120
+ #: `:16` -- exactly 5 * 2**-11, hence exact in float32.
121
+ _F1 = np.float32(0.00244140625)
122
+
123
+ #: `:19-30`, built once at import time. IDL slices are inclusive; the Python
124
+ #: slices below add one to every upper bound. `1.6`, `-3.846` and `0.018356`
125
+ #: are the three coefficients NOT exactly representable in float32.
126
+ _C0 = np.zeros(49, dtype=np.float32)
127
+ _C0[9:22] = np.float32(1.6)
128
+ _C0[24] = np.float32(-3.846)
129
+
130
+ _C1 = np.ones(49, dtype=np.float32)
131
+ _C1[1:7] = _F1
132
+ _C1[7:9] = _F1 * np.float32(2)
133
+ _C1[9:22] = _F1 * np.float32(10)
134
+ _C1[22:24] = _F1 * np.float32(2)
135
+ _C1[24] = np.float32(0.018356)
136
+ _C1[25:33] = _F1
137
+ _C1[36:38] = _F1 / np.float32(2)
138
+
139
+
140
+ def _wrapped_int_pow2(exponent: int) -> int:
141
+ """``2^exponent`` (IDL's integer ``^``) as GDL evaluates it: a 16-bit
142
+ **signed INT**, wrapping modulo 65536 (`:38`, S4-h). Measured under GDL:
143
+ ``2^7 = 128``, ``2^15 = -32768``, ``2^16 = 0``, ``2^128 = 0``."""
144
+ p = pow(2, exponent) % 65536
145
+ if p >= 32768:
146
+ p -= 65536
147
+ return p
148
+
149
+
150
+ @dataclass
151
+ class SpecHK:
152
+ """``hk = spec_read_hk(...)``'s return struct (`:67`).
153
+
154
+ Source: ``spec_read_hk.pro:67`` (SODA-2)."""
155
+
156
+ #: `:40` -- ULONG. Carries S4-g (the signed low word) and the modulo-2**32
157
+ #: wrap that follows from it.
158
+ time: int
159
+ #: `:38` -- FLOAT, built from an exact mantissa and a 16-bit-wrapped
160
+ #: integer power of two (S4-h).
161
+ tas: np.float32
162
+ #: `:32` -- float32[49], the struct's own ``x`` tag (named ``y`` in the
163
+ #: source's local variables). Channel 0 is the `'HK'` marker word itself
164
+ #: (18507.0), not data.
165
+ x: np.ndarray
166
+ #: `:14` -- int16[53], the raw signed housekeeping words as read.
167
+ raw: np.ndarray
168
+
169
+
170
+ def spec_read_hk(
171
+ f: BinaryIO,
172
+ bpoint: int,
173
+ buffsize: int = 4114,
174
+ version: int = 1,
175
+ ) -> SpecHK:
176
+ """``hk = spec_read_hk(lun, bpoint, buffsize=buffsize, version=version)``.
177
+
178
+ ``f`` is an open binary SPEC raw file; ``bpoint`` the byte offset of the
179
+ housekeeping record's `'HK'` marker word (IDL's ``point_lun,lun,bpoint``,
180
+ `:13`). ``buffsize=4114`` reproduces the IDL's *effective* default: the
181
+ source declares ``buffsize`` as an optional positional with no explicit
182
+ default, and an omitted argument reaches ``spec_readint.pro:9``, which
183
+ defaults it to 4114 -- both vendored callers omit it.
184
+
185
+ ``version=1`` (2DS/HVPS3, 53 words) and ``version=2`` (3VCPI/Hawkeye,
186
+ 83 words, `:43-65`, ``_spec_read_hk_v2``) are both ported; any other
187
+ value raises ``ValueError``, matching the IDL's own fate at `:14`
188
+ (``hklength`` undefined). The refusal does not advance the file
189
+ position -- exactly as the IDL would not have read anything either.
190
+ """
191
+ if version == 2:
192
+ return _spec_read_hk_v2(f, bpoint, buffsize)
193
+ if version != 1:
194
+ raise ValueError(
195
+ f"spec_read_hk: version={version!r} is not 1 or 2 -- the IDL "
196
+ "leaves `hklength` undefined here and the next line dies "
197
+ "(spec_read_hk.pro:10-14)")
198
+
199
+ f.seek(bpoint)
200
+
201
+ # `:13-14` -- 53 signed words: marker, 48 channels, TAS hi/lo, time hi/lo.
202
+ x = spec_readint(f, 53, buffsize=buffsize, signed=True)
203
+
204
+ # `:32` -- INT * FLOAT -> FLOAT, then + FLOAT: two separate roundings.
205
+ y = x[0:49].astype(np.float32) * _C1 + _C0
206
+
207
+ hi = int(x[49])
208
+ lo = int(x[50])
209
+
210
+ # `:35` -- bits 13..7 of the high word are the low 7 bits of an IEEE
211
+ # exponent byte; the sign bit (15) and exponent MSB (14) are excluded.
212
+ exponent = ((hi & 0x3F80) >> 7) + 1
213
+
214
+ # `:36` -- 8 + 16 mantissa bits, MSB first. `hi & 0x7F` is the 7-bit low
215
+ # byte of the high word (bit 0 of the 8-bit result is always 0); `lo &
216
+ # 0xFFFF` masks a negative signed low word to its unsigned bit pattern,
217
+ # matching IDL's `'ffff'x` LONG mask under GDL.
218
+ hi_bits = [(hi & 0x7F) >> (7 - i) & 1 for i in range(8)]
219
+ lo_bits = [((lo & 0xFFFF) >> (15 - i)) & 1 for i in range(16)]
220
+ bits = hi_bits + lo_bits
221
+
222
+ # `:37` -- exact: every term is a dyadic fraction, so order cannot matter.
223
+ mantissa = np.float32(1.0 + sum(b / 2.0 ** i for i, b in enumerate(bits)))
224
+
225
+ # `:38` -- S4-h: a 16-bit-wrapped integer power of two, not `2.0 **
226
+ # exponent`.
227
+ p = _wrapped_int_pow2(exponent)
228
+ tas = np.float32(mantissa) * np.float32(p)
229
+
230
+ # `:40` -- S4-g: the low word is added signed, unmasked; ULONG + INT
231
+ # promotes to ULONG under GDL, so the whole sum is taken modulo 2**32.
232
+ # NOTE: the time halves are x[51]/x[52], distinct from the TAS halves
233
+ # x[49]/x[50] (`hi`/`lo` above) -- do not conflate the two.
234
+ time_hi = int(x[51])
235
+ time = (((time_hi & 0xFFFF) << 16) + int(x[52])) & 0xFFFFFFFF
236
+
237
+ return SpecHK(time=time, tas=tas, x=y, raw=x)
238
+
239
+
240
+ def _decode_tas(hi: int, lo: int) -> np.float32:
241
+ """`:35-38` / `:59-62`, identical in both versions (S4-h)."""
242
+ exponent = ((hi & 0x3F80) >> 7) + 1
243
+ hi_bits = [(hi & 0x7F) >> (7 - i) & 1 for i in range(8)]
244
+ lo_bits = [((lo & 0xFFFF) >> (15 - i)) & 1 for i in range(16)]
245
+ mantissa = np.float32(1.0 + sum(b / 2.0 ** i for i, b in enumerate(hi_bits + lo_bits)))
246
+ return np.float32(mantissa) * np.float32(_wrapped_int_pow2(exponent))
247
+
248
+
249
+ #: `:50`'s three FLOAT literals, widened to DOUBLE by `alog(rt)` (DOUBLE).
250
+ _T_A = float(np.float32(1.111e-3))
251
+ _T_B = float(np.float32(237e-6))
252
+ _T_C = float(np.float32(75.8e-9))
253
+
254
+
255
+ def _spec_read_hk_v2(f: BinaryIO, bpoint: int, buffsize: int) -> SpecHK:
256
+ """`:43-65` -- version 2 (3VCPI/Hawkeye/HVPS-4), 83 words.
257
+
258
+ - `:46` ``y = float(x)``, then `:49-56` overwrite three bands.
259
+ - `:49` ``rt = 6.5536e9*(1-x/65536d)/(5*x)`` on ``x[2:28]``: ``5*x`` is
260
+ **INT times INT, wrapping at 16 bits** before the DOUBLE division, so
261
+ any raw word above 6553 (or below -6553) gives a wrong-signed or wrong
262
+ denominator; a zero word divides by zero (``rt = +Inf``, temperature
263
+ -273.15); a negative ``rt`` gives NaN.
264
+ - `:50` DOUBLE Steinhart-Hart with FLOAT-literal coefficients, stored to
265
+ FLOAT. `:53` pressure and `:56` volts: FLOAT, two roundings.
266
+ - `:59-62` TAS from ``x[75:76]``, the v1 decode (S4-h included).
267
+ - `:64` ``time = ishft(ulong(x[72]),32) + ishft(ulong(x[73]),16) + x[74]``
268
+ -- a 32-bit shift of a 32-bit ULONG, then the signed low word added
269
+ unmasked as in v1 (S4-g). What GDL makes of the 32-bit shift is the
270
+ golden's; the port reproduces the measured value (see ``_ishft32``).
271
+ """
272
+ f.seek(bpoint)
273
+ x = spec_readint(f, 83, buffsize=buffsize, signed=True)
274
+ y = x.astype(np.float32) # `:46`
275
+
276
+ xt = x[2:29].astype(np.int64)
277
+ five_x = ((5 * xt + 32768) % 65536) - 32768 # INT*INT wraps
278
+ with np.errstate(divide="ignore", invalid="ignore"):
279
+ rt = float(np.float32(6.5536e9)) * (1 - xt / 65536.0) / five_x.astype(np.float64)
280
+ lr = np.log(rt)
281
+ t = np.float64(np.float32(-273.15)) + (_T_A + _T_B * lr + _T_C * lr ** 3) ** (-1)
282
+ y[2:29] = t.astype(np.float32)
283
+
284
+ y[29] = np.float32(np.float32(x[29]) * np.float32(5.72e-4)) - np.float32(3.75) # `:53`
285
+ y[34:54] = x[34:54].astype(np.float32) * _F1 # `:56`
286
+
287
+ tas = _decode_tas(int(x[75]), int(x[76]))
288
+
289
+ time = (_ishft32(int(x[72]) & 0xFFFFFFFF) + (((int(x[73]) & 0xFFFFFFFF) << 16)
290
+ & 0xFFFFFFFF) + int(x[74])) & 0xFFFFFFFF
291
+ return SpecHK(time=time, tas=tas, x=y, raw=x)
292
+
293
+
294
+ def _ishft32(v: int) -> int:
295
+ """``ishft(ulong(v), 32)`` as GDL evaluates it (`:64`): **unshifted**.
296
+ Measured (bank ``read_r1``, ``x[72]=1``; ``read_r3``, ``x[72]=2``): the
297
+ word is added as is, the x86 behaviour of a 32-bit shift whose count is
298
+ taken modulo 32. So the high time word lands on the low bits instead of
299
+ bits 32-47, which a ULONG cannot hold anyway. GDL-measured only; what
300
+ IDL returns for a shift >= the type's width is not confirmed here."""
301
+ return v & 0xFFFFFFFF