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,476 @@
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_index.pro`` -- walk a SPEC raw file two buffers at a time and
4
+ return the pointers to every image, housekeeping and mask record it
5
+ contains (P-b).
6
+
7
+ 161 lines of IDL. Signature `spec_index(lun, lite=, minimagesize=,
8
+ pointerstart=, pointerstop=, absolutepointer=, version=)`. Every vendored
9
+ caller passes **no keyword**: `soda2_buildindex.pro:12` `spec_index(1)` (the
10
+ production path, via `soda2_process_2d.pro:366`), `soda2_browse.pro:141`,
11
+ `soda2_imagedump.pro:49`. `lite`, `pointerstart`, `pointerstop`,
12
+ `absolutepointer` and `version` have no caller in the vendored tree (grepped
13
+ directly). `soda2_process_2d.pro:458-461` reads `numimages`, `firstp`,
14
+ `imagep` (relative: `i*y.buffsize + y.imagep[...]`), `hkp`, `ihk`,
15
+ `buffsize`, `bufftime`, `date`; `spec_absolutepointers.pro` reads
16
+ `numimages`, `firstp`, `pointer`, `imagep`. `arrayid`, `ibuffer`,
17
+ `particlecounter`, `count`, `error` are read by nothing outside the routine.
18
+
19
+ Validated against GDL by ``tests/test_soda2_spec_index.py``; bank at
20
+ ``gdl_oracle/run_soda2_spec_index_bank.py``, 29 cases (26 OK, one
21
+ ``ERROR``, two ``HALTED``), all matching -- including a third side, an
22
+ independent recomputation from the bank's own byte-placement table
23
+ (``bank.LAYOUT``), that predicts the golden without importing this module or
24
+ NumPy.
25
+
26
+ **Line-by-line** (IDL 0-based indexing; every index below is exactly what
27
+ the source writes):
28
+
29
+ - ``:12-19`` -- defaults `lite=0`, `minimagesize=2`, `pointerstart=0ULL`,
30
+ `absolutepointer=0`, `version=1` -> `hklength=53`; `version=2` -> 83; any
31
+ other version leaves `hklength` undefined and the IDL's own next use of it
32
+ dies -- this port raises :class:`ValueError` there instead, before any
33
+ read. **`version=1` here is the 2DS/HVPS3 -- the opposite numbering from
34
+ `spec_read_frame`, the same as `spec_read_hk`.** `:15`'s `buffsize=4114ULL`
35
+ default is dead code: `:30` always overwrites it before it is read.
36
+ - ``:21-23`` -- `f=fstat(lun)`; `pointerstop` defaults to the file size;
37
+ the bytes to read are `pointerstop` minus `pointerstart`.
38
+ - ``:26-30`` -- **buffer-size autodetection**: read the first
39
+ `10000<(f.size/2)` **signed** INT16 words from byte 0 of the file (not
40
+ from `pointerstart`); `w = where(x eq x[0] and x[1:*] eq x[1] and
41
+ x[2:*] eq x[2])` -- IDL's `and` truncates its array operands to the
42
+ shortest length (N-2 here), so this port only ever tests indices
43
+ `range(n-2)`; `buffsize = w[1]*2ULL`, i.e. twice the distance to the
44
+ **first repeat** of the file's own first three words (year, month,
45
+ "dummy" = weekday). Two failure modes, both bank-measured (S4-k): a data
46
+ word triple equal to the header triple within the scanned range gives a
47
+ wrong `buffsize` (`triple_autodetect`: `w=[0,108,2057,4114]`, `buffsize`
48
+ locks onto **216** instead of 4114, so `triple_full`'s later full walk
49
+ reads its third real header as data and `:72` halts); a file of one
50
+ buffer has `w=[0]` (no second match) and IDL dies with `% SPEC_INDEX:
51
+ Scalar subscript out of range [>]: (1)` at `:30` (`short`) -- this port
52
+ raises :class:`SpecIndexError` naming `spec_index.pro:30` for both the
53
+ no-second-match case and the fewer-than-three-words case it generalises.
54
+ - ``:33-35`` -- `headersize=16`; `ndataints=(buffsize-16-2)/2` = 2048 on
55
+ every fixture here -- one trailing "dummy" footer int per buffer is
56
+ skipped by construction.
57
+ - ``:37-44`` -- `thisbuffer`/`nextbuffer` are **UINT** (unsigned) arrays of
58
+ `ndataints`; seek to `pointerstart` and read the 8-INT16 **signed**
59
+ header (`year, month, dummy, day, hour, minute, second, millisecond`),
60
+ then `thisbuffer`. (The IDL then seeks back to `pointerstart` at `:44`,
61
+ a no-op for anything this port needs: the next real read, `:78`, always
62
+ repositions the file explicitly, so this port does not reproduce the
63
+ redundant seek.)
64
+ - ``:46-51`` -- `numbuffs = bytes2read/buffsize` (floor); `bufftime`
65
+ DOUBLE[numbuffs]; `buffpoint = lindgen(numbuffs)*buffsize` (LONG x
66
+ ULONG64 -> **ULONG64**); `firstp = lonarr(numbuffs)-1`; `numimages =
67
+ intarr(numbuffs)`; `date = lonarr(numbuffs)`.
68
+ - ``:53-68`` -- `numpointers = bytes2read/10`; `imagep = intarr(numpointers)`
69
+ (**INT16**, relative offsets <= 4110 on a 4114-byte buffer) or, with
70
+ `/absolutepointer`, `lon64arr(numpointers)` (**INT64**, full file offset);
71
+ `ibuffer`, `ihk` **LONG** (INT32); `particlecounter` **UINT** (UINT16);
72
+ `arrayid` **BYTE** (UINT8); `maskp = lon64arr(1000)`, `hkp =
73
+ lon64arr(100000)` -- **fixed capacities, no bound check** (S4-m, read
74
+ only -- not reachable by anything this bank builds).
75
+ - ``:71-72`` -- **`FOR i=0L, numbuffs-2`** -- the loop walks buffers
76
+ `0..numbuffs-2` only; the **last buffer's own data is never scanned**
77
+ (its header is read at `:79` and consumed only by `:144-145`, after the
78
+ loop). This port's `for i in range(numbuffs - 1)` reproduces exactly that
79
+ range (S4-i). `stop, 'File misaligned'` fires when `header.year` is
80
+ outside 2005..2050, checked for buffers `0..numbuffs-2` **only** -- the
81
+ final header is never range-checked (the bank's `main_rel` case carries
82
+ year 1999 in buffer 5, the never-checked last buffer, and it is accepted:
83
+ `date[5]=2451429`). This port raises :class:`SpecFileMisaligned` there,
84
+ reproducing the halt as an exception rather than IDL's interactive
85
+ `stop`.
86
+ - ``:75-76`` -- `bufftime[i] = hour*3600D + minute*60D + second +
87
+ millisecond/1000D`, DOUBLE, left to right -- reproduced as four
88
+ Python-float operations in the same order, no reassociation; goldens are
89
+ compared as 16-hex-digit IEEE-754 double bit patterns with no tolerance.
90
+ `date[i] = julday(month, day, year)`, the Julian Day Number as a LONG
91
+ (see :func:`julday`).
92
+ - ``:78-81`` -- `point_lun, lun, (i+1)*buffsize` -- **from the file start,
93
+ ignoring `pointerstart`** (S4-j). This port seeks to exactly
94
+ `(i + 1) * buffsize`, not `pointerstart + (i + 1) * buffsize` -- a
95
+ reproduced divergence, not a fix. Reads `header` (buffer i+1's) and
96
+ `nextbuffer`; `b = [thisbuffer, nextbuffer]` (`2*ndataints` UINT words).
97
+ - ``:83-138`` -- `REPEAT ... UNTIL j ge ndataints`, resuming from the
98
+ **carried-over `j`**. `CASE b[j] OF`:
99
+
100
+ - `12883` (`'2S'`): `nh = b[j+1] and 'fff'x`, `nv = b[j+2] and 'fff'x`,
101
+ `pc = b[j+3]`. If `nh>=minimagesize or nv>=minimagesize`:
102
+ `deltacounter = pc - lastparticlecounterh` if `nh>=minimagesize`, **then
103
+ overwritten** by `pc - lastparticlecounterv` if `nv>=minimagesize` (both
104
+ checks are independent `IF`s, not `IF/ELSE`). If `deltacounter != 0`
105
+ (UINT16 wraparound; only "not zero" is ever observed -- reproduced as
106
+ `(pc - last) & 0xFFFF` so the arithmetic reads like the source, per the
107
+ plan's U3): record `imagep = headersize + j*2` (relative) or
108
+ `i*buffsize + headersize + j*2` (absolute), `ibuffer = i`, `ihk =
109
+ max(hkc - 1, 0)`, `particlecounter = pc`, `firstp[i]` if this buffer's
110
+ first, `numimages[i] += 1`, `arrayid = 'H'` (72) then **unconditionally
111
+ overwritten by `'V'` (86)** when `nv>=minimagesize` too -- a dual H+V
112
+ frame is indexed exactly once, as `'V'`, and updates both
113
+ `lastparticlecounterh` and `lastparticlecounterv`. Always
114
+ `j += 5 + nh + nv`, even for a frame too small to index.
115
+ - `19787` (`'MK'`): `maskp[maskc] = i*buffsize + headersize + j*2`
116
+ (**always absolute**, regardless of `absolutepointer`); `j += 23`.
117
+ - `18507` (`'HK'`): `hkp[hkc] = i*buffsize + headersize + j*2` (also
118
+ always absolute); `j += hklength`.
119
+ - `20044` (`'NL'`): `j = ndataints` -- the rest of the buffer is skipped.
120
+ - `0`, `48813`: `j += 1`.
121
+ - anything else: `j += 1`.
122
+ - ``:139-141`` -- `j -= ndataints` (carrying into the next buffer -- a frame
123
+ straddling the boundary is indexed once and its remainder is *skipped*,
124
+ never re-walked); **`IF j ge ndataints THEN j=0`** -- a declared length
125
+ that overshoots the boundary by more than one buffer's worth resets the
126
+ walk to the very start of the next buffer rather than continuing the
127
+ carry (the bank's `nh4095_pc7` -> `h_pc8_after_reset` pair is the
128
+ discriminating case: dropping this reset loses `h_pc8_after_reset`
129
+ entirely, M2 below); `thisbuffer = nextbuffer`.
130
+ - ``:144-145`` -- after the loop, the last-read header's `bufftime`/`date`
131
+ are written for `numbuffs-1` -- the header belonging to the file's final
132
+ buffer, whose own data was never walked (S4-i, same finding).
133
+ - ``:148`` -- `lite=1` returns `{bufftime, buffpoint, firstp}` **after the
134
+ full walk has already run** -- the source's own comment ("very slow...
135
+ 'Lite' option") reads as if it skips the walk; it only skips building the
136
+ image/HK/mask arrays before returning. No caller uses it.
137
+ - ``:149-155`` -- trim to `[0 : max(imagec-1, 0)]` (IDL's `>` is MAX, not a
138
+ comparison) -- **an empty result is a 1-element zero array, never a
139
+ length-0 array**: with no images, `imagep=[0]`, `ibuffer=[0]`, `ihk=[0]`,
140
+ `particlecounter=[0]`, `arrayid=[0]`; with no HK records, `hkp=[0]`; no
141
+ mask records, `maskp=[0]` (bank-measured: `hk_rel` has `NIMG=1 IMAGEP=0`;
142
+ `frame_rel`/`s2_pstop` have `NHK=1 HKP=0`). This port's `_trim` helper
143
+ reproduces the sentinel exactly by slicing a zero-initialised array.
144
+ - ``:157-159`` -- returns `date, bufftime, pointer, firstp, imagep, hkp,
145
+ maskp, count, numimages, buffsize, ibuffer, ihk, particlecounter,
146
+ arrayid, error:0` -- measured tnames (`size(/tname)`): `LONG, DOUBLE,
147
+ ULONG64, LONG, INT, LONG64, LONG64, ULONG64, INT, ULONG64, LONG, LONG,
148
+ UINT, BYTE, INT` (`imagep` is `LONG64` with `/absolutepointer`).
149
+
150
+ **`spec_absolutepointers.pro`** (22 lines) is ported alongside this module
151
+ in :mod:`arrayprobe_soda2.spec_absolutepointers` -- it consumes exactly the
152
+ struct this function returns.
153
+
154
+ **Findings**: **S4-i** (the last
155
+ buffer of every file is never walked, and its header's year is never range
156
+ -checked), **S4-j** (`pointerstart` is honoured for the first buffer only;
157
+ every later seek is file-relative), **S4-k** (buffer-size autodetection
158
+ halts on a data triple equal to the header's own, and dies outright on a
159
+ one-buffer file), **S4-l** (images before the first HK record take index 0,
160
+ and a file with no HK record at all hands pointer 0 -- the file's own first
161
+ header -- to `spec_read_hk`), **S4-m** (`maskp`/`hkp` are fixed-capacity
162
+ arrays with no bound check, read only, not measured here).
163
+ """
164
+ from __future__ import annotations
165
+
166
+ import struct
167
+ from dataclasses import dataclass
168
+ from typing import BinaryIO
169
+
170
+ import numpy as np
171
+ from numpy.typing import DTypeLike
172
+
173
+ __all__ = [
174
+ "SpecIndex",
175
+ "SpecIndexLite",
176
+ "SpecIndexError",
177
+ "SpecFileMisaligned",
178
+ "julday",
179
+ "spec_index",
180
+ ]
181
+
182
+
183
+ class SpecIndexError(ValueError):
184
+ """`:30` -- the buffer-size autodetection found fewer than two matches
185
+ for the file's own first three words, so IDL's `w[1]` is a scalar
186
+ subscript out of range.
187
+
188
+ Source: ``spec_index.pro:30`` (SODA-2)."""
189
+
190
+
191
+ class SpecFileMisaligned(RuntimeError):
192
+ """`:72` -- IDL's `stop, 'File misaligned'`. Measured under GDL
193
+ (two separate runs): `stop` here printed the message and
194
+ returned control within seconds rather than blocking, unlike the
195
+ `soda2_samplearea` bank -- see `run_soda2_spec_index_bank`'s module
196
+ docstring.
197
+
198
+ Source: ``spec_index.pro:72`` (SODA-2).
199
+
200
+ Carries the ``buffsize`` the `:26-30` autodetection computed before the
201
+ walk that raised this -- `:72` fires only after `buffsize` is already
202
+ known, and `triple_full`'s own halt is evidence about *that* value
203
+ (216, not 4114; SODA-2 register entry S4-k) as much as about the halt itself.
204
+ """
205
+
206
+ def __init__(self, message: str, buffsize: int | None = None) -> None:
207
+ super().__init__(message)
208
+ self.buffsize = buffsize
209
+
210
+
211
+ def julday(month: int, day: int, year: int) -> int:
212
+ """The Julian Day Number IDL's `julday(month, day, year)` returns for a
213
+ date at 00:00 (no fractional-day argument is ever passed here) --
214
+ Fliegel-Van Flandern, ported rather than transcribed from `julday.pro`
215
+ (not in the vendored tree; IDL's own library routine). Bank-measured:
216
+ ``julday(9,6,2016) == 2457638``, ``julday(9,7,1999) == 2451429``,
217
+ ``julday(1,1,2000) == 2451545``, ``julday(9,2,2016) == 2457634``; the
218
+ day-0 arithmetic case ``julday(9,0,2016) == 2457632`` is GDL-measured
219
+ only, not IDL-confirmed (nothing in the fixtures reaches it).
220
+ """
221
+ a = (14 - month) // 12
222
+ y = year + 4800 - a
223
+ m = month + 12 * a - 3
224
+ return day + (153 * m + 2) // 5 + 365 * y + y // 4 - y // 100 + y // 400 - 32045
225
+
226
+
227
+ @dataclass
228
+ class SpecIndexLite:
229
+ """`lite=1`'s return (`:148`) -- built only after the full walk has
230
+ already run; no caller in the vendored tree uses it."""
231
+
232
+ bufftime: np.ndarray # float64[numbuffs]
233
+ buffpoint: np.ndarray # uint64[numbuffs]
234
+ firstp: np.ndarray # int32[numbuffs], -1 where a buffer has no image
235
+
236
+
237
+ @dataclass
238
+ class SpecIndex:
239
+ """`spec_index`'s return struct (`:157-159`), one field per IDL tag.
240
+ Dtypes are the measured `size(/tname)` values, not assumed.
241
+
242
+ Source: ``spec_index.pro:157-159`` (SODA-2)."""
243
+
244
+ date: np.ndarray # int32[numbuffs] -- julday(month,day,year)
245
+ bufftime: np.ndarray # float64[numbuffs]
246
+ pointer: np.ndarray # uint64[numbuffs] -- IDL's `buffpoint`
247
+ firstp: np.ndarray # int32; -1 where a buffer has no image
248
+ imagep: np.ndarray # int16 (relative, :55) or int64 (absolute, :56); [0] when empty
249
+ hkp: np.ndarray # int64, always an absolute file offset; [0] when empty
250
+ maskp: np.ndarray # int64, always an absolute file offset; [0] when empty
251
+ count: int # numbuffs
252
+ numimages: np.ndarray # int16
253
+ buffsize: int
254
+ ibuffer: np.ndarray # int32; [0] when empty
255
+ ihk: np.ndarray # int32; [0] when empty
256
+ particlecounter: np.ndarray # uint16; [0] when empty
257
+ arrayid: np.ndarray # uint8: 72 'H', 86 'V'; [0] when empty
258
+ error: int = 0
259
+
260
+
261
+ def _read_header(f: BinaryIO) -> tuple[int, int, int, int, int, int, int, int]:
262
+ """8 signed INT16 words: `year, month, dummy, day, hour, minute, second,
263
+ millisecond` (`:33`'s anonymous struct)."""
264
+ return struct.unpack("<8h", f.read(16)) # type: ignore[return-value]
265
+
266
+
267
+ def _trim(values: list[int], dtype: DTypeLike) -> np.ndarray:
268
+ """`arr[0 : max(count-1, 0)]` (`:149-155`) via a growing Python list
269
+ instead of IDL's fixed-capacity pre-allocation: empty -> the `[0]`
270
+ sentinel (matching a zero-initialised IDL array sliced to one element),
271
+ non-empty -> exactly the collected values.
272
+
273
+ Built via an int64 array, then narrowed with `.astype(dtype)` (W2b,
274
+ D.3): a plain `np.asarray(values, dtype=dtype)` on Python ints out of
275
+ `dtype`'s range raises under NumPy 2's NEP-50 rules, where IDL's own
276
+ assignment into a fixed-width array (e.g. `imagep[imagec]=headersize+
277
+ j*2` into an `intarr`, `spec_index.pro:96`) silently wraps. `.astype`
278
+ reproduces the wrap instead of raising where IDL wraps -- latent on
279
+ real SPEC data (needs `buffsize > 32.7 kB`, measured 4114 in every
280
+ fixture and on UND's 0914 HVPS3 file), kept for a pathological file."""
281
+ return np.asarray(values if values else [0], dtype=np.int64).astype(dtype)
282
+
283
+
284
+ def spec_index(
285
+ f: BinaryIO,
286
+ *,
287
+ lite: bool = False,
288
+ minimagesize: int = 2,
289
+ pointerstart: int = 0,
290
+ pointerstop: int | None = None,
291
+ absolutepointer: bool = False,
292
+ version: int = 1,
293
+ ) -> SpecIndex | SpecIndexLite:
294
+ """``idx = spec_index(lun, lite=lite, minimagesize=minimagesize,
295
+ pointerstart=pointerstart, pointerstop=pointerstop,
296
+ absolutepointer=absolutepointer, version=version)``.
297
+
298
+ Source: ``spec_index.pro`` (SODA-2); bare line references here are into that file.
299
+
300
+ ``f`` is an open binary SPEC raw file. Every vendored caller passes no
301
+ keyword at all; `minimagesize=2`, `pointerstart=0`,
302
+ `absolutepointer=False` and `version=1` are IDL's own effective
303
+ defaults (`:12-19`). `pointerstop=None` reproduces "defaults to the
304
+ file size" (`:22`).
305
+
306
+ Raises :class:`SpecIndexError` where IDL's own buffer-size
307
+ autodetection would die (`:30`, a one-buffer file or fewer than three
308
+ words to scan), :class:`SpecFileMisaligned` where IDL's `stop, 'File
309
+ misaligned'` would halt (`:72`, a header year outside 2005..2050 in any
310
+ buffer but the last -- the last is never checked, SODA-2 register entry S4-i), and
311
+ :class:`ValueError` for any `version` other than 1 or 2 (`:18-19`
312
+ leaves `hklength` undefined and the IDL's own next use of it dies).
313
+ None of the three refusals advances the file position past what the
314
+ autodetection scan itself required.
315
+ """
316
+ if version == 1:
317
+ hklength = 53
318
+ elif version == 2:
319
+ hklength = 83
320
+ else:
321
+ raise ValueError(
322
+ f"spec_index: version={version!r} is not 1 or 2 -- the IDL "
323
+ "leaves `hklength` undefined here and the next line dies "
324
+ "(spec_index.pro:18-19)")
325
+
326
+ f.seek(0, 2)
327
+ size = f.tell()
328
+ if pointerstop is None:
329
+ pointerstop = size
330
+ bytes2read = pointerstop - pointerstart
331
+
332
+ # `:26-30` -- buffer-size autodetection, from byte 0 regardless of
333
+ # `pointerstart`. IDL's `and` on operands of length N, N-1, N-2
334
+ # truncates to the shortest (N-2), so only `range(n-2)` is ever tested.
335
+ f.seek(0)
336
+ n = min(10000, size // 2)
337
+ if n < 3:
338
+ raise SpecIndexError(
339
+ "spec_index: fewer than three words in the file to scan for "
340
+ "the buffer-size autodetection (spec_index.pro:27-30)")
341
+ x = np.frombuffer(f.read(2 * n), dtype="<i2")
342
+ hits = [i for i in range(n - 2)
343
+ if x[i] == x[0] and x[i + 1] == x[1] and x[i + 2] == x[2]]
344
+ if len(hits) < 2:
345
+ raise SpecIndexError(
346
+ "spec_index: the buffer-size autodetection found fewer than "
347
+ "two matches for the file's own first three words -- IDL dies "
348
+ "with 'Scalar subscript out of range [>]: (1)' at "
349
+ "spec_index.pro:30")
350
+ buffsize = hits[1] * 2
351
+
352
+ headersize = 16
353
+ ndataints = (buffsize - headersize - 2) // 2
354
+
355
+ f.seek(pointerstart)
356
+ header = _read_header(f)
357
+ thisbuffer = np.frombuffer(f.read(2 * ndataints), dtype="<u2")
358
+
359
+ numbuffs = bytes2read // buffsize
360
+ bufftime = np.zeros(numbuffs, dtype=np.float64)
361
+ pointer = np.arange(numbuffs, dtype=np.uint64) * np.uint64(buffsize)
362
+ firstp = np.full(numbuffs, -1, dtype=np.int32)
363
+ numimages = np.zeros(numbuffs, dtype=np.int16)
364
+ date = np.zeros(numbuffs, dtype=np.int32)
365
+
366
+ imagep_list: list[int] = []
367
+ ibuffer_list: list[int] = []
368
+ ihk_list: list[int] = []
369
+ particlecounter_list: list[int] = []
370
+ arrayid_list: list[int] = []
371
+ maskp_list: list[int] = []
372
+ hkp_list: list[int] = []
373
+
374
+ imagec = 0
375
+ maskc = 0
376
+ hkc = 0
377
+ j = 0
378
+ lastparticlecounterh = 0
379
+ lastparticlecounterv = 0
380
+ nh = nv = 0 # only meaningful while inside a '2S' branch
381
+
382
+ for i in range(numbuffs - 1): # `FOR i=0L, numbuffs-2` (:71)
383
+ year, month, _dummy, day, hour, minute, second, millisecond = header
384
+ if year < 2005 or year > 2050:
385
+ raise SpecFileMisaligned(
386
+ f"spec_index.pro:72: header.year={year} is outside "
387
+ f"2005..2050 at buffer i={i} of {numbuffs}",
388
+ buffsize=buffsize)
389
+ bufftime[i] = hour * 3600.0 + minute * 60.0 + second + millisecond / 1000.0
390
+ date[i] = julday(month, day, year)
391
+
392
+ # `:78` -- file-relative, ignoring `pointerstart` (S4-j).
393
+ f.seek((i + 1) * buffsize)
394
+ header = _read_header(f)
395
+ nextbuffer = np.frombuffer(f.read(2 * ndataints), dtype="<u2")
396
+ b = np.concatenate([thisbuffer, nextbuffer])
397
+
398
+ while True:
399
+ tag = int(b[j])
400
+ if tag == 12883: # '2S'
401
+ nh = int(b[j + 1]) & 0xFFF
402
+ nv = int(b[j + 2]) & 0xFFF
403
+ pc = int(b[j + 3])
404
+ if nh >= minimagesize or nv >= minimagesize:
405
+ deltacounter = 0
406
+ if nh >= minimagesize:
407
+ deltacounter = (pc - lastparticlecounterh) & 0xFFFF
408
+ if nv >= minimagesize:
409
+ deltacounter = (pc - lastparticlecounterv) & 0xFFFF
410
+ if deltacounter != 0:
411
+ if absolutepointer:
412
+ imagep_list.append(i * buffsize + headersize + j * 2)
413
+ else:
414
+ imagep_list.append(headersize + j * 2)
415
+ ibuffer_list.append(i)
416
+ ihk_list.append(max(hkc - 1, 0))
417
+ particlecounter_list.append(pc)
418
+ if firstp[i] == -1:
419
+ firstp[i] = imagec
420
+ numimages[i] += 1
421
+ arrayid = 0
422
+ if nh >= minimagesize:
423
+ arrayid = 72 # 'H'
424
+ lastparticlecounterh = pc
425
+ if nv >= minimagesize:
426
+ arrayid = 86 # 'V' -- overwrites 'H' for a dual frame
427
+ lastparticlecounterv = pc
428
+ arrayid_list.append(arrayid)
429
+ imagec += 1
430
+ j += 5 + nh + nv
431
+ elif tag == 19787: # 'MK' -- always absolute
432
+ maskp_list.append(i * buffsize + headersize + j * 2)
433
+ maskc += 1
434
+ j += 23
435
+ elif tag == 18507: # 'HK' -- always absolute
436
+ hkp_list.append(i * buffsize + headersize + j * 2)
437
+ hkc += 1
438
+ j += hklength
439
+ elif tag == 20044: # 'NL'
440
+ j = ndataints
441
+ else: # 0, 48813 ('BEAD'), or anything unrecognised
442
+ j += 1
443
+ if j >= ndataints:
444
+ break
445
+
446
+ j -= ndataints
447
+ if j >= ndataints: # `:140` -- a giant overshoot resets, not carries
448
+ j = 0
449
+ thisbuffer = nextbuffer
450
+
451
+ # `:143-145` -- the last-read header, never range-checked (S4-i).
452
+ year, month, _dummy, day, hour, minute, second, millisecond = header
453
+ date[numbuffs - 1] = julday(month, day, year)
454
+ bufftime[numbuffs - 1] = hour * 3600.0 + minute * 60.0 + second + millisecond / 1000.0
455
+
456
+ if lite:
457
+ return SpecIndexLite(bufftime=bufftime, buffpoint=pointer, firstp=firstp)
458
+
459
+ imagep_dtype = np.int64 if absolutepointer else np.int16
460
+ return SpecIndex(
461
+ date=date,
462
+ bufftime=bufftime,
463
+ pointer=pointer,
464
+ firstp=firstp,
465
+ imagep=_trim(imagep_list, imagep_dtype),
466
+ hkp=_trim(hkp_list, np.int64),
467
+ maskp=_trim(maskp_list, np.int64),
468
+ count=numbuffs,
469
+ numimages=numimages,
470
+ buffsize=buffsize,
471
+ ibuffer=_trim(ibuffer_list, np.int32),
472
+ ihk=_trim(ihk_list, np.int32),
473
+ particlecounter=_trim(particlecounter_list, np.uint16),
474
+ arrayid=_trim(arrayid_list, np.uint8),
475
+ error=0,
476
+ )