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,181 @@
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
+ """``binary_dof.pro`` -- depth-of-field rejection by neighbour compactness.
4
+
5
+ Source: ``SODA2/abansemer-soda2-afcea15/binary_dof.pro`` (33 lines). Called
6
+ from exactly one place, ``soda2_processbuffer.pro:303``, inside the SPEC
7
+ branch already ported as :mod:`arrayprobe_soda2.processbuffer_spec`, and
8
+ only when ``(*pop).dofreject eq 3``::
9
+
10
+ dof[c] = binary_dof(x.image)
11
+
12
+ ``x.image`` is the decoded frame, IDL dims ``[128, nslices]``
13
+ (``spec_read_frame.pro:29``); this package's convention holds it
14
+ **transposed**, ``(nslices, 128)`` uint8 (``spec_read_frame.py:204``). The
15
+ result lands in ``dofflag``/``dof`` (``soda2_processbuffer.pro:744``) and
16
+ reaches output.
17
+
18
+ What ``binary_dof.pro`` does, by line:
19
+
20
+ - ``:1`` -- the function takes ``bitimage`` and returns ``neighbor_count``
21
+ through a keyword.
22
+ - ``:5`` -- an image holding any value above 1 halts IDL with a
23
+ "must be binary" message.
24
+ - ``:6`` -- ``s`` is the image's dimensions.
25
+ - ``:8-13`` -- an image under 3 pixels on either side is zero-padded to at
26
+ least 3x3 (original in the low corner); otherwise it is used as is.
27
+ - ``:16`` -- a 3x3 kernel: 0.7 on the diagonals, 1 on the edges, 0 centre.
28
+ - ``:17`` -- ``neighbor_count`` is the sum, over shaded pixels, of the
29
+ zero-edged convolution of the (padded) image with that kernel.
30
+ - ``:21`` -- ``area`` is the shaded-pixel total of the unpadded image.
31
+ - ``:22`` -- ``dof`` starts at 0.
32
+ - ``:23-31`` -- ``dof`` becomes 1 for area 1 unconditionally, and for areas
33
+ 2-6 when ``neighbor_count`` reaches 2, 5, 8, 11 and 17 respectively;
34
+ above 6, when it reaches three times the area.
35
+ - ``:32`` -- returns ``dof``.
36
+
37
+ **``stop`` -> ``ValueError``.** ``:5``'s ``stop`` is an interactive IDL
38
+ halt; this port raises :class:`ValueError` instead, a deliberate,
39
+ documented divergence.
40
+ In practice this is unreachable from ``:303`` -- ``x.image`` is binary by
41
+ construction out of ``spec_decompress`` -- confirmed under GDL (bank case
42
+ ``value_two``, ``status=HALTED``); this turned out to be fine and is not
43
+ a defect.
44
+
45
+ **The GDL oracle needed a zero-ring embedding, not a raw call** (measured
46
+ 2026-09-14). On this machine's GDL (v1.1.2-52),
47
+ ``EDGE_CONSTANT`` is accepted by ``convol`` but silently **ignored** --
48
+ edge outputs come back zero exactly as the no-keyword default -- and a 3x3
49
+ kernel is **refused** on any array with a dimension equal to 3
50
+ (``% CONVOL: Incompatible dimensions for Array and Kernel``). Since every
51
+ real particle typically touches slice 0 and slice n-1 (both array edges),
52
+ a raw GDL call gives the wrong ``neighbor_count`` for essentially every
53
+ case, not just a corner: measured ``binary_dof(bytarr(3,3)+1b)`` gives
54
+ ``NC=6.8, DOF=0`` under GDL where IDL's documented ``EDGE_CONSTANT``
55
+ (pad-with-constant) computes ``NC=35.2, DOF=1``.
56
+
57
+ The bank instead calls the **unmodified** ``binary_dof.pro`` on the image
58
+ embedded in a one-pixel ring of zeros. This equals IDL's
59
+ ``EDGE_CONSTANT=0`` result on the unpadded image **by derivation from the
60
+ keyword's definition** (pad-with-constant), not by measurement against
61
+ IDL: the zeroed GDL edge outputs then fall on the padding ring, which
62
+ ``* image`` masks to 0 regardless; interior sums are exact; ``area =
63
+ total(bitimage)`` is unchanged by zero padding; and both dimensions are
64
+ now >= 3, so the "Incompatible dimensions" refusal cannot fire. Both GDL
65
+ facts are **oracle notes**, not
66
+ SODA-2 findings -- the routine itself is unmodified.
67
+
68
+ **IDL semantics this port models:**
69
+
70
+ - ``:6-13`` padding to ``[s0>3, s1>3]`` is output-neutral under
71
+ ``EDGE_CONSTANT=0`` (a zero-filled convolution edge either way); this
72
+ port never pads -- ``test_unpadded_and_zero_ring_embedded_images_agree``
73
+ pins that a 1-, 2- and 3-slice image gives the same ``neighbor_count``
74
+ whether or not it is embedded in a zero ring first.
75
+ - ``:16-17`` the kernel is symmetric with a zero centre, so orientation
76
+ and correlation-vs-convolution conventions are moot; for each ON pixel,
77
+ ``neighbor_count`` accumulates the weighted count of its ON 8-neighbours
78
+ (direct 1.0, diagonal 0.7). ``total()`` of a FLOAT array is FLOAT;
79
+ accumulation order/precision of IDL ``total`` is undocumented for this
80
+ purpose, so this port sums explicitly in **float32**, in IDL memory
81
+ order (diode fastest, then slice -- plain C-order over the transposed
82
+ ``(nslices, 128)`` array).
83
+ - ``:21-31`` ``area`` is FLOAT; the ``CASE`` compares FLOAT against
84
+ integer literals (``1.0 eq 1`` is true in IDL). A blank image
85
+ (``area = 0``) falls to ``ELSE``, and ``0 ge 0`` is true -- **accepted**
86
+ (finding S4-v).
87
+
88
+ Validated against GDL by ``tests/test_soda2_binary_dof.py``; bank at
89
+ ``gdl_oracle/run_soda2_binary_dof_bank.py``.
90
+ """
91
+ from __future__ import annotations
92
+
93
+ from dataclasses import dataclass
94
+
95
+ import numpy as np
96
+
97
+ __all__ = ["KERNEL", "THRESHOLDS", "BinaryDof", "binary_dof"]
98
+
99
+ #: ``binary_dof.pro:16``, transcribed verbatim. FLOAT, symmetric, centre 0.
100
+ KERNEL = np.array(
101
+ [[0.7, 1.0, 0.7], [1.0, 0.0, 1.0], [0.7, 1.0, 0.7]], dtype=np.float32,
102
+ )
103
+
104
+ #: ``binary_dof.pro:23-29``. ``area == 1`` accepts unconditionally (``None``
105
+ #: means "no threshold test needed" -- handled separately below).
106
+ THRESHOLDS: dict[int, float | None] = {1: None, 2: 2.0, 3: 5.0, 4: 8.0, 5: 11.0, 6: 17.0}
107
+
108
+ _OFFSETS = (
109
+ (-1, -1, 0.7), (-1, 0, 1.0), (-1, 1, 0.7),
110
+ (0, -1, 1.0), (0, 1, 1.0),
111
+ (1, -1, 0.7), (1, 0, 1.0), (1, 1, 0.7),
112
+ )
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class BinaryDof:
117
+ """``binary_dof.pro``'s return value plus its ``neighbor_count=``
118
+ output keyword and the ``area`` it computed along the way."""
119
+
120
+ dof: int
121
+ neighbor_count: np.float32
122
+ area: np.float32
123
+
124
+
125
+ def binary_dof(bitimage: np.ndarray) -> BinaryDof:
126
+ """``d = binary_dof(bitimage, neighbor_count=nc)``.
127
+
128
+ Source: ``binary_dof.pro`` (SODA-2).
129
+
130
+ ``bitimage`` is a 2-D binary (0/1) array, this package's
131
+ ``(nslices, 128)`` convention. A 1-D 128-vector (the one-slice IDL
132
+ frame ``[128, 1]``, itself 2-D) is reshaped to ``(1, 128)``.
133
+ """
134
+ arr = np.asarray(bitimage)
135
+ if arr.ndim == 1:
136
+ arr = arr.reshape(1, -1)
137
+ if arr.size == 0:
138
+ max_val = 0
139
+ else:
140
+ max_val = int(arr.max())
141
+ if max_val > 1:
142
+ raise ValueError("binary_dof.pro:5: Bitimage must be binary")
143
+
144
+ img = np.asarray(arr, dtype=np.uint8)
145
+ f = img.astype(np.float32)
146
+ nrows, ncols = f.shape
147
+
148
+ # `:17` -- for each ON pixel, sum the weighted ON 8-neighbours, in IDL
149
+ # memory order (diode fastest, then slice: plain C-order here).
150
+ contrib = np.zeros_like(f, dtype=np.float32)
151
+ for dr, dc, weight in _OFFSETS:
152
+ shifted = np.zeros_like(f, dtype=np.float32)
153
+ src_r0, src_r1 = max(0, -dr), nrows - max(0, dr)
154
+ src_c0, src_c1 = max(0, -dc), ncols - max(0, dc)
155
+ dst_r0, dst_r1 = max(0, dr), nrows - max(0, -dr)
156
+ dst_c0, dst_c1 = max(0, dc), ncols - max(0, -dc)
157
+ if src_r1 > src_r0 and src_c1 > src_c0:
158
+ shifted[dst_r0:dst_r1, dst_c0:dst_c1] = f[src_r0:src_r1, src_c0:src_c1]
159
+ contrib += np.float32(weight) * shifted
160
+
161
+ masked = contrib * f
162
+ neighbor_count = np.float32(0)
163
+ for v in masked.ravel(order="C"):
164
+ neighbor_count = np.float32(neighbor_count + v)
165
+
166
+ area = np.float32(img.sum())
167
+
168
+ area_int = int(area)
169
+ dof = 0
170
+ named_thr = THRESHOLDS.get(area_int) if float(area_int) == float(area) else None
171
+ if area == np.float32(1):
172
+ dof = 1
173
+ elif float(area_int) == float(area) and area_int in THRESHOLDS:
174
+ if named_thr is not None and neighbor_count >= np.float32(named_thr):
175
+ dof = 1
176
+ else:
177
+ else_thr = np.float32(area * np.float32(3))
178
+ if neighbor_count >= else_thr:
179
+ dof = 1
180
+
181
+ return BinaryDof(dof=dof, neighbor_count=neighbor_count, area=area)
@@ -0,0 +1,113 @@
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
+ """`soda2_buildindex.pro:8-17` (SPEC branch);
4
+ the generic `REPEAT` loop at `:20-61`, reached for SEA (the CIP
5
+ route through :func:`read2dbuffer.read2dbuffer_sea`) -- :func:`buildindex_generic`.
6
+
7
+ Vendored source: `SODA2/abansemer-soda2-afcea15/soda2_buildindex.pro`.
8
+ Bank: `gdl_oracle/run_soda2_preloop_bank.py`, golden
9
+ `tests/data/gdl_soda2_preloop_golden.json`.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import gzip
14
+ import os
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import BinaryIO
18
+
19
+ import numpy as np
20
+
21
+ from .spec_index import SpecIndex, spec_index
22
+
23
+ #: `:32` -- ``bignumber = 5000000``, the index arrays' fixed length.
24
+ _BIGNUMBER = 5_000_000
25
+
26
+
27
+ @dataclass
28
+ class GenericIndex:
29
+ """`soda2_buildindex.pro:60`'s ``{bufftime, date, pointer, count, error}``,
30
+ or the error returns ``{error:2}`` (empty file, `:28`) and ``{error:1}``
31
+ (fewer than two buffers, `:54`), which carry ``count=0`` here. ``pointer``
32
+ and ``date`` are LONG (`:33,:35` ``lonarr``), ``bufftime`` DOUBLE."""
33
+
34
+ bufftime: np.ndarray
35
+ date: np.ndarray
36
+ pointer: np.ndarray
37
+ count: int
38
+ error: int
39
+
40
+
41
+ def buildindex_generic(path: str | Path, op: dict) -> GenericIndex:
42
+ """`soda2_buildindex.pro:20-61`: walk the file with ``soda2_read2dbuffer``
43
+ and keep every buffer with ``eof eq 0`` and ``0 < time < 200000``
44
+ (`:42`; ``time`` already includes ``op.timeoffset``). A ``.gz`` file is
45
+ opened decompressed (`:22-24`, ``compress=1``); the SPEC branch (`:8-17`)
46
+ opens without ``compress=``, as IDL does."""
47
+ from .read2dbuffer import read2dbuffer
48
+
49
+ fn = str(path)
50
+ compress = fn[-3:] == ".gz" # :21-22
51
+ # :25 `fstat(1).size` on a `compress=1` lun is the compressed on-disk
52
+ # length (GDL-measured: 279 for a 256-byte payload; 20 for an empty .gz),
53
+ # so an empty .gz never takes the error-2 branch and walks to EOF at once.
54
+ if os.path.getsize(fn) == 0: # :25-29
55
+ return GenericIndex(np.zeros(0), np.zeros(0, np.int32), np.zeros(0, np.int32), 0, 2)
56
+ with (gzip.open(fn, "rb") if compress else open(fn, "rb")) as f: # :24
57
+ pointer: list[int] = []
58
+ bufftime: list[float] = []
59
+ date: list[int] = []
60
+ while True: # :39-49
61
+ x = read2dbuffer(f, op) # type: ignore[arg-type]
62
+ if x.eof == 0 and 0 < float(x.time) < 200000:
63
+ if len(pointer) >= _BIGNUMBER:
64
+ raise RuntimeError("soda2_buildindex.pro:43: pointer[c] subscript out of range")
65
+ pointer.append(int(x.pointer))
66
+ bufftime.append(float(x.time))
67
+ date.append(int(x.date))
68
+ if x.eof == 1:
69
+ break
70
+ c = len(pointer)
71
+ if c < 2: # :52-54
72
+ return GenericIndex(np.zeros(0), np.zeros(0, np.int32), np.zeros(0, np.int32), 0, 1)
73
+ return GenericIndex(bufftime=np.asarray(bufftime, dtype=np.float64),
74
+ date=np.asarray(date, dtype=np.int32),
75
+ pointer=np.asarray([lonarr_store(p) for p in pointer], dtype=np.int32),
76
+ count=c, error=0)
77
+
78
+
79
+ def lonarr_store(value: int) -> int:
80
+ """What `pointer[c] = x.pointer` (`soda2_buildindex.pro:43`) leaves in a
81
+ `lonarr` element: IDL/GDL converts a LONG64 to 32-bit LONG by two's-complement
82
+ wrap, with no error (measured under GDL,
83
+ `tests/data/gdl_soda2_lonarr_wrap_golden.json`: 2147483648 -> -2147483648,
84
+ 3000000000 -> -1294967296, 5000000000 -> 705032704). NumPy's `int32` cast
85
+ raises instead, so the wrap is done explicitly here."""
86
+ return ((int(value) + 2**31) % 2**32) - 2**31
87
+
88
+
89
+ def point_lun(f: BinaryIO, pointer: int) -> None:
90
+ """`soda2_process_2d.pro:451` ``point_lun, lun, pointer``. Under GDL a
91
+ negative (wrapped, S9-t) pointer is ignored: the position is unchanged
92
+ and no error is raised (golden ``negative_seek``)."""
93
+ if int(pointer) >= 0:
94
+ f.seek(int(pointer))
95
+
96
+
97
+ def buildindex(path: str | Path, op: dict) -> SpecIndex | GenericIndex:
98
+ """`soda2_buildindex.pro:8-17`. Opens `path`, calls `spec_index` with
99
+ **no keywords** (`:12`), closes, then adds `op["timeoffset"]` to
100
+ `bufftime` (`:15`) -- same FLOAT-widening rule as
101
+ `read2dbuffer.read2dbuffer_spec` (T7). `spec_index`'s own exceptions
102
+ (`SpecIndexError`, `SpecFileMisaligned`) propagate unchanged. Any other
103
+ format takes the generic walk (`:20-61`, :func:`buildindex_generic`)."""
104
+ if op.get("format") != "SPEC":
105
+ return buildindex_generic(path, op)
106
+
107
+ with open(path, "rb") as f:
108
+ idx = spec_index(f) # no keyword -> always SpecIndex, never SpecIndexLite
109
+ assert isinstance(idx, SpecIndex)
110
+
111
+ offset = float(op.get("timeoffset", 0.0)) # FLOAT -> DOUBLE widening (T7)
112
+ idx.bufftime = idx.bufftime + offset
113
+ return idx
@@ -0,0 +1,285 @@
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
+ """SODA-2's DMT CIP image decoder : ``decompress_dmt3.pro`` (133
4
+ lines) and ``decode_header_slice.pro`` (39), ported whole, with the two bit
5
+ helpers they call (``dec2bin8.pro``, ``bin2dec.pro``) folded in.
6
+
7
+ ``decompress_dmt3`` is what ``soda2_processbuffer.pro:130`` calls for
8
+ ``probetype eq 'CIP'``; ``decompress_dmt.pro`` (the older version) has no
9
+ caller in the vendored tree and is not ported.
10
+
11
+ Vendored sources (never edited): ``SODA2/abansemer-soda2-afcea15/
12
+ decompress_dmt3.pro``, ``decode_header_slice.pro``, ``dec2bin8.pro``,
13
+ ``bin2dec.pro``. GDL bank: ``gdl_oracle/run_soda2_cip_bank.py``.
14
+
15
+ **The compression** (DMT manual, as the IDL reads it): each header byte
16
+ ``rlehb`` carries three flags and a 5-bit ``count``. ``0x80`` alone: write
17
+ ``count+1`` bytes of ``0x00`` (shadowed); ``0x40`` alone: ``count+1`` bytes of
18
+ ``0xFF`` (blank); no flag: copy the next ``count+1`` bytes literally;
19
+ ``0x20`` (dummy), or ``0x80|0x40`` together: nothing. A particle starts with
20
+ a sync slice (eight ``0xAA``) followed by a header ("time") slice; a slice is
21
+ 8 bytes = 64 diodes.
22
+
23
+ **IDL semantics this port reproduces** (the bank covers the revert, null and nominal paths;
24
+ the ``ipos == 0`` and overflow halts are read, with the ``[0:-1]`` rule measured under GDL):
25
+
26
+ - ``:13`` -- ``image=bytarr(8,20000)+255`` is **INT**, not BYTE (``BYTE +
27
+ INT``), so the decompressed ``image`` and the ``not(image)`` at ``:126`` are
28
+ 16-bit; ``dec2bin8`` then reads only the low 8 bits.
29
+ - ``:28-34`` -- the first sync search keeps a candidate only when the byte
30
+ *before* the eight ``0xAA`` is a literal-run header with ``count`` in
31
+ ``7..31``.
32
+ - ``:39``, ``:49`` -- the ``c``-th (last) sync is never decompressed:
33
+ ``syncpos[c]`` is the array's zero initialiser, so ``FOR cipos=syncpos[c-1],
34
+ -1`` runs no iterations.
35
+ - ``:49-78`` -- the inner ``FOR`` modifies its own loop variable
36
+ (``cipos=cipos+count+1``), and IDL honours that; after the loop ``cipos`` is
37
+ one past the last value tested, which ``:43`` then compares with the next
38
+ sync position to detect a literal run that overran it ("decompression
39
+ error": revert to the particle's start, ``:45-46``).
40
+ - ``:69`` -- a literal run that would read past the buffer is skipped whole
41
+ (no bytes written, ``ipos`` and ``cipos`` not advanced).
42
+ - ``:81``, ``:86`` -- ``image[0:ipos-1]`` with ``ipos == 0`` is ``image[0:-1]``
43
+ -- the **whole** 160 000-element array (IDL 8 and GDL both read a negative
44
+ range end from the array's end; measured under GDL).
45
+ - ``:96`` -- the second sync search (over the decompressed slices) is what
46
+ defines the particles; it tests bytes 0, 1 and 7 of a slice and the slice
47
+ total ``1360`` (= 8 x 170).
48
+ - ``:123-124`` -- ``slice_count`` counts the slices from a sync to the next
49
+ sync **minus one**, i.e. the header slice plus the image slices; the caller
50
+ adds 2 to the sync index for the first image slice and ``slice_count-1``
51
+ for the last, so each particle's last slice is the *next* particle's sync
52
+ slice (blanked by ``soda2_processbuffer.pro:180``).
53
+ - ``decode_header_slice.pro:13-35`` -- the header's 8 bytes are reversed and
54
+ read MSB-first: the 64-bit word is the header read little-endian; bits
55
+ 63-57 slice count, 56 DoF, 55-51 hour, 50-45 minute, 44-39 second, 38-29
56
+ millisecond, 28-16 the 125-ns counter, 15-0 the particle counter.
57
+ """
58
+ from __future__ import annotations
59
+
60
+ from dataclasses import dataclass
61
+
62
+ import numpy as np
63
+
64
+ __all__ = ["HeaderSlice", "Dmt3Result", "decode_header_slice", "decompress_dmt3"]
65
+
66
+ _IMAGE_LEN = 8 * 20000
67
+ _SYNC_ARRAY_LEN = 1000 # `:27` syncpos=intarr(1000)
68
+ _SLICE_ARRAY_LEN = 500 # `:88-93`
69
+
70
+
71
+ class DecompressDmtError(RuntimeError):
72
+ """An IDL halt (subscript out of range) this port raises, naming the line."""
73
+
74
+
75
+ @dataclass
76
+ class HeaderSlice:
77
+ """``decode_header_slice.pro:37``'s return. ``particle_count``,
78
+ ``slice_count``, ``time`` and ``time_sfm`` are 1-element arrays in IDL
79
+ (``bin2dec`` returns ``ulonarr(n)``); scalars here, the values are the
80
+ same."""
81
+
82
+ particle_count: int
83
+ slice_count: int
84
+ dof: int
85
+ time: float
86
+ time_sfm: float
87
+
88
+
89
+ def decode_header_slice(header: np.ndarray) -> HeaderSlice:
90
+ """``decode_header_slice.pro``. ``header`` is 8 values 0..255 (the INT
91
+ slice of the decompressed image); only each value's low 8 bits are read
92
+ (``dec2bin8.pro:9``)."""
93
+ h = [int(v) & 0xFF for v in np.asarray(header)[::-1]] # :13 reverse
94
+ w = 0
95
+ for byte in h: # :16 dec2bin8, MSB first
96
+ w = (w << 8) | byte
97
+ particle_count = w & 0xFFFF # :19 bslice[48:63]
98
+ slice_count = (w >> 57) & 0x7F # :22 bslice[0:6]
99
+ dof = (w >> 56) & 1 # :25 bslice[7]
100
+ hour = (w >> 51) & 0x1F # :28 bslice[8:12]
101
+ minute = (w >> 45) & 0x3F # :29 bslice[13:18]
102
+ second = (w >> 39) & 0x3F # :30 bslice[19:24]
103
+ millisecond = (w >> 29) & 0x3FF # :31 bslice[25:34]
104
+ counter = (w >> 16) & 0x1FFF # :32 bslice[35:47]
105
+ # :34-35 -- left to right in DOUBLE; `1.0e9` is a FLOAT literal, exact.
106
+ time = (hour * 10000.0 + minute * 100.0 + float(second)
107
+ + millisecond / 1000.0 + counter * 125.0 / 1.0e9)
108
+ time_sfm = (hour * 3600.0 + minute * 60.0 + float(second)
109
+ + millisecond / 1000.0 + counter * 125.0 / 1.0e9)
110
+ return HeaderSlice(particle_count=particle_count, slice_count=slice_count,
111
+ dof=dof, time=time, time_sfm=time_sfm)
112
+
113
+
114
+ @dataclass
115
+ class Dmt3Result:
116
+ """``decompress_dmt3.pro:129-131`` (``null=False``) or the ``nullbuffer``
117
+ of ``:18-19`` (``null=True``: ``slice_count`` 0, ``header_slice_count``
118
+ 999, everything else 0 -- so the caller's ``good1`` test at
119
+ ``soda2_processbuffer.pro:134`` finds nothing)."""
120
+
121
+ null: bool
122
+ image: np.ndarray # INT, (8*slices,) -- `:13`, INT not BYTE
123
+ bitimage: np.ndarray # BYTE, (slices, 64): port layout, slice first
124
+ sync_ind: np.ndarray # INT
125
+ time_elap: np.ndarray # DOUBLE
126
+ time_sfm: np.ndarray # DOUBLE
127
+ particle_count: np.ndarray # LONG
128
+ slice_count: np.ndarray # INT
129
+ dof: np.ndarray # BYTE
130
+ remainder: np.ndarray # BYTE
131
+ header_slice_count: np.ndarray # INT
132
+
133
+
134
+ def _null(image: np.ndarray) -> Dmt3Result:
135
+ z = np.zeros(1, dtype=np.int16)
136
+ return Dmt3Result(null=True, image=image, bitimage=np.zeros((0, 64), dtype=np.uint8),
137
+ sync_ind=z, time_elap=np.zeros(1), time_sfm=np.zeros(1),
138
+ particle_count=np.zeros(1, dtype=np.int32),
139
+ slice_count=np.zeros(1, dtype=np.int16),
140
+ dof=np.zeros(1, dtype=np.uint8), remainder=np.zeros(1, dtype=np.uint8),
141
+ header_slice_count=np.array([999], dtype=np.int16))
142
+
143
+
144
+ def _bitimage(image: np.ndarray, slices: int) -> np.ndarray:
145
+ """``:126`` -- ``reform(reverse(dec2bin8(not(image)),1),64,slices)`` in the
146
+ port's ``(slices, 64)`` layout: diode ``8k+b`` of slice ``s`` is bit ``b``
147
+ (LSB first) of ``not(image[8s+k])``'s low byte."""
148
+ low = (~image[: slices * 8].astype(np.int16)).astype(np.uint16) & 0xFF
149
+ bits = ((low[:, None] >> np.arange(8, dtype=np.uint16)[None, :]) & 1).astype(np.uint8)
150
+ return bits.reshape(slices, 64)
151
+
152
+
153
+ def decompress_dmt3(cimage: np.ndarray) -> Dmt3Result:
154
+ """``decompress_dmt3.pro``: ``cimage`` is the BYTE buffer as read
155
+ (``readseabuffer_caps.pro:34``, 4098 bytes for the UND CIP)."""
156
+ cimage = np.asarray(cimage, dtype=np.uint8)
157
+ image = np.full(_IMAGE_LEN, 255, dtype=np.int16) # :13 INT
158
+ nbytes = cimage.size # :21
159
+ if nbytes <= 1: # :22
160
+ return _null(image)
161
+
162
+ # :25-34 -- the first sync search.
163
+ # Vectorised, same test per `cipos` in 0..nbytes-9: bytes cipos+1..cipos+8
164
+ # all 170, and 7 <= cimage[cipos] <= 31. Matches are kept in ascending order.
165
+ cb = cimage.astype(np.int64)
166
+ syncpos = np.zeros(_SYNC_ARRAY_LEN, dtype=np.int64)
167
+ ncand = nbytes - 8
168
+ hits = np.zeros(0, dtype=np.int64)
169
+ if ncand > 0:
170
+ run = np.concatenate([[0], np.cumsum(cb == 170)])
171
+ pos = np.arange(ncand)
172
+ eight = (run[pos + 9] - run[pos + 1]) == 8
173
+ lead = (cb[:ncand] >= 7) & (cb[:ncand] <= 31)
174
+ hits = np.flatnonzero(eight & lead)
175
+ c = int(hits.size)
176
+ if c > _SYNC_ARRAY_LEN:
177
+ raise DecompressDmtError(
178
+ "decompress_dmt3.pro:31: syncpos[c] subscript out of range "
179
+ f"(more than {_SYNC_ARRAY_LEN} syncs)")
180
+ syncpos[:c] = hits
181
+ if c < 2: # :36
182
+ return _null(image)
183
+
184
+ ipos = 0
185
+ lastgoodipos = 0
186
+ cipos = 0 # :38
187
+ for i in range(c): # :39
188
+ if ipos % 8 != 0: # :40-42
189
+ ipos = ipos + 8 - (ipos % 8)
190
+ if cipos > int(syncpos[i]): # :43-47
191
+ ipos = lastgoodipos
192
+ image[ipos:] = 255
193
+ lastgoodipos = ipos # :48
194
+ cipos = int(syncpos[i]) # :49 FOR start
195
+ if i + 1 >= _SYNC_ARRAY_LEN:
196
+ raise DecompressDmtError("decompress_dmt3.pro:49: syncpos[i+1] subscript out of range")
197
+ end = int(syncpos[i + 1]) - 1
198
+ while cipos <= end:
199
+ rlehb = int(cb[cipos]) # :51
200
+ zeroes = (rlehb & 128) == 128 # :52
201
+ ones = (rlehb & 64) == 64 # :53
202
+ dummy = (rlehb & 32) == 32 # :54
203
+ count = rlehb & 31 # :55
204
+ if zeroes and not ones and not dummy: # :57-60
205
+ if ipos + count >= _IMAGE_LEN:
206
+ raise DecompressDmtError("decompress_dmt3.pro:58: image subscript out of range")
207
+ image[ipos: ipos + count + 1] = 0
208
+ ipos = ipos + count + 1
209
+ if ones and not zeroes and not dummy: # :62-65
210
+ if ipos + count >= _IMAGE_LEN:
211
+ raise DecompressDmtError("decompress_dmt3.pro:63: image subscript out of range")
212
+ image[ipos: ipos + count + 1] = 255
213
+ ipos = ipos + count + 1
214
+ if not zeroes and not ones and not dummy: # :67-77
215
+ if cipos + count + 1 < nbytes:
216
+ if ipos + count >= _IMAGE_LEN:
217
+ raise DecompressDmtError(
218
+ "decompress_dmt3.pro:73: image subscript out of range")
219
+ image[ipos: ipos + count + 1] = cb[cipos + 1: cipos + count + 2]
220
+ ipos = ipos + count + 1
221
+ cipos = cipos + count + 1
222
+ cipos += 1 # FOR increment
223
+
224
+ # :81 -- `image[0:ipos-1]`; ipos == 0 reads `[0:-1]`, the whole array.
225
+ if ipos > 0:
226
+ image = image[:ipos]
227
+ slices = image.size // 8 # :84-85
228
+ if slices > 0: # :86, same `[0:-1]` rule
229
+ image = image[: slices * 8]
230
+
231
+ # :87-110 -- the second sync search, over whole slices.
232
+ sync_ind: list[int] = []
233
+ time_l: list[float] = []
234
+ time_total: list[float] = []
235
+ particle_count: list[int] = []
236
+ dof: list[int] = []
237
+ header_slice_count: list[int] = []
238
+ starttime = 0.0
239
+ # :94-96, vectorised: slices 0..slices-2 whose bytes 0, 1 and 7 are 170 and
240
+ # whose total is 1360; visited in ascending order as the IDL loop does.
241
+ nsearch = max(slices - 1, 0)
242
+ if nsearch > 0:
243
+ sl = image[: nsearch * 8].reshape(nsearch, 8).astype(np.int64)
244
+ match = ((sl[:, 0] == 170) & (sl[:, 1] == 170) & (sl[:, 7] == 170)
245
+ & (sl.sum(axis=1) == 1360))
246
+ candidates = np.flatnonzero(match)
247
+ else:
248
+ candidates = np.zeros(0, dtype=np.int64)
249
+ for i in (int(k) for k in candidates):
250
+ ss = 8 * i
251
+ se = ss + 7
252
+ if len(sync_ind) >= _SLICE_ARRAY_LEN:
253
+ raise DecompressDmtError(
254
+ "decompress_dmt3.pro:97: sync_ind[sync_count] subscript out of range "
255
+ f"(more than {_SLICE_ARRAY_LEN} sync slices)")
256
+ params = decode_header_slice(image[ss + 8: se + 9]) # :99
257
+ if not sync_ind:
258
+ starttime = params.time_sfm # :105
259
+ sync_ind.append(i)
260
+ particle_count.append(params.particle_count)
261
+ dof.append(params.dof)
262
+ header_slice_count.append(params.slice_count)
263
+ time_l.append(params.time_sfm - starttime)
264
+ time_total.append(params.time_sfm)
265
+ sync_count = len(sync_ind)
266
+ if sync_count <= 2: # :113
267
+ return _null(image)
268
+
269
+ si = np.asarray(sync_ind, dtype=np.int16) # :115-120
270
+ # :123-124 -- `fix(slices-1)`; INT arithmetic.
271
+ slice_stop = np.concatenate([si[1:], np.array([slices - 1], dtype=np.int16)])
272
+ slice_count = (slice_stop - si - 1).astype(np.int16)
273
+
274
+ bitimage = _bitimage(image, slices) # :126
275
+ remainder = cimage[int(syncpos[c - 1]):].copy() # :127
276
+
277
+ return Dmt3Result(
278
+ null=False, image=image, bitimage=bitimage, sync_ind=si,
279
+ time_elap=np.asarray(time_l, dtype=np.float64),
280
+ time_sfm=np.asarray(time_total, dtype=np.float64),
281
+ particle_count=np.asarray(particle_count, dtype=np.int32),
282
+ slice_count=slice_count, dof=np.asarray(dof, dtype=np.uint8),
283
+ remainder=remainder,
284
+ header_slice_count=np.asarray(header_slice_count, dtype=np.int16),
285
+ )