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,350 @@
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_processbuffer.pro:612-747`` -- the shared per-particle tail, SPEC path.
4
+
5
+ Round 6-A. Ports "Code common to all probes" (`:612-747`) for the
6
+ locals `processbuffer_spec.process_spec_buffer` produces
7
+ (`probetype in {'2DS','HVPS3'}`, `subformat 0`): a `SpecBufferParticles`
8
+ (never a `NullBuffer` -- the caller, :func:`soda2_processbuffer` in
9
+ `processbuffer_spec.py`, passes a `NullBuffer` straight through without
10
+ calling this module, exactly as IDL returns `nullbuffer` at `:267`/`:339`
11
+ before reaching `:612`).
12
+
13
+ **Convention.** This package's `bitimage` is `(nslices+1, 128)` uint8,
14
+ slice axis first (`processbuffer_spec.py`'s docstring). IDL's
15
+ `bitimage[fp:lp, startline:stopline]` is diode-then-slice; the equivalent
16
+ slice here is ``bitimage[startline:stopline+1, fp:lp+1]``, i.e. `roi` is
17
+ `(roilen, ndiodes)` -- exactly `fillholes.py`'s and `findsize.py`'s own
18
+ `(slices, diodes)` convention, so no per-call transpose is needed.
19
+ `label_blobs.py` names its axes generically (`s0`/`s1`); the flood fill is
20
+ symmetric in the two axes, so passing `(roilen, ndiodes)` there is also
21
+ correct, just not the axis identity its own docstring assumes for the
22
+ `:687-689` caller in IDL terms.
23
+
24
+ **A 1-slice ROI is 1-D in IDL** (`bitimage[fp:lp, s:s]` drops the trailing
25
+ dimension). Reproduced here: when `roilen == 1`, `roi`/`roi_orig` are
26
+ squeezed to 1-D (`roi[0]`) before `label_blobs`, `fillholes` and
27
+ `soda2_findsize` see them -- all three already handle 1-D input.
28
+
29
+ **Not ported / refused before any leaf call** (never invented):
30
+
31
+ - `greythresh > 0` (`:666`) -- every SPEC entry in `soda2_probespecs.pro`
32
+ carries `greythresh 0`; refused by name.
33
+ - HAIL (`:656-663`) and 1D2D's `area75` (`:638`) -- unreachable for SPEC;
34
+ `area75` stays zeros.
35
+
36
+ **Findings** (measured against the GDL bank,
37
+ `gdl_oracle/run_soda2_processbuffer_spec_bank.py`):
38
+
39
+ - **S5-f**: `stuckbits=1` corrupts diode `numdiodes-8` in every buffer that
40
+ follows a clean second -- `fixstuckbits`'s S4-x negative-index corruption
41
+ reached through `:615`'s always-defined `h=sbhist` for SPEC
42
+ (`soda2_process_2d.pro:41,498`).
43
+ - **S5-g**: an all-overload (empty-particle) buffer reaches the tail with
44
+ an all-zero `bitimage`; `streak = max(diodetotal)/mean(diodetotal) gt 3`
45
+ is `0/0`, an IDL floating-point error whose *value* is well defined
46
+ (`NaN gt 3` is false, `streak=0`) -- computed here under
47
+ `np.errstate(all="ignore")`.
48
+ - **S5-h**: the same empty ROI makes `where(roihist gt 0, nw)` return
49
+ `nw=0`, `w=-1` (IDL's no-match sentinel), so
50
+ `xspan = max(-1)-min(-1)+1 = 1` and `diodegaps = 1 - 0 = 1`, not 0.
51
+
52
+
53
+
54
+ """
55
+ from __future__ import annotations
56
+
57
+ from dataclasses import dataclass
58
+ from typing import Any
59
+
60
+ import numpy as np
61
+
62
+ from .backfill import soda2_backfill
63
+ from .fillholes import fillholes
64
+ from .findsize import soda2_findsize
65
+ from .fixraking import fixraking
66
+ from .fixstuckbits import fixstuckbits
67
+ from .label_blobs import label_blobs
68
+ from .poisson_spot_correct import poisson_spot_correct
69
+ from .processbuffer_spec import SpecBufferParticles
70
+
71
+ __all__ = ["TailOp", "ProcessedBuffer", "process_buffer_tail"]
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class TailOp:
76
+ """The `(*pop)` fields the tail (`:612-747`) reads, beyond `SpecOp`.
77
+ No defaults -- every field is a fidelity-relevant threshold and must
78
+ be given explicitly (the same discipline `profiles.py` applies to
79
+ `FidelityProfile`). IDL types in comments; `res`/`yres` are FLOAT.
80
+
81
+ Source: ``soda2_processbuffer.pro:612-747`` (SODA-2)."""
82
+
83
+ stuckbits: int
84
+ rakefix: int
85
+ greythresh: int
86
+ dioderange: tuple[int, int]
87
+ numdiodes: int
88
+ keeplargest: int
89
+ res: float # FLOAT
90
+ yres: float # FLOAT
91
+ #: Speed only, and the ONE field here that carries a default. Every other
92
+ #: field is a fidelity-relevant threshold and must be given explicitly; this
93
+ #: one moves no written byte -- label_blobs routes _label_region through
94
+ #: arrayprobe_soda2.jit_kernels when set, and
95
+ #: tests/test_soda2_label_region_jit_identity.py proves the two paths
96
+ #: byte-identical with mutation tests showing the comparison discriminates.
97
+ #: Default False, so an op that does not set it is unchanged.
98
+ jit: bool = False
99
+
100
+
101
+ @dataclass
102
+ class ProcessedBuffer:
103
+ """`soda2_processbuffer.pro:740-747`'s 40-field return structure, in
104
+ declaration order."""
105
+
106
+ diam: np.ndarray
107
+ xsize: np.ndarray
108
+ ysize: np.ndarray
109
+ xextent: np.ndarray
110
+ areasize: np.ndarray
111
+ oned: np.ndarray
112
+ twod: np.ndarray
113
+ probetime: np.ndarray
114
+ reftime: float
115
+ rawtime: np.ndarray
116
+ ar: np.ndarray
117
+ arfilled: np.ndarray
118
+ aspr: np.ndarray
119
+ rejectbuffer: int
120
+ bitimage: np.ndarray
121
+ allin: np.ndarray
122
+ centerin: np.ndarray
123
+ streak: int
124
+ zd: np.ndarray
125
+ sizecorrection: np.ndarray
126
+ dhist: np.ndarray
127
+ nslices: int
128
+ missed: int
129
+ diodegaps: np.ndarray
130
+ overloadflag: np.ndarray
131
+ dofflag: np.ndarray
132
+ xpos: np.ndarray
133
+ ypos: np.ndarray
134
+ orientation: np.ndarray
135
+ area_orig: np.ndarray
136
+ area_filled: np.ndarray
137
+ perimeterarea: np.ndarray
138
+ area75: np.ndarray
139
+ particlecounter: np.ndarray
140
+ edgetouch: np.ndarray
141
+ inttime: np.ndarray
142
+ clocktas: np.ndarray
143
+ startline: np.ndarray
144
+ stopline: np.ndarray
145
+ numregions: np.ndarray
146
+
147
+
148
+ class RakefixNotPorted(NotImplementedError):
149
+ """Formerly raised for `soda2_processbuffer.pro:616` `rakefix>0`; no
150
+ longer raised now that `fixraking.pro` is ported (`fixraking.py`).
151
+ Kept for import compatibility."""
152
+
153
+
154
+ class GreythreshNotPorted(NotImplementedError):
155
+ """`soda2_processbuffer.pro:666`: `greythresh>0` grey-probe adjustment
156
+ not ported; no SPEC entry in `soda2_probespecs.pro` carries a nonzero
157
+ `greythresh`."""
158
+
159
+
160
+ class RestoreSliceNotPorted(NotImplementedError):
161
+ """Formerly raised for `soda2_processbuffer.pro:678` `restore_slice`
162
+ true; no longer raised now that `soda2_backfill.pro` is ported
163
+ (`backfill.py`). Kept for import compatibility."""
164
+
165
+
166
+ def _dioderange(op: TailOp) -> tuple[int, int]:
167
+ fp, lp = op.dioderange
168
+ if lp == 0:
169
+ lp = op.numdiodes - 1
170
+ return fp, lp
171
+
172
+
173
+ def process_buffer_tail(
174
+ p: SpecBufferParticles, op: TailOp, lastdhist: np.ndarray,
175
+ ) -> ProcessedBuffer:
176
+ """``soda2_processbuffer.pro:612-747``, SPEC path only. ``lastdhist``
177
+ is ``(*pmisc).lastdhist`` -- unused directly (``fixstuckbits`` already
178
+ consumed it at ``:615`` when ``op.stuckbits`` is set, via the caller),
179
+ kept as a parameter only to assert its shape against ``op.numdiodes``.
180
+ """
181
+ lastdhist = np.asarray(lastdhist)
182
+ if lastdhist.shape != (op.numdiodes,):
183
+ raise ValueError(
184
+ f"lastdhist shape {lastdhist.shape} != (numdiodes,)="
185
+ f"({op.numdiodes},)")
186
+
187
+ if op.greythresh > 0:
188
+ raise GreythreshNotPorted(
189
+ "soda2_processbuffer.pro:666: greythresh>0 grey-probe path "
190
+ "not ported")
191
+
192
+ num_images = p.num_images
193
+ # `:613-615`. `bitimage_orig` is a copy of the buffer's own image,
194
+ # taken before `fixstuckbits` (trap 8) -- `roi_orig` is built from it
195
+ # below so stuck-bit corruption never reaches `dhist`. `fixstuckbits`
196
+ # is diode-axis-first (`h=lastdhist` has length `numdiodes`), so the
197
+ # buffer's own (slice, diode) layout is transposed in and back out.
198
+ bitimage_orig = p.bitimage
199
+ if op.stuckbits:
200
+ bitimage = fixstuckbits(bitimage_orig.T, h=lastdhist).T
201
+ else:
202
+ bitimage = bitimage_orig
203
+ # `:616`. `fixraking` is [diode, slice] like `fixstuckbits`, so the
204
+ # buffer's (slice, diode) layout is transposed in and back out.
205
+ if op.rakefix > 0:
206
+ bitimage = fixraking(bitimage.T, op.rakefix).T
207
+
208
+ # `:617-618`. `total(bitimage,2)` in IDL's [diode,slice] layout sums
209
+ # over slices, leaving one value per diode -- axis=0 here.
210
+ with np.errstate(all="ignore"):
211
+ diodetotal = bitimage.sum(axis=0).astype(np.float32)
212
+ ratio = np.max(diodetotal) / np.mean(diodetotal)
213
+ streak = 1 if ratio > 3 else 0
214
+
215
+ fp, lp = _dioderange(op)
216
+
217
+ diam = np.zeros(num_images, dtype=np.float32)
218
+ xsize = np.zeros(num_images, dtype=np.float32)
219
+ ysize = np.zeros(num_images, dtype=np.float32)
220
+ xextent = np.zeros(num_images, dtype=np.float32)
221
+ areasize = np.zeros(num_images, dtype=np.float32)
222
+ oned = np.zeros(num_images, dtype=np.float32)
223
+ twod = np.zeros(num_images, dtype=np.float32)
224
+ allin = np.zeros(num_images, dtype=np.uint8)
225
+ centerin = np.zeros(num_images, dtype=np.uint8)
226
+ edgetouch = np.zeros(num_images, dtype=np.uint8)
227
+ arearatio = np.zeros(num_images, dtype=np.float32)
228
+ arearatiofilled = np.zeros(num_images, dtype=np.float32)
229
+ aspr = np.zeros(num_images, dtype=np.float32)
230
+ orientation = np.zeros(num_images, dtype=np.float32)
231
+ area_orig = np.zeros(num_images, dtype=np.float32)
232
+ area_filled = np.zeros(num_images, dtype=np.float32)
233
+ perimeterarea = np.zeros(num_images, dtype=np.float32)
234
+ area75 = np.zeros(num_images, dtype=np.float32) # :638, 1D2D only, unreachable
235
+ zd = np.zeros(num_images, dtype=np.float32)
236
+ sizecorrection = np.ones(num_images, dtype=np.float32)
237
+ xpos = np.zeros(num_images, dtype=np.float32)
238
+ ypos = np.zeros(num_images, dtype=np.float32)
239
+ diodegaps = np.zeros(num_images, dtype=np.int16)
240
+ numregions = np.zeros(num_images, dtype=np.uint8)
241
+ dhist = np.zeros(op.numdiodes, dtype=np.int16)
242
+
243
+ overloadflag = p.overload
244
+
245
+ nslices = 0
246
+
247
+ for i in range(num_images):
248
+ s, e = int(p.startline[i]), int(p.stopline[i])
249
+ roi: Any = bitimage[s:e + 1, fp:lp + 1]
250
+ roi_orig: Any = bitimage_orig[s:e + 1, fp:lp + 1]
251
+ roilen = e - s + 1
252
+ nslices += roilen
253
+
254
+ if roilen == 1:
255
+ roi = roi[0]
256
+ roi_orig = roi_orig[0]
257
+
258
+ # `:678` -- `soda2_backfill` is applied to the ROI when `restore_slice` is set. 2DC branch
259
+ # only (`:114-115`); roi_orig is untouched.
260
+ if p.restore_slice:
261
+ roi = soda2_backfill(roi)
262
+
263
+ # `:686-700` -- keeplargest.
264
+ if op.keeplargest != 0:
265
+ # `jit` is a speed-only switch: label_blobs routes _label_region
266
+ # through arrayprobe_soda2.jit_kernels when set, and
267
+ # tests/test_soda2_label_region_jit_identity.py proves the two
268
+ # paths byte-identical (np.array_equal, with mutation tests showing
269
+ # the comparison is a real discriminator). Default off, so an op
270
+ # that does not set it is unchanged.
271
+ _jit = bool(getattr(op, "jit", False))
272
+ if op.keeplargest == 1:
273
+ blobs = label_blobs(roi, dilatelength=2, jit=_jit)
274
+ elif op.keeplargest == 2:
275
+ blobs = label_blobs(roi, dilatelength=1, jit=_jit)
276
+ else:
277
+ blobs = label_blobs(roi, dilatelength=0, all_neighbors=True, jit=_jit)
278
+ nblobs = int(blobs.max()) if blobs.size else 0
279
+ numregions[i] = nblobs % 256
280
+ if nblobs > 1:
281
+ counts = np.bincount(blobs.ravel().astype(np.int64),
282
+ minlength=nblobs + 1)[1:nblobs + 1]
283
+ ilargest = int(np.argmax(counts)) # first maximum
284
+ good = blobs == (ilargest + 1)
285
+ roi2 = np.zeros_like(roi)
286
+ roi2[good] = roi[good]
287
+ roi = roi2
288
+
289
+ # `:703-704`.
290
+ if roilen == 1:
291
+ roihist = roi_orig.astype(np.float64)
292
+ else:
293
+ roihist = roi_orig.sum(axis=0).astype(np.float64)
294
+ dhist[fp:lp + 1] += roihist.astype(np.int16)
295
+
296
+ # `:707-709`.
297
+ w = np.flatnonzero(roihist > 0)
298
+ nw = w.size
299
+ if nw == 0:
300
+ xspan = 1 # max(-1)-min(-1)+1, IDL no-match sentinel -- S5-h
301
+ else:
302
+ xspan = int(w.max()) - int(w.min()) + 1
303
+ diodegaps[i] = xspan - nw
304
+
305
+ # `:712-716`.
306
+ area_orig[i] = float(np.sum(roi, dtype=np.float64))
307
+ roifilled = fillholes(roi, jit=bool(getattr(op, "jit", False)))
308
+ area_filled[i] = float(np.sum(roifilled, dtype=np.float64))
309
+ pc = poisson_spot_correct(area_orig[i], area_filled[i])
310
+ sizecorrection[i] = pc.correction
311
+ zd[i] = pc.zd
312
+
313
+ # `:719-737`.
314
+ yres_eff = np.float32(op.yres) * np.float32(p.stretch[i])
315
+ part = soda2_findsize(
316
+ roi, np.float32(op.res), yres_eff,
317
+ voidarea=float(area_filled[i]) - float(area_orig[i]))
318
+ diam[i] = part.diam
319
+ xsize[i] = part.xsize
320
+ ysize[i] = part.ysize
321
+ xextent[i] = part.xextent
322
+ oned[i] = part.oned
323
+ twod[i] = part.twod
324
+ areasize[i] = part.areasize
325
+ arearatio[i] = part.ar
326
+ arearatiofilled[i] = part.arfilled
327
+ aspr[i] = part.aspr
328
+ allin[i] = part.allin
329
+ centerin[i] = part.centerin
330
+ edgetouch[i] = part.edgetouch
331
+ xpos[i] = part.c[0]
332
+ ypos[i] = part.c[1]
333
+ orientation[i] = part.orientation
334
+ perimeterarea[i] = part.perimeterarea
335
+
336
+ return ProcessedBuffer(
337
+ diam=diam, xsize=xsize, ysize=ysize, xextent=xextent,
338
+ areasize=areasize, oned=oned, twod=twod,
339
+ probetime=p.time_sfm, reftime=p.reftime, rawtime=p.rawtime,
340
+ ar=arearatio, arfilled=arearatiofilled, aspr=aspr,
341
+ rejectbuffer=0, bitimage=bitimage, allin=allin, centerin=centerin,
342
+ streak=streak, zd=zd, sizecorrection=sizecorrection, dhist=dhist,
343
+ nslices=nslices, missed=p.missed, diodegaps=diodegaps,
344
+ overloadflag=overloadflag, dofflag=p.dof, xpos=xpos, ypos=ypos,
345
+ orientation=orientation, area_orig=area_orig,
346
+ area_filled=area_filled, perimeterarea=perimeterarea,
347
+ area75=area75, particlecounter=p.particle_count,
348
+ edgetouch=edgetouch, inttime=p.inttime, clocktas=p.clocktas,
349
+ startline=p.startline, stopline=p.stopline, numregions=numregions,
350
+ )
@@ -0,0 +1,245 @@
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_process_2d.pro:147-172`` -- the ASCII/CSV and netCDF PTH (true
4
+ airspeed) readers. The ``dat``/``sav`` branch (``:131-145``) is
5
+ ``process_2d._pth_from_sav``; this module is the other two formats.
6
+
7
+ Provenance: ``SODA2/abansemer-soda2-afcea15/soda2_process_2d.pro:147-172``
8
+ plus ``restorenc.pro`` / ``ncdf2sav.pro`` (the netCDF branch's reader), Aaron
9
+ Bansemer, NCAR. Copyright (C) 2016 UCAR, 3-clause BSD. Validated against GDL
10
+ by ``tests/test_soda2_pth_readers.py``; bank
11
+ ``gdl_oracle/run_soda2_pth_readers_bank.py`` lifts ``:126-127,129,147-172``
12
+ out of the vendored file verbatim at run time, over tiny synthetic fixtures
13
+ ``tests/data/soda2_pth_*``; golden ``tests/data/gdl_soda2_pth_readers_golden.json``.
14
+
15
+ **ASCII/CSV (``:147-162``)**, suffix ``txt`` or ``csv``, line by line:
16
+
17
+ - ``:152`` ``readf,lun,v`` -- one line into a string. The file is split on
18
+ ``\\n``; a CR before it stays in the string and is harmless (below). An
19
+ empty file's first ``readf`` is an end-of-file I/O error, caught by
20
+ ``:150``'s ``on_ioerror`` -- nothing is read.
21
+ - ``:153`` ``float(strsplit(v, '[ ,\\t]+', /regex, /extract))`` -- empty
22
+ pieces dropped (leading blanks, a trailing comma). Each piece converts by
23
+ its **longest numeric prefix** (``102x`` -> 102, ``1.00d2`` -> 100,
24
+ ``0x68`` -> 104, ``NaN``/``Inf``); a piece with **no** numeric prefix is a
25
+ type-conversion error, and ``on_ioerror`` jumps to ``bad:`` -- **the whole
26
+ row is dropped, even when only a third, unused column is junk**. All
27
+ GDL-measured (``csv_badtime``, ``csv_exotic``); the hex literal in
28
+ particular is GDL's ``strtod`` and is not IDL-confirmed. The result is
29
+ FLOAT, so a time is rounded to float32 **before** ``round()``:
30
+ ``36001.4999`` becomes ``36001.5`` and indexes as 36002 (``txt_float32``).
31
+ - ``:154`` ``i = (round(fields[0]) - op.starttime)/op.rate > 0`` -- ``> 0``
32
+ is IDL's maximum operator: a row **before** ``starttime`` is not rejected,
33
+ it is clamped to record 0 and overwrites from there (``csv_window``). A NaN
34
+ time rounds to LONG's most negative value and clamps the same way
35
+ (``csv_nantime``). ``round`` is half away from zero.
36
+ - ``:156`` accepted when there are >= 2 fields, ``i lt numrecords`` and
37
+ ``0 < fields[1] < 500`` -- **500**, where the SAVE (``:135``) and netCDF
38
+ (``:167``) branches bound at 400. ``pth_tas[i:*] = fields[1]``: every
39
+ accepted row fills forward to the end, so the last row read wins from its
40
+ own index (out-of-order rows included). A DOUBLE subscript truncates.
41
+ - ``:161`` ``got_pth=1`` **unconditionally** -- a file with no accepted row
42
+ (or no rows) still sets it, so ``aircrafttas`` becomes an all-zero
43
+ ``pth_tas`` rather than falling back to the probe TAS (``txt_empty``,
44
+ ``csv_allbad``). The SAVE branch stops at ``:136`` instead.
45
+
46
+ **netCDF (``:164-172``)**, suffix ``nc``:
47
+
48
+ - ``:165`` restores TIME and TASX from ``op.pth`` through ``restorenc`` -> ``ncdf2sav``,
49
+ which upper-cases both the list and each variable name before comparing
50
+ (its own comment says "case sensitive"; it is not -- ``nc_lowercase``), keeps
51
+ the **first** variable of each name in variable-id order ("Skipped
52
+ duplicate", ``nc_duplicate``), and reads with ``ncdf_varget``: **raw**
53
+ values, no ``scale_factor``/``_FillValue`` (``nc_packed``).
54
+ - ``:167`` ``good = where(tasx gt 0 and tasx lt 400 and time ge starttime and
55
+ time le stoptime)`` -- when TIME and TASX differ in length the ``and``
56
+ truncates to the shorter (``nc_mismatch``). **No count is checked**: with
57
+ no match ``where`` returns -1 and ``data.time[-1]``/``data.tasx[-1]`` are
58
+ the **last** elements, so a TAS the filter just rejected still fills
59
+ ``pth_tas`` from the last sample's record (``nc_nogood``, GDL-measured;
60
+ IDL 8's negative scalar subscript reads the same, not IDL-confirmed).
61
+ - ``:168-170`` ``itas = (round(time[good]) - starttime)/rate``;
62
+ ``pth_tas[itas[i]:*] = tasx[good[i]]``.
63
+ - A file without a TASX (or TIME) variable halts at ``:167`` ("Tag name
64
+ ... is undefined for STRUCT", ``nc_notasx``): :class:`PthReaderHalt`.
65
+
66
+ **Refused by name** (unreached by the bank, so not ported): a TIME or TASX of
67
+ more than one dimension (high-rate ``TASX(Time, sps25)``), and a subscript
68
+ ``:170`` would put outside ``pth_tas`` (IDL halts; which way GDL goes there
69
+ is unmeasured).
70
+
71
+ ``starttime``/``rate`` are taken as Python floats (the DOUBLE literals every
72
+ driver bank uses). ``example_batch.pro:7,31`` passes INT ``starttime``/
73
+ ``rate``, making ``:154``/``:168`` LONG division; for the non-negative
74
+ numerators an accepted row can have (``:154`` clamps; ``:167`` filters on
75
+ ``time ge starttime``), LONG division and DOUBLE-then-truncate give the same
76
+ subscript (derived).
77
+ """
78
+ from __future__ import annotations
79
+
80
+ import re
81
+ from pathlib import Path
82
+ from typing import Any
83
+
84
+ import numpy as np
85
+
86
+ __all__ = ["PthReaderHalt", "pth_suffix", "read_pth_ascii", "read_pth_ncdf", "read_pth"]
87
+
88
+
89
+ def pth_suffix(pth: str) -> str:
90
+ """``:129`` takes the suffix as the last dot-separated piece of ``op.pth``: the last
91
+ non-empty ``.``-separated token (``strsplit`` drops empty tokens), the
92
+ whole name when it has no ``.``, and ``''`` when every token is empty.
93
+ Case-sensitive, as ``:131-164``'s ``eq`` tests are.
94
+
95
+ Source: ``soda2_process_2d.pro:129`` (SODA-2)."""
96
+ tokens = [t for t in pth.split(".") if t]
97
+ return tokens[-1] if tokens else ""
98
+
99
+
100
+ class PthReaderHalt(RuntimeError):
101
+ """An IDL halt inside ``:147-172``, raised naming the line."""
102
+
103
+
104
+ #: `:153`'s delimiter regex, `'[ ,' + STRING(9B) + ']+'`.
105
+ _SPLIT = re.compile(rb"[ ,\t]+")
106
+
107
+ #: The numeric prefix a GDL string-to-FLOAT conversion accepts, measured by
108
+ #: the bank: optional blanks and sign, then hex (`0x68`), NaN/Inf, or a
109
+ #: decimal with an optional `e`/`E`/`d`/`D` exponent.
110
+ _NUMBER = re.compile(
111
+ rb"\s*([+-]?)(?:(0[xX][0-9a-fA-F]+)"
112
+ rb"|(nan|inf(?:inity)?)"
113
+ rb"|((?:\d+\.?\d*|\.\d+)(?:[eEdD][+-]?\d+)?))",
114
+ re.IGNORECASE,
115
+ )
116
+
117
+ _LONG_MIN = -(2 ** 31)
118
+
119
+
120
+ def _to_float32(piece: bytes) -> np.float32 | None:
121
+ """One `:153` element; ``None`` is IDL's type-conversion error."""
122
+ m = _NUMBER.match(piece)
123
+ if m is None:
124
+ return None
125
+ sign = -1.0 if m.group(1) == b"-" else 1.0
126
+ if m.group(2):
127
+ value = float(int(m.group(2), 16))
128
+ elif m.group(3):
129
+ value = float(m.group(3).decode())
130
+ else:
131
+ value = float(m.group(4).replace(b"d", b"e").replace(b"D", b"e").decode())
132
+ return np.float32(sign * value)
133
+
134
+
135
+ def _idl_round_long(value: float) -> int:
136
+ """IDL ``ROUND`` of a FLOAT to LONG: half away from zero; NaN (and
137
+ anything outside LONG) becomes LONG's most negative value, measured
138
+ (``csv_nantime``) as clamping to record 0 through ``:154``'s ``> 0``."""
139
+ if not np.isfinite(value):
140
+ return _LONG_MIN
141
+ r = int(np.floor(abs(value) + 0.5))
142
+ r = -r if value < 0 else r
143
+ if r > 2 ** 31 - 1 or r < _LONG_MIN:
144
+ return _LONG_MIN
145
+ return r
146
+
147
+
148
+ def read_pth_ascii(path: str | Path, starttime: float, rate: float,
149
+ numrecords: int) -> np.ndarray:
150
+ """``:147-162`` -- returns ``pth_tas`` (float32[numrecords]); the caller
151
+ sets ``got_pth = 1`` whatever this returns (``:161``).
152
+
153
+ Source: ``soda2_process_2d.pro:147-162`` (SODA-2)."""
154
+ pth_tas = np.zeros(numrecords, dtype=np.float32) # `:127`
155
+ content = Path(path).read_bytes()
156
+ lines = content.split(b"\n")
157
+ if content.endswith(b"\n"):
158
+ lines = lines[:-1] # `eof(lun)` is true after the last terminator
159
+ for line in lines:
160
+ pieces = [p for p in _SPLIT.split(line) if p != b""]
161
+ if not pieces:
162
+ continue # `strsplit` returns '' -- at most one field: `:156` skips it
163
+ parsed = [_to_float32(p) for p in pieces]
164
+ fields = [f for f in parsed if f is not None]
165
+ if len(fields) != len(parsed):
166
+ continue # `:150` on_ioerror -> `bad:`, the whole row
167
+ i = max((_idl_round_long(float(fields[0])) - starttime) / rate, 0.0)
168
+ tas = fields[1] if len(fields) > 1 else None
169
+ if (tas is not None and i < numrecords
170
+ and tas > 0 and tas < np.float32(500)):
171
+ pth_tas[int(i):] = tas
172
+ return pth_tas
173
+
174
+
175
+ def _first_var(ds: Any, upper: str) -> Any:
176
+ """``ncdf2sav``: the first variable (id order) whose upper-cased name is
177
+ ``upper``; later ones are "Skipped duplicate variable"."""
178
+ for name, var in ds.variables.items():
179
+ if name.upper() == upper:
180
+ return var
181
+ return None
182
+
183
+
184
+ def read_pth_ncdf(path: str | Path, starttime: float, stoptime: float,
185
+ rate: float, numrecords: int) -> np.ndarray:
186
+ """``:164-172`` -- returns ``pth_tas`` (float32[numrecords]).
187
+
188
+ Source: ``soda2_process_2d.pro:164-172`` (SODA-2)."""
189
+ from netCDF4 import Dataset
190
+
191
+ pth_tas = np.zeros(numrecords, dtype=np.float32) # `:127`
192
+ with Dataset(str(path), "r") as ds:
193
+ tvar = _first_var(ds, "TIME")
194
+ vvar = _first_var(ds, "TASX")
195
+ for var, tag in ((tvar, "TIME"), (vvar, "TASX")):
196
+ if var is None:
197
+ raise PthReaderHalt(
198
+ f"soda2_process_2d.pro:167: Tag name: {tag} is undefined "
199
+ "for STRUCT (no such variable in the PTH netCDF)")
200
+ var.set_auto_maskandscale(False) # `ncdf_varget`: raw values
201
+ # A high-rate (2-D, seconds x sps) variable is indexed in IDL's
202
+ # element order, sps fastest -- C order of netCDF4's (time, sps)
203
+ # array. With a 1-D TIME and a 2-D TASX the `and` below keeps the
204
+ # shorter length, so second k's time pairs with second 0's samples
205
+ # (GDL golden `nc_hirate_tasx2d`, SODA-2 finding S9-u).
206
+ time = np.asarray(tvar[:]).ravel(order="C")
207
+ tasx = np.asarray(vvar[:]).ravel(order="C")
208
+
209
+ n = min(time.size, tasx.size) # IDL `and` of unequal arrays: the shorter
210
+ mask = ((tasx[:n] > 0) & (tasx[:n] < 400)
211
+ & (time[:n] >= starttime) & (time[:n] <= stoptime))
212
+ good = np.nonzero(mask)[0]
213
+ if good.size == 0:
214
+ good = np.array([-1]) # `where` -> -1, unchecked: the last element
215
+ for g in good:
216
+ t = float(time[g])
217
+ if not np.isfinite(t):
218
+ raise NotImplementedError(
219
+ "soda2_process_2d.pro:168: round() of a non-finite TIME -- "
220
+ "unmeasured")
221
+ # `round()`: identity on integer types, half away from zero otherwise.
222
+ rt = t if np.issubdtype(time.dtype, np.integer) else float(
223
+ np.sign(t) * np.floor(abs(t) + 0.5))
224
+ itas = (rt - starttime) / rate
225
+ idx = int(np.trunc(itas))
226
+ if not 0 <= idx < numrecords:
227
+ raise NotImplementedError(
228
+ f"soda2_process_2d.pro:170: subscript {itas!r} outside "
229
+ f"pth_tas[0:{numrecords - 1}] -- IDL halts; unmeasured")
230
+ pth_tas[idx:] = np.float32(tasx[g])
231
+ return pth_tas
232
+
233
+
234
+ def read_pth(pth: str | Path, suffix: str, starttime: float, stoptime: float,
235
+ rate: float, numrecords: int) -> tuple[np.ndarray, int]:
236
+ """``:147-172`` dispatch on ``suffix`` (``:129``, case-sensitive):
237
+ returns ``(pth_tas, got_pth)``. ``dat``/``sav`` is not this module's
238
+ (``process_2d._pth_from_sav``); any other suffix raises ``ValueError``.
239
+
240
+ Source: ``soda2_process_2d.pro:147-172`` (SODA-2)."""
241
+ if suffix in ("txt", "csv"):
242
+ return read_pth_ascii(pth, starttime, rate, numrecords), 1
243
+ if suffix == "nc":
244
+ return read_pth_ncdf(pth, starttime, stoptime, rate, numrecords), 1
245
+ raise ValueError(f"read_pth: suffix {suffix!r} is not txt, csv or nc")
@@ -0,0 +1,11 @@
1
+ # PEP 561 marker.
2
+ #
3
+ # This package is fully annotated and `mypy src` is clean, but without this
4
+ # file a type checker in a DOWNSTREAM project ignores every annotation --
5
+ # PEP 561 says an installed package's types are invisible unless it says so.
6
+ # Nothing in this repository would ever have noticed: `mypy src` runs against
7
+ # the source tree, where the marker is irrelevant.
8
+ #
9
+ # Added 2026-09-12 in a release-readiness pass. `tests/test_py_typed.py`
10
+ # asserts one exists per shipped package and that setuptools is told to
11
+ # include it, because a marker that is not packaged is the same as no marker.