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,1364 @@
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`` -- the SODA-2 driver, SPEC path and (CIP-1) the
4
+ SEA/CIP route,
5
+ raw bytes to the in-memory ``data``. Composes every module
6
+ ported in rounds
7
+ 5-6 (``update_op``, ``buildindex``, ``process_hk``, ``read2dbuffer``,
8
+ ``processbuffer_spec``/``processbuffer_tail``, ``particlesort``,
9
+ ``sample_area``) into the whole driver body. **Round 9
10
+ wires in the PBP writers** (``pbp_writer.py``): ``particlefile
11
+ == 1`` (``.pbp.csv``) and ``ncdfparticlefile in (1,)`` (``.pbp.nc``, the
12
+ non-image variant) now write real per-particle output, one call, raw bytes
13
+ to ``.pbp.*``. ``fn_pbp`` reprocesses from an existing ``.pbp.nc``
14
+ (``:30-35``, ``:584-617``; :mod:`reprocess_pbp`) and writes no particle file.
15
+
16
+ Vendored source: ``SODA2/abansemer-soda2-afcea15/soda2_process_2d.pro``, 742
17
+ lines. **Never edited.** Its scope table, traps and GDL bank are recorded in the
18
+ project's development record.
19
+
20
+ **Not ported here:**
21
+ - ``:241-354``, ``:286-306`` -- particle-image output (``ncdfparticlefile ==
22
+ 2``) is ported on the serial path; with ``jobs > 1`` it raises
23
+ ``PbpImagesNotPorted`` before any file read.
24
+ - ``:732-739`` -- the widget/``print`` notification after the SAVE (a
25
+ ``dialog_message`` or ``print, infoline``): console only, not reproduced.
26
+
27
+ **PTH files:** ``dat``/``sav`` (`:131-145`, W2) -- ``_pth_from_sav``
28
+ below; ``txt``/``csv``/``nc`` (`:147-172`) --
29
+ ``pth_readers.read_pth``. ``pth`` set and missing raises at ``:185-186`` (an
30
+ IDL ``stop``).
31
+
32
+ **Ported late:** the ASCII PSD export (``:722-726``, ``asciipsdfile``, W4;
33
+ ``export_ascii.soda2_export_ascii``) and, after it in IDL order,
34
+ the IDL SAVE file (``:729-731``, ``savfile``, W1;
35
+ ``save_writer.save_process_data``), which replaced the earlier
36
+ ``pbp_writer.SaveFileNotPorted`` -- that class was defined but never raised,
37
+ so ``savfile=1`` (the ``update_op`` default) silently wrote no ``.dat``.
38
+ - ``:376`` -- more than one raw file in ``op.fn`` (SPEC-only scope, same
39
+ restriction ``spec_process_hk``/``soda2_buildindex`` already carry).
40
+ - ``:493`` -- ``activetimefrommissed`` (an IDL ``stop``, "Under development"
41
+ in the source itself).
42
+
43
+ **S6-f (read-only):** the
44
+ early ``return`` at both ``:430-433`` and ``:576`` fires **after** the PBP
45
+ files are opened (``:197-354``) but **before** the tail close block
46
+ (``:689-721``, ``close,lun_pbp`` / ``ncdf_close,ncdf_id``) ever runs -- so a
47
+ window with no buffers, or a tail flush that lands exactly on empty, leaves
48
+ both ``.pbp.csv`` and ``.pbp.nc`` open with header/definitions written but
49
+ never closed. This port reproduces it exactly: :func:`soda2_process_2d`
50
+ returns ``None`` on both paths without calling ``close_pbp_ncdf``/
51
+ ``csv_f.close()`` when writers were opened.
52
+
53
+ **Traps**, cited to the plan's numbering (S6-a..S6-d are the measured/derived
54
+ findings):
55
+
56
+ 1. (S6-a) The processing window includes one buffer at or before
57
+ ``starttime`` and one at or after ``stoptime`` (`:427-429`):
58
+ ``firstbuff = max(where(bufftime lt starttime)) > 0`` (no match -> ``-1 >
59
+ 0`` -> 0); ``lastbuff = min(where(bufftime gt stoptime))`` (no match ->
60
+ ``numbuffs-1``). Both edge buffers are processed and folded into the edge
61
+ time records via ``timeindex``'s clamp at `:454`.
62
+ 2. (S6-b) A date mismatch of more than 5 days between ``op.date`` and the
63
+ file's own first buffer date makes the driver **silently adopt the file's
64
+ date** (`:410-418`); a mismatch of 1-5 days shifts every buffer by whole
65
+ days and typically empties the requested window (returns ``None``).
66
+ 3. (S6-c) ``lastdhist`` is read from the **current** record's ``dhist``
67
+ after it has already been updated with the just-processed buffer
68
+ (`:497-498``, order preserved exactly).
69
+ 4. ``numrecords``/``timeindex``/``buffindex`` are IDL ``long()`` --
70
+ truncation toward zero, not floor.
71
+ 5. ``x``'s per-field dtypes at the ``particlesort`` call (`:113-117``,
72
+ `:510-544``) -- see ``_X_DTYPES`` below.
73
+ 6. ``probetas = interpol(house.tas, house.time, b.time)`` (`:462``) runs
74
+ only when ``nimages > 0``.
75
+ 7. (S6-d, S6-f) The 10,000,000-particle flush (`:565-573``): ``soda2_particlesort``
76
+ is called on ``x[0:istop]``, then ``istop`` resets to -1 and
77
+ ``ncdf_offset`` advances; if the buffers processed after the last flush
78
+ add no particles, ``istop`` stays -1 and the driver returns ``None`` at
79
+ `:576`, **discarding nothing new but reporting no output** for that tail
80
+ -- and (S6-f) leaving any open PBP writers unclosed.
81
+ 8. Concentration dtypes (`:625-675``): ``spec1d`` is float32, taken before
82
+ the ``corr_fac`` clamp (IDL's ``>`` is MAX, not comparison) is applied to
83
+ both ``spec1d`` and ``d.spec2d``/``d.spec2d_aspr`` in place.
84
+ ``soda2_samplearea``'s IDL signature carries a ``smethod`` positional
85
+ parameter between ``eawmethod`` and ``wavelength``
86
+ (``soda2_samplearea.pro:1``); it is never read in that function's body
87
+ (grepped directly), and this port's ``sample_area.sample_area`` already
88
+ omits it -- confirmed, not guessed.
89
+ 9. ``orientation_index`` (`:669-673``) only ever fires when a bin's total
90
+ orientation histogram exceeds 50 counts; never reached on the tracked
91
+ fixtures.
92
+ 10. ``aircrafttas`` (`:652-653``): ``pth_tas`` when ``got_pth == 1``
93
+ (``fixedtas > 0``), else ``d.tas``.
94
+ 11. ``buffindex`` (the driver's local, returned as ``data.ind``) is kept as
95
+ computed -- "for output only" per the source's own comment -- and can be
96
+ negative for a buffer before ``starttime``.
97
+
98
+ Findings registered: S6-a, S6-b, S6-c, S6-d (``tests/test_soda2_findings_are_registered.py``).
99
+ """
100
+ from __future__ import annotations
101
+
102
+ import logging
103
+ import os
104
+ import time
105
+ from collections.abc import Mapping, Sequence
106
+ from dataclasses import dataclass
107
+ from datetime import datetime
108
+ from typing import Any, cast
109
+
110
+ import numpy as np
111
+
112
+ from . import processbuffer_cip as _pb_cip
113
+ from . import processbuffer_spec as _pb_spec
114
+ from . import processbuffer_tail as _pb_tail
115
+ from .buildindex import GenericIndex, buildindex, point_lun
116
+ from .export_ascii import soda2_export_ascii
117
+ from .particlesort import (
118
+ Accumulator,
119
+ ParticlesortOptions,
120
+ new_accumulator,
121
+ soda2_particlesort,
122
+ spec_sort_locals,
123
+ )
124
+ from .pbp_writer import (
125
+ PbpImagesNotPorted,
126
+ close_pbp_ncdf,
127
+ open_pbp_csv,
128
+ open_pbp_ncdf,
129
+ pbp_filename,
130
+ write_pbp_csv_buffer,
131
+ write_pbp_ncdf_buffer,
132
+ write_pbp_ncdf_images,
133
+ )
134
+ from .process_hk import HouseData, _interpol, process_hk
135
+ from .processbuffer_cip import CipMisc, CipOp, soda2_processbuffer_cip
136
+ from .processbuffer_spec import NullBuffer, SpecMisc, SpecOp, soda2_processbuffer
137
+ from .processbuffer_tail import TailOp
138
+ from .pth_readers import pth_suffix as _pth_suffix
139
+ from .pth_readers import read_pth
140
+ from .read2dbuffer import DmtBuffer2D, SeaBuffer2D, read2dbuffer
141
+ from .sample_area import sample_area
142
+ from .save_writer import save_process_data
143
+ from .timeconv import soda2_parsedate
144
+ from .update_op import update_op
145
+
146
+ __all__ = ["ProcessData", "SeaHouse", "NUM2PROCESS", "soda2_process_2d"]
147
+
148
+ #: `:565` `num2process` literal -- a module constant, overridable per call
149
+ #: for tests (§3 trap 7).
150
+ NUM2PROCESS = 10_000_000
151
+
152
+ #: `:105` `maxslices` -- the image flush threshold (`:564`), overridable for tests.
153
+ MAXSLICES = 10_000_000
154
+
155
+ #: `:113-117` -- the ``basestruct`` dtypes, keyed by the lower-case tag name.
156
+ #: ``particlesort.py``'s ``X_TAGS`` lists the subset ``soda2_particlesort``
157
+ #: itself reads; this table is the superset the driver's ``x`` struct
158
+ #: actually declares (plus ``startline``/``stopline``, always 0 here --
159
+ #: ``ncdfparticlefile eq 2`` only, lane B).
160
+ _X_DTYPES: dict[str, Any] = {
161
+ "buffertime": np.float64, "probetime": np.float64, "reftime": np.float64,
162
+ "rawtime": np.float64, "inttime": np.float64,
163
+ "diam": np.float32, "xsize": np.float32, "ysize": np.float32,
164
+ "xextent": np.float32, "areasize": np.float32, "oned": np.float32,
165
+ "twod": np.float32, "arearatio": np.float32, "arearatiofilled": np.float32,
166
+ "aspectratio": np.float32, "area": np.float32, "areafilled": np.float32,
167
+ "perimeterarea": np.float32, "area75": np.float32, "xpos": np.float32,
168
+ "ypos": np.float32, "probetas": np.float32, "aircrafttas": np.float32,
169
+ "zd": np.float32, "sizecorrection": np.float32, "missed": np.float32,
170
+ "orientation": np.float32,
171
+ "allin": np.uint8, "centerin": np.uint8, "edgetouch": np.uint8,
172
+ "dofflag": np.uint8, "numregions": np.uint8,
173
+ "particlecounter": np.int32,
174
+ "diodegaps": np.int16,
175
+ "startline": np.uint64, "stopline": np.uint64,
176
+ "overloadflag": np.uint8,
177
+ }
178
+
179
+ #: `x` keys, driver declaration order (`:510-544``, plus `startline`/`stopline`).
180
+ _X_KEYS = tuple(_X_DTYPES.keys())
181
+
182
+ #: The two composed per-buffer calls as *this module* bound them at import.
183
+ #:
184
+ #: They are a substitution surface, not just an import. The 2016 UND emulation
185
+ #: (the ``rollover-65536`` part) recompiles
186
+ #: ``processbuffer_spec.py`` whole and **rebinds ``process_2d.soda2_processbuffer``**
187
+ #: on this module, because its target is inline in ``process_spec_buffer`` and
188
+ #: has no separately-named call to patch; ``soda2_particlesort`` is rebound the
189
+ #: same way. The serial loop below therefore calls these names as module
190
+ #: globals, exactly as before the front/tail split, so a rebind still takes
191
+ #: effect.
192
+ #:
193
+ #: Recorded here so :func:`process_2d_parallel.refuse_unsplittable` can *refuse*
194
+ #: ``jobs > 1`` when one has been replaced: the split loop calls the two halves
195
+ #: directly and cannot honour a replaced composition. (``soda2_particlesort`` is
196
+ #: not in this dict -- the split path reaches it through this module's own
197
+ #: ``_flush``, so a rebind of it is honoured.)
198
+ _PRISTINE_CALLS: dict[str, Any] = {
199
+ "soda2_processbuffer": soda2_processbuffer,
200
+ "soda2_processbuffer_cip": soda2_processbuffer_cip,
201
+ }
202
+
203
+
204
+ @dataclass
205
+ class SeaHouse:
206
+ """``house={op:op}`` (``soda2_process_2d.pro:394``) -- the SEA/CIP
207
+ branch's housekeeping placeholder when ``n_elements(op.seatag) lt 2``
208
+ (`:397-398` then skips ``process_cip1d_sea``). CIP-1: a
209
+ ``seatag`` of two or more elements fires ``process_cip1d_sea`` instead,
210
+ which gives ``data.house`` a different struct entirely (its own tag set, no
211
+ ``time``/``tas``/``nb``): `soda2_process_2d` then stores
212
+ :func:`process_hk.process_cip1d_sea`'s result, not this placeholder."""
213
+
214
+ op: dict
215
+
216
+
217
+ class Soda2ProcessError(RuntimeError):
218
+ """An IDL ``stop`` this module reproduces as a raise, naming the line."""
219
+
220
+
221
+ @dataclass
222
+ class ProcessData:
223
+ """``data`` (`:678-687``), declaration order. ``date_processed`` is
224
+ non-deterministic (like UIOOPS's ``'Creation Time'``) -- exclude it from
225
+ every comparison.
226
+
227
+ Source: ``soda2_process_2d.pro:678-687`` (SODA-2)."""
228
+
229
+ op: dict
230
+ time: np.ndarray
231
+ tas: np.ndarray
232
+ probetas: np.ndarray
233
+ midbins: np.ndarray
234
+ activetime: np.ndarray
235
+ date_processed: str
236
+ sa: np.ndarray
237
+ intspec_all: np.ndarray
238
+ intspec_accepted: np.ndarray
239
+ intendbins: np.ndarray
240
+ intmidbins: np.ndarray
241
+ count_rejected: np.ndarray
242
+ total_count_rejected: np.ndarray
243
+ count_accepted: np.ndarray
244
+ count_missed: np.ndarray
245
+ missed_hist: np.ndarray
246
+ conc1d: np.ndarray
247
+ spec1d: np.ndarray
248
+ spec2d: np.ndarray
249
+ spec2d_aspr: np.ndarray
250
+ corr_fac: np.ndarray
251
+ poisson_fac: np.ndarray
252
+ intcutoff: np.ndarray
253
+ zdspec: np.ndarray
254
+ zdendbins: np.ndarray
255
+ zdmidbins: np.ndarray
256
+ pointer: np.ndarray
257
+ ind: np.ndarray
258
+ currentfile: np.ndarray
259
+ numbuffsaccepted: np.ndarray
260
+ numbuffsrejected: np.ndarray
261
+ dhist: np.ndarray
262
+ hist3d: np.ndarray
263
+ spec2d_orientation: np.ndarray
264
+ orientation_index: np.ndarray
265
+ #: ``dict`` when two or more SEA tags give process_cip1d_sea's record (`:397-398`).
266
+ house: HouseData | SeaHouse | dict
267
+ pbpstartindex: np.ndarray
268
+ pbp_csv_path: str | None = None
269
+ """Path of the ``.pbp.csv`` this call wrote (``particlefile=1``); ``None`` when none was
270
+ opened. Port tooling only (for the ``.pbp.call`` sidecar): not a ``data`` field
271
+ of `soda2_process_2d.pro`, and it changes no number."""
272
+ pbp_ncdf_path: str | None = None
273
+ """Same, for the ``.pbp.nc`` (``ncdfparticlefile>=1``)."""
274
+ save_path: str | None = None
275
+ """Same, for the IDL SAVE ``.dat`` (``savfile=1``)."""
276
+
277
+
278
+ def _spec_op(op: dict) -> SpecOp:
279
+ """``op`` dict -> :class:`processbuffer_spec.SpecOp`. Every field is read
280
+ by name; a field ``update_op`` did not supply is a ``KeyError``."""
281
+ return SpecOp(
282
+ probetype=str(op["probetype"]),
283
+ subformat=int(op["subformat"]),
284
+ probeid=str(op["probeid"]),
285
+ dofreject=int(op["dofreject"]),
286
+ stretchcorrect=int(op["stretchcorrect"]),
287
+ yres=float(op["yres"]),
288
+ res=float(op["res"]),
289
+ )
290
+
291
+
292
+ def _tail_op(op: dict, *, jit: bool = False) -> TailOp:
293
+ """``op`` dict -> :class:`processbuffer_tail.TailOp`.
294
+
295
+ ``jit`` is the ONE field that does not come from the ``op`` dict, and
296
+ deliberately: it is a resource knob, not an IDL ``op`` tag, so it arrives as
297
+ :func:`soda2_process_2d`'s keyword argument and never enters the struct the
298
+ ``.pbp.call`` sidecar records -- the same treatment ``jobs`` and ``chunks``
299
+ get, and for the same reason (it moves no written byte).
300
+ """
301
+ dr = op["dioderange"]
302
+ return TailOp(
303
+ stuckbits=int(op["stuckbits"]),
304
+ rakefix=int(op["rakefix"]),
305
+ greythresh=int(op["greythresh"]),
306
+ dioderange=(int(dr[0]), int(dr[1])),
307
+ numdiodes=int(op["numdiodes"]),
308
+ keeplargest=int(op["keeplargest"]),
309
+ res=float(op["res"]),
310
+ yres=float(op["yres"]),
311
+ jit=bool(jit),
312
+ )
313
+
314
+
315
+ def _as_float(value: Any) -> np.ndarray:
316
+ """An ``op`` bin ladder or threshold as the IDL FLOAT it stands for, held
317
+ in double so every comparison against it runs in double as IDL's does.
318
+
319
+ The driver reads the op's floats as FLOAT everywhere else -- the
320
+ concentration block's ``endbins`` (`:628-629`), ``res``/``yres`` in the
321
+ buffer processing -- and SODA-2's own ladders are FLOAT literals
322
+ (``soda2.pro:383``, ``example_batch.pro:28``). Held as the decimal double
323
+ instead, an edge such as ``0.2`` sits below FLOAT ``0.2`` and moves a
324
+ particle whose aspect ratio is exactly FLOAT ``0.2`` (a one-pixel line five
325
+ pixels long) up one bin at `:163`."""
326
+ return np.asarray(value, dtype=np.float32).astype(np.float64)
327
+
328
+
329
+ def _corr_fac_at_least_one(corr_fac: np.ndarray) -> np.ndarray:
330
+ """`:663-665` ``(d.corr_fac[i] > 1.0)``, one record at a time: IDL's MAX
331
+ operator on a scalar keeps the left operand only when ``gt`` is true, so a
332
+ NaN factor becomes 1.0 (GDL: ``!values.f_nan > 0.01`` is 0.0100000),
333
+ where ``np.maximum`` would carry the NaN into every spectrum of that
334
+ record. A NaN factor comes from a Poisson fit that returns ``a[1] = 0``
335
+ (``fit_poisson`` with no usable interarrival, `soda2_particlesort.pro:97-98`)."""
336
+ return np.where(corr_fac > np.float32(1.0), corr_fac, np.float32(1.0)).astype(np.float32)
337
+
338
+
339
+ def _psopts(op: dict, starttime: float, rate: float) -> ParticlesortOptions:
340
+ """``op`` dict -> :class:`particlesort.ParticlesortOptions`."""
341
+ return ParticlesortOptions(
342
+ starttime=starttime,
343
+ rate=rate,
344
+ clusterthresh=float(_as_float(op["clusterthresh"])),
345
+ inttime_reject=int(op["inttime_reject"]),
346
+ smethod=str(op["smethod"]),
347
+ apply_psc=int(op["apply_psc"]),
348
+ apply_psc_sizelimit=float(_as_float(op["apply_psc_sizelimit"])),
349
+ water=int(op["water"]),
350
+ endbins=_as_float(op["endbins"]),
351
+ arendbins=_as_float(op["arendbins"]),
352
+ eawmethod=str(op["eawmethod"]),
353
+ res=float(op["res"]),
354
+ dofreject=int(op["dofreject"]),
355
+ format=str(op["format"]),
356
+ probetype=str(op["probetype"]),
357
+ )
358
+
359
+
360
+ def _idl_round(x: np.ndarray) -> np.ndarray:
361
+ """IDL ``ROUND()``: round-half-away-from-zero (``np.round`` is
362
+ round-half-to-even and disagrees on exact ``.5`` values)."""
363
+ # IDL round() never lets |x| + 0.5 carry: GDL gives round(0.49999999999999994d)
364
+ # = 0 and round(1.4999999999999998d) = 1, where floor(|x| + 0.5) gives 1 and 2.
365
+ # x - trunc(x) is exact in double. Applied pass 6 (pass 5 item 4).
366
+ t = np.trunc(x)
367
+ return t + np.where(np.abs(x - t) >= 0.5, np.sign(x), 0.0)
368
+
369
+
370
+ def _pth_from_sav(pth: str, starttime: float, stoptime: float, rate: float,
371
+ numrecords: int) -> np.ndarray:
372
+ """``:128-145`` -- ``op.pth`` suffix ``dat``/``sav``: ``restore, op.pth``
373
+ binds the file's top-level ``data`` structure (``data.time``,
374
+ ``data.tas``). ``d.time`` (the comparison target at ``:133``) is the
375
+ accumulator's own time grid, ``op.starttime + op.rate*dindgen(numrecords)``
376
+ (``:62``, DOUBLE) -- not anything read from the file."""
377
+ from scipy.io import readsav
378
+
379
+ restored = readsav(pth)
380
+ pth_data = restored["data"]
381
+ # scipy.io.readsav already returns native-byte-order arrays; the
382
+ # explicit swap matches the reference-extraction convention and is a no-op if readsav's own
383
+ # conversion already ran.
384
+ data_time = np.asarray(pth_data["time"][0])
385
+ data_time = data_time.astype(data_time.dtype.newbyteorder("=")).astype(np.float64)
386
+ data_tas = np.asarray(pth_data["tas"][0])
387
+ data_tas = data_tas.astype(data_tas.dtype.newbyteorder("="))
388
+
389
+ time_grid = starttime + rate * np.arange(numrecords, dtype=np.float64) # `d.time`, `:62`
390
+ # `:133` `total(d.time - data.time) ne 0`: IDL subtracts over the SHORTER
391
+ # operand and `total` sums left to right, so a file whose first records
392
+ # match the grid takes the whole-file branch below whatever its length.
393
+ n_common = min(time_grid.size, data_time.size)
394
+ diff_total = 0.0
395
+ for k in range(n_common):
396
+ diff_total += float(time_grid[k] - data_time[k])
397
+ if diff_total != 0.0:
398
+ # `:134-139` -- nearest-point fill.
399
+ good = np.nonzero(
400
+ (data_tas > 0) & (data_tas < 400)
401
+ & (data_time >= starttime) & (data_time <= stoptime)
402
+ )[0]
403
+ if good.size == 0:
404
+ raise Soda2ProcessError(
405
+ "soda2_process_2d.pro:136: stop -- Time mismatch for TAS "
406
+ "file.")
407
+ itas = np.trunc(
408
+ (_idl_round(data_time[good]) - starttime) / rate
409
+ ).astype(np.int64) # IDL truncates a floating subscript
410
+ # `:127` allocates `pth_tas` as a FLOAT array: FLOAT whatever `data.tas` is.
411
+ pth_tas = np.zeros(numrecords, dtype=np.float32)
412
+ for i in range(good.size):
413
+ start_idx = int(itas[i])
414
+ # `:139` `pth_tas[itas[i]:*]`: a start past the end halts, and a
415
+ # negative one counts from the end (GDL: `p[-4.5d:*]` on ten
416
+ # elements sets the last four), which a record rounded to before
417
+ # a fractional `starttime` reaches when `rate` < 0.5.
418
+ if not -numrecords <= start_idx < numrecords:
419
+ raise Soda2ProcessError(
420
+ "soda2_process_2d.pro:139: subscript out of range "
421
+ f"[{start_idx}:*] for pth_tas of {numrecords} records")
422
+ pth_tas[start_idx:] = data_tas[good[i]]
423
+ return pth_tas
424
+ # `:141` -- whole-variable reassignment: `pth_tas` takes on `data.tas`'s
425
+ # own dtype (FLOAT32 on the measured UND `SODA2_TAS.dat`) and its own
426
+ # length. A shorter file halts the buffer loop at `:468` when a buffer's
427
+ # record lies past its end; a longer one leaves `data.tas` whole, invalid
428
+ # airspeeds included.
429
+ return data_tas
430
+
431
+
432
+ def _new_x() -> dict[str, list]:
433
+ return {key: [] for key in _X_KEYS}
434
+
435
+
436
+ def _append_particle(x: dict[str, list], p: Any, buffer_time: float,
437
+ aircrafttas_i: float, idx: int) -> None:
438
+ """`:510-544` -- one row of ``x`` from ``p`` (a
439
+ :class:`processbuffer_tail.ProcessedBuffer`), index ``idx`` into its
440
+ per-particle arrays."""
441
+ x["buffertime"].append(buffer_time)
442
+ x["probetime"].append(p.probetime[idx])
443
+ x["reftime"].append(p.reftime)
444
+ x["rawtime"].append(p.rawtime[idx])
445
+ x["inttime"].append(p.inttime[idx])
446
+ x["diam"].append(p.diam[idx])
447
+ x["xsize"].append(p.xsize[idx])
448
+ x["ysize"].append(p.ysize[idx])
449
+ x["xextent"].append(p.xextent[idx])
450
+ x["oned"].append(p.oned[idx])
451
+ x["twod"].append(p.twod[idx])
452
+ x["areasize"].append(p.areasize[idx])
453
+ x["arearatio"].append(p.ar[idx])
454
+ x["arearatiofilled"].append(p.arfilled[idx])
455
+ x["aspectratio"].append(p.aspr[idx])
456
+ x["area"].append(p.area_orig[idx])
457
+ x["areafilled"].append(p.area_filled[idx])
458
+ x["perimeterarea"].append(p.perimeterarea[idx])
459
+ x["area75"].append(p.area75[idx])
460
+ x["allin"].append(p.allin[idx])
461
+ x["centerin"].append(p.centerin[idx])
462
+ x["edgetouch"].append(p.edgetouch[idx])
463
+ x["probetas"].append(p.clocktas[idx])
464
+ x["aircrafttas"].append(aircrafttas_i)
465
+ x["zd"].append(p.zd[idx])
466
+ x["sizecorrection"].append(p.sizecorrection[idx])
467
+ x["xpos"].append(p.xpos[idx])
468
+ x["ypos"].append(p.ypos[idx])
469
+ x["numregions"].append(p.numregions[idx])
470
+ x["diodegaps"].append(p.diodegaps[idx])
471
+ # `:540` assigns `p.missed` to the buffer's slice of `x.missed` -- IDL broadcasts a scalar
472
+ # (SPEC's per-buffer count) or assigns element-wise (CIP's per-particle
473
+ # array, `processbuffer_cip.CipBufferParticles.missed`). CIP-1 §2.2.
474
+ x["missed"].append(p.missed[idx] if np.ndim(p.missed) > 0 else p.missed)
475
+ x["particlecounter"].append(p.particlecounter[idx])
476
+ x["overloadflag"].append(p.overloadflag[idx])
477
+ x["dofflag"].append(p.dofflag[idx])
478
+ x["orientation"].append(p.orientation[idx])
479
+ # `:546-553` (`ncdfparticlefile eq 2` only) -- 0 here; the serial loop
480
+ # overwrites both with the offset image indices when images are on.
481
+ x["startline"].append(0)
482
+ x["stopline"].append(0)
483
+
484
+
485
+ def _x_to_arrays(x: Mapping[str, Any]) -> dict[str, np.ndarray]:
486
+ """``x``'s columns as the ``basestruct`` dtypes (`:113-117`).
487
+
488
+ Takes a mapping of *sequences*, not specifically lists, so the parallel
489
+ path can hand it already-typed columns: ``np.asarray`` on a same-dtype
490
+ array is a no-op and on a list of Python floats is the element-by-element
491
+ conversion the serial path performs -- the same values either way."""
492
+ return {key: np.asarray(x[key], dtype=_X_DTYPES[key]) for key in _X_KEYS}
493
+
494
+
495
+ def _flush(psopts: ParticlesortOptions, x: Mapping[str, Any],
496
+ d: Accumulator, istop: int, *,
497
+ csv_f: Any = None, ncdf_ds: Any = None,
498
+ ncdf_offset: int = 0, image: np.ndarray | None = None,
499
+ slices_written: int = 0,
500
+ inewbuffer: np.ndarray | None = None) -> int:
501
+ """`:565-576`/`:578-581` -- slice ``x[0:istop]``, convert to the
502
+ ``basestruct`` dtypes, and call :func:`particlesort.soda2_particlesort`.
503
+
504
+ Round 9: the IDL passes ``lun_pbp, ncdf_offset, ncdf_id, pbpprops``
505
+ straight into ``soda2_particlesort`` (`:567``, `:579``) and it writes the
506
+ buffer inline; this port keeps ``soda2_particlesort``'s
507
+ signature unchanged and writes here instead, using
508
+ :func:`particlesort.spec_sort_locals` for the same
509
+ ``truetime``/``interarrival`` locals ``soda2_particlesort`` computed
510
+ internally (`:22``, `:28``) and the ``rejectionflag`` it returns.
511
+ Returns the number of particles flushed (``istop + 1``, or 0 when
512
+ ``istop < 0``) so the caller can advance ``ncdf_offset`` the way `:569`
513
+ does.
514
+ """
515
+ if istop < 0:
516
+ return 0
517
+ sliced = {key: x[key][: istop + 1] for key in _X_KEYS}
518
+ arrays = _x_to_arrays(sliced)
519
+ rejectionflag = soda2_particlesort(psopts, arrays, d, inewbuffer=inewbuffer)
520
+ if csv_f is not None or ncdf_ds is not None:
521
+ truetime, interarrival = spec_sort_locals(arrays, format=psopts.format)
522
+ if csv_f is not None:
523
+ write_pbp_csv_buffer(csv_f, arrays, istop, truetime, rejectionflag)
524
+ if ncdf_ds is not None:
525
+ write_pbp_ncdf_buffer(ncdf_ds, arrays, istop, truetime,
526
+ interarrival, rejectionflag, ncdf_offset)
527
+ if image is not None:
528
+ # `soda2_particlesort.pro:264-276`, after the PBP variables.
529
+ write_pbp_ncdf_images(ncdf_ds, arrays, istop, image,
530
+ ncdf_offset, slices_written)
531
+ return istop + 1
532
+
533
+
534
+ def _image_chunk(chunks: Sequence[np.ndarray]) -> np.ndarray:
535
+ """`:567`/`:580` ``image[*, 0:image_offset_local-1]``, slice-first."""
536
+ if not chunks:
537
+ return np.zeros((0, 0), dtype=np.uint8)
538
+ return np.concatenate(chunks, axis=0)
539
+
540
+
541
+ @dataclass
542
+ class _LoopContext:
543
+ """Everything the per-buffer work reads that does not change between
544
+ buffers -- the driver's loop invariants, gathered so that
545
+ :func:`_front_half` and :func:`_tail_half` can be called identically from
546
+ the serial loop below, from the parallel plan's carry-in sweep and from
547
+ each parallel worker (:mod:`process_2d_parallel`).
548
+
549
+ Every field is picklable: a worker rebuilds its context from this and
550
+ nothing else, so a field added here is a field the parallel path sees.
551
+ Computes nothing."""
552
+
553
+ op: dict
554
+ op_format: str
555
+ spec_op: SpecOp | None
556
+ cip_op: CipOp | None
557
+ tail_op: TailOp
558
+ starttime: float
559
+ rate: float
560
+ numrecords: int
561
+ numdiodes: int
562
+ pth_tas: np.ndarray
563
+ bufftime: np.ndarray
564
+ buffpoint: np.ndarray
565
+ bufffile: np.ndarray
566
+ fn_list: list[str]
567
+ y: Any
568
+ house: HouseData | SeaHouse | dict
569
+
570
+
571
+ def _front_half(ctx: _LoopContext, i: int, f: Any,
572
+ misc: SpecMisc | CipMisc) -> tuple[Any, float, int, float]:
573
+ """`:449-470` -- the buffer read and the **state-carrying** half of
574
+ ``soda2_processbuffer``, for buffer ``i`` of an already-open ``f``.
575
+
576
+ Returns ``(front, b_time, timeindex, aircrafttas_i)``. ``misc`` is mutated
577
+ in place exactly where the IDL writes ``(*pmisc)``; nothing else is
578
+ touched -- no ``dhist``, no ``x``, no accumulator. That is what makes the
579
+ loop splittable: this half carries the whole cross-buffer chain
580
+ (``lastclock``/``lastbufftime``/``maxsfm`` for SPEC,
581
+ ``lastclock``/``lastparticlecount`` for CIP). It costs **2.7 %** of the
582
+ loop on CIP, measured on the UND 2016-09-06 CIP (60 buffers: read 3.63 ms,
583
+ front 10.70 ms, tail 518.29 ms per buffer;
584
+ measured 2026-09-17), and about
585
+ 15 % of the split loop on a 1 GB 2D-S file (derived from the sweep, pool and
586
+ replay times in the 2D-S SODA-2 replay launch log).
587
+
588
+ **Used by the parallel path only** -- by the carry-in sweep and by every
589
+ worker, so those two cannot drift apart. The serial loop below does NOT
590
+ call it: it calls the composed ``soda2_processbuffer`` /
591
+ ``soda2_processbuffer_cip`` as module globals, because those are a
592
+ substitution surface (see ``_PRISTINE_CALLS``) that a split into halves
593
+ cannot honour. So this function is a *second written form* of `:449-470`,
594
+ and the thing that keeps it honest is
595
+ ``tests/test_soda2_parallel.py``'s byte comparison of the two paths on
596
+ both routes -- not the type checker and not this docstring. An earlier
597
+ version of this refactor had the serial loop call these halves; it was
598
+ reverted when the suite showed it silently bypassed every SODA-2
599
+ correction and the 2016 UND emulation.
600
+ """
601
+ point_lun(f, int(ctx.buffpoint[i]))
602
+ b = read2dbuffer(f, ctx.op)
603
+ b.time = float(ctx.bufftime[i]) # `:451`
604
+ # `:454` -- IDL long() truncation, then clamp into [0, numrecords-1].
605
+ timeindex = int(np.clip(np.trunc((b.time - ctx.starttime) / ctx.rate),
606
+ 0, ctx.numrecords - 1))
607
+
608
+ # `:462` `probetas=interpol(house.tas, house.time, b.time)`: SPEC only
609
+ # (the format test at `:457`) -- `GenericIndex`
610
+ # (the SEA/CIP index) has none of the fields this block reads
611
+ # (`buildindex.py:23-34`), so it is skipped for SEA, not adapted.
612
+ if ctx.op_format == "SPEC":
613
+ y, house = ctx.y, ctx.house
614
+ assert not isinstance(y, GenericIndex)
615
+ assert isinstance(house, HouseData)
616
+ assert isinstance(misc, SpecMisc)
617
+ misc.nimages = int(y.numimages[i])
618
+ if misc.nimages > 0:
619
+ # `:460` `i*y.buffsize + y.imagep[...]` is IDL `LONG * ULONG64 +
620
+ # INT[]` -> ULONG64, stored into the LON64 field at `:40`. NumPy
621
+ # 2's weak-scalar rule would otherwise keep the array's int16
622
+ # dtype and either wrap (i <= 7) or raise OverflowError (i >= 8)
623
+ # on a real buffer count -- W2b.
624
+ firstp_i = int(y.firstp[i])
625
+ misc.imagepointers = cast(Sequence[int], (
626
+ np.int64(i) * np.int64(y.buffsize)
627
+ + y.imagep[firstp_i: firstp_i + misc.nimages].astype(np.int64)
628
+ ))
629
+ misc.hkpointers = cast(Sequence[int], y.hkp[
630
+ y.ihk[firstp_i: firstp_i + misc.nimages]
631
+ ])
632
+ misc.probetas = _interpol(house.tas, house.time, b.time)
633
+
634
+ # `:468` -- unconditional, every format.
635
+ aircrafttas_i = float(ctx.pth_tas[timeindex])
636
+
637
+ front: Any
638
+ # Through the module, never a bound name: `process_spec_buffer` is a
639
+ # registered hook point (`enhancement_hooks.HOOK_POINTS`), substituted by
640
+ # setting the attribute on `processbuffer_spec`, and a bound name would not
641
+ # see it -- which is how the composed `soda2_processbuffer` reads it too.
642
+ if ctx.op_format == "SPEC":
643
+ assert ctx.spec_op is not None and isinstance(misc, SpecMisc)
644
+ misc.aircrafttas = aircrafttas_i
645
+ front = _pb_spec.process_spec_buffer(f, b.time, ctx.spec_op, misc)
646
+ else:
647
+ assert ctx.cip_op is not None and isinstance(misc, CipMisc)
648
+ assert isinstance(b, (SeaBuffer2D, DmtBuffer2D))
649
+ # `buffer_tas` is `b.tas` (`soda2_processbuffer.pro:195`, which
650
+ # fills `clocktas` from the buffer's own TAS), not `pmisc.aircrafttas`
651
+ # -- measured by grep (CIP-1 §2.2). DMT has no `stoptime` (`:106`).
652
+ front = _pb_cip.process_cip_buffer(b.image, b.time, getattr(b, "stoptime", 0.0),
653
+ float(b.tas),
654
+ ctx.cip_op, misc)
655
+ # `:474-486`'s `activetime_sea` update (using the `stoptime` the CIP
656
+ # branch leaves in the caller's buffer) is not ported: `:648` reads it
657
+ # only for `probetype ne 'CIP'`, so CIP's own activetime is the
658
+ # deadtime formula applied after the loop (`:677-683`).
659
+ return front, b.time, timeindex, aircrafttas_i
660
+
661
+
662
+ def _tail_half(ctx: _LoopContext, front: Any, lastdhist: np.ndarray) -> Any:
663
+ """`:612-747` -- the shared image-processing tail, **97.3 %** of the loop
664
+ and a pure function of its own buffer once ``lastdhist`` is dead
665
+ (``processbuffer_tail.py:195-196`` reads it only under
666
+ ``op.stuckbits``). A ``NullBuffer`` from the front half is returned
667
+ without calling the tail, matching IDL's early ``nullbuffer`` returns
668
+ (``soda2_processbuffer.pro:267``/``:339``/``:135``/``:140``/``:160``)."""
669
+ if isinstance(front, NullBuffer):
670
+ return front
671
+ return _pb_tail.process_buffer_tail(front, ctx.tail_op, lastdhist)
672
+
673
+
674
+ #: One liveness line per this many buffers when ``report_every`` is passed.
675
+ #: Silent by default, so a library caller's output is unchanged.
676
+ REPORT_EVERY_BUFFERS = 20_000
677
+
678
+ #: Its own logger, never given a persistent handler and ``propagate`` left on so
679
+ #: ``arrayprobe.cli``'s handler carries it into the run's log. Mirrors
680
+ #: ``readers/spec.py``'s ``_report_part_progress``, which solved this for the
681
+ #: decode in pair J.
682
+ _progress_logger = logging.getLogger(f"{__name__}.progress")
683
+
684
+
685
+ def _report_progress(i: int, first: int, last: int, started: float) -> None:
686
+ """One line saying where a long run has got to.
687
+
688
+ WHY THIS EXISTS (2026-09-17). ``soda2 run`` printed **nothing** for its
689
+ entire duration. On ACE-ENA RF18 -- dense cloud, and the per-particle output
690
+ is 287 MB against 07-07's 12.8 MB -- the SPEC pass ran **11.5 hours** in
691
+ complete silence. A healthy long run and a wedged one were indistinguishable
692
+ from outside, and the coordinator killed it as pathological when it was
693
+ neither: it had finished its per-particle stage and was in accumulation.
694
+ Roughly 24 CPU-hours were discarded on a misreading that a single printed
695
+ line per 20,000 buffers would have prevented.
696
+
697
+ This changes no computed number: it reads the loop counter and writes to a
698
+ log, nothing more.
699
+ """
700
+ done = i - first + 1
701
+ total = last - first + 1
702
+ elapsed = time.monotonic() - started
703
+ rate = done / elapsed if elapsed > 0 else 0.0
704
+ eta = (total - done) / rate if rate > 0 else float("nan")
705
+ _progress_logger.info(
706
+ " ...buffer %d of %d (%.1f%%), %.0f buff/s, %.1f min elapsed, ETA %.1f min",
707
+ done, total, 100.0 * done / total, rate, elapsed / 60.0, eta / 60.0)
708
+
709
+
710
+ def _reprocess_from_pbp(fn_pbp: str, op_format: str, psopts: ParticlesortOptions,
711
+ d: Accumulator, num2process: int) -> None:
712
+ """`:584-617` -- the reprocess branch: particles come from ``fn_pbp`` in
713
+ blocks of ``num2process`` and go straight to ``soda2_particlesort``.
714
+
715
+ SPEC: `:593-597` recomputes the particle time with ``spec_newtime`` over
716
+ the whole file and `:606` hands each block its slice as
717
+ ``reprocessed_time``. `:599` loops ``i = 0 .. n/num2process`` inclusive,
718
+ so when ``n`` is a multiple of ``num2process`` the last pass reads at
719
+ offset ``n`` and halts (:class:`reprocess_pbp.PbpRestoreError`)."""
720
+ from .reprocess_pbp import pbp_particle_count, restore_pbp, spec_newtime
721
+
722
+ n = pbp_particle_count(fn_pbp)
723
+ newtime: np.ndarray | None = None
724
+ if op_format == "SPEC":
725
+ whole = restore_pbp(fn_pbp)
726
+ newtime = spec_newtime(whole.columns["rawtime"], whole.columns["buffertime"],
727
+ whole.columns["probetas"], whole.global_attrs["yres"])
728
+ for i in range(n // num2process + 1):
729
+ block = restore_pbp(fn_pbp, offset=i * num2process, count=num2process)
730
+ cols = block.columns
731
+ nblock = cols["time"].size
732
+ reprocessed_time = None
733
+ if op_format == "SPEC":
734
+ assert newtime is not None
735
+ reprocessed_time = newtime[i * num2process: i * num2process + nblock]
736
+ arrays = {k: np.asarray(v, dtype=_X_DTYPES[k]) if k in _X_DTYPES else v
737
+ for k, v in cols.items()}
738
+ soda2_particlesort(psopts, arrays, d, reprocessed_time=reprocessed_time)
739
+
740
+
741
+ def soda2_process_2d(
742
+ op: dict,
743
+ *,
744
+ fn_pbp: str | None = None,
745
+ num2process: int = NUM2PROCESS,
746
+ report_every: int = 0,
747
+ jobs: int = 1,
748
+ chunks: int = 0,
749
+ jit: bool = False,
750
+ stamp_profile: str | None = None,
751
+ ) -> ProcessData | None:
752
+ """``soda2_process_2d, op`` -- SPEC path, and the SEA/CIP route (a
753
+ 1-element ``op.seatag``, or two or more, which adds the CIP-1D
754
+ housekeeping of ``process_cip1d_sea``), raw bytes to the in-memory ``data``.
755
+ Returns ``None`` exactly where the IDL ``return``s with no output
756
+ (`:430-433`, `:576`).
757
+
758
+ Source: ``soda2_process_2d.pro`` (SODA-2); bare line references here are into that file.
759
+
760
+ ``jobs`` (default 1, serial -- the IDL has no parallelism and this changes
761
+ no computed number) splits the buffer loop (`:449-573`) across that many
762
+ processes; ``chunks`` (default 0 = ``4 * jobs``) is how many contiguous
763
+ buffer ranges it is split into, more than ``jobs`` for balance because a
764
+ buffer's cost is its particle count. Every number the run produces comes
765
+ from the same per-buffer calls in the same buffer order and from this
766
+ function's own bookkeeping and ``_flush``; byte-identity is asserted on a
767
+ real fixture by ``tests/test_soda2_parallel.py``, not claimed here.
768
+ ``jobs > 1`` is refused, by name, where the split would not be exact --
769
+ see :func:`process_2d_parallel.run_parallel_loop`.
770
+
771
+ ``jit`` (default False) routes ``label_blobs``'s ``_label_region`` -- and
772
+ ``fillholes``' own call to it -- through :mod:`arrayprobe_soda2.jit_kernels`'
773
+ numba flood fill. Speed only: the kernel is exact by construction and
774
+ ``tests/test_soda2_label_region_jit_identity.py`` asserts it with
775
+ ``np.array_equal``, so it is not recorded in the ``op`` struct, exactly as
776
+ ``jobs``/``chunks`` are not. It reaches the per-buffer work as
777
+ :attr:`processbuffer_tail.TailOp.jit`, which rides in ``_LoopContext`` and so
778
+ reaches a ``jobs > 1`` worker as well as the serial loop
779
+ (``tests/test_soda2_jit_flag.py``).
780
+
781
+ ``stamp_profile`` (default None) is the configuration name a driver ran this under; it is
782
+ written into ``.pbp.nc`` as the ``arrayprobe_profile`` global attribute
783
+ (:func:`pbp_writer.engine_attrs`), ``"unstated"`` when None. Metadata only: it is not
784
+ recorded in ``op`` and moves no computed number."""
785
+ if jobs < 1:
786
+ raise ValueError(f"jobs must be >= 1 (got {jobs})")
787
+ op = update_op(op)
788
+
789
+ # `:30-35` -- reprocess from an existing `.pbp.nc`; no particle files are
790
+ # written on this path ("since they may overwrite while in process").
791
+ reprocess = fn_pbp is not None
792
+ if reprocess:
793
+ if not os.path.isfile(str(fn_pbp)):
794
+ raise Soda2ProcessError("soda2_process_2d.pro:32: stop -- PBP file not found.")
795
+ op = {**op, "ncdfparticlefile": 0, "particlefile": 0}
796
+
797
+ op_format = str(op.get("format"))
798
+ op_probetype = str(op.get("probetype"))
799
+ if op_format == "SPEC":
800
+ pass
801
+ elif op_format == "SEA":
802
+ # `soda2_read2dbuffer.pro:77-82` / `soda2_processbuffer.pro:205-262`:
803
+ # only the CIP route (`:69-76` / `:129-203`) is ported; CIPG, 2DC,
804
+ # 1D2D, HVPS and HAIL each need their own read/process branch.
805
+ if op_probetype != "CIP":
806
+ raise NotImplementedError(
807
+ "soda2_read2dbuffer.pro:77-82 / soda2_processbuffer.pro:205-262: "
808
+ f"SEA probetype {op_probetype!r} not ported (only CIP is)")
809
+ # `soda2_process_2d.pro:397-398`: `process_cip1d_sea` fires whenever
810
+ # `n_elements(op.seatag) ge 2` and replaces `house`; ported below
811
+ # (`process_hk.process_cip1d_sea`, GDL-matched on all 17 fields).
812
+ elif op_format == "DMT":
813
+ # `soda2_read2dbuffer.pro:91-107` (one branch for every probetype) and
814
+ # `soda2_processbuffer.pro:129-203` (CIP; PIP is 'CIP' since
815
+ # `soda2_update_op.pro:49`). CIPG (`:205-262`) is not ported.
816
+ if op_probetype != "CIP":
817
+ raise NotImplementedError(
818
+ "soda2_processbuffer.pro:205-262: DMT probetype "
819
+ f"{op_probetype!r} not ported (only CIP, incl. PIP, is)")
820
+ elif op_format == "RAF":
821
+ # `soda2_read2dbuffer.pro:19-66` / `soda2_processbuffer.pro:28-78`:
822
+ # Fast-2DC (F2DC, F2DC_v2, `:28-78`) and 2DC (`:80-127`) are ported;
823
+ # HVPS1, F2DC66 and every other RAF probetype are refused by name.
824
+ if op_probetype not in ("F2DC", "F2DC_v2", "2DC"):
825
+ raise NotImplementedError(
826
+ "soda2_processbuffer.pro:22-127: RAF probetype "
827
+ f"{op_probetype!r} not ported (only F2DC, F2DC_v2 and 2DC are)")
828
+ if jobs > 1:
829
+ # `soda2_process_2d.pro:39`: `f2d_remainder` (Fast-2DC) and
830
+ # `lastclock` (2DC, `soda2_processbuffer.pro:119-121`) carry
831
+ # across every buffer, and 2DC's `inewbuffer` (`:441`, `:506`)
832
+ # spans the whole loop; a chunk boundary would cut them.
833
+ raise NotImplementedError(
834
+ "soda2_process_2d.pro:39: RAF "
835
+ f"{'2DC' if op_probetype == '2DC' else 'Fast-2DC'} with jobs > 1 -- the "
836
+ "per-buffer carry crosses chunk boundaries; run jobs=1")
837
+ else:
838
+ raise NotImplementedError(
839
+ "soda2_process_2d.pro: only op.format in ('SPEC', 'SEA', 'DMT', 'RAF') is "
840
+ f"ported (got {op.get('format')!r})")
841
+
842
+ fn = op["fn"]
843
+ fn_list = list(fn) if isinstance(fn, (list, tuple)) else [fn]
844
+
845
+ if jobs > 1:
846
+ # Beside the driver's other configuration refusals above, and before
847
+ # anything is opened: a `jobs > 1` this module cannot split exactly
848
+ # must cost no file. (S6-f's early returns leave open PBP writers
849
+ # behind them; a refusal has no business joining them.)
850
+ from .process_2d_parallel import refuse_unsplittable
851
+ refuse_unsplittable(op, fn_list, jobs)
852
+
853
+ pth = str(op.get("pth", ""))
854
+ pth_suffix = _pth_suffix(pth) # `:129`
855
+ pth_file_exists = pth != "" and os.path.exists(pth)
856
+ if pth != "" and not pth_file_exists:
857
+ raise Soda2ProcessError(
858
+ "soda2_process_2d.pro:185-186: stop -- PTH file not found")
859
+ # A `pth` that exists with any other suffix (including `dat`/`sav`,
860
+ # handled below) falls through here unchanged -- IDL's `:128-172` has
861
+ # no branch for an unrecognised suffix and silently leaves `got_pth=0`,
862
+ # a preserved quirk (e.g. a case-mismatched `.DAT`), not raised.
863
+
864
+ # `:336` -- IDL tests `eq 1`, not `ge 1`; any other nonzero value writes
865
+ # no CSV (silently, in the vendored source -- read-only, not measured).
866
+ particlefile = int(op.get("particlefile", 0))
867
+ # `:241` -- IDL tests `ge 1`; `== 2` (particle images) is refused inside
868
+ # :func:`pbp_writer.open_pbp_ncdf` (``PbpImagesNotPorted``), not here.
869
+ ncdfparticlefile = int(op.get("ncdfparticlefile", 0))
870
+ # `:105-109` / `:546-553` (particle-image output): the image accumulator, held
871
+ # as a list of per-buffer slice-first chunks (IDL preallocates
872
+ # `bytarr(numdiodes, maxslices)` whatever the switch; the port allocates
873
+ # only what is appended). `slices_written` is IDL's `image_offset` at the
874
+ # last flush; `image_offset` the running total.
875
+ images = ncdfparticlefile == 2
876
+ image_chunks: list[np.ndarray] = []
877
+ image_offset = 0
878
+ image_offset_local = 0
879
+ slices_written = 0
880
+ if images and jobs > 1:
881
+ raise PbpImagesNotPorted(
882
+ "soda2_process_2d.pro:546-553 -- particle images on the parallel driver")
883
+
884
+ starttime = float(op["starttime"])
885
+ stoptime = float(op["stoptime"])
886
+ # `:644,:646` (S6-e): `fltarr(numrecords) + op.rate` takes IDL's type
887
+ # promotion -- FLOAT for an INT, LONG or FLOAT `rate`, DOUBLE only for a
888
+ # DOUBLE one. Measured under GDL (`run_soda2_save_writer_bank.py`
889
+ # `rate_types`, and the `help` check): `{rate:1}`, `{rate:1L}` and
890
+ # `{rate:1.0}` give FLOAT, `{rate:1.0d}` DOUBLE; `frame_full`/
891
+ # `frame_stretch` (`rate:1.0d`) measure DOUBLE. The caller's IDL type is
892
+ # only visible before `float()` below: an integer (Python `int`, any
893
+ # `np.integer`) or `np.float32` means FLOAT; `np.float64` or a plain
894
+ # Python float means DOUBLE -- the port's standing convention that a
895
+ # Python float is a C double (IDL's bare `1.0` is FLOAT: pass
896
+ # `np.float32` for it). Before that measurement an integer `rate` gave DOUBLE here,
897
+ # which is every TOML `rate = 1` and SODA-2's own example scripts.
898
+ rate_in = op["rate"]
899
+ activetime_dtype = (np.float32
900
+ if isinstance(rate_in, (int, np.integer, np.float32))
901
+ else np.float64)
902
+ rate = float(rate_in)
903
+ numrecords = int((stoptime - starttime) / rate + 1) # `:49`, IDL long() truncation
904
+
905
+ d = new_accumulator(_psopts(op, starttime, rate), numrecords)
906
+ numbuffsaccepted = np.zeros(numrecords, dtype=np.int16)
907
+ numbuffsrejected = np.zeros(numrecords, dtype=np.int16)
908
+ dhist = np.zeros((numrecords, int(op["numdiodes"])), dtype=np.int32)
909
+ lastdhist = np.zeros(int(op["numdiodes"]), dtype=np.int32)
910
+
911
+ date = soda2_parsedate(str(op["date"])) # `:100-109`
912
+
913
+ # `:126-189` -- `numrecords` is needed to size/resolve `pth_tas`, so
914
+ # this port resolves it here rather than at `:49`'s IDL position; the
915
+ # refusal/existence checks above already ran before any raw `fn` file
916
+ # read, matching the source's own ordering guarantee.
917
+ if pth_file_exists and pth_suffix in ("dat", "sav"):
918
+ # `:131-145`.
919
+ pth_tas = _pth_from_sav(pth, starttime, stoptime, rate, numrecords)
920
+ got_pth = 1
921
+ elif pth_file_exists and pth_suffix in ("txt", "csv", "nc"):
922
+ # `:147-172` -- pth_readers (wired at integration).
923
+ # `pthdat` stays unset for these formats: `:144` sets it only in the
924
+ # SAVE branch.
925
+ pth_tas, got_pth = read_pth(pth, pth_suffix, starttime, stoptime,
926
+ rate, numrecords)
927
+ elif pth_file_exists:
928
+ # `:128-172` has no branch for this suffix -- IDL silently leaves
929
+ # `got_pth=0`.
930
+ got_pth = 0
931
+ pth_tas = np.zeros(numrecords, dtype=np.float32)
932
+ else:
933
+ # `:173-177` -- `file_test(op.pth)` false; `pth==''` (`pth!=''`
934
+ # and missing already raised above).
935
+ fixedtas = float(op.get("fixedtas", 0.0))
936
+ if fixedtas > 0:
937
+ got_pth = 1
938
+ pth_tas = np.zeros(numrecords, dtype=np.float32) + np.float32(fixedtas)
939
+ else:
940
+ got_pth = 0
941
+ pth_tas = np.zeros(numrecords, dtype=np.float32)
942
+
943
+ # `:190-354` -- PBP writer setup, round 9. Opened here (relative IDL
944
+ # order: after the PTH/TAS block, before buildindex) so that S6-f's
945
+ # early returns below (`:430-433`, `:576`) can leave them open,
946
+ # unclosed, exactly as the vendored source does -- never move this
947
+ # block after the `firstbuff`/`lastbuff` check.
948
+ date_map = {"month": date.month, "day": date.day, "year": date.year}
949
+ csv_f: Any = None
950
+ ncdf_ds: Any = None
951
+ ncdf_offset = 0
952
+ fn_pbp_out: str | None = None
953
+ fn_ncdf_out: str | None = None
954
+ if particlefile == 1:
955
+ fn_pbp_out = pbp_filename(op, str(op["shortname"]), extension=".pbp.csv")
956
+ csv_f = open_pbp_csv(fn_pbp_out, op, date_map)
957
+ if ncdfparticlefile >= 1:
958
+ fn_ncdf_out = pbp_filename(op, str(op["shortname"]), extension=".pbp.nc")
959
+ ncdf_ds = open_pbp_ncdf(fn_ncdf_out, op, date_map, pthdat=None,
960
+ stamp_profile=stamp_profile)
961
+
962
+ # `:364-391` -- one index per raw file, concatenated in `op.fn` order with
963
+ # a per-buffer file index; SPEC stops on the second file (`:376`), after
964
+ # the first file's index was built. A file whose `error` is neither 0
965
+ # nor 1 is skipped, as GDL's loop does.
966
+ firstfile = True
967
+ for ifile, path in enumerate(fn_list):
968
+ y = buildindex(path, op)
969
+ if y.error == 0:
970
+ if firstfile:
971
+ bufftime = np.asarray(y.bufftime, dtype=np.float64)
972
+ buffdate = np.asarray(y.date, dtype=np.int64)
973
+ buffpoint = np.asarray(y.pointer)
974
+ bufffile = np.full(y.count, ifile, dtype=np.uint8)
975
+ else:
976
+ if op_format == "SPEC":
977
+ raise Soda2ProcessError(
978
+ "soda2_process_2d.pro:376: stop -- Multiple files not "
979
+ "supported with SPEC format, need to concatenate raw "
980
+ "files first")
981
+ bufftime = np.concatenate(
982
+ [bufftime, np.asarray(y.bufftime, dtype=np.float64)])
983
+ buffdate = np.concatenate(
984
+ [buffdate, np.asarray(y.date, dtype=np.int64)])
985
+ buffpoint = np.concatenate([buffpoint, np.asarray(y.pointer)])
986
+ bufffile = np.concatenate(
987
+ [bufffile, np.full(y.count, ifile, dtype=np.uint8)])
988
+ firstfile = False
989
+ if y.error == 1:
990
+ raise Soda2ProcessError(
991
+ "soda2_process_2d.pro:385-389: stop -- error building index, "
992
+ "verify probe ID and/or SEA tags are correct")
993
+
994
+ # `:394-398` -- housekeeping. SPEC: `spec_process_hk`. SEA/CIP with
995
+ # `n_elements(op.seatag) ge 2` (including `update_op.py`'s default
996
+ # 3-element `[33000,0,0]`): `process_cip1d_sea` replaces `house`
997
+ # (`:397-398`). Any other SEA/DMT case: IDL's own `house={op:op}`
998
+ # placeholder.
999
+ house: HouseData | SeaHouse | dict
1000
+ if op_format == "SPEC":
1001
+ assert not isinstance(y, GenericIndex) # SPEC always indexes to SpecIndex.
1002
+ house = process_hk(op, y=y)
1003
+ elif (op_format == "SEA" and op_probetype == "CIP"
1004
+ and np.atleast_1d(np.asarray(op.get("seatag"))).size >= 2):
1005
+ # `:397-398` call `process_cip1d_sea` without writing, returning `house` --
1006
+ # `house` becomes that routine's `data` struct outright.
1007
+ from .process_hk import process_cip1d_sea
1008
+ house = process_cip1d_sea(op)
1009
+ else:
1010
+ house = SeaHouse(op=op)
1011
+
1012
+ # `:408-418` -- date check (S6-b).
1013
+ startdate = int(date.julday)
1014
+ if abs(int(buffdate[0]) - startdate) > 5:
1015
+ startdate = int(buffdate[0])
1016
+ bufftime = bufftime + 86400.0 * (buffdate - startdate)
1017
+
1018
+ # `:419-423` -- sort; buffindex "for output only".
1019
+ order = np.argsort(bufftime, kind="stable")
1020
+ bufftime = bufftime[order]
1021
+ buffpoint = buffpoint[order]
1022
+ bufffile = bufffile[order]
1023
+ buffindex = np.trunc((bufftime - starttime) / rate).astype(np.int64)
1024
+
1025
+ numbuffs = bufftime.size
1026
+ pbpstartindex = np.zeros(numbuffs, dtype=np.int32)
1027
+
1028
+ # `:427-429` -- trap 1 / S6-a.
1029
+ lt_start = np.nonzero(bufftime < starttime)[0]
1030
+ firstbuff = max(int(lt_start.max()), 0) if lt_start.size else 0
1031
+ gt_stop = np.nonzero(bufftime > stoptime)[0]
1032
+ lastbuff = int(gt_stop.min()) if gt_stop.size else numbuffs - 1
1033
+
1034
+ if (lastbuff - firstbuff) <= 0:
1035
+ return None
1036
+
1037
+ currentfile = -1
1038
+ istop = -1
1039
+ f = None
1040
+ # Lists on the serial path, typed columns on the parallel one; `_flush` and
1041
+ # `_x_to_arrays` accept either and convert each element the same way.
1042
+ x: dict[str, Any] = _new_x()
1043
+ psopts = _psopts(op, starttime, rate)
1044
+
1045
+ misc = SpecMisc(
1046
+ nimages=0, hkpointers=cast(Sequence[int], np.array([0])),
1047
+ imagepointers=cast(Sequence[int], np.array([0])),
1048
+ probetas=0.0, aircrafttas=0.0, lastclock=0.0, lastbufftime=0.0,
1049
+ maxsfm=0.0,
1050
+ )
1051
+ spec_op = _spec_op(op) if op_format == "SPEC" else None
1052
+ tail_op = _tail_op(op, jit=jit)
1053
+ cip_op = CipOp(probetype=op_probetype, format=op_format,
1054
+ strictcounter=int(op["strictcounter"])) if op_format != "SPEC" else None
1055
+ cip_misc = CipMisc() if op_format != "SPEC" else None
1056
+ from .processbuffer_f2dc import F2dcMisc, F2dcOp
1057
+ f2d_op = F2dcOp(probetype=op_probetype)
1058
+ f2d_misc = F2dcMisc() # `soda2_process_2d.pro:39`, one per run
1059
+ from .processbuffer_2dc import TwoDcMisc, TwoDcOp
1060
+ twodc_op = TwoDcOp(probetype=op_probetype, format=op_format,
1061
+ yres=float(op.get("yres", op.get("res", 0.0))))
1062
+ twodc_misc = TwoDcMisc() # `(*pmisc).lastclock`, `soda2_process_2d.pro:39`
1063
+ # `:441` allocates `inewbuffer` as a LONG array: one entry per buffer,
1064
+ # set at `:506` for each accepted buffer, never reset at a flush, and
1065
+ # passed whole to every `soda2_particlesort` call (`:567`, `:579`). Only
1066
+ # the 2DC block (`soda2_particlesort.pro:65-76`) reads it.
1067
+ inewbuffer = np.zeros(max(lastbuff - firstbuff + 1, 0), dtype=np.int32)
1068
+
1069
+ ctx = _LoopContext(
1070
+ op=op, op_format=op_format, spec_op=spec_op, cip_op=cip_op, tail_op=tail_op,
1071
+ starttime=starttime, rate=rate, numrecords=numrecords,
1072
+ numdiodes=int(op["numdiodes"]), pth_tas=pth_tas, bufftime=bufftime,
1073
+ buffpoint=buffpoint, bufffile=bufffile, fn_list=[str(p) for p in fn_list],
1074
+ y=y, house=house,
1075
+ )
1076
+ loop_misc: SpecMisc | CipMisc = misc if op_format == "SPEC" else cast(CipMisc, cip_misc)
1077
+
1078
+ if jobs > 1:
1079
+ # `:449-573`, split across processes. Opt-in; refuses rather than
1080
+ # guesses (see `refuse_unsplittable`). The per-buffer work is
1081
+ # `_front_half`/`_tail_half`, a second written form of this loop's own
1082
+ # `:449-470` (see `_front_half`); the bookkeeping below is not written
1083
+ # twice -- it is replayed in buffer order from what the workers report,
1084
+ # and the particles go to this function's own `_flush`.
1085
+ from .process_2d_parallel import run_parallel_loop
1086
+ istop, ncdf_offset, x = run_parallel_loop(
1087
+ ctx, firstbuff, lastbuff, loop_misc, jobs=jobs, chunks=chunks,
1088
+ report_every=report_every, d=d, dhist=dhist,
1089
+ numbuffsaccepted=numbuffsaccepted, numbuffsrejected=numbuffsrejected,
1090
+ pbpstartindex=pbpstartindex, num2process=num2process, psopts=psopts,
1091
+ flush=_flush, csv_f=csv_f, ncdf_ds=ncdf_ds)
1092
+ if int(op.get("activetimefrommissed", 0)) == 1:
1093
+ raise Soda2ProcessError(
1094
+ "soda2_process_2d.pro:493: stop -- activetimefrommissed "
1095
+ "'Under development'")
1096
+
1097
+ #: The serial loop's iteration set -- empty when `run_parallel_loop` above
1098
+ #: already did the work, so the body below stays the one and only written
1099
+ #: form of the driver's bookkeeping.
1100
+ buffer_range = range(firstbuff, lastbuff + 1) if (jobs == 1 and not reprocess) else range(0)
1101
+ if reprocess:
1102
+ assert fn_pbp is not None
1103
+ _reprocess_from_pbp(str(fn_pbp), op_format, psopts, d, num2process)
1104
+
1105
+ _started = time.monotonic()
1106
+ try:
1107
+ for i in buffer_range:
1108
+ if report_every > 0 and (i - firstbuff) and (i - firstbuff) % report_every == 0:
1109
+ _report_progress(i, firstbuff, lastbuff, _started)
1110
+ if currentfile != int(bufffile[i]):
1111
+ if f is not None:
1112
+ f.close()
1113
+ f = open(fn_list[int(bufffile[i])], "rb")
1114
+ currentfile = int(bufffile[i])
1115
+ assert f is not None
1116
+
1117
+ point_lun(f, int(buffpoint[i]))
1118
+ b = read2dbuffer(f, op)
1119
+ b.time = float(bufftime[i]) # `:451`
1120
+ # `:454` -- IDL long() truncation, then clamp into [0, numrecords-1].
1121
+ timeindex = int(np.clip(np.trunc((b.time - starttime) / rate), 0, numrecords - 1))
1122
+
1123
+ # `:462` `probetas=interpol(house.tas, house.time, b.time)`: SPEC
1124
+ # only (the format test at `:457`) --
1125
+ # `GenericIndex` (the SEA/CIP index) has none of the fields this
1126
+ # block reads (`buildindex.py:23-34`), so it is skipped for SEA,
1127
+ # not adapted.
1128
+ if op_format == "SPEC":
1129
+ assert not isinstance(y, GenericIndex)
1130
+ assert isinstance(house, HouseData)
1131
+ misc.nimages = int(y.numimages[i])
1132
+ if misc.nimages > 0:
1133
+ # `:460` `i*y.buffsize + y.imagep[...]` is IDL `LONG * ULONG64 +
1134
+ # INT[]` -> ULONG64, stored into the LON64 field at `:40`. NumPy
1135
+ # 2's weak-scalar rule would otherwise keep the array's int16
1136
+ # dtype and either wrap (i <= 7) or raise OverflowError (i >= 8)
1137
+ # on a real buffer count -- W2b.
1138
+ firstp_i = int(y.firstp[i])
1139
+ misc.imagepointers = cast(Sequence[int], (
1140
+ np.int64(i) * np.int64(y.buffsize)
1141
+ + y.imagep[firstp_i: firstp_i + misc.nimages].astype(np.int64)
1142
+ ))
1143
+ misc.hkpointers = cast(Sequence[int], y.hkp[
1144
+ y.ihk[firstp_i: firstp_i + misc.nimages]
1145
+ ])
1146
+ misc.probetas = _interpol(house.tas, house.time, b.time)
1147
+
1148
+ # `:468` -- unconditional, every format.
1149
+ aircrafttas_i = float(pth_tas[timeindex])
1150
+ b_time = b.time
1151
+
1152
+ # The COMPOSED per-buffer call, read as a module global, unchanged
1153
+ # from before the front/tail split: the 2016 UND reference script
1154
+ # rebinds `process_2d.soda2_processbuffer` for the 2016 UND
1155
+ # emulation, and a bound name would silently drop that. The split
1156
+ # loop, which calls the two halves separately, refuses instead
1157
+ # (`process_2d_parallel.refuse_unsplittable`).
1158
+ if op_format == "SPEC":
1159
+ assert spec_op is not None
1160
+ misc.aircrafttas = aircrafttas_i
1161
+ p = soda2_processbuffer(f, b.time, spec_op, tail_op, misc, lastdhist)
1162
+ elif op_format == "RAF" and op_probetype == "2DC":
1163
+ # `soda2_process_2d.pro:470` calls `soda2_processbuffer` per buffer,
1164
+ # whose `CASE` takes the 2DC arm at `soda2_processbuffer.pro:80`
1165
+ # (`:80-127`, then the shared tail); `twodc_misc.lastclock`
1166
+ # persists across buffers as `(*pmisc)` does.
1167
+ from .processbuffer_2dc import soda2_processbuffer_2dc
1168
+ assert isinstance(b.image, np.ndarray) # a RAF buffer always carries one
1169
+ p = soda2_processbuffer_2dc(
1170
+ b.image, b.time, float(b.tas), twodc_op, tail_op, twodc_misc,
1171
+ lastdhist)
1172
+ elif op_format == "RAF":
1173
+ # `soda2_processbuffer.pro:28-78`; `f2d_misc` persists across
1174
+ # buffers as `(*pmisc)` does (`soda2_process_2d.pro:39`).
1175
+ from .processbuffer_f2dc import soda2_processbuffer_f2dc
1176
+ # A RAF buffer that reached here was read whole (a short read
1177
+ # returns the null buffer earlier), so its image is an array.
1178
+ assert isinstance(b.image, np.ndarray)
1179
+ p = soda2_processbuffer_f2dc(
1180
+ b.image, b.time, float(b.tas), f2d_op, tail_op, f2d_misc, lastdhist)
1181
+ else:
1182
+ assert cip_op is not None and cip_misc is not None
1183
+ assert isinstance(b, (SeaBuffer2D, DmtBuffer2D))
1184
+ # `buffer_tas` is `b.tas` (`soda2_processbuffer.pro:195`, which
1185
+ # fills `clocktas` from the buffer's own TAS), not
1186
+ # `pmisc.aircrafttas` -- measured by grep (CIP-1 §2.2).
1187
+ # A DMT buffer has no `stoptime` tag (`:106`); `:199-202`
1188
+ # never reads it for that format, so 0.0 is a placeholder.
1189
+ p, _stoptime = soda2_processbuffer_cip(
1190
+ b.image, b.time, getattr(b, "stoptime", 0.0), float(b.tas),
1191
+ cip_op, tail_op, cip_misc, lastdhist)
1192
+ # `:474-486`'s `activetime_sea` update (using the discarded
1193
+ # `_stoptime`) is not ported: `:648` reads it only for
1194
+ # `probetype ne 'CIP'`, so CIP's own activetime is the
1195
+ # deadtime formula already applied below (`:677-683`).
1196
+
1197
+ if int(op.get("activetimefrommissed", 0)) == 1:
1198
+ raise Soda2ProcessError(
1199
+ "soda2_process_2d.pro:493: stop -- activetimefrommissed "
1200
+ "'Under development'")
1201
+
1202
+ if not isinstance(p, NullBuffer):
1203
+ dhist[timeindex, :] = dhist[timeindex, :] + p.dhist
1204
+ lastdhist = dhist[max(timeindex - 1, 0), :]
1205
+
1206
+ if isinstance(p, NullBuffer) or p.rejectbuffer != 0:
1207
+ numbuffsrejected[timeindex] += 1
1208
+ else:
1209
+ numbuffsaccepted[timeindex] += 1
1210
+ n = p.diam.size
1211
+ istart = istop + 1
1212
+ istop = istart + n - 1
1213
+ inewbuffer[i - firstbuff] = istart # `:506`
1214
+ pbpstartindex[i] = istart + ncdf_offset # `:507` -- fix, round 9.
1215
+ for k in range(n):
1216
+ _append_particle(x, p, b_time, aircrafttas_i, k)
1217
+ if images:
1218
+ # `:546-553`. `nslices` is the bitimage's own slice count
1219
+ # (dummy first slice included), not `p.nslices`.
1220
+ bitimage = np.asarray(p.bitimage, dtype=np.uint8)
1221
+ nslices = bitimage.shape[0]
1222
+ image_chunks.append(bitimage)
1223
+ x["startline"][istart:istop + 1] = [
1224
+ int(v) + image_offset for v in np.asarray(p.startline)[:n]]
1225
+ x["stopline"][istart:istop + 1] = [
1226
+ int(v) + image_offset for v in np.asarray(p.stopline)[:n]]
1227
+ image_offset += nslices
1228
+ image_offset_local += nslices
1229
+
1230
+ if istop + 500 > num2process or image_offset_local + 10000 > MAXSLICES:
1231
+ ncdf_offset += _flush(psopts, x, d, istop, csv_f=csv_f,
1232
+ ncdf_ds=ncdf_ds, ncdf_offset=ncdf_offset,
1233
+ image=_image_chunk(image_chunks) if images else None,
1234
+ slices_written=slices_written,
1235
+ inewbuffer=inewbuffer)
1236
+ istop = -1
1237
+ x = _new_x()
1238
+ slices_written += image_offset_local
1239
+ image_offset_local = 0
1240
+ image_chunks = []
1241
+ finally:
1242
+ if f is not None:
1243
+ f.close()
1244
+
1245
+ if reprocess:
1246
+ pass
1247
+ elif istop < 0:
1248
+ # S6-f: the IDL `return` at `:576` fires before `:689-721`'s close
1249
+ # block -- `csv_f`/`ncdf_ds`, if open, are left unclosed here too,
1250
+ # reproducing the vendored bug rather than fixing it.
1251
+ return None
1252
+ else:
1253
+ _flush(psopts, x, d, istop, csv_f=csv_f, ncdf_ds=ncdf_ds, ncdf_offset=ncdf_offset,
1254
+ image=_image_chunk(image_chunks) if images else None,
1255
+ slices_written=slices_written, inewbuffer=inewbuffer)
1256
+
1257
+ # `:625-675` -- concentration.
1258
+ spec1d = d.spec2d.sum(axis=2, dtype=np.float32)
1259
+ numbins = len(op["endbins"]) - 1
1260
+ endbins = np.asarray(op["endbins"], dtype=np.float32)
1261
+ midbins = (endbins[0:numbins] + endbins[1: numbins + 1]) / np.float32(2.0)
1262
+ binwidth = endbins[1: numbins + 1] - endbins[0:numbins]
1263
+
1264
+ dioderange = op["dioderange"]
1265
+ numdiodes = int(op["numdiodes"])
1266
+ if int(dioderange[0]) != 0 or int(dioderange[1]) != 0:
1267
+ numactivediodes = int(dioderange[1]) - int(dioderange[0]) + 1
1268
+ else:
1269
+ numactivediodes = numdiodes
1270
+
1271
+ sa = sample_area(
1272
+ midbins, float(op["res"]), float(op["armwidth"]), numactivediodes,
1273
+ str(op["eawmethod"]), np.float32(op["wavelength"]), float(op["dofconst"]),
1274
+ dof=np.asarray(op["customdof"], dtype=np.float32),
1275
+ )[0]
1276
+
1277
+ if int(op.get("ignoredeadtime", 0)) == 1:
1278
+ activetime = np.full(numrecords, rate, dtype=activetime_dtype)
1279
+ else:
1280
+ activetime = np.clip(
1281
+ np.full(numrecords, rate, dtype=activetime_dtype) - d.deadtime,
1282
+ 0.0, rate,
1283
+ ).astype(activetime_dtype)
1284
+
1285
+ probetas = d.tas
1286
+ aircrafttas = pth_tas if got_pth == 1 else probetas
1287
+
1288
+ orientation_index = np.zeros((numrecords, numbins), dtype=np.float32)
1289
+ conc1d = np.zeros((numrecords, numbins), dtype=np.float32)
1290
+
1291
+ corr_fac_clamped = _corr_fac_at_least_one(d.corr_fac)
1292
+ spec1d = spec1d * corr_fac_clamped[:, None]
1293
+ d.spec2d[:, :, :] = d.spec2d * corr_fac_clamped[:, None, None]
1294
+ d.spec2d_aspr[:, :, :] = d.spec2d_aspr * corr_fac_clamped[:, None, None]
1295
+
1296
+ for i in range(numrecords):
1297
+ if float(aircrafttas[i]) * float(activetime[i]) > 0:
1298
+ conc1d[i, :] = (
1299
+ spec1d[i, :] / (sa * aircrafttas[i] * activetime[i])
1300
+ / (binwidth / np.float32(1.0e6))
1301
+ )
1302
+ for j in range(numbins):
1303
+ hist = d.spec2d_orientation[i, j, :]
1304
+ omax = float(np.nanmax(hist)) if hist.size else 0.0
1305
+ totspec = float(np.nansum(hist))
1306
+ if totspec > 50:
1307
+ orientation_index[i, j] = omax / totspec
1308
+
1309
+ # `:677` -- `string(systime(/julian), format='(C(CYI, "/", CMOI2.2,
1310
+ # "/", CDI2.2, " ", CHI2.2, ":", CMI2.2, ":", CSI2.2))')`: local time
1311
+ # (`systime(/julian)` without `/UTC`), `YYYY/MM/DD HH:MM:SS`. The value
1312
+ # is non-deterministic; its *form* is not, and it is written into the
1313
+ # SAVE file. Before the SAVE writer this was `datetime.now(UTC).isoformat()`.
1314
+ date_processed = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
1315
+
1316
+ # `:689-721` -- close the PBP writers (only reached on this path; S6-f's
1317
+ # early returns above skip this by construction, matching the IDL).
1318
+ if csv_f is not None:
1319
+ csv_f.close()
1320
+ if ncdf_ds is not None:
1321
+ close_pbp_ncdf(ncdf_ds, pthdat=None)
1322
+
1323
+ result = ProcessData(
1324
+ op=op, time=d.time, tas=aircrafttas, probetas=probetas, midbins=midbins,
1325
+ activetime=activetime, date_processed=date_processed, sa=sa,
1326
+ intspec_all=d.intspec_all, intspec_accepted=d.intspec_accepted,
1327
+ intendbins=d.intendbins, intmidbins=d.intmidbins,
1328
+ count_rejected=d.count_rejected, total_count_rejected=d.total_count_rejected,
1329
+ count_accepted=d.count_accepted, count_missed=d.count_missed,
1330
+ missed_hist=d.missed_hist, conc1d=conc1d, spec1d=spec1d, spec2d=d.spec2d,
1331
+ spec2d_aspr=d.spec2d_aspr, corr_fac=d.corr_fac, poisson_fac=d.poisson_fac,
1332
+ intcutoff=d.intcutoff, zdspec=d.zdspec, zdendbins=d.zdendbins,
1333
+ zdmidbins=d.zdmidbins, pointer=buffpoint, ind=buffindex, currentfile=bufffile,
1334
+ numbuffsaccepted=numbuffsaccepted, numbuffsrejected=numbuffsrejected,
1335
+ dhist=dhist, hist3d=d.hist3d, spec2d_orientation=d.spec2d_orientation,
1336
+ orientation_index=orientation_index, house=house, pbpstartindex=pbpstartindex,
1337
+ pbp_csv_path=fn_pbp_out, pbp_ncdf_path=fn_ncdf_out,
1338
+ )
1339
+
1340
+ # `:722-726`: the ASCII PSD/counts export. IDL tests
1341
+ # `eq 1` here (not `ge 1`, unlike `ncdfparticlefile`'s `ge 1` above);
1342
+ # reproduced verbatim -- any other nonzero value writes nothing.
1343
+ if int(op.get("asciipsdfile", 0)) == 1:
1344
+ fn_asciipsd = pbp_filename(op, str(op["shortname"]), extension=".txt")
1345
+ soda2_export_ascii(result, fn_asciipsd)
1346
+
1347
+ # `:729-731`: the output name comes from `soda2_filename`, and
1348
+ # the data are saved, compressed, only when `op.savfile` is 1.
1349
+ # `eq 1`, not `ge 1`: any other value writes nothing, as in the IDL.
1350
+ # `update_op` defaults `savfile` to 1, so a run writes the `.dat` unless
1351
+ # the caller sets `savfile=0` -- before the SAVE writer it silently never did.
1352
+ if int(op.get("savfile", 0)) == 1:
1353
+ if "outdir" not in {str(k).lower() for k in op}:
1354
+ # `soda2_filename.pro:5` reads `op.outdir`, a tag
1355
+ # `soda2_update_op` never defaults: IDL halts here.
1356
+ raise Soda2ProcessError(
1357
+ "soda2_process_2d.pro:729 / soda2_filename.pro:5: op has no "
1358
+ "OUTDIR tag -- IDL halts before writing the SAVE file (set "
1359
+ "op['outdir'], or savfile=0)")
1360
+ fn_out = pbp_filename(op, str(op["shortname"]))
1361
+ save_process_data(fn_out, result, compress=True)
1362
+ result.save_path = fn_out
1363
+
1364
+ return result