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,156 @@
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
+ """Reprocess-from-PBP: ``soda2_restore_pbp.pro`` and ``spec_newtime.pro``,
4
+ the two helpers ``soda2_process_2d.pro``'s ``fn_pbp`` branch (`:584-617`)
5
+ calls. Source: SODA-2 (``SODA2/abansemer-soda2-afcea15/``).
6
+
7
+ The driver half (the loop at `:599-613`) lives in
8
+ :func:`arrayprobe_soda2.process_2d.soda2_process_2d`; this module only reads
9
+ the ``.pbp.nc`` and recomputes the SPEC particle time.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ import numpy as np
17
+
18
+ from .particlesort import idl_median
19
+
20
+ __all__ = ["PbpRestoreError", "SpecNewtimeStop", "pbp_particle_count",
21
+ "restore_pbp", "spec_newtime"]
22
+
23
+
24
+ class PbpRestoreError(RuntimeError):
25
+ """An ``ncdf_varget`` read the IDL could not perform (offset past the end)."""
26
+
27
+
28
+ class SpecNewtimeStop(RuntimeError):
29
+ """``spec_newtime.pro:7`` -- ``stop, 'File does not contain full rawtime,
30
+ just truncated.'``"""
31
+
32
+
33
+ class SpecNewtimeSubscriptError(IndexError):
34
+ """A subscript ``spec_newtime.pro`` evaluates out of range, where the IDL halts:
35
+ ``rawtime[1:*]`` at `:10` on a one-particle file (GDL 8.4: "Subscript out of
36
+ range [s:*]")."""
37
+
38
+
39
+ @dataclass
40
+ class RestoredPbp:
41
+ """``soda2_restore_pbp``'s return: the per-particle columns (every
42
+ variable whose length equals ``time``'s, `:17-24`) plus ``x.global``."""
43
+
44
+ columns: dict[str, np.ndarray]
45
+ global_attrs: dict[str, Any] = field(default_factory=dict)
46
+
47
+
48
+ def pbp_particle_count(fn: str) -> int:
49
+ """`:587` -- ``restorenc, fn_pbp, 'pbp', var='time'``; only the length
50
+ is used (`:599`, `:611`)."""
51
+ import netCDF4
52
+
53
+ with netCDF4.Dataset(fn, "r") as ds:
54
+ return int(ds.variables["time"].shape[0])
55
+
56
+
57
+ def restore_pbp(fn: str, offset: int = 0, count: int | None = None) -> RestoredPbp:
58
+ """``soda2_restore_pbp.pro:1-30`` over ``restorenc``/``ncdf2sav``.
59
+
60
+ ``ncdf_varget`` with ``offset`` past the last record cannot read; IDL
61
+ halts there (read from the IDL documentation, not measured under GDL),
62
+ raised here as :class:`PbpRestoreError`. ``offset + count`` past the end
63
+ reads to the end, IDL's documented ``COUNT`` reduction."""
64
+ import netCDF4
65
+
66
+ with netCDF4.Dataset(fn, "r") as ds:
67
+ n = int(ds.variables["time"].shape[0])
68
+ if offset >= n:
69
+ raise PbpRestoreError(
70
+ f"soda2_restore_pbp.pro:7 / ncdf2sav.pro:83 -- ncdf_varget "
71
+ f"offset {offset} is past the {n} records in {fn}")
72
+ stop = n if count is None else min(n, offset + count)
73
+ cols: dict[str, np.ndarray] = {}
74
+ for name, var in ds.variables.items():
75
+ if var.ndim != 1 or var.shape[0] != n:
76
+ continue
77
+ arr = np.asarray(var[offset:stop])
78
+ if isinstance(arr, np.ma.MaskedArray):
79
+ arr = arr.data
80
+ cols[name.lower()] = np.asarray(arr)
81
+ glob = {a.lower(): ds.getncattr(a) for a in ds.ncattrs()}
82
+ return RestoredPbp(columns=cols, global_attrs=glob)
83
+
84
+
85
+ def spec_newtime(rawtime: np.ndarray, buffertime: np.ndarray,
86
+ probetas: np.ndarray, yres: Any) -> np.ndarray:
87
+ """``spec_newtime.pro:1-39`` on the columns ``restorenc`` reads (`:5`).
88
+
89
+ Kept as the IDL has it:
90
+
91
+ - `:7` stops unless ``max(rawtime) >= 2^31``.
92
+ - `:15-16` ``where(..., nrollover)`` with no match returns ``-1``, and a
93
+ scalar ``-1`` subscript is the last element, so with no rollover the
94
+ **last** particle's counter delta gains ``2^32``.
95
+ - `:19` ``yres/(1.0e6*probetas)`` is FLOAT arithmetic (``probetas`` is
96
+ FLOAT in the file) widened to DOUBLE after the division.
97
+ - `:23`, `:33` ``where(...)`` with no match is likewise ``-1``.
98
+ - `:34` ``median`` without ``/EVEN`` (upper-middle element).
99
+ - `:10` ``rawtime[1:*]`` on one particle is out of range and halts the IDL.
100
+ - `:34` subscripts ``buffertime`` with ``itimematch[matches]`` but ``elaptime``
101
+ with ``[itimematch[matches]]``. When ``matches`` is ``-1`` (no buffer end in
102
+ the period) the inner value is a SCALAR, so ``buffertime``'s subscript wraps
103
+ a negative index (``-2`` -> ``n-2``) while ``elaptime``'s, an array, is
104
+ clipped to 0; when ``matches`` is an array both are clipped. Measured under
105
+ GDL 8.4 (``tests/data/gdl_soda2_spec_newtime_single_buffer_golden.json``).
106
+ """
107
+ rawtime = np.asarray(rawtime, dtype=np.float64)
108
+ buffertime = np.asarray(buffertime, dtype=np.float64)
109
+ if float(rawtime.max()) < 2.0 ** 31:
110
+ raise SpecNewtimeStop(
111
+ "spec_newtime.pro:7: stop -- File does not contain full rawtime, just truncated.")
112
+ n = rawtime.size
113
+ if n < 2:
114
+ raise SpecNewtimeSubscriptError(
115
+ "spec_newtime.pro:10: Subscript out of range [s:*] (rawtime[1:*] on one particle)")
116
+ # `:10-11` -- `[0, a[1:*] - a]`: the subtraction runs to the shorter operand.
117
+ dcounter = np.concatenate([[0.0], rawtime[1:] - rawtime[:-1]])
118
+ dbuffer = np.concatenate([[0.0], buffertime[1:] - buffertime[:-1]])
119
+ # `:15-16`.
120
+ rollover = np.nonzero((dcounter < 0) | (dbuffer > 200))[0]
121
+ nrollover = rollover.size
122
+ if nrollover == 0:
123
+ dcounter[-1] += 2.0 ** 32 # `where` -> -1 -> last element
124
+ else:
125
+ dcounter[rollover] += 2.0 ** 32
126
+ # `:19-20`.
127
+ probetas32 = np.asarray(probetas, dtype=np.float32)
128
+ freq = (np.float32(yres) / (np.float32(1.0e6) * probetas32)).astype(np.float64)
129
+ inttime = dcounter * freq
130
+ # `:23-25`.
131
+ hits = np.nonzero(dbuffer > 0)[0]
132
+ itimematch = (hits - 1) if hits.size else np.array([-2])
133
+ newtime = buffertime.copy()
134
+ elaptime = buffertime * 0.0
135
+ # `:28-36` -- no `-1` on the loop bound.
136
+ for i in range(nrollover + 1):
137
+ istart = 0 if i == 0 else int(rollover[i - 1])
138
+ istop = n - 1 if i == nrollover else int(rollover[i]) - 1
139
+ elaptime[istart:istop + 1] = np.cumsum(inttime[istart:istop + 1])
140
+ matches = np.nonzero((itimematch >= istart) & (itimematch <= istop))[0]
141
+ if matches.size == 0:
142
+ # `where` -> scalar -1 -> the last element, a SCALAR subscript value:
143
+ # `buffertime[v]` wraps a negative v (IDL halts below -n), while
144
+ # `elaptime[[v]]` is an array subscript and is clipped.
145
+ v = int(itimematch[-1])
146
+ if v < -n:
147
+ raise SpecNewtimeSubscriptError(
148
+ f"spec_newtime.pro:34: Scalar subscript out of range [<0]: ({v})")
149
+ b_idx = np.array([v + n if v < 0 else v])
150
+ e_idx = np.clip(np.array([v]), 0, n - 1)
151
+ else:
152
+ # An array subscript out of range is clipped by IDL, not wrapped.
153
+ b_idx = e_idx = np.clip(itimematch[matches], 0, n - 1)
154
+ offset = idl_median(buffertime[b_idx] - elaptime[e_idx])
155
+ newtime[istart:istop + 1] = elaptime[istart:istop + 1] + offset
156
+ return newtime
@@ -0,0 +1,264 @@
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
+ """SODA-2 sample area — a port of ``soda2_samplearea.pro``.
4
+
5
+ Source: ``SODA2/abansemer-soda2-afcea15/soda2_samplearea.pro`` (35 lines),
6
+ Aaron Bansemer, NCAR, 2010. Copyright (C) 2016 UCAR, 3-clause BSD (see that
7
+ tree's ``LICENSE.txt``); this file is a from-source reimplementation, and the
8
+ BSD notice rides with it under that licence's clause 1.
9
+
10
+ Chosen as the port's first stage because it calls nothing else, and because
11
+ every constant in it is attributable to published literature the IDL source
12
+ itself cites.
13
+
14
+ **This docstring said the opposite for a day.** As written on 2026-09-10 it
15
+ gave the stage's reason as "no IDL interpreter is installed on this machine and
16
+ doctrine layer 2 (a differential oracle) is therefore unavailable". That became
17
+ false on 2026-09-11, when GDL ``v1.1.2-52-gfa46d3a4`` was installed and
18
+ confirmed running routines out of the vendored tree (``scripts/validation/gdl/``,
19
+ and ``tests/test_gdl_oracle.py`` asserts
20
+ sixteen bit-decoder cases against answers derived in Python rather than against
21
+ the fixture's own contents). The literature-attributable reason above stands on
22
+ its own and is why the stage order does not change; the missing-oracle reason
23
+ is gone. **A later stage of this port may and should use the differential
24
+ oracle** -- the stage order in V1.4 was derived from its absence and is no
25
+ longer forced by it.
26
+
27
+ **The two IDL clamps this routine carries.** In IDL, ``<`` and ``>`` are the
28
+ binary MIN and MAX operators, not comparisons -- the single most dangerous
29
+ idiom in this codebase to port (design record V1.3). Both appear here:
30
+
31
+ dof = dof < prht -> min(dof, prht)
32
+ sa = (dof*eff_wid * 1e-12) > 0 -> max(..., 0)
33
+
34
+ A porter who reads them as Python comparisons gets a boolean where a clamped
35
+ float belongs, and nothing raises. ``tests/test_soda2_sample_area.py`` drives
36
+ both operands past their clamp boundaries rather than only testing nominal
37
+ values, because inside the boundary the two readings can agree by accident.
38
+
39
+ **One deliberate, documented divergence.** The IDL reaches
40
+ ``ELSE: stop, 'Sample volume method not supported'`` for an unrecognised
41
+ ``eawmethod``. IDL's ``stop`` halts into the interactive debugger; it is not
42
+ an exception. Measured under GDL on 2026-09-12 (`unsupported_method` in the
43
+ bank), the run comes back with no result at all, recorded as ``status=ERROR``.
44
+ This port raises ``UnsupportedSampleVolumeMethod`` instead. That is a
45
+ divergence, named here rather than left implicit -- the shape of the failure
46
+ changes, the fact that it fails does not.
47
+
48
+ **Precision: this routine runs in SINGLE precision, and that is not cosmetic.**
49
+ Established 2026-09-12 by ``gdl_oracle/run_soda2_sample_area_bank.py``, GDL
50
+ running the unmodified source. Two separate things were measured, and they
51
+ cost very different amounts:
52
+
53
+ 1. **The arithmetic is FLOAT.** ``:17-18`` force ``float(diam)`` and
54
+ ``float(res)``, and every literal in the chain (``1e6``, ``2.0``, ``1.0e4``,
55
+ ``1e-12``) is a bare decimal, which IDL types as FLOAT. Every field this
56
+ routine is fed from ``soda2_probespecs.pro`` is declared ``0.0`` in that
57
+ file's ``base`` structure (``:9-10``), so ``res``, ``armwidth``,
58
+ ``numdiodes``, ``dofconst`` and ``wavelength`` all arrive as FLOAT in
59
+ production. A float64 port disagreed with GDL by **1.4e-7 relative**, which
60
+ is one float32 epsilon and exactly what that reading predicts.
61
+ 2. **The Lawson sentinel at ``:14`` is type-sensitive, and it costs a factor of
62
+ 2.7.** ``IF (wavelength eq 0.785e-6)`` compares against a **FLOAT** literal.
63
+ Fed the same physical wavelength as a DOUBLE, GDL does **not** take the
64
+ branch: ``dofconst`` stays at Knollenberg's 3.0 instead of Lawson's 8.12,
65
+ and every sample area comes out **2.707x** too small. Measured, same
66
+ geometry, only the literal's type changed:
67
+
68
+ ========================== ========== =====================
69
+ bank case dofconst ``sa[0]``
70
+ ========================== ========== =====================
71
+ ``wavelength_float_lawson`` 8.12 6.620126927e-09
72
+ ``wavelength_double_lawson`` 3.0 2.445859853e-09
73
+ ========================== ========== =====================
74
+
75
+ Production takes the FLOAT branch, because probespecs' field is FLOAT. This
76
+ is finding **S1-a**.
77
+
78
+ **How the port models an IDL type without an IDL type system.** ``diam`` and
79
+ ``res`` are narrowed to ``float32`` unconditionally, because the source does
80
+ that itself. Every other numeric input keeps whatever dtype the caller gives
81
+ it, and a plain Python ``float`` is taken as **FLOAT**, since that is what
82
+ every caller in the SODA-2 tree passes. NumPy's promotion rules then reproduce
83
+ IDL's: pass ``np.float64(0.785e-6)`` and the sentinel misses, exactly as GDL
84
+ does. There is no flag for this and there should not be -- a flag would let a
85
+ caller select a precision, where the original lets a caller select a *type* and
86
+ derives the precision from it.
87
+ """
88
+
89
+ from __future__ import annotations
90
+
91
+ from typing import Any
92
+
93
+ import numpy as np
94
+ from numpy.typing import ArrayLike, NDArray
95
+
96
+ __all__ = [
97
+ "EAW_METHODS",
98
+ "UnsupportedSampleVolumeMethod",
99
+ "sample_area",
100
+ ]
101
+
102
+ #: The three effective-array-width methods ``soda2_samplearea.pro``'s CASE
103
+ #: block accepts. Any other value reaches its ``stop``.
104
+ EAW_METHODS = ("reconstruct", "centerin", "allin")
105
+
106
+ #: Knollenberg (1970), the IDL's own attribution at ``:12``. FLOAT, as written.
107
+ _DOFCONST_DEFAULT = np.float32(3.0)
108
+
109
+ #: Lawson (2006), for SPEC probes, applied by the source only when the
110
+ #: wavelength matches this value exactly (``:14``) -- an exact float compare
111
+ #: on a physical constant, preserved as written rather than widened to a
112
+ #: tolerance, since widening it would change which probes take this branch.
113
+ #:
114
+ #: **A float32, deliberately.** ``0.785e-6`` in the IDL is a bare decimal and
115
+ #: therefore FLOAT. Written as ``np.float32`` here so NumPy's own promotion
116
+ #: reproduces IDL's: against a float32 wavelength the comparison happens in
117
+ #: float32 and matches; against a float64 one both widen to float64 and it
118
+ #: does *not*. Measured under GDL -- see the module docstring, finding S1-a.
119
+ #: A plain ``0.785e-6`` here would have made the port take the SPEC branch in
120
+ #: a case where the original does not, by a factor of 2.707.
121
+ _SPEC_WAVELENGTH = np.float32(0.785e-6)
122
+ _DOFCONST_SPEC = np.float32(8.12)
123
+
124
+
125
+ def _F(value: float) -> np.float32:
126
+ """A bare IDL decimal literal, which is FLOAT and not DOUBLE.
127
+
128
+ Spelled out at every site rather than left to NumPy, because a Python
129
+ literal in the same expression would silently promote the whole thing to
130
+ float64 and quietly undo the single precision this routine runs in.
131
+ """
132
+ return np.float32(value)
133
+
134
+
135
+ def _as_idl(value: Any) -> Any:
136
+ """Keep the caller's dtype, treating a plain Python value as IDL FLOAT.
137
+
138
+ IDL derives an expression's precision from its operands, and every field
139
+ ``soda2_probespecs.pro`` feeds this routine is declared ``0.0`` -- FLOAT.
140
+ A caller who genuinely means an IDL DOUBLE passes ``np.float64(...)`` (or
141
+ a float64 array), and NumPy's promotion then reproduces what GDL does with
142
+ a DOUBLE, including missing the Lawson sentinel.
143
+
144
+ A bare Python list is FLOAT for the same reason a bare Python float is:
145
+ ``np.asarray([...])`` would otherwise default to float64 and silently
146
+ promote the whole computation. That is not hypothetical -- it is what the
147
+ ``dof_supplied_*`` bank cases caught in this module on 2026-09-12.
148
+ """
149
+ if isinstance(value, (np.generic, np.ndarray)):
150
+ return value
151
+ if isinstance(value, (list, tuple)):
152
+ return np.asarray(value, dtype=np.float32)
153
+ # Note, recorded because a mutation that does not fire is a finding and not
154
+ # a detail: deleting the branch above breaks nothing on NumPy 2.5, where
155
+ # ``np.float32([...])`` happens to return a float32 *array* rather than
156
+ # raising. The branch stays because that coincidence is not a documented
157
+ # guarantee, and `TheIdlTypeRule` pins the behaviour directly instead of
158
+ # relying on a mutation to guard it.
159
+ return np.float32(value)
160
+
161
+
162
+ class UnsupportedSampleVolumeMethod(ValueError):
163
+ """Raised where ``soda2_samplearea.pro`` reaches its ``stop`` statement.
164
+
165
+ See this module's docstring: IDL's ``stop`` is an interactive debugger
166
+ halt, so this exception is a deliberate divergence, not a reproduction.
167
+ """
168
+
169
+
170
+ def sample_area(
171
+ diam: ArrayLike,
172
+ res: Any,
173
+ armwidth: Any,
174
+ numdiodes: Any,
175
+ eawmethod: str,
176
+ wavelength: Any,
177
+ dofconst: Any = 0.0,
178
+ dof: ArrayLike | None = None,
179
+ ) -> tuple[NDArray[Any], NDArray[Any], NDArray[Any]]:
180
+ """Sample area in m^2, per ``soda2_samplearea.pro``.
181
+
182
+ Returns ``(sa, dof, eff_wid)``. The IDL returns ``sa`` and passes ``dof``
183
+ and ``eff_wid`` back through keyword outputs; a tuple is the Python
184
+ equivalent, and callers that want only the area take ``[0]``.
185
+
186
+ Units, as the IDL's own header states them: ``diam`` in micrometres,
187
+ ``res`` in micrometres, ``armwidth`` in centimetres, ``wavelength`` in
188
+ metres. The returned ``dof`` is in micrometres and ``sa`` in m^2.
189
+
190
+ ``dofconst=0.0`` means "not specified in the original op structure" and
191
+ selects the literature default, exactly as the IDL's ``IF dofconst eq 0``
192
+ does -- zero is a sentinel here, not a value.
193
+
194
+ ``dof=None`` (or an all-zero array) means "compute it", mirroring the
195
+ source's ``IF total(dof) eq 0`` test. Note that test is on the *total*:
196
+ a caller supplying a mixed array of zeros and non-zeros gets the whole
197
+ array kept, not the zeros filled in. Preserved as written.
198
+ """
199
+ if eawmethod not in EAW_METHODS:
200
+ raise UnsupportedSampleVolumeMethod(
201
+ f"Sample volume method not supported: {eawmethod!r}. "
202
+ f"soda2_samplearea.pro accepts {EAW_METHODS}."
203
+ )
204
+
205
+ # `diam=float(diam)` / `res=float(res)` at :17-18. These two narrowings
206
+ # are unconditional in the source -- IDL's `float()` is a cast to single
207
+ # precision, not Python's "make it a real number" -- so they happen here
208
+ # whatever the caller passed, and they are why a float64 caller still gets
209
+ # a single-precision answer.
210
+ diam_arr = np.asarray(diam, dtype=np.float32)
211
+ res_f = np.float32(res)
212
+
213
+ # Everything below keeps the dtype the caller supplied, because IDL does:
214
+ # the type of `wavelength` is the type of the probespecs field it came
215
+ # from. `_as_idl` turns a plain Python float into FLOAT, which is what
216
+ # every caller in the SODA-2 tree passes.
217
+ wl = _as_idl(wavelength)
218
+ arm = _as_idl(armwidth)
219
+ ndiodes = _as_idl(numdiodes)
220
+ dconst: Any = _as_idl(dofconst)
221
+
222
+ if dconst == 0.0:
223
+ dconst = _DOFCONST_DEFAULT
224
+ # `:14` compares against a FLOAT literal. Against a float64 wavelength
225
+ # both widen and this is FALSE even for the same physical value --
226
+ # measured under GDL, finding S1-a. Do not "fix" it with np.isclose.
227
+ if wl == _SPEC_WAVELENGTH:
228
+ dconst = _DOFCONST_SPEC
229
+
230
+ # r^2/lambda, in metres: (diam[um] -> m, halved for radius), squared.
231
+ # `1e6` and `2.0` are bare IDL decimals, hence FLOAT.
232
+ r2overlam = (diam_arr / _F(1e6) / _F(2.0)) ** 2 / wl
233
+
234
+ dof_arr = np.zeros_like(r2overlam) if dof is None else np.asarray(_as_idl(dof))
235
+ if dof_arr.sum() == 0:
236
+ # *2 is for the +/-; 1e6 converts metres to micrometres.
237
+ dof_arr = 2 * dconst * r2overlam * _F(1.0e6)
238
+
239
+ prht = arm * _F(1.0e4) # cm -> um
240
+
241
+ # IDL `dof = dof < prht` -- MIN, not a comparison. Limits depth of field
242
+ # to the physical distance between the probe arms.
243
+ dof_arr = np.minimum(dof_arr, prht)
244
+
245
+ eff_wid: Any
246
+ if eawmethod == "reconstruct":
247
+ # Heymsfield & Parrish (1978) eq. 17, the source's own citation.
248
+ eff_wid = res_f * ndiodes + _F(0.72) * diam_arr
249
+ elif eawmethod == "centerin":
250
+ # A SCALAR, and deliberately: `eff_wid=res*numdiodes` at :28 has no
251
+ # `diam` in it, so IDL produces one number however many particles were
252
+ # passed, and a caller reading the `eff_wid` keyword output gets one
253
+ # number back. Broadcasting into `sa` below is unaffected. Measured
254
+ # under GDL -- the golden's `EW` list is length 1 for every `centerin`
255
+ # case and length n for the other two methods.
256
+ eff_wid = res_f * ndiodes
257
+ else: # "allin" -- the membership check above leaves no other case.
258
+ eff_wid = res_f * (ndiodes - _F(1.0)) - diam_arr
259
+
260
+ # IDL `sa = (...) > 0` -- MAX, not a comparison. Forbids a negative
261
+ # sample area, which `allin` produces once diam exceeds the array width.
262
+ sa = np.maximum(dof_arr * eff_wid * _F(1e-12), 0)
263
+
264
+ return np.asarray(sa), np.asarray(dof_arr), np.asarray(eff_wid)