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,558 @@
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`` PBP writers.
4
+
5
+ Ports the two on-path per-particle-file writers that ``soda2_process_2d.pro``
6
+ opens before the buffer loop and closes after it: the ASCII/CSV file (W3,
7
+ gated by ``op.particlefile eq 1``) and the per-particle netCDF-4 file (W2,
8
+ gated by ``op.ncdfparticlefile ge 1``). The IDL SAVE file (W1,
9
+ ``save_writer.save_process_data``) and the ASCII PSD export (W4,
10
+ ``export_ascii.soda2_export_ascii``) are ported in their own modules and called
11
+ from ``process_2d``, not here.
12
+
13
+ Provenance: ``SODA2/abansemer-soda2-afcea15/soda2_process_2d.pro`` lines
14
+ 190-354 (setup) and 696-731 (tail); ``soda2_particlesort.pro`` lines 186-298
15
+ (per-buffer body); ``soda2_filename.pro`` (whole file, 24 lines).
16
+ Copyright (C) 2016 UCAR, 3-clause BSD.
17
+
18
+ Imports nothing from ``arrayprobe``/``arrayprobe_uiops`` (separate port,
19
+ own oracle discipline, like every other ``arrayprobe_soda2`` module).
20
+
21
+ **Functions consumed as plain arguments, not a driver object**:
22
+ lane A's driver calls these at three points -- header before the buffer
23
+ loop, body per buffer, close after the concentration block. See
24
+ ``run_with_writers`` below for the three call sites, named for the merge.
25
+
26
+ **Scope:**
27
+ - ``op.ncdfparticlefile == 2`` (particle images: ``:286-306``, ``:264-276``)
28
+ -- ported on the serial path (the SODA-2 particle-image output; a GDL golden is pending);
29
+ the parallel driver raises :class:`PbpImagesNotPorted`, and so does an image
30
+ chunk of fewer than two slices (``:275``, unmeasured).
31
+ - ``op.asciipsdfile == 1`` (W4, ``soda2_export_ascii.pro``) -- ported as
32
+ ``export_ascii.soda2_export_ascii``, called from ``process_2d``.
33
+ :class:`AsciiPsdNotPorted` is kept only so an old import does not break;
34
+ nothing raises it.
35
+ - The IDL SAVE file (W1, ``:729-731``) -- **ported** as
36
+ ``save_writer.save_process_data``, called from ``process_2d``.
37
+ :class:`SaveFileNotPorted` is kept only so an old import does not break;
38
+ nothing raises it (before the SAVE writer nothing did either, so ``savfile=1`` silently
39
+ wrote no ``.dat``).
40
+
41
+ **Findings** (candidates, to verify):
42
+ - S6-i: CSV writes ``x[i].inttime`` (the raw tag) while netCDF writes the
43
+ clamped ``interarrival`` (``soda2_particlesort.pro:198`` vs the CSV
44
+ special-case at ``:293-294``, which falls through to the generic
45
+ ``nw eq 1`` branch at ``:289-290`` for ``inttime`` since it *is* a tag of
46
+ ``x`` -- only ``time`` and ``rejectionflag`` are not).
47
+ - S6-k: ``.pbp.nc``'s ``rejectionflag`` is declared ``/byte`` (netCDF signed
48
+ ``NC_BYTE``, int8); bit 128 (S5-a) stores as -128 for any reader that
49
+ honours the type. CSV prints the unsigned value (``format='(i0)'`` on the
50
+ raw ``uint8``).
51
+ """
52
+ from __future__ import annotations
53
+
54
+ import datetime as _dt
55
+ from collections.abc import Mapping
56
+ from pathlib import Path
57
+ from typing import IO, Any
58
+
59
+ import numpy as np
60
+
61
+ __all__ = [
62
+ "PBPPROPS",
63
+ "AsciiPsdNotPorted",
64
+ "PbpImagesNotPorted",
65
+ "SaveFileNotPorted",
66
+ "sfm2hms",
67
+ "pbp_filename",
68
+ "open_pbp_csv",
69
+ "write_pbp_csv_buffer",
70
+ "open_pbp_ncdf",
71
+ "write_pbp_ncdf_buffer",
72
+ "write_pbp_ncdf_images",
73
+ "PBP_IMAGE_INDEX_VARS",
74
+ "close_pbp_ncdf",
75
+ ]
76
+
77
+
78
+ class PbpImagesNotPorted(NotImplementedError):
79
+ """A particle-image case (``op.ncdfparticlefile == 2``) still refused: the
80
+ parallel driver and unmeasured chunk shapes. The serial path is ported
81
+ (``soda2_process_2d.pro:286-306``, ``:546-553``,
82
+ ``soda2_particlesort.pro:264-276``; the particle-image output)."""
83
+
84
+
85
+ class AsciiPsdNotPorted(NotImplementedError):
86
+ """``op.asciipsdfile == 1`` (``soda2_export_ascii.pro``) lies outside this module; its
87
+ port is :mod:`arrayprobe_soda2.export_ascii`."""
88
+
89
+
90
+ class SaveFileNotPorted(NotImplementedError):
91
+ """Retired: the IDL SAVE file (``soda2_process_2d.pro:729-731``) is written by
92
+ ``save_writer.save_process_data``. Kept for import compatibility only;
93
+ nothing raises it."""
94
+
95
+
96
+ #: ``soda2_process_2d.pro:202-238`` -- ``[varname, longname, unit, datatype,
97
+ #: ascii_format]``, transcribed verbatim (order matters: it is both the
98
+ #: netCDF variable-definition order and the CSV column order).
99
+ PBPPROPS: tuple[tuple[str, str, str, str, str], ...] = (
100
+ ("time", "UTC time", "seconds", "double", "f0.5"),
101
+ ("probetime", "Unadjusted probe particle time", "seconds", "double", "f0.5"),
102
+ ("buffertime", "Buffer time", "seconds", "double", "f0.5"),
103
+ ("rawtime", "Raw time", "slices or seconds", "double", "f0.5"),
104
+ ("reftime", "Reference time for buffer matching", "seconds", "double", "f0.5"),
105
+ ("inttime", "Interarrival time from previous particle", "seconds", "float", "e0.5"),
106
+ ("diam", "Particle diameter from circle fit. No Poisson spot size corrections applied", "microns", "float", "f0.1"),
107
+ ("xsize", "X-size (across array). No Poisson spot size corrections applied", "microns", "float", "f0.1"),
108
+ ("ysize", "Y-size (along airflow). No Poisson spot size corrections applied", "microns", "float", "f0.1"),
109
+ ("xextent", "Maximum x-size (across array) for a single slice. No Poisson spot size corrections applied", "microns", "float", "f0.1"),
110
+ ("oned", "1-D emulation size. Number of latched pixels. No Poisson spot size corrections applied", "microns", "float", "f0.1"),
111
+ ("twod", "2-D emulation size. Maximum number of shaded pixels on a single slice. No Poisson spot size corrections applied", "microns", "float", "f0.1"),
112
+ ("areasize", "Equivalent area size. No Poisson spot size corrections applied", "microns", "float", "f0.1"),
113
+ ("arearatio", "Area ratio", "unitless", "float", "f0.2"),
114
+ ("arearatiofilled", "Area ratio with particle voids filled", "unitless", "float", "f0.2"),
115
+ ("aspectratio", "Aspect ratio", "unitless", "float", "f0.2"),
116
+ ("area", "Number of shaded pixels", "pixels", "short", "i0"),
117
+ ("areafilled", "Number of shaded pixels including voids", "pixels", "short", "i0"),
118
+ ("perimeterarea", "Number of shaded pixels on particle perimeter", "pixels", "short", "i0"),
119
+ ("area75", "Number of shaded pixels at the 75% (or grey level-3) shading", "pixels", "short", "i0"),
120
+ ("xpos", "X-position of particle center (across array)", "pixels", "float", "f0.2"),
121
+ ("ypos", "Y-position of particle center (along airflow)", "pixels", "float", "f0.2"),
122
+ ("allin", "All-in flag (1=all-in)", "unitless", "byte", "i0"),
123
+ ("centerin", "Center-in flag (1=center-in)", "unitless", "byte", "i0"),
124
+ ("dofflag", "Depth of field flag from probe, if available (1=accepted)", "unitless", "byte", "i0"),
125
+ ("edgetouch", "Edge touch (1=left 2=right 3=both)", "unitless", "byte", "i0"),
126
+ ("sizecorrection", "Size correction factor from Korolev 2007 (D_edge/D0). Use to adjust sizes in this file if necessary", "unitless", "float", "f0.2"),
127
+ ("zd", "Z position from Korolev correction", "microns", "float", "f0.2"),
128
+ ("missed", "Missed particle count", "number", "float", "i0"),
129
+ ("probetas", "True air speed for probe clock", "m/s", "float", "f0.2"),
130
+ ("aircrafttas", "True air speed for aircraft (if available)", "m/s", "float", "f0.2"),
131
+ ("overloadflag", "Overload flag", "boolean", "byte", "i0"),
132
+ ("particlecounter", "Particle counter", "number", "long", "i0"),
133
+ ("orientation", "Particle orientation relative to array axis", "degrees", "float", "f0.2"),
134
+ ("rejectionflag", "Particle rejection code (see soda2_reject.pro for codes)", "unitless", "byte", "i0"),
135
+ ("numregions", "Number of connected regions (blobs) in the particle image, if the KEEP_LARGEST option is enabled", "count", "byte", "i0"),
136
+ ("diodegaps", "Number of unshaded diodes between the first and last shaded diodes", "count", "short", "i0"),
137
+ )
138
+
139
+ #: The two PBP columns that are not tags of ``x`` (``soda2_particlesort.pro:293-294``).
140
+ _NOT_X_TAGS = {"time", "rejectionflag"}
141
+
142
+ _NCDF_TYPE = {"float": "f4", "double": "f8", "byte": "i1", "short": "i2", "long": "i4"}
143
+
144
+
145
+ def sfm2hms(sfm: float) -> int:
146
+ """``sfm2hms.pro``: seconds-from-midnight to an ``HHMMSS`` integer (IDL
147
+ LONG). ``soda2_filename.pro:20``, ``soda2_process_2d.pro:253-254`` and
148
+ ``soda2_export_ncdf.pro:56-57`` all call this; ``timeconv.py`` does not
149
+ carry it, so it is defined here and is the canonical port; moving it
150
+ into ``timeconv.py`` would be a rename, not a re-derivation.
151
+
152
+ **No wrap at midnight**: ``sfm=long(sfm_in)``,
153
+ ``hour=sfm/3600l``, ``minute=(sfm mod 3600)/60``, ``sec=(sfm mod 3600) mod
154
+ 60`` -- nothing reduces modulo 86400, so 86401 s is ``240001`` and 90061 s
155
+ ``250101``. Applying ``% 86400`` (``000001``) would disagree with the source,
156
+ visibly in ``soda2_export_ncdf``'s ``TimeInterval``. IDL's ``long()`` and integer
157
+ ``/`` truncate toward zero and ``mod`` takes the dividend's sign, so a
158
+ negative ``sfm`` gives a negative result (-5 s is ``-5``), unlike
159
+ Python's floor ``divmod``. Every case pinned by
160
+ the GDL bank ``run_soda2_sfm2hms_bank.py`` (not included in this package)."""
161
+ s = int(sfm) # IDL long() truncates toward zero, as int() does
162
+ hour = _idl_div(s, 3600)
163
+ rem = s - 3600 * hour # IDL `sfm mod 3600`: the dividend's sign
164
+ minute = _idl_div(rem, 60)
165
+ sec = rem - 60 * minute
166
+ return 10000 * hour + 100 * minute + sec
167
+
168
+
169
+ def _idl_div(a: int, b: int) -> int:
170
+ """IDL integer ``/``: truncation toward zero (Python's ``//`` floors)."""
171
+ q = abs(a) // abs(b)
172
+ return q if (a >= 0) == (b > 0) else -q
173
+
174
+
175
+ def _idl_six_digit_int(value: int) -> str:
176
+ """IDL format ``(i06)``: zero-padded to width 6, the sign inside the
177
+ width (-5 is ``-00005``), and six asterisks when the value does not fit
178
+ -- measured under GDL for ``sfm2hms`` >= 1000000, i.e. ``starttime`` at
179
+ or past 100 h (``run_soda2_sfm2hms_bank.py``)."""
180
+ text = f"{int(value):06d}"
181
+ return "*" * 6 if len(text) > 6 else text
182
+
183
+
184
+ def _idl_hms_string(hms: int) -> str:
185
+ """``soda2_process_2d.pro:253-256``: ``tb='0000'+strtrim(string(hms),2)``,
186
+ then ``strmid(tb,5,2,/r)+':'+strmid(tb,3,2,/r)+':'+strmid(tb,1,2,/r)``.
187
+
188
+ ``/REVERSE_OFFSET`` counts the *start* from the end of the string (0 = the
189
+ last character) and still reads forward, so the three pieces are
190
+ ``s[-6:-4]``, ``s[-4:-2]``, ``s[-2:]`` -- ``HH:MM:SS`` -- except that a start
191
+ before the string's first character is clamped to it and two characters
192
+ are still taken (measured under GDL: hms 5 -> ``00:00:05``, where a Python
193
+ slice would give ``0:00:05``). Until 2026-09-14 this port read ``/r`` as
194
+ reversing the field order and wrote ``SS:MM:HH``; the whole-driver GDL
195
+ golden caught it."""
196
+ s = "0000" + str(int(hms))
197
+
198
+ def strmid_r(first: int, length: int) -> str:
199
+ start = max(len(s) - 1 - first, 0)
200
+ return s[start:start + length]
201
+
202
+ return f"{strmid_r(5, 2)}:{strmid_r(3, 2)}:{strmid_r(1, 2)}"
203
+
204
+
205
+ def pbp_filename(
206
+ op: Mapping[str, Any],
207
+ suffix: str,
208
+ *,
209
+ extension: str = ".dat",
210
+ outdir: str | None = None,
211
+ ) -> str:
212
+ """``soda2_filename.pro``. ``op`` is a plain mapping of IDL tag name
213
+ (upper- or lower-case, looked up case-insensitively as ``tag_names``
214
+ would present them) to value."""
215
+ lower = {k.lower(): v for k, v in op.items()}
216
+ if outdir is None:
217
+ outdir = str(lower["outdir"])
218
+
219
+ filetag = ""
220
+ if "filetag" in lower and len(str(lower["filetag"])) > 0:
221
+ filetag = "_" + str(lower["filetag"])
222
+
223
+ if "probetype" in lower and lower["probetype"] in ("2DS", "3VCPI", "HVPS4"):
224
+ suffix = suffix + "_" + str(lower["probeid"])
225
+
226
+ hhmmss = _idl_six_digit_int(sfm2hms(float(lower["starttime"]))) # `:20`, form='(i06)'
227
+ return (
228
+ f"{outdir}{str(lower['date']).strip()}_{hhmmss}_{suffix}{filetag}{extension}"
229
+ )
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # W3: ASCII/CSV
234
+ # ---------------------------------------------------------------------------
235
+
236
+ def open_pbp_csv(fn_pbp: str, op: Mapping[str, Any], date: Mapping[str, str]) -> IO[str]:
237
+ """``soda2_process_2d.pro:336-354``. Text mode, ``\\n`` line endings
238
+ (IDL's ``printf`` writes ``\\n``, not the platform default)."""
239
+ f = open(fn_pbp, "w", newline="\n")
240
+ f.write("Source: SODA-2 OAP Processing Software\n")
241
+ f.write(f"Flight Date (mm/dd/yyyy): {date['month']}/{date['day']}/{date['year']}\n")
242
+ f.write(f"Date Processed: {_dt.datetime.now().ctime()}\n")
243
+ f.write("Variable Descriptions: \n")
244
+ # `:350` `string(i+1, format='(4i)')` -- `4` is a REPEAT COUNT (unused,
245
+ # since only one value is printed), not a field width; the field takes
246
+ # the default `I` width for the loop variable's own type. Measured under
247
+ # GDL, R8B (2026-09-14): `i`'s initial value `0` is INT and *stays* INT
248
+ # even though the loop bound `n_elements(tagnames)-1` is LONG (a
249
+ # separately-probed fact -- IDL does not widen the index to the bound's
250
+ # type here), and `string(<INT>, format='(4i)')` right-justifies in a
251
+ # **7-character** field (`' 1'`), not 4.
252
+ # `tests/data/gdl_soda2_pbp_one_buffer_3p.pbp.csv` line 5 is the golden.
253
+ for i, (name, longname, unit, _dtype, _fmt) in enumerate(PBPPROPS):
254
+ f.write(f"{i + 1:7d}. {name}: {longname} [{unit}]\n")
255
+ f.write("-------------------------------------------\n")
256
+ # :353 -- trailing-comma suppression (the "colon" in `(99(a0,:,","))`).
257
+ f.write(",".join(name for name, *_ in PBPPROPS) + "\n")
258
+ return f
259
+
260
+
261
+ def _idl_format_scalar(value: Any, fmt: str) -> str:
262
+ """A small subset of IDL ``format=`` strings used by ``pbpprops[4,*]``:
263
+ ``i0`` (bare integer), ``fN.M``/``f0.M`` (fixed), ``e0.5`` (scientific,
264
+ 5 digits after the point, IDL's minimal-width ``e0.5``)."""
265
+ if fmt == "i0":
266
+ return str(int(value))
267
+ if fmt.startswith("f"):
268
+ _, dec = fmt[1:].split(".")
269
+ return f"{float(value):.{int(dec)}f}"
270
+ if fmt.startswith("e"):
271
+ _, dec = fmt[1:].split(".")
272
+ s = f"{float(value):.{int(dec)}e}"
273
+ mantissa, exp = s.split("e")
274
+ exp_i = int(exp)
275
+ return f"{mantissa}e{'+' if exp_i >= 0 else '-'}{abs(exp_i):02d}"
276
+ raise ValueError(f"unhandled ascii_format {fmt!r}")
277
+
278
+
279
+ def write_pbp_csv_buffer(
280
+ f: IO[str],
281
+ x: Mapping[str, np.ndarray],
282
+ istop: int,
283
+ truetime: np.ndarray,
284
+ rejectionflag: np.ndarray,
285
+ ) -> None:
286
+ """``soda2_particlesort.pro:279-298``. ``time`` and ``rejectionflag``
287
+ are not tags of ``x`` (SODA-2 register entry S6-i notes ``inttime`` IS a tag, so it takes the
288
+ generic branch and prints the raw value, not the clamped ``interarrival``
289
+ netCDF writes)."""
290
+ numparticles = istop + 1
291
+ for i in range(numparticles):
292
+ parts = []
293
+ for name, _longname, _unit, _dtype, fmt in PBPPROPS:
294
+ if name == "rejectionflag":
295
+ parts.append(_idl_format_scalar(int(rejectionflag[i]), "i0"))
296
+ elif name == "time":
297
+ parts.append(_idl_format_scalar(float(truetime[i]), "f0.5"))
298
+ else:
299
+ parts.append(_idl_format_scalar(x[name][i], fmt))
300
+ f.write(",".join(parts) + "\n")
301
+
302
+
303
+ # ---------------------------------------------------------------------------
304
+ # W2: per-particle netCDF-4
305
+ # ---------------------------------------------------------------------------
306
+
307
+ #: The two provenance global attributes every SODA-2 netCDF product carries (author, 2026-09-24; batch 5
308
+ #: item 5): the same names and the same "unstated" value as
309
+ #: ``arrayprobe.provenance.engine_attrs``, spelled here because this package never imports the
310
+ #: port. Not IDL output -- the GDL-golden comparisons exclude both, as they exclude
311
+ #: ``DateCreated``/``DateProcessed``.
312
+ ENGINE_ATTR = "arrayprobe_engine"
313
+ PROFILE_ATTR = "arrayprobe_profile"
314
+ PROFILE_UNSTATED = "unstated"
315
+
316
+
317
+ def engine_attrs(stamp_profile: str | None) -> dict[str, str]:
318
+ """``{arrayprobe_engine: "soda2", arrayprobe_profile: stamp_profile or "unstated"}``.
319
+
320
+ SODA-2 has no fidelity profile: its configuration is the ``op`` structure, already written
321
+ as global attributes. ``stamp_profile`` is the name a driver ran it under, when it had one;
322
+ a library call that names none writes ``"unstated"`` -- never a name inferred from ``op``.
323
+ """
324
+ text = PROFILE_UNSTATED if stamp_profile is None else str(stamp_profile)
325
+ if not text or any(c in text for c in " \r\n"):
326
+ raise ValueError(f"profile {text!r} cannot be carried as a stamp value")
327
+ return {ENGINE_ATTR: "soda2", PROFILE_ATTR: text}
328
+
329
+
330
+ def soda2_stamp_profile(config_path: str | Path) -> str:
331
+ """The ``stamp_profile`` a config-driven SODA-2 run carries: ``config:<file name>``.
332
+
333
+ SODA-2 reads no fidelity profile (``arrayprobe soda2 run`` refuses a ``[fidelity]`` table),
334
+ so the only name a run is made under is its config file's. Whitespace, which a stamp value
335
+ cannot hold (:func:`engine_attrs`), becomes ``_``; the full path stays in the ``.pbp.call``
336
+ sidecar's ``config_path``."""
337
+ name = "_".join(Path(config_path).name.split())
338
+ return f"config:{name}"
339
+
340
+
341
+ def open_pbp_ncdf(
342
+ fn_ncdf: str, op: Mapping[str, Any], date: Mapping[str, str],
343
+ pthdat: Mapping[str, Any] | None = None,
344
+ *,
345
+ stamp_profile: str | None = None,
346
+ ) -> Any:
347
+ """``soda2_process_2d.pro:240-333``, with the ``ncdfparticlefile == 2``
348
+ image variables (`:286-306`). Returns an open
349
+ ``netCDF4.Dataset`` in data mode (IDL's ``ncdf_control,/endef``)."""
350
+ import netCDF4
351
+
352
+ Path(fn_ncdf).unlink(missing_ok=True) # :243 -- file_delete before create; /clobber fails on netCDF-4.
353
+ ds = netCDF4.Dataset(fn_ncdf, "w", format="NETCDF4")
354
+ ds.createDimension("Time", None)
355
+
356
+ lower = {k.lower(): v for k, v in op.items()}
357
+ starttimestr = _idl_hms_string(sfm2hms(float(lower["starttime"])))
358
+ stoptimestr = _idl_hms_string(sfm2hms(float(lower["stoptime"])))
359
+
360
+ ds.Source = "SODA-2 OAP Processing Software"
361
+ ds.FlightDate = f"{date['month']}/{date['day']}/{date['year']}"
362
+ ds.DateProcessed = _dt.datetime.now().ctime()
363
+ ds.TimeInterval = f"{starttimestr}-{stoptimestr}"
364
+
365
+ # B1 (§C.4, measured against the fresh GDL golden): IDL's
366
+ # `tag_names(op)` returns every tag upper-cased, so `:265`'s
367
+ # `ncdf_attput, ncdf_id, tn[i], v, /global` writes upper-case global
368
+ # attribute names whatever case `op`'s literal was declared in. B5: the
369
+ # golden's attribute dtypes are the caller's own IDL types (RATE
370
+ # float32, STARTTIME/STOPTIME float64, ENDBINS an int array, several
371
+ # int16 scalars) -- `np.asarray(value)` on the value as given preserves
372
+ # whatever dtype the caller passed, rather than widening every Python
373
+ # int/float to int64/float64 the way a bare `setattr(ds, name, value)`
374
+ # would.
375
+ for name, value in op.items():
376
+ key = name.upper()
377
+ if isinstance(value, str):
378
+ setattr(ds, key, value if value != "" else "none") # :267
379
+ else:
380
+ setattr(ds, key, np.asarray(value))
381
+ for name, value in engine_attrs(stamp_profile).items(): # in-file provenance: not IDL output
382
+ ds.setncattr(name, value)
383
+
384
+ # Storage settings are what IDL REQUESTS, keyword for keyword (A2
385
+ # layout check, 2026-10-03): every `ncdf_vardef` in
386
+ # `soda2_process_2d.pro:275-330` passes `gzip=` and none passes
387
+ # `/SHUFFLE`, so the shuffle filter is off on every variable. netCDF4-python
388
+ # turns shuffle ON by default for `zlib=True`, so it is pinned off here.
389
+ # GDL honours `/SHUFFLE` when given (the writer bank's own `/shuffle`,
390
+ # `gdl_oracle/run_soda2_pbp_writer_bank.py:213-217`, is not in the IDL
391
+ # source), and the driver golden written through the verbatim source has
392
+ # shuffle off everywhere (`gdl_soda2_pbp_driver_frame_*.pbp.nc`).
393
+ # `tests/test_soda2_pbp_storage_matches_idl.py` asserts this.
394
+ for name, longname, unit, dtype, _fmt in PBPPROPS:
395
+ var = ds.createVariable(name, _NCDF_TYPE[dtype], ("Time",), zlib=True, complevel=5,
396
+ shuffle=False) # :275-279
397
+ var.longname = longname
398
+ var.units = unit
399
+
400
+ ncdfparticlefile = int(lower.get("ncdfparticlefile", 1))
401
+ if ncdfparticlefile == 2:
402
+ # `:286-306` (particle-image output). IDL's `[diodedimid, slicedimid]` is
403
+ # column-major, so the file declares (Slice, Diode) -- the package's
404
+ # slice-first convention; `chunk=[numdiodes, 1024]` likewise reverses.
405
+ # Dimension order and storage settings are read, not yet measured
406
+ # against GDL (a GDL golden will settle them).
407
+ numdiodes = int(lower["numdiodes"])
408
+ ds.createDimension("Diode", None)
409
+ ds.createDimension("Slice", None)
410
+ for vname, longname in PBP_IMAGE_INDEX_VARS:
411
+ v = ds.createVariable(vname, "u4", ("Time",), zlib=True, complevel=5,
412
+ shuffle=False) # :290-299
413
+ v.longname = longname
414
+ v.units = "unitless"
415
+ v = ds.createVariable("image", "u1", ("Slice", "Diode"), zlib=True, complevel=8,
416
+ shuffle=False, chunksizes=(1024, numdiodes)) # :303
417
+ v.longname = "Particle images"
418
+ v.units = "unitless"
419
+
420
+ if pthdat is not None:
421
+ # `:309-330`: `gzip=5`, no `/SHUFFLE`, the same request as the
422
+ # `pbpprops` loop above. (A note here until 2026-10-03 called the
423
+ # `pthdat_extrap` golden's shuffle asymmetry a GDL quirk; it was the
424
+ # writer bank's own `/shuffle` on the `pbpprops` loop, which the IDL
425
+ # source does not pass.)
426
+ pkeys = {k.upper() for k in pthdat}
427
+ if "LAT" in pkeys:
428
+ v = ds.createVariable("lat", "f8", ("Time",), zlib=True, complevel=5, shuffle=False)
429
+ v.longname, v.units = "Latitude", "degrees"
430
+ if "LON" in pkeys:
431
+ v = ds.createVariable("lon", "f8", ("Time",), zlib=True, complevel=5, shuffle=False)
432
+ v.longname, v.units = "Longitude", "degrees"
433
+ if "GALT" in pkeys:
434
+ v = ds.createVariable("alt", "f8", ("Time",), zlib=True, complevel=5, shuffle=False)
435
+ v.longname, v.units = "GPS altitude", "meters"
436
+ if "T" in pkeys:
437
+ v = ds.createVariable("t", "f8", ("Time",), zlib=True, complevel=5, shuffle=False)
438
+ v.longname, v.units = "Temperature", "degrees Celsius"
439
+
440
+ return ds
441
+
442
+
443
+ def write_pbp_ncdf_buffer(
444
+ ds: Any,
445
+ x: Mapping[str, np.ndarray],
446
+ istop: int,
447
+ truetime: np.ndarray,
448
+ interarrival: np.ndarray,
449
+ rejectionflag: np.ndarray,
450
+ ncdf_offset: int,
451
+ ) -> None:
452
+ """``soda2_particlesort.pro:186-261``. ``time`` <- ``truetime``,
453
+ ``inttime`` <- ``interarrival`` (the clamped local, SODA-2 register entry S6-i -- NOT
454
+ ``x['inttime']``, which is what the CSV writer uses); every other
455
+ variable is ``x[name][0:istop]``."""
456
+ numparticles = istop + 1
457
+ sl = slice(ncdf_offset, ncdf_offset + numparticles)
458
+ ds.variables["time"][sl] = truetime[:numparticles]
459
+ ds.variables["inttime"][sl] = interarrival[:numparticles]
460
+ ds.variables["rejectionflag"][sl] = rejectionflag[:numparticles]
461
+ for name, _longname, _unit, _dtype, _fmt in PBPPROPS:
462
+ if name in ("time", "inttime", "rejectionflag"):
463
+ continue
464
+ ds.variables[name][sl] = np.asarray(x[name])[:numparticles]
465
+
466
+
467
+ #: `:290-301` -- the four per-particle image index variables, in definition order.
468
+ PBP_IMAGE_INDEX_VARS: tuple[tuple[str, str], ...] = (
469
+ ("starty", "Index of start slice (y-position) in image array"),
470
+ ("stopy", "Index of stop slice (y-position) in image array"),
471
+ ("startx", "Index of start diode (x-position) in image array"),
472
+ ("stopx", "Index of stop diode (x-position) in image array"),
473
+ )
474
+
475
+
476
+ def write_pbp_ncdf_images(
477
+ ds: Any,
478
+ x: Mapping[str, np.ndarray],
479
+ istop: int,
480
+ image: np.ndarray,
481
+ ncdf_offset: int,
482
+ image_offset: int,
483
+ ) -> None:
484
+ """``soda2_particlesort.pro:264-276`` (``ncdfparticlefile eq 2``).
485
+ ``image`` is this flush's chunk, slice-first ``(nslices, numdiodes)``;
486
+ ``image_offset`` is the driver's ``slices_written``. ``startx`` is zeros
487
+ and ``stopx`` the chunk's diode width less one (`:269-272`)."""
488
+ image = np.asarray(image)
489
+ if image.ndim != 2 or image.shape[0] < 2:
490
+ # `:275` on a one-slice or empty chunk: IDL collapses `image[*,0:0]`
491
+ # to 1-D, and `0:-1` is unmeasured -- refused until GDL measures it.
492
+ raise PbpImagesNotPorted(
493
+ "soda2_particlesort.pro:275 -- image chunk of fewer than two slices, not measured")
494
+ numparticles = istop + 1
495
+ sl = slice(ncdf_offset, ncdf_offset + numparticles)
496
+ ds.variables["starty"][sl] = np.asarray(x["startline"])[:numparticles]
497
+ ds.variables["stopy"][sl] = np.asarray(x["stopline"])[:numparticles]
498
+ ds.variables["startx"][sl] = np.zeros(numparticles, dtype=np.int16)
499
+ ds.variables["stopx"][sl] = np.zeros(numparticles, dtype=np.int16) + (image.shape[1] - 1)
500
+ ds.variables["image"][image_offset:image_offset + image.shape[0], 0:image.shape[1]] = image
501
+
502
+
503
+ def _idl_interpol(v: np.ndarray, x: np.ndarray, xout: np.ndarray) -> np.ndarray:
504
+ """IDL/GDL ``INTERPOL(V, X, XOUT)``, regular linear case (no
505
+ ``/LSQUADRATIC``, ``/QUADRATIC`` or ``/SPLINE``) -- **not** ``np.interp``,
506
+ which clamps outside ``[X[0], X[-1]]``. IDL's own documentation: outside
507
+ the range of ``X``, the two nearest points are extrapolated linearly.
508
+ GDL's own stub (``share/gnudatalanguage/lib/utilities/interpol.pro``,
509
+ read 2026-09-14) sorts ``X`` (and ``V`` with it) when called
510
+ with three arguments and then dispatches to the built-in
511
+ ``GDL_INTERPOL``; the sort is reproduced here (``np.interp`` requires an
512
+ ascending abscissa anyway). Measured against GDL 1.1.2
513
+ (``gdl_oracle/probe_pthdat_hang.py``, ``tests/data/
514
+ gdl_soda2_pbp_writer_golden.json``'s ``pthdat_extrap`` case,
515
+ ``tests/data/gdl_soda2_pbp_pthdat_extrap.pbp.nc``): ``x=[1,2]``,
516
+ ``v=[10,20]`` (lat) evaluated at ``xout=[0.5, 2.5]`` gives ``[5, 25]``,
517
+ the slope of the (only, so nearest) segment carried past both ends.
518
+
519
+ Two points minimum (IDL's ``INTERPOL`` itself needs at least two to
520
+ define a slope); a single-abscissa ``pthdat.time`` is out of scope here,
521
+ as it is for IDL. Duplicate or otherwise degenerate abscissae are not
522
+ explored -- GDL's linear-extrapolation slope computation is a built-in
523
+ (``GDL_INTERPOL``, not a ``.pro`` file), so its behaviour there cannot be
524
+ read, only measured, and no case exercising it has been measured.
525
+ """
526
+ x = np.asarray(x, dtype=np.float64)
527
+ v = np.asarray(v, dtype=np.float64)
528
+ xout = np.asarray(xout, dtype=np.float64)
529
+ order = np.argsort(x)
530
+ xs, vs = x[order], v[order]
531
+ out = np.interp(xout, xs, vs) # correct in-range; clamps at the tails
532
+ if xs.size >= 2:
533
+ below = xout < xs[0]
534
+ if np.any(below):
535
+ slope = (vs[1] - vs[0]) / (xs[1] - xs[0])
536
+ out = np.where(below, vs[0] + slope * (xout - xs[0]), out)
537
+ above = xout > xs[-1]
538
+ if np.any(above):
539
+ slope = (vs[-1] - vs[-2]) / (xs[-1] - xs[-2])
540
+ out = np.where(above, vs[-1] + slope * (xout - xs[-1]), out)
541
+ return out
542
+
543
+
544
+ def close_pbp_ncdf(ds: Any, pthdat: Mapping[str, Any] | None = None) -> None:
545
+ """``soda2_process_2d.pro:696-721`` tail: interpolate PTH variables onto
546
+ the written ``time`` axis, then close, via ``_idl_interpol`` -- IDL's
547
+ ``INTERPOL`` linearly extrapolates outside ``pthdat.time``'s range;
548
+ ``np.interp`` would clamp there instead. Measured under GDL
549
+ (``pthdat_extrap`` golden case)."""
550
+ if pthdat is not None:
551
+ ptime = np.asarray(ds.variables["time"][:])
552
+ pkeys = {k.upper(): k for k in pthdat}
553
+ for pkey, ncname in (("LAT", "lat"), ("LON", "lon"), ("GALT", "alt"), ("T", "t")):
554
+ if pkey in pkeys and ncname in ds.variables:
555
+ src_time = np.asarray(pthdat["time"])
556
+ src_val = np.asarray(pthdat[pkeys[pkey]])
557
+ ds.variables[ncname][:] = _idl_interpol(src_val, src_time, ptime)
558
+ ds.close()