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,371 @@
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_read2dbuffer.pro`, SPEC branch
4
+ (`:15-17`, `:109-117`); the SEA branch's CIP route
5
+ (`:69-89`, :func:`read2dbuffer_sea`); the DMT/PADS branch (`:91-107`,
6
+ :func:`read2dbuffer_dmt`, bank `gdl_oracle/run_soda2_dmt_bank.py`). RAF, TXT,
7
+ T28, HVPS1995 and the legacy SEA probes stay unported.
8
+
9
+ Vendored source: `SODA2/abansemer-soda2-afcea15/soda2_read2dbuffer.pro`.
10
+ Bank: `gdl_oracle/run_soda2_preloop_bank.py`, golden
11
+ `tests/data/gdl_soda2_preloop_golden.json`.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import struct
17
+ from dataclasses import dataclass
18
+ from typing import Any, BinaryIO
19
+
20
+ import numpy as np
21
+
22
+ from .spec_index import _read_header, julday
23
+
24
+
25
+ @dataclass
26
+ class Buffer2D:
27
+ """The structure ``soda2_read2dbuffer.pro`` (SODA-2) returns, e.g. the SPEC branch at
28
+ ``:116``, one field per IDL tag."""
29
+ time: float | np.integer
30
+ image: int
31
+ difftime: float
32
+ eof: int
33
+ tas: float | np.integer | np.floating
34
+ pointer: int
35
+ date: int
36
+ overload: int
37
+
38
+
39
+ def _fstat_size(f: BinaryIO) -> int:
40
+ """IDL `fstat(lun).size`: the on-disk size of the file behind `f` (for a
41
+ `gzip` stream, the compressed length, as GDL reports it).
42
+
43
+ A `GzipFile` is unwrapped to the stream it reads from before any length is
44
+ taken: seeking to the end of the `GzipFile` itself would give the
45
+ DECOMPRESSED length, which GDL never reports."""
46
+ import gzip
47
+ while isinstance(f, gzip.GzipFile) and getattr(f, "fileobj", None) is not None:
48
+ f = f.fileobj # type: ignore[assignment]
49
+ try:
50
+ fd = f.fileno()
51
+ except (AttributeError, OSError, ValueError):
52
+ name = getattr(f, "name", None)
53
+ if isinstance(name, (str, bytes, os.PathLike)) and os.path.exists(name):
54
+ return os.stat(name).st_size
55
+ here = f.tell()
56
+ f.seek(0, 2)
57
+ size = f.tell()
58
+ f.seek(here)
59
+ return size
60
+ return os.fstat(fd).st_size
61
+
62
+
63
+ def read2dbuffer_spec(f: BinaryIO, op: dict) -> Buffer2D:
64
+ """`soda2_read2dbuffer.pro:15-17` (EOF test) then `:109-117` (the SPEC
65
+ branch). `f` is an open binary file already positioned by the caller
66
+ (`point_lun,1,buffpoint[i]`, driver `:451`)."""
67
+ pointer = f.tell() # :15
68
+
69
+ # :17 returns the null buffer at end of file -- true only when the file
70
+ # position is exactly at end-of-file; a partial header (fewer than 16
71
+ # bytes left) is NOT eof(), so `readu` below raises instead.
72
+ #
73
+ # A bounded probe: only len(tail) in {0, 1-15, >=16} is used here (the
74
+ # three-way test below, and the message quotes it only when < 16). The
75
+ # probe read the whole remainder of the file until 2026-09-15, once per
76
+ # buffer -- quadratic in file size, 7.3 s per buffer on a 622 MB UND file,
77
+ # where IDL's eof() is O(1). Same answers, byte for byte:
78
+ # tests/test_soda2_read2dbuffer_bounded.py.
79
+ start = f.tell()
80
+ tail = f.read(16)
81
+ f.seek(start)
82
+ if len(tail) == 0:
83
+ # :16 nullbuffer -- INT tas/time (the struct literal declares them
84
+ # 0, not 0.0/0d).
85
+ return Buffer2D(image=0, tas=np.int16(0), time=np.int16(0),
86
+ difftime=0.0, eof=1, pointer=pointer, overload=0,
87
+ date=0)
88
+ if len(tail) < 16:
89
+ raise EOFError(
90
+ "soda2_read2dbuffer.pro:110 readu on a partial 8-word header "
91
+ f"({len(tail)} bytes remain) -- IDL 'End of file encountered'.")
92
+
93
+ year, month, _dummy, day, hour, minute, second, millisecond = _read_header(f)
94
+ time = hour * 3600.0 + minute * 60.0 + second * 1.0 + millisecond / 1000.0 # :112, DOUBLE
95
+ date = julday(month, day, year) if year > 0 else 0 # :113
96
+
97
+ fixedtas = op.get("fixedtas", np.float32(0.0))
98
+ tas = float(fixedtas) if float(fixedtas) > 0 else 100.0 # :114, FLOAT
99
+
100
+ timeoffset = op.get("timeoffset", np.float32(0.0))
101
+ # FLOAT widening rule (T7): a np.float32 timeoffset is widened via
102
+ # Python float() the same way IDL widens FLOAT -> DOUBLE, carrying
103
+ # float32 rounding into the double sum.
104
+ offset = float(timeoffset)
105
+ return Buffer2D(time=time + offset, image=0, difftime=0.0, eof=0,
106
+ tas=np.float32(tas), pointer=pointer, date=date,
107
+ overload=0)
108
+
109
+
110
+ @dataclass
111
+ class SeaBuffer2D:
112
+ """`soda2_read2dbuffer.pro:86-88`'s SEA return. ``stoptime``
113
+ is the field `soda2_processbuffer.pro:200` overwrites through the caller's
114
+ ``b`` (IDL passes it by reference)."""
115
+
116
+ time: float
117
+ stoptime: float
118
+ image: np.ndarray
119
+ difftime: float
120
+ eof: int
121
+ tas: np.floating
122
+ pointer: int
123
+ imagepoint: int
124
+ timepoint: int
125
+ date: int
126
+ overload: int
127
+
128
+
129
+ CIP1D_RECORD_BYTES = 180
130
+
131
+
132
+ def _decode_cip1d(payload: bytes) -> dict:
133
+ """`readseabuffer_caps.pro:26-28`, `:40-41` -- one CIP-1D image record.
134
+
135
+ The IDL struct is fourteen little-endian fields, 180 bytes: header,
136
+ bytecount, oversizereject (INT), count (INT[62], bytes 6-130), dofreject,
137
+ endreject (INT), housekeeping (INT[16], bytes 134-166), particlecounter
138
+ (UINT, 166-168), secmsec, hourmin, hostsynccounter, resetflag, checksum,
139
+ trailer (INT). `probetime` is the `:40-41` decode of hourmin and secmsec,
140
+ a DOUBLE; the INT operands promote to LONG for the masks, which for a
141
+ negative INT selects the same bits as its unsigned pattern.
142
+ """
143
+ if len(payload) < CIP1D_RECORD_BYTES:
144
+ raise ValueError(f"CIP-1D record needs {CIP1D_RECORD_BYTES} bytes, got {len(payload)}")
145
+ head = struct.unpack_from("<3h", payload, 0)
146
+ count = np.frombuffer(payload, "<i2", 62, 6).astype(np.int16)
147
+ dofreject, endreject = struct.unpack_from("<2h", payload, 130)
148
+ housekeeping = np.frombuffer(payload, "<i2", 16, 134).astype(np.int16)
149
+ (particlecounter,) = struct.unpack_from("<H", payload, 166)
150
+ secmsec, hourmin, hostsync, resetflag, checksum, trailer = struct.unpack_from(
151
+ "<6h", payload, 168)
152
+ probetime = (((hourmin & 1984) >> 6) * 10000.0 + (hourmin & 63) * 100.0
153
+ + ((secmsec & 64512) >> 10) + (secmsec & 1023) / 1000.0)
154
+ return {"header": head[0], "bytecount": head[1], "oversizereject": head[2],
155
+ "count": count, "dofreject": dofreject, "endreject": endreject,
156
+ "housekeeping": housekeeping, "particlecounter": particlecounter,
157
+ "secmsec": secmsec, "hourmin": hourmin, "hostsynccounter": hostsync,
158
+ "resetflag": resetflag, "checksum": checksum, "trailer": trailer,
159
+ "probetime": float(probetime)}
160
+
161
+
162
+ def _nullbuffer(pointer: int) -> Buffer2D:
163
+ """`:16` -- INT tas/time (the struct literal declares them 0, not 0.0/0d)."""
164
+ return Buffer2D(image=0, tas=np.int16(0), time=np.int16(0), difftime=0.0,
165
+ eof=1, pointer=pointer, overload=0, date=0)
166
+
167
+
168
+ def _at_eof(f: BinaryIO) -> bool:
169
+ """IDL ``eof(lun)``: true only exactly at end of file (O(1) probe)."""
170
+ start = f.tell()
171
+ probe = f.read(1)
172
+ f.seek(start)
173
+ return len(probe) == 0
174
+
175
+
176
+ def read2dbuffer_sea(f: BinaryIO, op: dict) -> Buffer2D | SeaBuffer2D:
177
+ """`soda2_read2dbuffer.pro:15-17` then `:69-89` (the SEA branch), for
178
+ ``probetype`` ``'CIP'``/``'CIPG'`` (`:72-76`: ``readseabuffer_caps`` with
179
+ ``tag=op.seatag[0]``). The legacy SEA probes (2DC, 1D2D, HVPS, HAIL:
180
+ `:77-82`, ``read2dseabuffer.pro``) are refused by name."""
181
+ from .sea import SeaEOF, idl_sfm, readseabuffer_caps
182
+
183
+ pointer = f.tell() # :15
184
+ if _at_eof(f): # :17
185
+ return _nullbuffer(pointer)
186
+ probetype = str(op.get("probetype"))
187
+ if probetype not in ("CIP", "CIPG"):
188
+ raise NotImplementedError(
189
+ f"soda2_read2dbuffer.pro:77-82: SEA probetype {probetype!r} needs "
190
+ "read2dseabuffer.pro, not ported (only the CIP route, :72-76, is)")
191
+ fixedtas = op.get("fixedtas", np.float32(0.0)) # :74, FLOAT
192
+ tas = np.float32(fixedtas) if float(fixedtas) > 0 else np.float32(100.0)
193
+ seatag = np.atleast_1d(np.asarray(op["seatag"]))
194
+ a = readseabuffer_caps(f, tag=int(seatag[0]), probetype="CIP") # :75
195
+ if isinstance(a, SeaEOF): # :84
196
+ return _nullbuffer(pointer)
197
+ date = julday(a.month, a.day, a.year) if a.year > 0 else 0 # :85
198
+ offset = float(op.get("timeoffset", np.float32(0.0))) # FLOAT widening (T7)
199
+ return SeaBuffer2D( # :86-88
200
+ time=idl_sfm(a.starttime) + offset, stoptime=idl_sfm(a.stoptime) + offset,
201
+ image=a.image, difftime=0.0, eof=0, tas=tas, pointer=pointer,
202
+ imagepoint=a.imagepoint, timepoint=a.timepoint, date=date, overload=0)
203
+
204
+
205
+ @dataclass
206
+ class DmtBuffer2D:
207
+ """`soda2_read2dbuffer.pro:106`'s DMT return: ``image`` is the raw
208
+ ``bytarr(4096)`` (`:93`), ``eof`` 1 when fewer than 4112 bytes remained
209
+ (`:98`; the header is then all zeros, so ``time`` is ``timeoffset``)."""
210
+
211
+ time: float
212
+ image: np.ndarray
213
+ difftime: float
214
+ eof: int
215
+ tas: np.floating
216
+ pointer: int
217
+ date: int
218
+ overload: int
219
+
220
+
221
+ def read2dbuffer_dmt(f: BinaryIO, op: dict) -> Buffer2D | DmtBuffer2D:
222
+ """`soda2_read2dbuffer.pro:15-17` then `:91-107` (the DMT/PADS branch,
223
+ every ``probetype``: PIP is already ``'CIP'`` by `soda2_update_op.pro:49`).
224
+
225
+ Layout (`:92-93`): 8 INT16 ``year, month, day, hour, minute, second,
226
+ millisecond, weekday`` then 4096 image bytes -- 4112 bytes; ``subformat
227
+ 0`` (PACS) appends 12 bytes read into ``dummy`` (`:94,:99`), so a record
228
+ is 4124 bytes there. `:98` reads the record only when at least 4112 bytes
229
+ remain, else ``eofile=1`` with the struct still zero; `:99` then reads the
230
+ 12 dummy bytes **regardless**, so a PACS file whose remainder is under 12
231
+ bytes makes IDL's ``readu`` raise ``End of file encountered``
232
+ (``EOFError`` here). `:101` divides milliseconds by 100 for ``subformat
233
+ 2`` (the PADS centisecond error)."""
234
+ pointer = f.tell() # :15
235
+ if _at_eof(f): # :17
236
+ return _nullbuffer(pointer)
237
+ subformat = int(op.get("subformat", 0))
238
+ start = f.tell()
239
+ # :96-98 `fstat(lun).size`: on a `compress=1` lun this is the compressed
240
+ # on-disk length (measured under GDL, gdl_soda2_gz_input_golden.json).
241
+ remaining = _fstat_size(f) - start
242
+ year = month = day = hour = minute = second = millisecond = 0
243
+ image: np.ndarray = np.zeros(4096, dtype=np.uint8)
244
+ eofile = 0
245
+ if remaining >= 4112: # :98
246
+ year, month, day, hour, minute, second, millisecond, _weekday = \
247
+ struct.unpack("<8h", f.read(16))
248
+ image = np.frombuffer(f.read(4096), dtype=np.uint8).copy()
249
+ else:
250
+ eofile = 1
251
+ if subformat == 0: # :99
252
+ dummy = f.read(12)
253
+ if len(dummy) < 12:
254
+ raise EOFError(
255
+ "soda2_read2dbuffer.pro:99 readu on the 12 dummy bytes with "
256
+ f"{len(dummy)} remaining -- IDL 'End of file encountered'.")
257
+ divisor = 100.0 if subformat == 2 else 1000.0 # :100-101
258
+ time = hour * 3600.0 + minute * 60.0 + second * 1.0 + millisecond / divisor # :102
259
+ date = julday(month, day, year) if year > 0 else 0 # :103
260
+ fixedtas = op.get("fixedtas", np.float32(0.0)) # :104, FLOAT
261
+ tas = np.float32(fixedtas) if float(fixedtas) > 0 else np.float32(100.0)
262
+ offset = float(op.get("timeoffset", np.float32(0.0))) # FLOAT widening (T7)
263
+ return DmtBuffer2D(time=time + offset, image=image, difftime=0.0, eof=eofile,
264
+ tas=tas, pointer=pointer, date=date, overload=0)
265
+
266
+
267
+ @dataclass
268
+ class RafBuffer2D:
269
+ """`soda2_read2dbuffer.pro:64-65`'s RAF return: ``image`` is ``a.image``
270
+ (2DC ``ulonarr(1024)``, F2DC/F2DC_v2 ``ulon64arr(512)``, HVPS1
271
+ ``intarr(2048)``, `:21-31`), ``a`` the whole swapped record."""
272
+
273
+ time: float
274
+ image: np.ndarray
275
+ difftime: int
276
+ eof: int
277
+ tas: np.integer | np.floating
278
+ pointer: int
279
+ date: int
280
+ overload: np.floating
281
+ a: dict
282
+
283
+
284
+ _RAF_HEAD = ">BB9h" # :21-22 probetype, probenumber (BYTE), 9 INT tags
285
+
286
+
287
+ def _raf_image_dtype(probetype: str) -> str:
288
+ """`:21-31`: the image array per probe type (big-endian after :54)."""
289
+ if probetype in ("F2DC", "F2DC_v2"): # :24-27
290
+ return ">u8"
291
+ if probetype == "HVPS1": # :28-31
292
+ return ">i2"
293
+ return ">u4" # :21-23
294
+
295
+
296
+ class RafSubformatError(RuntimeError):
297
+ """The IDL ``stop`` at `:42`/`:44`, raised instead of halting."""
298
+
299
+
300
+ def read2dbuffer_raf(f: BinaryIO, op: dict) -> RafBuffer2D | Buffer2D:
301
+ """`soda2_read2dbuffer.pro:19-66`, the NCAR RAF branch."""
302
+ pointer = f.tell() # :15
303
+ subformat = int(op.get("subformat", 0))
304
+ if pointer < 157: # :34 skip the xml tag
305
+ f.seek(0) # :35
306
+ s = f.read(1000) # :36-37
307
+ if len(s) < 1000:
308
+ raise EOFError("soda2_read2dbuffer.pro:37 readu of bytarr(1000) "
309
+ "past end of file -- IDL 'End of file encountered'.")
310
+ pos = s.find(b"</PMS2D>") # :38 strpos
311
+ f.seek(pos + 9) # :39 (pos=-1 -> 8)
312
+ if pos == -1: # :40 new identifier, 2011
313
+ pos = s.find(b"</OAP>") # :41
314
+ f.seek(pos + 7) # :42
315
+ if subformat != 3: # :43
316
+ raise RafSubformatError(
317
+ "soda2_read2dbuffer.pro:43 stop: </OAP> file with "
318
+ f"subformat {subformat} (needs 3) -- leads to bad TAS")
319
+ elif subformat == 3: # :45
320
+ raise RafSubformatError(
321
+ "soda2_read2dbuffer.pro:45 stop: </PMS2D> file with "
322
+ "subformat 3 -- leads to bad TAS")
323
+ img_dt = np.dtype(_raf_image_dtype(op.get("probetype", "")))
324
+ nimg = 4116 - struct.calcsize(_RAF_HEAD)
325
+ size = _fstat_size(f)
326
+ while True: # :49-55 REPEAT
327
+ if size - f.tell() < 4116: # :51
328
+ return _nullbuffer(pointer)
329
+ rec = f.read(4116) # :52 readu; :53 swap_endian
330
+ head = struct.unpack(_RAF_HEAD, rec[:20])
331
+ image = np.frombuffer(rec[20:20 + nimg], dtype=img_dt).astype(
332
+ img_dt.newbyteorder("="))
333
+ probeid = bytes(head[:2]).decode("latin-1") # :54 string([type, number])
334
+ if probeid == op.get("probeid"): # :55
335
+ break
336
+ keys = ("probetype", "probenumber", "hours", "minutes", "seconds", "year",
337
+ "month", "day", "tas", "milliseconds", "overload")
338
+ # Header words are scalars; "image" (an array) joins the same record below.
339
+ a: dict[str, Any] = {k: (np.uint8(v) if i < 2 else np.int16(v))
340
+ for i, (k, v) in enumerate(zip(keys, head, strict=True))}
341
+ a["image"] = image
342
+ if subformat == 3: # :57 TAS format changed 2011
343
+ tas = a["tas"]
344
+ else:
345
+ tas = np.float32(a["tas"] * np.float32(125.0) / np.float32(255.0))
346
+ time = (int(a["hours"]) * 3600.0 + int(a["minutes"]) * 60.0 # :58 last slice
347
+ + int(a["seconds"]) * 1.0 + int(a["milliseconds"]) / 1000.0)
348
+ time = time + float(np.float32(op.get("timeoffset", np.float32(0.0)))) # :60
349
+ date = julday(int(a["month"]), int(a["day"]), max(int(a["year"]), 1)) # :61 year>1
350
+ overload = np.float32(a["overload"] / np.float32(1000.0)) # :62
351
+ return RafBuffer2D(time=time, image=image, difftime=0, eof=0, tas=tas,
352
+ pointer=pointer, date=date, overload=overload, a=a)
353
+
354
+
355
+ def read2dbuffer(f: BinaryIO, op: dict) -> Buffer2D | SeaBuffer2D | DmtBuffer2D | RafBuffer2D:
356
+ """Dispatches on `op["format"]`: `'SPEC'` (`:109-117`), `'SEA'`
357
+ (`:69-89`, the CIP route) and `'DMT'` (`:91-107`) are ported.
358
+
359
+ Source: ``soda2_read2dbuffer.pro`` (SODA-2); bare line references here are into that file."""
360
+ fmt = op.get("format")
361
+ if fmt == "SEA":
362
+ return read2dbuffer_sea(f, op)
363
+ if fmt == "DMT":
364
+ return read2dbuffer_dmt(f, op)
365
+ if fmt == "RAF":
366
+ return read2dbuffer_raf(f, op)
367
+ if fmt != "SPEC":
368
+ raise NotImplementedError(
369
+ "soda2_read2dbuffer.pro:118-210 (formats TXT/T28/HVPS1995) are "
370
+ "not ported; SPEC, SEA (CIP), DMT and RAF (:19-66) are.")
371
+ return read2dbuffer_spec(f, op)
@@ -0,0 +1,246 @@
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_reject.pro`` -- SODA-2's per-particle accept/reject decision.
4
+
5
+ 38 lines of IDL, no callees. Returns a **bit sum**, not a code: the source's
6
+ own comment calls the criteria *"in increasing order of importance"*, which
7
+ describes a priority the code does not implement. It adds. A particle failing
8
+ five criteria comes back as the sum of five powers of two, and the caller is
9
+ left to decode it.
10
+
11
+ Provenance: ``SODA2/abansemer-soda2-afcea15/soda2_reject.pro`` (whole file),
12
+ Aaron Bansemer, NCAR, 2009. Copyright (C) 2016 UCAR, 3-clause BSD.
13
+ Validated against GDL by ``tests/test_soda2_reject.py``; bank at
14
+ ``gdl_oracle/run_soda2_reject_bank.py``, 31 cases, all matching.
15
+
16
+ **The bits, and which of them are mutually exclusive.**
17
+
18
+ ====== ========================================== ==========================
19
+ bit criterion gated by
20
+ ====== ========================================== ==========================
21
+ 1 area ratio < 0.10 or > 1.0 --
22
+ 2 interarrival below cutoff (either side) --
23
+ 4 binning size outside the bin ladder --
24
+ 8 all-in / centre-in violated ``eawmethod``
25
+ 16 cluster of two or more ``clusterthresh > 0``
26
+ 32 water-droplet rejection ``water`` in {1, 2}
27
+ 64 irregular-only rejection ``water == -1``
28
+ 128 depth-of-field flag clear ``dofreject >= 1``
29
+ ====== ========================================== ==========================
30
+
31
+ Bits 32 and 64 are **mutually exclusive by construction** -- one needs
32
+ ``water`` positive and the other needs it negative -- so **255 is unreachable**
33
+ and the true ceiling is 223. Measured: the bank's ``all_eight_bits_is_unreachable``
34
+ case drives every reachable criterion at once and returns **222**, not 223,
35
+ because an ``arearatio`` high enough to trip bit 64 is by definition inside
36
+ bit 1's accepted band. A port that summed all eight would still pass every
37
+ single-bit case, which is why that case exists.
38
+
39
+ **``eawmethod`` gates bit 8 in a way that has no default.** ``'centerin'``
40
+ tests ``a.centerin``, ``'allin'`` tests ``a.allin``, and ``'reconstruct'``
41
+ matches neither -- so under reconstruction bit 8 is unreachable however the
42
+ particle sits on the array. That is correct (a reconstructed particle is
43
+ *meant* to be partial), and it is worth knowing it is achieved by falling off
44
+ the end of two `IF`s rather than by an explicit branch.
45
+
46
+ **NaN is not handled uniformly, and this is preserved.** Measured under GDL:
47
+
48
+ - ``arearatio`` NaN -> bit 1 does **not** fire. ``lt`` and ``gt`` are both
49
+ false for NaN, so a particle with an unmeasurable area ratio is *accepted*
50
+ by the criterion meant to catch bad area ratios.
51
+ - ``inttime`` NaN -> bit 2 does **not** fire, same reason.
52
+ - ``binningsize`` NaN -> bit 4 **does** fire. This is the one place the
53
+ routine tests ``finite()`` explicitly.
54
+
55
+ Finding **S3-b**. The port reproduces all three,
56
+ which in NumPy means the comparisons must be left as plain ``<``/``>`` on
57
+ values that may be NaN and must not be pre-screened.
58
+
59
+ **The return type changes with the answer.** ``reject=0b`` is BYTE; every
60
+ ``reject+=N`` adds an untyped IDL literal, which is INT, and ``BYTE + INT``
61
+ promotes. Measured: ``size(r,/tname)`` is ``BYTE`` for an accepted particle and
62
+ ``INT`` for a rejected one. Finding **S3-a**. This port returns a plain Python
63
+ ``int`` and records the IDL type alongside it in ``RejectResult.idl_type``,
64
+ because reproducing a type that varies with the value is not something a
65
+ Python ``int`` can do, and silently picking one would misreport the other.
66
+ """
67
+ from __future__ import annotations
68
+
69
+ import math
70
+ from collections.abc import Sequence
71
+ from dataclasses import dataclass
72
+ from typing import NamedTuple
73
+
74
+ import numpy as np
75
+
76
+ __all__ = [
77
+ "EAW_METHODS",
78
+ "Particle",
79
+ "RejectOptions",
80
+ "RejectResult",
81
+ "REJECT_BITS",
82
+ "soda2_reject",
83
+ ]
84
+
85
+ #: The three values ``eawmethod`` takes. Only two of them reach bit 8.
86
+ EAW_METHODS = ("reconstruct", "centerin", "allin")
87
+
88
+ #: bit -> what it means, in the source's own words. Exposed so a caller can
89
+ #: decode a sum without re-deriving the table from the comments.
90
+ REJECT_BITS: dict[int, str] = {
91
+ 1: "low area ratio",
92
+ 2: "below interarrival",
93
+ 4: "out of size range",
94
+ 8: "all-in / centre-in",
95
+ 16: "cluster",
96
+ 32: "water",
97
+ 64: "irregular-only",
98
+ 128: "depth-of-field flag",
99
+ }
100
+
101
+
102
+ @dataclass
103
+ class Particle:
104
+ """The tags of ``soda2_readpbp``'s per-particle structure that this
105
+ routine reads. Deliberately only those six: a fuller record would invite
106
+ the port to consult a field the original does not."""
107
+
108
+ arearatio: float
109
+ arearatiofilled: float
110
+ allin: int
111
+ centerin: int
112
+ diam: float
113
+ dofflag: int
114
+
115
+
116
+ @dataclass
117
+ class RejectOptions:
118
+ """The tags of ``op`` that this routine reads, through ``(*pop)``.
119
+
120
+ ``clusterthresh`` has a default here for the same reason
121
+ ``soda2_update_op.pro:22`` gives it one: it is absent from ``op`` as built
122
+ by ``soda2.pro:455`` and is added later, so a caller that skipped that
123
+ step would hit a missing-tag error rather than a disabled feature.
124
+ """
125
+
126
+ endbins: Sequence[float] | np.ndarray
127
+ eawmethod: str
128
+ water: int = 0
129
+ res: float = 0.0
130
+ dofreject: int = 0
131
+ clusterthresh: float = 0.0
132
+
133
+
134
+ class RejectResult(NamedTuple):
135
+ """``reject`` plus the IDL type the original would have returned.
136
+
137
+ ``idl_type`` is not decoration: it is the one thing about this routine's
138
+ output that a Python ``int`` cannot carry, and it is measurably
139
+ value-dependent (SODA-2 register entry S3-a). Callers comparing against an IDL run need
140
+ it; callers doing arithmetic can ignore it.
141
+ """
142
+
143
+ reject: int
144
+ idl_type: str
145
+
146
+ def reasons(self) -> list[str]:
147
+ """The set bits, in the source's own words. A convenience, and not a
148
+ reproduction of anything -- the IDL returns only the sum."""
149
+ return [text for bit, text in REJECT_BITS.items() if self.reject & bit]
150
+
151
+
152
+ def _res_times_ten(res: float) -> float:
153
+ """``(*pop).res*10.0`` (`:20`, `:24`, `:29`). ``10.0`` is a FLOAT
154
+ literal, so a FLOAT ``res`` -- a plain Python number here, as everywhere
155
+ this package reads the op -- multiplies in single precision; only a
156
+ ``numpy.float64`` (an IDL DOUBLE ``res``) keeps the product double. The
157
+ difference is a comparison boundary: FLOAT 2.3 (2.2999999523) times 10 is
158
+ 23.0 in single precision and 22.9999995 in double, so a ``diam`` of 23.0
159
+ is not above it in IDL (GDL-measured,
160
+ ``tests/test_soda2_reject.py::TheWaterSizeThresholdIsAFloatProduct``)."""
161
+ if isinstance(res, np.float64):
162
+ return float(res * 10.0)
163
+ return float(np.float32(res) * np.float32(10.0))
164
+
165
+
166
+ def soda2_reject(
167
+ a: Particle,
168
+ inttime: float,
169
+ nextinttime: float,
170
+ cutoff: float,
171
+ clustercount: int,
172
+ binningsize: float,
173
+ pop: RejectOptions,
174
+ ) -> RejectResult:
175
+ """``r = soda2_reject(a, inttime, nextinttime, cutoff, clustercount,
176
+ binningsize, pop)``.
177
+
178
+ Source: ``soda2_reject.pro`` (SODA-2).
179
+
180
+ Argument order and names follow the IDL exactly. ``pop`` is a pointer
181
+ there and a plain object here; nothing in this routine mutates it.
182
+
183
+ Every comparison below is written as the source writes it, including the
184
+ strictness of each boundary -- measured at the boundary in the bank rather
185
+ than inferred, because ``lt``/``le`` is the kind of detail a reader
186
+ reconstructs wrongly and a test at the midpoint never catches:
187
+
188
+ - ``arearatio`` exactly 0.10 or exactly 1.0 is **accepted**.
189
+ - ``binningsize`` exactly ``min(endbins)`` is **accepted**; exactly
190
+ ``max(endbins)`` is **rejected**. The ladder is half-open at the top and
191
+ closed at the bottom, which is the opposite of what most bin conventions
192
+ do and is preserved.
193
+ """
194
+ reject = 0
195
+
196
+ # :11 -- `lt`/`gt` are both false for NaN, so a NaN area ratio survives.
197
+ if a.arearatio < 0.10 or a.arearatio > 1.0:
198
+ reject += 1
199
+
200
+ # :12 -- either side of the particle. Same NaN behaviour.
201
+ if inttime < cutoff or nextinttime < cutoff:
202
+ reject += 2
203
+
204
+ # :13 -- the only explicit `finite()` test in the routine.
205
+ if (binningsize < min(pop.endbins)
206
+ or binningsize >= max(pop.endbins)
207
+ or not math.isfinite(binningsize)):
208
+ reject += 4
209
+
210
+ # :14-15 -- two `IF`s, not a CASE: 'reconstruct' falls off the end and
211
+ # bit 8 is then unreachable for it.
212
+ if pop.eawmethod == "allin" and a.allin == 0:
213
+ reject += 8
214
+ if pop.eawmethod == "centerin" and a.centerin == 0:
215
+ reject += 8
216
+
217
+ # :16
218
+ if pop.clusterthresh > 0 and clustercount >= 2:
219
+ reject += 16
220
+
221
+ # :19-26 -- water 1 and 2 differ in one threshold, 0.50 against 0.70.
222
+ res10 = _res_times_ten(pop.res)
223
+ if pop.water == 1:
224
+ if (a.arearatiofilled < 0.40
225
+ or (a.arearatiofilled < 0.50 and a.diam > res10)
226
+ or binningsize > 6000):
227
+ reject += 32
228
+ if pop.water == 2:
229
+ if (a.arearatiofilled < 0.40
230
+ or (a.arearatiofilled < 0.70 and a.diam > res10)
231
+ or binningsize > 6000):
232
+ reject += 32
233
+
234
+ # :29-31 -- the inverse selection: keep the irregulars, drop the round.
235
+ if pop.water == -1:
236
+ if (a.arearatio >= 0.50
237
+ or (a.arearatio >= 0.40 and a.diam <= res10)):
238
+ reject += 64
239
+
240
+ # :34-36
241
+ if pop.dofreject >= 1 and a.dofflag == 0:
242
+ reject += 128
243
+
244
+ # See RejectResult: BYTE until the first `+=`, INT thereafter. Measured,
245
+ # not derived from a promotion table.
246
+ return RejectResult(reject, "BYTE" if reject == 0 else "INT")