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,703 @@
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_particlesort.pro:1-171`` -- SODA-2's per-buffer accumulation step.
4
+ Sorts a batch of particle structures into the
5
+ per-second accumulation arrays (``d``): PSD spectra, interarrival spectra,
6
+ deadtime, missed-particle histograms, the accept/reject tally.
7
+
8
+ Provenance: ``SODA2/abansemer-soda2-afcea15/soda2_particlesort.pro``, lines
9
+ 1-171 only, Aaron Bansemer, NCAR, 2009. Copyright (C) 2016 UCAR, 3-clause BSD.
10
+
11
+ **Scope, exactly as agreed in the sizing-core plan (section C.1) -- everything else is
12
+ out of scope for this module, not silently dropped:**
13
+
14
+ - ``:172-300`` (the netCDF/ASCII per-particle-file writes) -- handled by the PBP/SAVE writers.
15
+ - The ``2DC`` deadtime block (``:64-76``) is ported (``_deadtime_2dc``):
16
+ the gap between buffers, zeroed for format ``RAF`` (``:69``), summed per
17
+ time index and capped at ``op.rate`` (``:74``), *assigned* (not added)
18
+ before the forward ``:125-127`` accumulation. It needs ``inewbuffer``.
19
+ - The ``TXT`` interarrival/truetime branch (``:43-46``) -- refused by name;
20
+ only ``op.format in ("SPEC", "SEA", "DMT", "RAF")`` is ported. The ``SEA`` branch
21
+ (``:30-42``) was added by CIP-1, the driver's
22
+ own SEA/CIP dispatch requiring it (``process_2d.py``'s ``_flush``). The
23
+ ``DMT`` (PADS/PACS) path was added in pass 5 item 7b: it is the
24
+ *pre-branch default* -- ``truetime`` from ``:12``, ``interarrival =
25
+ difftime`` from ``:13``/``:16`` -- plus the **forward** deadtime ``ELSE``
26
+ of ``:125-127``, which ``:59``'s ``deadtime`` feeds; asserted bit for bit
27
+ against the whole-driver GDL golden ``tests/data/gdl_soda2_dmt_golden.json``
28
+ (``tests/test_soda2_dmt_driver.py``).
29
+ - ``reprocessed_time`` -- accepted as a keyword-equivalent argument and
30
+ applied exactly where ``:28`` applies it (one assignment).
31
+
32
+ Imports nothing from ``arrayprobe`` or ``arrayprobe_uiops`` (``arrayprobe_soda2``
33
+ is a separate port with its own oracle discipline).
34
+
35
+ **GDL bank**: ``scripts/validation/gdl/
36
+ run_soda2_particlesort_bank.py`` (14 cases, all OK), golden at
37
+ ``tests/data/gdl_soda2_particlesort_golden.json``. Two traps below were
38
+ measured WRONG against round 5's reading of the IDL and are now fixed and
39
+ cited to the golden case that forced each (the first hypothesis -> trap 10 / S5-q; the
40
+ second -> trap 3 / S5-p). Everything else in this list was read correctly the first time and
41
+ the bank confirms it.
42
+
43
+
44
+ **Traps preserved, each cited to the plan trap that named it:**
45
+
46
+ 1. ``:22`` ``x.inttime > 0`` is MAX, not comparison -- a negative ``inttime``
47
+ clamps to 0.
48
+ 2. ``:12`` uses IDL ``MEDIAN`` without ``/EVEN``: for an even-length array
49
+ this is the **upper**-middle sorted element, not an average of the two
50
+ middle elements. Exposed as :func:`idl_median`; unused for the SPEC path
51
+ after ``:28`` overrides ``truetime``, computed anyway for fidelity.
52
+ 3. ``:50-56`` the cluster loop is sequential and self-referential
53
+ (``cluster[i-1]`` is read after the previous iteration wrote it); a
54
+ Python loop, not a vectorised one, and the running cluster count
55
+ **wraps modulo 256 at the 256th chained particle** -- measured by the
56
+ R6C GDL bank's ``cluster_300`` case (H2, finding **S5-p**), not the
57
+ round-5 port's saturate-at-255. ``clustercount`` is ``BYTE + INT``
58
+ (promotes to INT), then storing that INT into the BYTE ``cluster`` array
59
+ truncates; the wrap zeroes the whole ``cluster[i-cluster[i-1]:i]`` range,
60
+ so a 256-particle chain is entirely un-clustered and the chain restarts
61
+ at 2 on the next particle. Round 5's docstring said "saturates at 255" --
62
+ that was the port's own behaviour read back as if it were the IDL's,
63
+ never measured; the bank refutes it.
64
+ 4. ``:60`` ``long((truetime-starttime)/rate)`` truncates toward zero, so a
65
+ particle before ``starttime`` gets ``timeindex = 0``, never negative.
66
+ 5. ``:79`` the outer loop bound is ``(max(timeindex)<d.numrecords)`` -- IDL's
67
+ binary ``<`` is MIN here, so the loop's upper bound is
68
+ ``min(max(timeindex), numrecords)`` **inclusive**, and the inner guard
69
+ ``itime lt d.numrecords`` (``:81``) then silently drops any particle whose
70
+ ``timeindex`` lands exactly on ``numrecords``. Finding **S5-c**.
71
+ 6. ``:87`` ``intbin=max(where(...))`` returns ``-1`` (``nw=0``) when nothing
72
+ matches; the increment is guarded by ``nw gt 0``, so an interarrival
73
+ below the first ``intendbins`` edge is silently uncounted.
74
+ 7. ``:92`` the shattering-correction branch (``fit_poisson``) fires only
75
+ when ``op.inttime_reject == 1`` **and** the second already holds more
76
+ than 100 particles. See ``fit_poisson.py`` for why this branch has no
77
+ GDL oracle.
78
+ 8. ``:102-124`` SPEC deadtime is applied **backward**, split only across the
79
+ start and stop time index -- the source's own comment marks the
80
+ intermediate full-deadtime fill as deliberately removed (``:119-121``,
81
+ preserved as a comment, not code). Read-only finding, not measured.
82
+ 9. ``:159-163`` ``sizebin=max(where(op.endbins le binningsize))`` with a
83
+ special case for ``binningsize == endbins[0]``; ``arbin``/``asprbin`` use
84
+ strict ``lt``. When ``binningsize`` is below ``endbins[0]`` and not
85
+ exactly equal, ``sizebin`` stays ``-1`` -- IDL's negative-subscript
86
+ convention reads the **last** row of ``d.spec2d``, which this port
87
+ reproduces because Python's own ``[-1]`` indexing means the same thing.
88
+ Not yet measured whether IDL actually permits this without erroring;
89
+ flagged for the GDL bank. Finding **S5-b**.
90
+ 10. ``:177`` ``ireject=where(reject and [1,2,4,8,16,32,64])`` tests only the
91
+ first seven reject bits -- bit 128 (depth-of-field) is never counted in
92
+ ``d.count_rejected``, which is why that array has 7 columns
93
+ (``soda2_process_2d.pro:65``, ``count_rejected:lonarr(numrecords,7)``).
94
+ A particle rejected on bit 128 alone gives ``ireject=[-1]``, so
95
+ ``d.count_rejected[itime,-1]`` increments the array's **last** column
96
+ (the bit-64 column), not a dedicated bit-128 column. Finding **S5-a**.
97
+ **``d.count_rejected[itime,ireject[0]]++`` takes the FIRST (lowest-bit)
98
+ column, not the highest** -- measured by the R6C GDL bank's
99
+ ``multi_bit_reject`` case (bits 1+8: IDL column 0, the round-5 port's
100
+ ``_max_where`` gave column 3). H1, finding **S5-q**: the source's own
101
+ comment "Increment for each reason" is wrong -- it increments one
102
+ column, for the lowest-numbered reason.
103
+ 11. ``:154`` ``binningsize /= sizecorrection`` runs under ``apply_psc``;
104
+ ``sizecorrection == 0`` divides by zero in FLOAT (IEEE inf, no
105
+ exception), pushing ``sizebin`` past every ``endbins`` edge. Finding
106
+ **S5-d**.
107
+ 12. ``:83`` the per-second TAS, the mean of the particles' ``probetas``, is an IDL FLOAT
108
+ mean; ported as a running float32 accumulation (not ``numpy.mean`` on
109
+ the float32 array, which sums in a wider working type by default) so a
110
+ sequential-summation order is reproduced. Finding **S5-e** if a
111
+ divergence from ``numpy.mean`` is later measured on real data.
112
+ """
113
+ from __future__ import annotations
114
+
115
+ from dataclasses import dataclass
116
+
117
+ import numpy as np
118
+
119
+ from arrayprobe_soda2.reject import Particle, RejectOptions, soda2_reject
120
+
121
+ __all__ = [
122
+ "Accumulator",
123
+ "ParticlesortOptions",
124
+ "Soda2ParticlesortError",
125
+ "idl_median",
126
+ "new_accumulator",
127
+ "soda2_particlesort",
128
+ ]
129
+
130
+
131
+ class Soda2ParticlesortError(RuntimeError):
132
+ """An IDL subscript-range halt this module reproduces as a raise, naming
133
+ the line. CIP-1: ``soda2_particlesort.pro:39``'s ``truetime[1:*]`` halts in IDL
134
+ for a 1-particle ``x`` (the finding derived for the SPEC branch's own
135
+ ``:13``, same construct, `run_soda2_process_2d_bank.py` module docstring)."""
136
+
137
+ #: The particle-structure tags this module reads from ``x`` (sizing-core plan C.2),
138
+ #: plus the six ``soda2_reject`` needs (``arearatio``, ``arearatiofilled``,
139
+ #: ``allin``, ``centerin``, ``diam``, ``dofflag`` -- already listed below).
140
+ X_TAGS = (
141
+ "probetime",
142
+ "buffertime",
143
+ "reftime",
144
+ "inttime",
145
+ "overloadflag",
146
+ "probetas",
147
+ "missed",
148
+ "xsize",
149
+ "ysize",
150
+ "areasize",
151
+ "xextent",
152
+ "oned",
153
+ "twod",
154
+ "diam",
155
+ "sizecorrection",
156
+ "arearatiofilled",
157
+ "arearatio",
158
+ "aspectratio",
159
+ "orientation",
160
+ "zd",
161
+ "allin",
162
+ "centerin",
163
+ "dofflag",
164
+ )
165
+
166
+
167
+ def idl_median(values: np.ndarray) -> float:
168
+ """IDL ``MEDIAN(values)`` without ``/EVEN``: for an even-length array
169
+ this is the upper-middle sorted element, not an average. Python 0-based
170
+ ``sorted[n // 2]`` lands on exactly that element for both parities."""
171
+ sorted_values = np.sort(np.asarray(values, dtype=np.float64))
172
+ n = sorted_values.size
173
+ return float(sorted_values[n // 2])
174
+
175
+
176
+ def _max_where(condition: np.ndarray) -> tuple[int, int]:
177
+ """``max(where(condition), nw)``: the largest index where ``condition``
178
+ is true, and the count of true entries. ``(-1, 0)`` when none match,
179
+ matching IDL's ``WHERE`` returning ``-1`` on no match."""
180
+ idx = np.nonzero(condition)[0]
181
+ if idx.size == 0:
182
+ return -1, 0
183
+ return int(idx.max()), int(idx.size)
184
+
185
+
186
+ def _first_where(condition: np.ndarray) -> tuple[int, int]:
187
+ """``where(condition)`` indexed at ``[0]``: the SMALLEST index where
188
+ ``condition`` is true (IDL's ``where()`` returns matches in ascending
189
+ order), and the count of true entries. ``(-1, 0)`` when none match.
190
+
191
+ Used only at ``:177``'s ``ireject=where(...)`` / ``ireject[0]`` -- the R6C
192
+ GDL bank's ``multi_bit_reject`` case (bits 1+8: IDL column 0, the
193
+ round-5 port's ``_max_where`` gave column 3) measured that IDL takes the
194
+ FIRST element, not the last. Finding S5-q."""
195
+ idx = np.nonzero(condition)[0]
196
+ if idx.size == 0:
197
+ return -1, 0
198
+ return int(idx.min()), int(idx.size)
199
+
200
+
201
+ #: ``:162-163``'s ``0.99`` and ``0.01`` are FLOAT literals.
202
+ _F99 = float(np.float32(0.99))
203
+ _F01 = float(np.float32(0.01))
204
+
205
+
206
+ def _idl_clamp_99_01(value: float) -> float:
207
+ """``value<0.99>0.01`` on an IDL scalar (``:162-163``). The binary MIN/MAX
208
+ operators on a scalar keep the left operand only when the comparison is
209
+ true, so a NaN comes out as 0.99 (GDL: ``!values.f_nan<0.99>0.01`` is
210
+ 0.990000), where Python's ``min``/``max`` and NumPy's keep the NaN. Both
211
+ bounds are FLOAT, so the clamp lands on 0.99000000953674316, not 0.99."""
212
+ v = value if value < _F99 else _F99
213
+ return v if v > _F01 else _F01
214
+
215
+
216
+ def _idl_histogram_0_49(values: np.ndarray) -> np.ndarray:
217
+ """``histogram(values, min=0, max=49)``: 50 integer bins, values outside
218
+ ``[0, 49]`` excluded entirely (not clipped into an edge bin)."""
219
+ counts = np.zeros(50, dtype=np.float64)
220
+ in_range = values[(values >= 0) & (values <= 49)]
221
+ idx, freq = np.unique(np.floor(in_range).astype(np.int64), return_counts=True)
222
+ counts[idx] = freq
223
+ return counts
224
+
225
+
226
+ @dataclass
227
+ class ParticlesortOptions:
228
+ """The ``op`` (``*pop``) tags this module reads. ``format`` must be
229
+ ``"SPEC"``, ``"SEA"``, ``"DMT"`` or ``"RAF"`` and ``probetype`` must not be
230
+ ``"2DC"``; anything else raises ``NotImplementedError`` naming the source
231
+ line the unported branch lives at."""
232
+
233
+ starttime: float
234
+ rate: float
235
+ clusterthresh: float
236
+ inttime_reject: int
237
+ smethod: str
238
+ apply_psc: int
239
+ apply_psc_sizelimit: float
240
+ water: int
241
+ endbins: np.ndarray
242
+ arendbins: np.ndarray
243
+ eawmethod: str
244
+ res: float = 0.0
245
+ dofreject: int = 0
246
+ format: str = "SPEC"
247
+ probetype: str = ""
248
+
249
+ def as_reject_options(self) -> RejectOptions:
250
+ return RejectOptions(
251
+ endbins=self.endbins,
252
+ eawmethod=self.eawmethod,
253
+ water=self.water,
254
+ res=self.res,
255
+ dofreject=self.dofreject,
256
+ clusterthresh=self.clusterthresh,
257
+ )
258
+
259
+
260
+ @dataclass
261
+ class Accumulator:
262
+ """``d``, transcribed from ``soda2_process_2d.pro:49-104``. Every field's
263
+ dtype mirrors the IDL literal it was built from (``fltarr`` -> float32,
264
+ ``lonarr`` -> int32, ``dblarr``/``dindgen`` -> float64)."""
265
+
266
+ numrecords: int
267
+ numbins: int
268
+ numarbins: int
269
+ time: np.ndarray
270
+ count_accepted: np.ndarray
271
+ count_rejected: np.ndarray
272
+ total_count_rejected: np.ndarray
273
+ count_missed: np.ndarray
274
+ missed_hist: np.ndarray
275
+ spec2d: np.ndarray
276
+ spec2d_aspr: np.ndarray
277
+ spec2d_orientation: np.ndarray
278
+ numintbins: int
279
+ intendbins: np.ndarray
280
+ intmidbins: np.ndarray
281
+ intspec_all: np.ndarray
282
+ intspec_accepted: np.ndarray
283
+ numzdbins: int
284
+ zdendbins: np.ndarray
285
+ zdmidbins: np.ndarray
286
+ zdspec: np.ndarray
287
+ tas: np.ndarray
288
+ poisson_fac: np.ndarray
289
+ corr_fac: np.ndarray
290
+ intcutoff: np.ndarray
291
+ deadtime: np.ndarray
292
+ hist3d: np.ndarray
293
+
294
+
295
+ def _idl_powf(base: float | np.ndarray, exponent: float | np.ndarray) -> np.ndarray:
296
+ """IDL FLOAT^FLOAT, platform-independently: the correctly rounded double
297
+ power narrowed to FLOAT (the same rule ``export_ascii._idl_alog10`` uses
298
+ for ``alog10``). ``numpy.power`` on float32 calls the C runtime's ``powf``,
299
+ which is not correctly rounded under glibc."""
300
+ out = np.power(np.asarray(base, dtype=np.float64), np.asarray(exponent, dtype=np.float64))
301
+ return out.astype(np.float32)
302
+
303
+
304
+ def new_accumulator(op: ParticlesortOptions, numrecords: int) -> Accumulator:
305
+ """``d={...}`` from ``soda2_process_2d.pro:49-104``. ``numbins``/
306
+ ``numarbins`` come from ``op.endbins``/``op.arendbins`` the way the
307
+ source derives them (``n_elements(endbins)-1``)."""
308
+ numbins = len(op.endbins) - 1
309
+ numarbins = len(op.arendbins) - 1
310
+ numintbins = 40
311
+ iminpower, imaxpower = -7, 1
312
+ span = imaxpower - iminpower
313
+ # IDL ``10.0^float``: the double-precision power rounded once to FLOAT.
314
+ # Measured against the GDL golden (all 81 edges bit-identical); numpy's
315
+ # own float32 power is the platform ``powf`` and differs from it by one
316
+ # ULP in 13 of 81 edges under glibc, in none under the MSVC runtime.
317
+ intendbins = _idl_powf(10.0, (np.arange(numintbins + 1, dtype=np.float32) / numintbins)
318
+ * span + iminpower)
319
+ intmidbins = _idl_powf(10.0, ((np.arange(numintbins, dtype=np.float32) + 0.5) / numintbins)
320
+ * span + iminpower)
321
+ numzdbins = 163
322
+
323
+ return Accumulator(
324
+ numrecords=numrecords,
325
+ numbins=numbins,
326
+ numarbins=numarbins,
327
+ time=op.starttime + op.rate * np.arange(numrecords, dtype=np.float64),
328
+ count_accepted=np.zeros(numrecords, dtype=np.int32),
329
+ count_rejected=np.zeros((numrecords, 7), dtype=np.int32),
330
+ total_count_rejected=np.zeros(numrecords, dtype=np.int32),
331
+ count_missed=np.zeros(numrecords, dtype=np.int32),
332
+ missed_hist=np.zeros((numrecords, 50), dtype=np.float32),
333
+ spec2d=np.zeros((numrecords, numbins, numarbins), dtype=np.float32),
334
+ spec2d_aspr=np.zeros((numrecords, numbins, numarbins), dtype=np.float32),
335
+ spec2d_orientation=np.zeros((numrecords, numbins, 18), dtype=np.float32),
336
+ numintbins=numintbins,
337
+ intendbins=intendbins,
338
+ intmidbins=intmidbins,
339
+ intspec_all=np.zeros((numrecords, numintbins), dtype=np.float32),
340
+ intspec_accepted=np.zeros((numrecords, numintbins), dtype=np.float32),
341
+ numzdbins=numzdbins,
342
+ zdendbins=np.arange(numzdbins, dtype=np.float32) * 0.05 - 0.025,
343
+ zdmidbins=np.arange(numzdbins, dtype=np.float32) * 0.05,
344
+ zdspec=np.zeros((numbins, numzdbins), dtype=np.int32),
345
+ tas=np.zeros(numrecords, dtype=np.float32),
346
+ poisson_fac=np.zeros((numrecords, 3), dtype=np.float32),
347
+ corr_fac=np.ones(numrecords, dtype=np.float32),
348
+ intcutoff=np.zeros(numrecords, dtype=np.float32),
349
+ deadtime=np.zeros(numrecords, dtype=np.float32),
350
+ hist3d=np.zeros((numbins, numarbins, numarbins), dtype=np.float32),
351
+ )
352
+
353
+
354
+ def spec_sort_locals(
355
+ x: dict[str, np.ndarray], reprocessed_time: np.ndarray | None = None,
356
+ format: str = "SPEC",
357
+ ) -> tuple[np.ndarray, np.ndarray]:
358
+ """``soda2_particlesort.pro:22`` and ``:28`` (SPEC), ``:30-41`` (SEA) or
359
+ ``:12-16`` (the pre-branch default, which every format the IDL does not
360
+ override at ``:21-46`` takes -- here ``DMT`` and ``RAF``) --
361
+ the two locals the PBP writers consume (``truetime``, ``interarrival``),
362
+ extracted so the writers and their GDL test see exactly what
363
+ :func:`soda2_particlesort` used internally. Round 8-B (§D)
364
+ ported the SPEC branch as a pure extraction; CIP-1 adds the
365
+ ``format`` keyword for the SEA branch it ports here -- SPEC's own path
366
+ through this function is unchanged (same three lines, same default)."""
367
+ inttime = np.asarray(x["inttime"], dtype=np.float64)
368
+ buffertime = np.asarray(x["buffertime"], dtype=np.float64)
369
+ if format in ("DMT", "RAF"):
370
+ # :12-16 are the pre-branch default: only SPEC (:21-29), SEA (:30-41)
371
+ # and TXT (:43-46) override them, so RAF takes them exactly as DMT.
372
+ probetime = np.asarray(x["probetime"], dtype=np.float64)
373
+ reftime = np.asarray(x["reftime"], dtype=np.float64)
374
+ if probetime.size == 1:
375
+ # `:13` successive `truetime` differences, 0 first, floored at 0 -- the same
376
+ # out-of-range `1:*` as the SEA branch's `:39`; GDL halts one
377
+ # line earlier, at `:12`'s `median` of a 1-element struct field
378
+ # (`run_soda2_particlesort_bank.py`, `_PAD`).
379
+ raise Soda2ParticlesortError(
380
+ "soda2_particlesort.pro:12-13 -- median/truetime[1:*] halt in "
381
+ f"IDL for a 1-particle {format} flush (the :12-16 default)")
382
+ # :12 -- DOUBLE + scalar DOUBLE median (upper-middle for even n).
383
+ truetime = probetime + idl_median(buffertime - reftime)
384
+ # :13/:16 -- `[0,truetime[1:*]-truetime]>0`, no `inttime` at all.
385
+ interarrival = np.maximum(np.concatenate([[0.0], np.diff(truetime)]), 0.0)
386
+ return truetime, interarrival
387
+ if format == "SEA":
388
+ probetime = np.asarray(x["probetime"], dtype=np.float64)
389
+ reftime = np.asarray(x["reftime"], dtype=np.float64)
390
+ if probetime.size == 1:
391
+ # `:39` `it2 = [0,truetime[1:*]-truetime] > 0` -- IDL's
392
+ # subscript range `1:*` on a 1-element array is out of range and
393
+ # halts (the derived finding for the SPEC branch's own `:13`,
394
+ # same construct).
395
+ raise Soda2ParticlesortError(
396
+ "soda2_particlesort.pro:39 -- truetime[1:*] halts in IDL "
397
+ "for a 1-particle SEA flush")
398
+ interarrival = np.maximum(inttime, 0.0) # :32
399
+ truetime = probetime - reftime + buffertime # :36
400
+ # :39 -- secondary interarrival calculation.
401
+ it2 = np.maximum(np.concatenate([[0.0], np.diff(truetime)]), 0.0)
402
+ # :40-41 -- bad interarrival times (>0.1 s off) zeroed. `0.1` is a
403
+ # FLOAT literal: DOUBLE `gt` compares against 0.100000001490116.
404
+ bad = np.abs(interarrival - it2) > np.float64(np.float32(0.1))
405
+ if np.any(bad):
406
+ interarrival = interarrival.copy()
407
+ interarrival[bad] = 0.0
408
+ return truetime, interarrival
409
+ interarrival = np.maximum(inttime, 0.0)
410
+ truetime = reprocessed_time if reprocessed_time is not None else buffertime
411
+ truetime = np.asarray(truetime, dtype=np.float64)
412
+ return truetime, interarrival
413
+
414
+
415
+ def _deadtime_2dc(op: ParticlesortOptions, d: Accumulator, truetime: np.ndarray,
416
+ timeindex: np.ndarray, inewbuffer: np.ndarray) -> None:
417
+ """``soda2_particlesort.pro:65-76``, bug for bug.
418
+
419
+ ``:68`` each dead time is a new buffer's first ``truetime`` minus the one
420
+ before it, floored at 0
421
+ (DOUBLE); ``:69`` the RAF arm replaces it with the INT scalar ``0``, so
422
+ every ``total(deadtimes[w])`` is 0 and the block *zeroes*
423
+ ``d.deadtime[itime]`` at each buffer start; ``:72-75`` loop
424
+ ``min(timeindex)..max(timeindex)`` and **assign** ``total(...) < op.rate``
425
+ (a sequential DOUBLE sum capped at the period, stored FLOAT) -- an
426
+ assignment, not an accumulation, so a second call for the same second
427
+ overwrites the first. The forward ``:125-127`` deadtime still adds on top.
428
+ """
429
+ if inewbuffer.size < 2:
430
+ # `inewbuffer[1:*]` on a 1-element array halts in IDL.
431
+ raise Soda2ParticlesortError(
432
+ "soda2_particlesort.pro:68 -- inewbuffer[1:*] halts in IDL "
433
+ "for a single buffer")
434
+ # IDL clips an out-of-range element of a subscript *array* to the array's
435
+ # bounds (no `compile_opt strictarrsubs` in this file): `inewbuffer` spans
436
+ # every buffer of the run and is never reset at a flush, so it holds 0 for
437
+ # rejected buffers (`-1` -> element 0) and stale starts from an earlier,
438
+ # larger flush (-> the last element). NumPy would wrap or raise instead.
439
+ # Checked under GDL 2026-10-07: `a=[1,2,3] & print, a[[-1,5]]` prints 1 3, and
440
+ # `tt=[10d,20,30] & nb=[0,2,7] & print, tt[nb]-tt[nb-1]` prints 0 10 0.
441
+ last = truetime.size - 1
442
+ nb = np.clip(inewbuffer[1:], 0, last)
443
+ nbm1 = np.clip(inewbuffer[1:] - 1, 0, last)
444
+ ideadtime = timeindex[nb] # :68
445
+ raf = op.format == "RAF" # :69
446
+ deadtimes = None if raf else np.maximum(truetime[nb] - truetime[nbm1], 0.0)
447
+ for itime in range(int(timeindex.min()), int(timeindex.max()) + 1): # :72
448
+ w = np.nonzero(ideadtime == itime)[0] # :73
449
+ if w.size == 0:
450
+ continue
451
+ if not 0 <= itime < d.numrecords:
452
+ raise Soda2ParticlesortError(
453
+ f"soda2_particlesort.pro:74 -- d.deadtime[{itime}] is out of "
454
+ f"range (numrecords {d.numrecords}); IDL halts")
455
+ if raf:
456
+ tot = 0.0 # total() of the INT scalar 0, however subscripted
457
+ else:
458
+ assert deadtimes is not None
459
+ tot = 0.0
460
+ for k in w: # TOTAL: sequential DOUBLE sum
461
+ tot += float(deadtimes[k])
462
+ d.deadtime[itime] = np.float32(min(tot, float(op.rate))) # :74 `< op.rate`
463
+
464
+
465
+ def soda2_particlesort(
466
+ op: ParticlesortOptions,
467
+ x: dict[str, np.ndarray],
468
+ d: Accumulator,
469
+ reprocessed_time: np.ndarray | None = None,
470
+ inewbuffer: np.ndarray | None = None,
471
+ ) -> np.ndarray:
472
+ """Port of ``soda2_particlesort.pro:1-171``. Mutates ``d`` in place and
473
+ returns ``rejectionflag`` (the IDL keeps it local); the PBP writers in
474
+ :mod:`arrayprobe_soda2.pbp_writer` consume it directly. ``inewbuffer``
475
+ (the IDL positional argument) is read only by the 2DC block
476
+ (``:65-76``) and is required there."""
477
+ if op.probetype == "2DC" and inewbuffer is None:
478
+ raise Soda2ParticlesortError(
479
+ "soda2_particlesort.pro:68 -- the 2DC deadtime block reads "
480
+ "inewbuffer; pass it")
481
+ if op.format not in ("SPEC", "SEA", "DMT", "RAF"):
482
+ raise NotImplementedError(
483
+ f"soda2_particlesort.pro:30-46 -- format {op.format!r} "
484
+ "(only 'SPEC', 'SEA', 'DMT' and 'RAF' are ported)"
485
+ )
486
+
487
+ probetime = np.asarray(x["probetime"], dtype=np.float64)
488
+ buffertime = np.asarray(x["buffertime"], dtype=np.float64)
489
+ reftime = np.asarray(x["reftime"], dtype=np.float64)
490
+ overloadflag = np.asarray(x["overloadflag"])
491
+ numparticles = probetime.size
492
+ rejectionflag = np.zeros(numparticles, dtype=np.uint8)
493
+
494
+ # :12 -- computed for fidelity; unused for SPEC after :28 overrides truetime.
495
+ _ = idl_median(buffertime - reftime)
496
+
497
+ # :22 -- MAX, not comparison (trap 1). :28 -- SPEC truetime override.
498
+ # :30-41 -- SEA truetime/interarrival (CIP-1, §2.3). :12-16 -- the
499
+ # DMT defaults (pass 5, item 7b).
500
+ truetime, interarrival = spec_sort_locals(x, reprocessed_time, format=op.format)
501
+
502
+ # :49-56 -- sequential, self-referential cluster loop (trap 3). BYTE +
503
+ # INT literal promotes to INT (`(cluster[i-1]+1)>2`), then storing that
504
+ # INT back into the BYTE `cluster` array WRAPS modulo 256, it does not
505
+ # saturate at 255 (H2, finding S5-p, measured by the R6C GDL bank's
506
+ # cluster_300 case: of 300 particles chained with clusterthresh>0, GDL
507
+ # accepts the first 255 -- the wrap at the 256th particle zeroes the
508
+ # whole `cluster[0:255]` range via `cluster[i-cluster[i-1]:i]=0`, and the
509
+ # chain restarts at 2 -- and rejects only the last 45, where a
510
+ # saturating port would instead reject 299 of 300).
511
+ cluster = np.zeros(numparticles, dtype=np.uint8)
512
+ for i in range(1, numparticles):
513
+ if interarrival[i] < op.clusterthresh:
514
+ clustercount = (max(int(cluster[i - 1]) + 1, 2)) % 256
515
+ start = i - int(cluster[i - 1])
516
+ cluster[start : i + 1] = clustercount
517
+
518
+ # :59 -- `interarrival*x.overloadflag`, DOUBLE * BYTE -> DOUBLE. Read
519
+ # only by the forward `ELSE` at :126 (DMT); superseded for SPEC and
520
+ # SEA/CIP by the backward deadtime block below (:102-124), same as the
521
+ # IDL leaves it unused there.
522
+ _deadtime_flagged = interarrival * overloadflag.astype(np.float64)
523
+ # :102 -- which deadtime method this op takes.
524
+ backward_deadtime = op.format == "SPEC" or (op.probetype == "CIP" and op.format == "SEA")
525
+ # :60 -- truncation toward zero (trap 4), not floor.
526
+ timeindex = np.trunc((truetime - op.starttime) / op.rate).astype(np.int64)
527
+
528
+ if numparticles > 1:
529
+ dtimeindex = np.diff(timeindex)
530
+ # non-monotonic: IDL only prints a warning, doesn't raise.
531
+ _ = dtimeindex.min() < 0 if dtimeindex.size else False
532
+
533
+ # :65-76 -- 2DC only: deadtime from the gaps between buffers.
534
+ if op.probetype == "2DC":
535
+ assert inewbuffer is not None
536
+ _deadtime_2dc(op, d, truetime, timeindex, np.asarray(inewbuffer, dtype=np.int64))
537
+
538
+ lo = max(int(timeindex.min()), 0) if numparticles else 0
539
+ hi = min(int(timeindex.max()), d.numrecords) if numparticles else -1
540
+
541
+ for itime in range(lo, hi + 1):
542
+ iparticles = np.nonzero(timeindex == itime)[0]
543
+ nparticles = iparticles.size
544
+ if not (0 <= itime < d.numrecords and nparticles > 0):
545
+ continue # trap 5: itime == numrecords is silently dropped
546
+
547
+ # :83 -- FLOAT mean via sequential accumulation (trap 12).
548
+ acc = np.float32(0.0)
549
+ for k in iparticles:
550
+ acc = np.float32(acc + np.float32(x["probetas"][k]))
551
+ d.tas[itime] = np.float32(acc / np.float32(nparticles))
552
+
553
+ for j in iparticles:
554
+ intbin, nw = _max_where(d.intendbins <= interarrival[j])
555
+ if nw > 0 and intbin < d.numintbins:
556
+ d.intspec_all[itime, intbin] += 1
557
+
558
+ if op.inttime_reject == 1 and d.intspec_all[itime, :].sum() > 100:
559
+ from arrayprobe_soda2.fit_poisson import fit_poisson
560
+
561
+ imax = int(np.argmax(d.intspec_all[itime, :]))
562
+ poisson_firstguess = d.intmidbins[imax] / 5.0
563
+ pf = fit_poisson(d.intspec_all[itime, :], d.intmidbins, poisson_firstguess, plot=False)
564
+ d.poisson_fac[itime, :] = pf.a
565
+ d.intcutoff[itime] = 1.0 / pf.a[1] * 0.05
566
+ d.corr_fac[itime] = 1.0 / (2 * np.exp(-d.intcutoff[itime] * pf.a[1]) - 1)
567
+
568
+ # :102-124 -- SPEC / SEA-CIP deadtime, applied backward (trap 8).
569
+ # :125-127 -- every other format (DMT here) accumulates :59's
570
+ # forward deadtime: FLOAT + TOTAL(DOUBLE) -> DOUBLE, stored FLOAT.
571
+ # IDL's TOTAL is a sequential double sum, so accumulate in order.
572
+ if not backward_deadtime:
573
+ total = 0.0
574
+ for j in iparticles:
575
+ total += float(_deadtime_flagged[j])
576
+ d.deadtime[itime] = np.float32(float(d.deadtime[itime]) + total)
577
+ else:
578
+ for j in iparticles:
579
+ if x["overloadflag"][j]:
580
+ deadtimestart = truetime[j] - interarrival[j]
581
+ deadtimestop = truetime[j]
582
+ timeindexstart = max(int(np.trunc((deadtimestart - op.starttime) / op.rate)), 0)
583
+ timeindexstop = int(np.trunc((deadtimestop - op.starttime) / op.rate))
584
+ if timeindexstart == timeindexstop:
585
+ d.deadtime[timeindexstart] += interarrival[j]
586
+ else:
587
+ d.deadtime[timeindexstart] += (
588
+ d.time[timeindexstart] + op.rate - deadtimestart
589
+ )
590
+ d.deadtime[timeindexstop] += deadtimestop - d.time[timeindexstop]
591
+
592
+ # :130 -- `x.missed` is FLOAT, `total()` a sequential FLOAT sum, and
593
+ # LONG + FLOAT is FLOAT, truncated back into the LONG array. Past 2^24
594
+ # the FLOAT sum rounds: a CIP's repeated counter gives missed = 65535
595
+ # per particle, and 300 of them total 19660544 under GDL, not 19660500.
596
+ missed32 = np.maximum(np.asarray(x["missed"], dtype=np.float32)[iparticles],
597
+ np.float32(0))
598
+ tot32 = np.cumsum(missed32, dtype=np.float32)[-1]
599
+ d.count_missed[itime] = int(np.float32(d.count_missed[itime]) + tot32)
600
+ d.missed_hist[itime, :] += _idl_histogram_0_49(np.asarray(x["missed"][iparticles]))
601
+
602
+ reject_opts = op.as_reject_options()
603
+ for j in iparticles:
604
+ j = int(j)
605
+ match op.smethod:
606
+ case "xsize":
607
+ binningsize = float(x["xsize"][j])
608
+ case "ysize":
609
+ binningsize = float(x["ysize"][j])
610
+ case "areasize":
611
+ binningsize = float(x["areasize"][j])
612
+ case "xextent":
613
+ binningsize = float(x["xextent"][j])
614
+ case "oned":
615
+ binningsize = float(x["oned"][j])
616
+ case "twod":
617
+ binningsize = float(x["twod"][j])
618
+ case _:
619
+ binningsize = float(x["diam"][j])
620
+
621
+ apply_psc = 0
622
+ if op.apply_psc == 1:
623
+ if op.apply_psc_sizelimit == 0:
624
+ apply_psc = 1
625
+ if op.apply_psc_sizelimit > 0 and binningsize <= op.apply_psc_sizelimit:
626
+ apply_psc = 1
627
+ if op.water >= 1:
628
+ apply_psc = 1
629
+ if apply_psc == 1:
630
+ # :154 -- trap 11: sizecorrection==0 divides to inf, not an
631
+ # exception (IDL FLOAT semantics, finding S5-d). NumPy's
632
+ # float32 division reproduces IEEE inf/nan where a plain
633
+ # Python float division would raise ZeroDivisionError.
634
+ with np.errstate(divide="ignore", invalid="ignore"):
635
+ binningsize = float(
636
+ np.float32(binningsize) / np.float32(x["sizecorrection"][j])
637
+ )
638
+
639
+ binningar = (
640
+ float(x["arearatiofilled"][j]) if op.water >= 1 else float(x["arearatio"][j])
641
+ )
642
+
643
+ particle = Particle(
644
+ arearatio=float(x["arearatio"][j]),
645
+ arearatiofilled=float(x["arearatiofilled"][j]),
646
+ allin=int(x["allin"][j]),
647
+ centerin=int(x["centerin"][j]),
648
+ diam=float(x["diam"][j]),
649
+ dofflag=int(x["dofflag"][j]),
650
+ )
651
+ nextidx = min(j + 1, numparticles - 1)
652
+ result = soda2_reject(
653
+ particle,
654
+ interarrival[j],
655
+ interarrival[nextidx],
656
+ float(d.intcutoff[itime]),
657
+ int(cluster[j]),
658
+ binningsize,
659
+ reject_opts,
660
+ )
661
+ reject = result.reject
662
+ rejectionflag[j] = reject & 0xFF
663
+
664
+ if reject == 0:
665
+ # :159-161 -- trap 9: le, with the first-bin special case.
666
+ sizebin, _nws = _max_where(op.endbins <= binningsize)
667
+ if binningsize == op.endbins[0]:
668
+ sizebin = 0
669
+ clamped_ar = _idl_clamp_99_01(binningar)
670
+ arbin, _nwa = _max_where(op.arendbins < clamped_ar)
671
+ clamped_aspr = _idl_clamp_99_01(float(x["aspectratio"][j]))
672
+ asprbin, _nwasp = _max_where(op.arendbins < clamped_aspr)
673
+ # IDL adds 90 in FLOAT, so the sum can round up across an
674
+ # integer (GDL: floor(69.99999237 + 90) / 10 = 16; the double
675
+ # sum gives 15). floor() -> LONG, then LONG / 10. Pass 6.
676
+ o32 = np.float32(x["orientation"][j]) + np.float32(90)
677
+ obin = min(int(np.floor(o32)) // 10, 17)
678
+
679
+ d.spec2d[itime, sizebin, arbin] += 1
680
+ d.spec2d_aspr[itime, sizebin, asprbin] += 1
681
+ d.spec2d_orientation[itime, sizebin, obin] += 1
682
+ d.count_accepted[itime] += 1
683
+ d.hist3d[sizebin, arbin, asprbin] += 1
684
+
685
+ intbin, nw = _max_where(d.intendbins <= interarrival[j])
686
+ if nw > 0 and intbin < d.numintbins:
687
+ d.intspec_accepted[itime, intbin] += 1
688
+
689
+ zdbin, _nzd = _max_where(d.zdendbins <= float(x["zd"][j]))
690
+ d.zdspec[sizebin, zdbin] += 1
691
+ else:
692
+ # :177 -- trap 10: bit 128 is never counted (S5-a); a
693
+ # no-overlap reject wraps to the last column via -1.
694
+ # ireject[0] (S5-q, measured by the R6C GDL bank's
695
+ # multi_bit_reject case): the FIRST set bit's column, not the
696
+ # highest -- `where()` returns ascending indices and IDL
697
+ # indexes element 0.
698
+ bits = np.array([1, 2, 4, 8, 16, 32, 64])
699
+ ireject, _n = _first_where((reject & bits) != 0)
700
+ d.count_rejected[itime, ireject] += 1
701
+ d.total_count_rejected[itime] += 1
702
+
703
+ return rejectionflag