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,732 @@
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_export_ascii.pro`` -- the ASCII particle-size-
4
+ distribution (or counts) export ``soda2_process_2d.pro:722-726`` calls when
5
+ ``op.asciipsdfile eq 1``.
6
+
7
+ Vendored source, read whole: ``SODA2/abansemer-soda2-afcea15/
8
+ soda2_export_ascii.pro`` (158 lines) and its call tree, all pure IDL:
9
+ ``compute_bulk_simple.pro`` (73), ``mmdiam.pro``, ``mvdiam.pro``,
10
+ ``meandiam.pro``, ``unnormalize.pro``. ``soda2_parsedate`` is already ported
11
+ (``timeconv.py``); ``soda2_filename`` is already ported as
12
+ :func:`arrayprobe_soda2.pbp_writer.pbp_filename`. Where this file was measured
13
+ against GDL, the result in a few places corrects the earlier design's
14
+ *derived, not yet measured* guesses.
15
+
16
+
17
+ Imports nothing from ``arrayprobe``/``arrayprobe_uiops`` (separate port, own
18
+ oracle discipline, like every other ``arrayprobe_soda2`` module).
19
+
20
+ **Scope refused by name:**
21
+ - ``1D2D`` housekeeping (`:19-43`) whose ``leftreject``/``rightreject``
22
+ fields are not integer-typed -- raises :class:`OneD2DHousekeepingNotPorted`.
23
+ The integer case is ported and asserted byte-for-byte against the GDL
24
+ golden (``gdl_oracle/run_soda2_export_ascii_1d2d_bank.py``, INT fields);
25
+ ``byte()`` of a float sum is not pinned by any bank case.
26
+ - ``minsize`` above every bin edge (`:14-15`) -- raises :class:`MinsizeOutOfRange`
27
+ naming the line; GDL-bank-verified as a real halt (or corrected here if the
28
+ bank showed otherwise -- see that design record's follow-up section).
29
+
30
+ **Surprises, each mapped to a GDL bank case in ``run_soda2_export_ascii_bank.py``:**
31
+
32
+ 1. ``a``/``b`` are undefined keywords the driver never passes, so
33
+ ``compute_bulk_simple``'s own defaults (0.00294, 1.9) become the values
34
+ the ice-branch header line prints (`:16`, `:106`) -- IDL keyword
35
+ arguments are by reference, so an undefined variable passed as a keyword
36
+ is *defined* by the callee's own default and that definition is visible
37
+ back in the caller. Bank case ``defaults_only``.
38
+ 2. The export mutates the caller's ``data.conc1d`` in place (`:138-139`):
39
+ ``data`` is ``soda2_process_2d.pro``'s own positional PRO argument, hence
40
+ pass-by-reference, so the NaN-to-zero rewrite is visible to whatever the
41
+ driver does with ``data`` afterward (here: nothing further reads it, but
42
+ the side effect is a general finding). This port reproduces
43
+ the mutation on the caller's own array, not a private copy. Bank case
44
+ ``nan_conc_side_effect``.
45
+ 3. ``minsize`` above every bin edge halts -- **measured** (``minsize_above_bins``),
46
+ and not for the reason first guessed: ``iminsize = min(where(endbins ge
47
+ minsize))`` is ``-1``, and IDL's negative indices count from the end, so
48
+ ``endbins[-1]`` and the slice ``(mass*spec)[binstart:binstop]`` with
49
+ ``binstart=-1`` do NOT raise -- they silently collapse to the array's
50
+ *last element only* (a length-1 slice). ``compute_bulk_simple`` then
51
+ calls ``mmdiam`` with a length-1 ``endbins`` slice, and
52
+ ``mmdiam.pro:12``'s ``z=fltarr(n)`` with ``n=n_elements(endbins)-1=0``
53
+ fails: GDL raises "Array dimensions must be greater than 0" there, not
54
+ at the ``endbins[-1]`` access this port first suspected.
55
+ 4. ``data.time`` is DOUBLE, printed with format ``i6`` (`:151`) -- whether
56
+ GDL rounds or truncates the fractional part decides the printed value;
57
+ bank case ``fractional_time``.
58
+ 5. The water branch (`op.water >= 1`) uses ``lwc``/``mvd``; the ice branch
59
+ uses ``iwc``/``dmedianmass`` (``mmdiam``). ``mmdiam``/``mvdiam``
60
+ interpolate on a cumulative array padded with a leading 0
61
+ (``interpol(endbins, [0,z], half)``); a run of empty bins makes ``z``
62
+ flat (repeated values, not strictly increasing) and IDL's ``INTERPOL``
63
+ tie-breaking there is implementation-defined. Bank cases ``ice_default``,
64
+ ``water_1``, ``water_2``, ``gappy_spectrum``.
65
+ 6. ``compute_bulk_simple`` clamps ice mass to 0.91x water mass per bin
66
+ (`:45`) and switches to water outright for ``acoeff > 0.52 and bcoeff ==
67
+ 3.0`` (`:46`) -- silent in the printed header, which always prints the
68
+ nominal ``a``, ``b``. Read-only; a documentation finding if GDL confirms
69
+ the printed header never reflects the substitution.
70
+ 7. ``1D2D`` housekeeping columns (`:19-43`) fire only when ``data`` has a
71
+ ``house`` with two or more fields AND ``probetype == '1D2D'``; a 1D2D
72
+ without one writes no house columns. ``byte(left+right)<1`` wraps the sum
73
+ modulo 256 before the clip, so both edges on at 128+128 reads 0
74
+ (``edge_sum_256``).
75
+ 8. Output formats, each pinned by the bank rather than assumed: ``(500e12.2)``
76
+ and ``(500i12)`` for the row body, ``(i6, 3e12.2, $)`` for the row prefix
77
+ (``$`` suppresses the newline), ``(500f9.2)``, ``(500e9.2)``,
78
+ ``(a6, 500a12)`` for the short-name header line. ``500`` is IDL's *repeat
79
+ count*, not a field width -- more than 500 values wraps onto a second
80
+ line; this port refuses ``numbins > 500`` rather than silently emulating
81
+ the wrap (no probe in this project's scope has that many bins).
82
+
83
+ The ``.conc.1Hz`` naming in the plan's row D is the UND/ADPAA product,
84
+ written by ADPAA, not by any SODA-2 routine
85
+ (``grep -ril "conc.1Hz" SODA2/`` is empty) -- this ``.txt`` is the only
86
+ SODA-2 ASCII PSD writer, so it *is* the port's answer to that row.
87
+ """
88
+ from __future__ import annotations
89
+
90
+ import dataclasses
91
+ from collections.abc import Mapping
92
+ from typing import Any
93
+
94
+ import numpy as np
95
+
96
+ from .pbp_writer import pbp_filename
97
+ from .timeconv import soda2_parsedate
98
+
99
+ __all__ = [
100
+ "MinsizeOutOfRange",
101
+ "OneD2DHousekeepingNotPorted",
102
+ "interpol",
103
+ "unnormalize",
104
+ "mmdiam",
105
+ "mvdiam",
106
+ "meandiam",
107
+ "compute_bulk_simple",
108
+ "soda2_export_ascii",
109
+ ]
110
+
111
+
112
+ class MinsizeOutOfRange(IndexError):
113
+ """``soda2_export_ascii.pro:14-15`` -- no bin edge is ``>= minsize``, so
114
+ ``iminsize = min(where(...))`` is ``-1``. Measured under GDL (case
115
+ ``minsize_above_bins``): this does NOT itself raise (IDL's negative
116
+ index -1 is the last element, a valid access) -- the real halt is one
117
+ level down, in ``mmdiam.pro:12``'s ``z=fltarr(n)`` with ``n=0``, because
118
+ ``binstart=-1`` collapses the ``endbins``/spec slices passed into
119
+ ``mmdiam`` to length 1. This port raises here, before calling
120
+ ``compute_bulk_simple`` at all, rather than reproducing the deeper
121
+ GDL stack -- the *user-visible* outcome (a halt for this input) is the
122
+ same either way, and this port has no ``fltarr(0)``-shaped failure mode
123
+ to reproduce faithfully."""
124
+
125
+
126
+ class OneD2DHousekeepingNotPorted(NotImplementedError):
127
+ """``soda2_export_ascii.pro:37`` -- ``byte(leftreject+rightreject)`` on
128
+ non-integer housekeeping fields: no GDL bank case pins IDL's float-to-byte
129
+ conversion, so this port refuses it rather than guess. Integer fields
130
+ are ported (`:19-43`)."""
131
+
132
+
133
+ def _house_columns(data: Any, probetype: Any, ntimes: int
134
+ ) -> tuple[list[str], list[str], list[np.ndarray]]:
135
+ """``soda2_export_ascii.pro:19-51``: titles, short names and per-row
136
+ integer columns of the housekeeping block (all empty unless ``data``
137
+ has a ``house`` with two or more fields and the probe is ``1D2D``).
138
+ ``house`` is a mapping (field names case-insensitive, as IDL tags)."""
139
+ house = getattr(data, "house", None)
140
+ if house is None:
141
+ return [], [], []
142
+ # `:19` -- `n_elements(tag_names(data.house)) gt 1`: a mapping's keys, or
143
+ # a structure-like object's fields (``process_hk.HouseData``, a dataclass).
144
+ if isinstance(house, Mapping):
145
+ fields = {str(k).lower(): v for k, v in house.items()}
146
+ elif dataclasses.is_dataclass(house):
147
+ fields = {f.name.lower(): getattr(house, f.name)
148
+ for f in dataclasses.fields(house)}
149
+ else:
150
+ fields = {str(k).lower(): v for k, v in vars(house).items()}
151
+ if len(fields) <= 1 or probetype != "1D2D":
152
+ return [], [], []
153
+ h = {k: np.asarray(v) for k, v in fields.items()}
154
+ # `:30-35` -- `bytarr(n)+1`, then mode 2, then mode 3 overriding it.
155
+ probemode = np.ones(ntimes, dtype=np.int64)
156
+ probemode[(h["dofnumreject"] != 0) & (h["dofpercent"] == 0)] = 2
157
+ probemode[h["dofpercent"] != 0] = 3
158
+ left, right = h["leftreject"], h["rightreject"]
159
+ for name, arr in (("leftreject", left), ("rightreject", right)):
160
+ if not np.issubdtype(arr.dtype, np.integer):
161
+ raise OneD2DHousekeepingNotPorted(
162
+ f"soda2_export_ascii.pro:37: byte() of a {arr.dtype} "
163
+ f"house.{name} is not pinned by the GDL bank")
164
+ # `:37` -- byte() keeps the low 8 bits of the integer sum; `<1` clips.
165
+ edgereject = np.minimum((left.astype(np.int64) + right.astype(np.int64)) % 256, 1)
166
+ titles = ["1D2D Probe Mode (1: No Depth of Field Rejections, 2: N75 Count "
167
+ "Rejection, 3: N75/N50 Ratio Rejection)",
168
+ "1D2D Edge-touch Rejection (0:Disabled, 1:Enabled)"]
169
+ return titles, ["ProbeMode", "EdgeReject"], [probemode, edgereject]
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # Call tree
174
+ # ---------------------------------------------------------------------------
175
+
176
+ def interpol(v: np.ndarray, x: np.ndarray,
177
+ xout: float | np.floating | np.ndarray) -> float | np.ndarray:
178
+ """IDL's 3-argument ``INTERPOL(V, X, XOUT)``: linear interpolation that
179
+ **extrapolates** past both ends of ``x`` using the nearest segment's
180
+ slope, rather than clamping (``numpy.interp`` clamps -- do not use it
181
+ here). ``x`` is located by the equivalent of IDL's ``VALUE_LOCATE``,
182
+ clamped to ``[0, n-2]`` so the two endpoint segments serve every
183
+ out-of-range query. Only the *left* extrapolation from a cumulative
184
+ sum's leading ``0`` pad is reachable from :func:`mmdiam`/:func:`mvdiam`
185
+ in this codebase; a run of empty bins makes ``x`` non-strictly-increasing
186
+ (repeated values), where the tie-breaking is implementation-defined and
187
+ pinned by the ``gappy_spectrum`` bank case, not assumed here."""
188
+ v_arr = np.asarray(v, dtype=np.float64)
189
+ x_arr = np.asarray(x, dtype=np.float64)
190
+ scalar_input = np.ndim(xout) == 0
191
+ xout_arr = np.atleast_1d(np.asarray(xout, dtype=np.float64))
192
+ n = len(x_arr)
193
+ idx = np.searchsorted(x_arr, xout_arr, side="right") - 1
194
+ idx = np.clip(idx, 0, n - 2)
195
+ x0, x1 = x_arr[idx], x_arr[idx + 1]
196
+ v0, v1 = v_arr[idx], v_arr[idx + 1]
197
+ denom = x1 - x0
198
+ with np.errstate(divide="ignore", invalid="ignore"):
199
+ result = v0 + (xout_arr - x0) * (v1 - v0) / denom
200
+ return float(result[0]) if scalar_input else result
201
+
202
+
203
+ def _as_idl_float(x: Any) -> np.ndarray:
204
+ """An operand as IDL would hold it: FLOAT/DOUBLE stay as they are, and
205
+ any integer operand meets a FLOAT literal in every expression below, so it
206
+ becomes FLOAT (IDL's INT * FLOAT promotion), never float64."""
207
+ arr = np.asarray(x)
208
+ return arr if np.issubdtype(arr.dtype, np.floating) else arr.astype(np.float32)
209
+
210
+
211
+ def _idl_total(x: np.ndarray, nan: bool = False) -> np.floating:
212
+ """IDL ``total(x)`` (``/nan`` optional) on a 1-D FLOAT or DOUBLE array:
213
+ **sequential** accumulation in the array's own type, first element first.
214
+
215
+ Measured under GDL (``run_soda2_compute_bulk_simple_bank.py``'s
216
+ ``semantics``): ``total([1e8, 1 x16, -1e8])`` on FLOAT is 0.0 of type FLOAT
217
+ -- every ``+1`` is lost against 1e8 -- where a float64 accumulator gives 16
218
+ and ``numpy.sum``'s pairwise float32 sum gives neither. ``numpy.cumsum`` is
219
+ sequential, so its last element is IDL's total. ``/nan`` skips NaN, which
220
+ for a sum is adding nothing."""
221
+ arr = np.asarray(x).ravel()
222
+ if nan:
223
+ arr = arr[~np.isnan(arr)]
224
+ if arr.size == 0:
225
+ return arr.dtype.type(0)
226
+ return np.cumsum(arr, dtype=arr.dtype)[-1]
227
+
228
+
229
+ def _idl_cube(x: np.ndarray) -> np.ndarray:
230
+ """IDL ``x^3`` with an INT exponent on FLOAT: ``(x*x)*x`` in the operand's
231
+ type. Measured under GDL: 0 of 3000 random FLOAT values differ from
232
+ this, 763 differ from ``powf`` (``numpy.power(x, 3)``)."""
233
+ return x * x * x
234
+
235
+
236
+ def _idl_powf(x: np.ndarray, y: float | np.floating[Any]) -> np.ndarray:
237
+ """IDL FLOAT^FLOAT: the double-precision power rounded to FLOAT, the same
238
+ rule as ``_idl_alog10``. numpy's float32 power calls the platform ``powf``,
239
+ which is correctly rounded under the MSVC runtime (where it matched the GDL
240
+ goldens) and not under glibc (one ULP off in ``dmass``/``msd``)."""
241
+ out = np.power(np.asarray(x, dtype=np.float64), np.float64(y))
242
+ return out.astype(np.float32)
243
+
244
+
245
+ def _idl_alog10(x: np.ndarray) -> np.ndarray:
246
+ """IDL ``alog10`` on FLOAT: the double-precision ``log10`` rounded to FLOAT.
247
+ Measured under GDL: 0 of 3000 differ from this, 7 differ from
248
+ numpy's own float32 ``log10``."""
249
+ arr = np.asarray(x)
250
+ if arr.dtype == np.float32:
251
+ with np.errstate(divide="ignore", invalid="ignore"):
252
+ return np.log10(arr.astype(np.float64)).astype(np.float32)
253
+ with np.errstate(divide="ignore", invalid="ignore"):
254
+ return np.log10(arr)
255
+
256
+
257
+ def unnormalize(spectra: np.ndarray, endbins: np.ndarray) -> np.ndarray:
258
+ """``unnormalize.pro`` (whole file, 16 lines). ``spectra`` in m^-4,
259
+ ``endbins`` in um; returns m^-3. 1-D or 2-D (``[ntimes, nbins]``) input,
260
+ same shape out.
261
+
262
+ In IDL's types, not float64: ``spec_un = spectra*0.0`` (`:7`) fixes
263
+ the 2-D result's type to the spectra's own, each row is
264
+ ``(spectra[i,*]*binwidth)/1.0e6`` with ``1.0e6`` a FLOAT literal, and a
265
+ wider row (DOUBLE ``endbins``) is rounded back on assignment. The 1-D
266
+ branch (`:12`) keeps the promoted type."""
267
+ spectra_arr = _as_idl_float(spectra)
268
+ endbins_arr = _as_idl_float(endbins)
269
+ binwidth = endbins_arr[1:] - endbins_arr[:-1]
270
+ if spectra_arr.ndim == 1:
271
+ return spectra_arr * binwidth / np.float32(1.0e6)
272
+ return (spectra_arr * binwidth / np.float32(1.0e6)).astype(spectra_arr.dtype)
273
+
274
+
275
+ def mmdiam(iwc_spec: np.ndarray, endbins: np.ndarray, nan: bool = False) -> np.ndarray:
276
+ """``mmdiam.pro`` (36 lines). ``iwc_spec`` un-normalized mass (g/m3),
277
+ 1-D or ``[ntimes, nbins]``; returns one value per time record. Pads the
278
+ cumulative-mass array with a leading 0 so the first bin is interpolable
279
+ (`:31`).
280
+
281
+ ``tmass`` (`:22`) is a sequential ``total`` in the spectrum's own type;
282
+ ``z`` (`:12`, ``fltarr``) is FLOAT whatever the spectrum's type, each
283
+ ``z[j] = total(iwc_spec[i,0:j])`` (`:23`) -- a sequential prefix sum,
284
+ which is ``cumsum``; ``[0,z]`` is FLOAT; GDL's ``INTERPOL`` computes in
285
+ double and returns FLOAT (measured)."""
286
+ nullvalue = np.nan if nan else 0.0
287
+ spec = np.atleast_2d(_as_idl_float(iwc_spec))
288
+ endbins_arr = _as_idl_float(endbins)
289
+ n = len(endbins_arr) - 1
290
+ ntimes = spec.shape[0]
291
+ mmd = np.zeros(ntimes, dtype=np.float32)
292
+ for i in range(ntimes):
293
+ tmass = _idl_total(spec[i, :])
294
+ z = np.cumsum(spec[i, :n], dtype=spec.dtype).astype(np.float32)
295
+ padded_z = np.concatenate((np.zeros(1, dtype=np.float32), z))
296
+ mmd[i] = interpol(endbins_arr, padded_z, tmass / np.float32(2.0))
297
+ if tmass == 0:
298
+ mmd[i] = nullvalue
299
+ return mmd
300
+
301
+
302
+ def mvdiam(conc_raw: np.ndarray, endbins: np.ndarray, nan: bool = False) -> np.ndarray:
303
+ """``mvdiam.pro`` (32 lines). ``conc_raw`` un-normalized concentration
304
+ (m^-3), ``[ntimes, nbins]``. ``midbins`` here is
305
+ ``(endbins[1:]+endbins[:-1])/2`` -- read directly off ``mvdiam.pro:13``,
306
+ which writes it as ``(endbins[1:*] + endbins)/2.0``, two arrays of
307
+ *different* length (n-1 and n): IDL arithmetic between differently-sized
308
+ arrays silently truncates both operands to the smaller size, using each
309
+ operand's own *first* N elements -- so ``endbins[1:*][i] + endbins[i]``
310
+ for ``i in 0..n-2`` is exactly ``endbins[i+1] + endbins[i]``, the
311
+ ordinary midpoint formula. No IDL bug; just an unusual way to write it.
312
+
313
+ In IDL's types: ``volume=(!pi/6)*midbins^3*conc_raw[i,*]`` (`:19`)
314
+ is ``((!pi/6)*((m*m)*m))*conc`` in FLOAT (``!pi`` is FLOAT, ``^3`` an INT
315
+ exponent), ``tvolume`` a sequential ``total``, ``z`` a FLOAT ``fltarr``
316
+ of sequential prefix sums."""
317
+ nullvalue = np.nan if nan else 0.0
318
+ conc_arr = np.atleast_2d(_as_idl_float(conc_raw))
319
+ endbins_arr = _as_idl_float(endbins)
320
+ midbins = (endbins_arr[1:] + endbins_arr[:-1]) / np.float32(2.0)
321
+ n = len(midbins)
322
+ ntimes = conc_arr.shape[0]
323
+ pi6 = np.float32(np.pi) / np.float32(6)
324
+ mvd = np.zeros(ntimes, dtype=np.float32)
325
+ for i in range(ntimes):
326
+ volume = pi6 * _idl_cube(midbins) * conc_arr[i, :]
327
+ tvolume = _idl_total(volume)
328
+ z = np.cumsum(volume[:n], dtype=volume.dtype).astype(np.float32)
329
+ padded_z = np.concatenate((np.zeros(1, dtype=np.float32), z))
330
+ mvd[i] = interpol(endbins_arr, padded_z, tvolume / np.float32(2.0))
331
+ if tvolume == 0:
332
+ mvd[i] = nullvalue
333
+ return mvd
334
+
335
+
336
+ def meandiam(conc_raw: np.ndarray, midbins: np.ndarray, nan: bool = False,
337
+ minimum: float = 0.0) -> np.ndarray:
338
+ """``meandiam.pro`` (29 lines). ``midbins`` (not ``endbins`` -- the
339
+ source's own ``:16`` guard checks this by comparing lengths and
340
+ ``stop``s otherwise; reproduced as :class:`ValueError`).
341
+
342
+ `:19` in IDL's types: ``total(conc*midbins)/(total(conc) > 0.0001)``,
343
+ both totals sequential in the operands' type, ``0.0001`` a FLOAT literal
344
+ and ``>`` IDL's maximum operator."""
345
+ nullvalue = np.nan if nan else 0.0
346
+ conc_arr = np.atleast_2d(_as_idl_float(conc_raw))
347
+ midbins_arr = _as_idl_float(midbins)
348
+ if len(midbins_arr) != conc_arr.shape[1]:
349
+ raise ValueError(
350
+ "meandiam.pro:16: stop -- Need to enter midbins rather than "
351
+ "endbins to meandiam")
352
+ ntimes = conc_arr.shape[0]
353
+ meand = np.zeros(ntimes, dtype=np.float32)
354
+ for i in range(ntimes):
355
+ total = _idl_total(conc_arr[i, :])
356
+ num = _idl_total(conc_arr[i, :] * midbins_arr)
357
+ meand[i] = num / np.maximum(total, total.dtype.type(np.float32(0.0001)))
358
+ if total == 0:
359
+ meand[i] = nullvalue
360
+ if minimum != 0:
361
+ totals = np.array([_idl_total(row) for row in conc_arr])
362
+ meand[totals < minimum] = nullvalue
363
+ return meand
364
+
365
+
366
+ def compute_bulk_simple(
367
+ conc1d: np.ndarray,
368
+ endbins: np.ndarray,
369
+ *,
370
+ binstart: int | None = None,
371
+ binstop: int | None = None,
372
+ acoeff: float | None = None,
373
+ bcoeff: float | None = None,
374
+ ) -> dict[str, np.ndarray]:
375
+ """``compute_bulk_simple.pro`` (73 lines). ``conc1d`` in m^-4
376
+ ``[ntimes, nbins]`` FLOAT, ``endbins`` in um. Returns a dict of one
377
+ FLOAT32 value (or ``[ntimes, nbins]`` array for ``msd``/``msdnorm``) per
378
+ key, matching the IDL structure's tag names.
379
+
380
+ NaN in ``conc1d`` is zeroed on this function's own working copy
381
+ (`:16-17`). Measured under GDL (bank case ``nan_and_inf``): the
382
+ write reaches the caller through a *bare variable* argument (by
383
+ reference) but not through a structure field (by value), and every
384
+ vendored caller passes a field (``data.conc1d``, ``(*p1).conc1d``), so
385
+ the private copy is the faithful reading.
386
+
387
+ **Arithmetic in IDL's types, bit for bit** (bank
388
+ the GDL bank ``run_soda2_compute_bulk_simple_bank.py`` (dev repository only),
389
+ all fifteen tags of
390
+ twelve cases bit-exact): every ``total`` is a sequential FLOAT sum
391
+ (:func:`_idl_total`), ``^3`` is ``(x*x)*x`` (:func:`_idl_cube`),
392
+ ``alog10`` is double-rounded-to-FLOAT (:func:`_idl_alog10`), and
393
+ ``unnormalize``/``mmdiam``/``mvdiam``/``meandiam`` stay FLOAT. A pairwise float64 sum
394
+ differs from these by 1-2 float32 ULPs. ``acoeff``/``bcoeff`` are held
395
+ FLOAT, as the two export callers' are (``soda2_export_ascii.pro:16``
396
+ passes undefined ``a``/``b``, so the FLOAT defaults at `:7-8` apply;
397
+ ``soda2_export_ncdf.pro:194-202`` passes none). The GUI callers
398
+ (``soda2_browse``/``soda2_compare``) pass widget values of unmeasured
399
+ type; a DOUBLE coefficient would promote the IDL computation to DOUBLE,
400
+ which this port does not model.
401
+ """
402
+ if acoeff is None:
403
+ acoeff = 0.00294
404
+ if bcoeff is None:
405
+ bcoeff = 1.9
406
+ acoeff_f = np.float32(acoeff)
407
+ bcoeff_f = np.float32(bcoeff)
408
+
409
+ endbins_arr = np.asarray(endbins, dtype=np.float32)
410
+ numbins = len(endbins_arr) - 1
411
+ midbins = (endbins_arr[:numbins] + endbins_arr[1:numbins + 1]) / np.float32(2.0)
412
+ binwidth = (endbins_arr[1:numbins + 1] - endbins_arr[:numbins]).astype(np.float32)
413
+
414
+ conc1d_arr = np.array(conc1d, dtype=np.float32, copy=True)
415
+ if conc1d_arr.ndim == 1:
416
+ conc1d_arr = conc1d_arr.reshape(1, -1)
417
+ conc1d_arr[~np.isfinite(conc1d_arr)] = np.float32(0.0)
418
+ num = conc1d_arr.shape[0]
419
+
420
+ if binstart is None:
421
+ binstart = 0
422
+ if binstop is None:
423
+ binstop = conc1d_arr.shape[1] - 1
424
+ sl = slice(binstart, binstop + 1)
425
+
426
+ pi = np.float32(np.pi) # IDL `!pi` is FLOAT (3.1415927), not DOUBLE.
427
+ # `^bcoeff` is FLOAT^FLOAT: the double power rounded to FLOAT (`_idl_powf`;
428
+ # numpy's float32 power is the platform `powf`, which agreed under the MSVC
429
+ # runtime, and is one ULP off under glibc); `^3` at `:44` is an INT
430
+ # exponent, i.e. (x*x)*x, which it does not.
431
+ mass: np.ndarray = acoeff_f * _idl_powf(midbins / np.float32(1.0e4), bcoeff_f)
432
+ mass_lwc = pi / np.float32(6) * _idl_cube(midbins / np.float32(1.0e4))
433
+ mass = np.minimum(mass, mass_lwc * np.float32(0.91)) # `:45`
434
+ if acoeff_f > np.float32(0.52) and bcoeff_f == np.float32(3.0):
435
+ mass = mass_lwc.copy() # `:46` -- silent water switch
436
+ dm6 = (np.float32(6) / pi) ** 2 * mass ** 2 * np.float32(1.0e6)
437
+ third = np.float32(1.0) / np.float32(3.0) # `1.0/3.0`, FLOAT / FLOAT
438
+ midbins_melted = _idl_powf(np.float32(6) / pi * mass, third) * np.float32(1.0e4)
439
+
440
+ iwc = np.zeros(num, dtype=np.float32)
441
+ lwc = np.zeros(num, dtype=np.float32)
442
+ dmass = np.zeros(num, dtype=np.float32)
443
+ dmassw = np.zeros(num, dtype=np.float32)
444
+ dmassmelted = np.zeros(num, dtype=np.float32)
445
+ dmedianmass = np.zeros(num, dtype=np.float32)
446
+ z = np.zeros(num, dtype=np.float32)
447
+ msd = np.zeros_like(conc1d_arr)
448
+ msdnorm = np.zeros_like(conc1d_arr)
449
+
450
+ # Every `total` below is IDL's sequential FLOAT accumulation (`_idl_total`),
451
+ # not numpy's pairwise sum and not float64 -- the 1-2 ULP gap the export bank measured
452
+ # through soda2_export_ncdf's netCDF (bank run_soda2_compute_bulk_simple).
453
+ for i in range(num):
454
+ spec = conc1d_arr[i, :] * binwidth / np.float32(1.0e6)
455
+ iwc[i] = _idl_total((mass * spec)[sl])
456
+ lwc[i] = _idl_total((mass_lwc * spec)[sl])
457
+ z[i] = _idl_total((dm6 * spec)[sl])
458
+ msd[i, :] = mass * spec
459
+ msdnorm[i, :] = mass * spec / (binwidth / np.float32(1.0e6))
460
+ if iwc[i] > 0:
461
+ dmass[i] = _idl_total((mass * spec * midbins)[sl]) / iwc[i]
462
+ dmassmelted[i] = _idl_total((mass * spec * midbins_melted)[sl]) / iwc[i]
463
+ dmedianmass[i] = mmdiam((mass * spec)[sl],
464
+ endbins_arr[binstart:binstop + 2])[0]
465
+ if lwc[i] > 0:
466
+ dmassw[i] = _idl_total((mass_lwc * spec * midbins)[sl]) / lwc[i]
467
+
468
+ u = unnormalize(conc1d_arr, endbins_arr)
469
+ nt = np.array([_idl_total(row, nan=True) for row in u[:, sl]], dtype=u.dtype) # `:66`
470
+ mvd = mvdiam(u[:, sl], endbins_arr[binstart:binstop + 2])
471
+ mnd = meandiam(u[:, sl], midbins[sl])
472
+
473
+ # `:71`: `10*(alog10(z))-7.2` -- INT 10 and the FLOAT literal 7.2 keep FLOAT.
474
+ dbzw = np.float32(10) * _idl_alog10(z)
475
+ dbz = dbzw - np.float32(7.2)
476
+
477
+ return {
478
+ "iwc": iwc, "lwc": lwc, "dmass": dmass, "dmedianmass": dmedianmass,
479
+ "dmassw": dmassw, "dmassmelted": dmassmelted, "dbz": dbz, "dbzw": dbzw,
480
+ "nt": nt, "mvd": mvd, "mnd": mnd, "msd": msd, "msdnorm": msdnorm,
481
+ "massparam": mass, "massparamlwc": mass_lwc,
482
+ }
483
+
484
+
485
+ # ---------------------------------------------------------------------------
486
+ # Format emulation -- one helper per ascii_format code, each pinned by the
487
+ # GDL bank (`run_soda2_export_ascii_bank.py`).
488
+ # ---------------------------------------------------------------------------
489
+
490
+ def _f_format(value: float, width: int, dec: int) -> str:
491
+ """IDL ``fW.D``: fixed-point, width ``W`` (0 = auto), ``D`` decimals."""
492
+ s = f"{float(value):.{dec}f}"
493
+ return s if width == 0 else f"{s:>{width}}"
494
+
495
+
496
+ def _e_format(value: float, width: int, dec: int) -> str:
497
+ """IDL ``eW.D``: scientific notation, sign always shown, exponent at
498
+ least 2 digits (expanding further for extreme magnitudes -- measured on
499
+ the PBP writer's ``tiny_inttime`` case, B8: ``1.00000e-120``, no
500
+ truncation)."""
501
+ s = f"{float(value):.{dec}e}"
502
+ mantissa, exp = s.split("e")
503
+ exp_i = int(exp)
504
+ body = f"{mantissa}e{'+' if exp_i >= 0 else '-'}{abs(exp_i):02d}"
505
+ return body if width == 0 else f"{body:>{width}}"
506
+
507
+
508
+ def _i_format(value: int, width: int) -> str:
509
+ """IDL ``iW``: right-justified integer, width ``W`` (0 = auto)."""
510
+ s = str(int(value))
511
+ return s if width == 0 else f"{s:>{width}}"
512
+
513
+
514
+ def _a_format(value: str, width: int) -> str:
515
+ """IDL ``aW``: right-justified string, width ``W`` (a longer value is
516
+ printed in full, never truncated)."""
517
+ return f"{value:>{width}}"
518
+
519
+
520
+ def _row_values(fmt: str, values: np.ndarray) -> str:
521
+ """A whole ``(500<code>)`` row: IDL's ``500`` is a *repeat count*, not a
522
+ width -- more than 500 values wraps onto a second output line, which
523
+ this port refuses rather than silently emulating (no probe in scope has
524
+ that many bins)."""
525
+ if len(values) > 500:
526
+ raise ValueError(
527
+ f"soda2_export_ascii.pro: numbins={len(values)} exceeds the "
528
+ "'(500...)' format's repeat count; the wrap-to-a-second-line "
529
+ "behaviour is not ported")
530
+ if fmt == "e12.2":
531
+ return "".join(_e_format(v, 12, 2) for v in values)
532
+ if fmt == "i12":
533
+ return "".join(_i_format(int(v), 12) for v in values)
534
+ if fmt == "f9.2":
535
+ return "".join(_f_format(v, 9, 2) for v in values)
536
+ if fmt == "e9.2":
537
+ return "".join(_e_format(v, 9, 2) for v in values)
538
+ raise ValueError(f"unhandled row format {fmt!r}")
539
+
540
+
541
+ # ---------------------------------------------------------------------------
542
+ # soda2_export_ascii
543
+ # ---------------------------------------------------------------------------
544
+
545
+ def soda2_export_ascii(
546
+ data: Any,
547
+ outfile: str | None = None,
548
+ *,
549
+ a: float | None = None,
550
+ b: float | None = None,
551
+ minsize: float | None = None,
552
+ counts: int = 0,
553
+ ) -> str:
554
+ """``soda2_export_ascii.pro`` (158 lines), byte-for-byte. ``data`` is the
555
+ ``ProcessData`` :func:`arrayprobe_soda2.process_2d.soda2_process_2d`
556
+ returns: ``.op`` (a dict, lower-case keys, as elsewhere in this
557
+ package), ``.conc1d``, ``.spec1d``, ``.midbins``, ``.sa``, ``.time``,
558
+ ``.date_processed``.
559
+
560
+ Returns the path written (``outfile`` if given, else the internal
561
+ default naming, `:63` -- not exercised by the driver, which always
562
+ passes ``outfile`` itself, `soda2_process_2d.pro:723-724`)."""
563
+ op: Mapping[str, Any] = data.op
564
+ lower = {k.lower(): v for k, v in op.items()}
565
+
566
+ if minsize is None:
567
+ minsize = 100.0
568
+ if float(lower["res"]) <= 15:
569
+ minsize = 50.0 # `:8-11`
570
+
571
+ endbins = np.asarray(lower["endbins"], dtype=np.float32)
572
+ ge = np.nonzero(endbins >= minsize)[0]
573
+ if ge.size == 0:
574
+ raise MinsizeOutOfRange(
575
+ "soda2_export_ascii.pro:14-15: min(where(endbins ge minsize)) "
576
+ f"is -1 for minsize={minsize} against endbins up to "
577
+ f"{float(endbins[-1])}")
578
+ iminsize = int(ge.min())
579
+ minsizestring = _f_format(float(endbins[iminsize]), 0, 2) # `f0.2`
580
+
581
+ # `:7-8` of compute_bulk_simple.pro -- visible back here because IDL
582
+ # keyword arguments are by reference (surprise 1).
583
+ if a is None:
584
+ a = 0.00294
585
+ if b is None:
586
+ b = 1.9
587
+ bulk100 = compute_bulk_simple(data.conc1d, endbins, binstart=iminsize,
588
+ acoeff=a, bcoeff=b)
589
+
590
+ # `:19-51` -- housekeeping columns, written as `i12` per row (`:153`).
591
+ housetitles, houseshortnames, housedata = _house_columns(
592
+ data, lower.get("probetype"), len(np.asarray(data.time)))
593
+
594
+ if int(counts) == 1:
595
+ longname = "counts"
596
+ description = "CountXXX: Particle counts per size bin [#]"
597
+ else:
598
+ longname = "concentration"
599
+ description = ("ConcXXX: Particle concentration per size bin, "
600
+ "normalized by bin width [#/m4]")
601
+
602
+ if outfile is None:
603
+ outfile = pbp_filename(
604
+ op, str(lower["shortname"]) + "_" + longname.upper(),
605
+ extension=".txt", outdir="") # `:63`
606
+
607
+ date = soda2_parsedate(str(lower["date"]))
608
+
609
+ lines: list[str] = []
610
+ if int(counts) == 1:
611
+ lines.append(f"Particle counts for the {lower['probetype']} probe "
612
+ f"in {lower['project']}")
613
+ else:
614
+ lines.append(f"Particle size distributions for the "
615
+ f"{lower['probetype']} probe in {lower['project']}")
616
+ if date.order == "mdy":
617
+ lines.append(f"Flight date (mm/dd/yyyy): {date.month}/{date.day}/{date.year}")
618
+ if date.order == "ymd":
619
+ lines.append(f"Flight date (yyyy/mm/dd): {date.year}/{date.month}/{date.day}")
620
+ lines.append(f"Processed: {data.date_processed}")
621
+ lines.append(f"Raw data source: {lower['fn']}")
622
+ lines.append(f"Sizing method: {lower['smethod']}")
623
+ if "eawmethod" in lower:
624
+ lines.append(f"Partial particle method: {lower['eawmethod']}")
625
+ if "reconstruct" in lower:
626
+ lines.append("Partial particle reconstruction: " +
627
+ ("off", "on")[int(lower["reconstruct"])])
628
+ if "inttime_reject" in lower:
629
+ lines.append("Shattering correction: " +
630
+ ("off", "on")[int(lower["inttime_reject"])])
631
+ if "timereject" in lower:
632
+ lines.append(f"Shattering correction: {lower['timereject']}")
633
+ lines.append("Liquid water processing: " +
634
+ ("off", "on", "strict")[int(lower["water"])])
635
+ lines.append("")
636
+ lines.append("Bin midpoints (microns):")
637
+ lines.append(_row_values("f9.2", np.asarray(data.midbins, dtype=np.float32)))
638
+ lines.append("Bin endpoints (microns):")
639
+ lines.append(_row_values("f9.2", endbins))
640
+ dofconst = float(lower["dofconst"]) if "dofconst" in lower else 0.0
641
+ doftitle = ("Sample area using a depth of field constant of "
642
+ f"{_f_format(dofconst, 0, 2)} (m^2):")
643
+ if "customdof" in lower and float(np.max(np.asarray(lower["customdof"]))) > 0:
644
+ doftitle = "Sample area (m^2) using a custom depth of field constant:"
645
+ lines.append(doftitle)
646
+ lines.append(_row_values("e9.2", np.asarray(data.sa, dtype=np.float32)))
647
+ lines.append("")
648
+ lines.append("Notes:")
649
+ lines.append(f" All bulk properties are computed using particles "
650
+ f"larger than {minsizestring} microns in size.")
651
+
652
+ water = int(lower["water"])
653
+ if water >= 1:
654
+ if water == 1:
655
+ lines.append(' This file contains "round" particles only, '
656
+ 'with area ratio > 0.5 and diameter < 6mm.')
657
+ if water == 2:
658
+ lines.append(' This file contains "round" particles only, '
659
+ 'with area ratio > 0.7 and diameter < 6mm.')
660
+ lines.append(" The intent is to process liquid drops only, "
661
+ "there may be substantial errors in LWC when ice "
662
+ "particles are also present.")
663
+ masstitle = "LWC: Estimated Liquid Water Content [g/m3]"
664
+ massshortname = "LWC"
665
+ mass = bulk100["lwc"]
666
+ diamtitle = "MVD: Median Volume Diameter [microns]"
667
+ diamshortname = "MVD"
668
+ diam = bulk100["mvd"]
669
+ else:
670
+ lines.append(" Size distributions were processed using ice "
671
+ "rejection criteria.")
672
+ lines.append(" Mass-size parameterization coefficients: a=" +
673
+ _e_format(a, 10, 2) + ", b=" + _f_format(b, 4, 2))
674
+ masstitle = "IWC: Estimated Ice Water Content [g/m3]"
675
+ massshortname = "IWC"
676
+ mass = bulk100["iwc"]
677
+ diamtitle = "MMD: Median Mass-weighted Diameter [microns]"
678
+ diamshortname = "MMD"
679
+ diam = bulk100["dmedianmass"]
680
+ lines.append("")
681
+
682
+ numbins = len(np.asarray(data.midbins))
683
+ shortname_word = "Count" if int(counts) == 1 else "Conc"
684
+ titles = [
685
+ "Time: Time at start of interval [UTC seconds]",
686
+ f"Nt: Total Concentration for Particles with D>{minsizestring}um [#/m3]",
687
+ masstitle, diamtitle, *housetitles, description,
688
+ ]
689
+ shortnames = [
690
+ "Time", "Nt", massshortname, diamshortname, *houseshortnames,
691
+ *[f"{shortname_word}{i + 1:03d}" for i in range(numbins)],
692
+ ]
693
+
694
+ lines.append("Variables:")
695
+ for title in titles:
696
+ lines.append(f" {title}")
697
+ lines.append("")
698
+ lines.append(_a_format(shortnames[0], 6) +
699
+ "".join(_a_format(s, 12) for s in shortnames[1:]))
700
+ lines.append("----------------------------------------------------")
701
+
702
+ nt = np.where(np.isfinite(bulk100["nt"]), bulk100["nt"], 0.0)
703
+ mass = np.where(np.isfinite(mass), mass, 0.0)
704
+ diam = np.where(np.isfinite(diam), diam, 0.0)
705
+
706
+ # `:138-139` -- mutates the CALLER's `data.conc1d` in place (surprise 2):
707
+ # `data` was passed by reference into `soda2_export_ascii`, so any
708
+ # further reader of the same `ProcessData` (e.g. a SAVE file written
709
+ # afterward) sees zeros, not NaN, at these positions.
710
+ conc1d = data.conc1d
711
+ conc1d[~np.isfinite(conc1d)] = 0.0
712
+
713
+ if int(counts) == 1:
714
+ data2write = data.spec1d
715
+ row_fmt = "i12"
716
+ else:
717
+ data2write = conc1d
718
+ row_fmt = "e12.2"
719
+
720
+ time_arr = np.asarray(data.time)
721
+ with open(outfile, "w", newline="\n") as f:
722
+ for line in lines:
723
+ f.write(line + "\n")
724
+ for i in range(len(time_arr)):
725
+ prefix = (_i_format(int(time_arr[i]), 6) +
726
+ _e_format(float(nt[i]), 12, 2) +
727
+ _e_format(float(mass[i]), 12, 2) +
728
+ _e_format(float(diam[i]), 12, 2) +
729
+ "".join(_i_format(int(col[i]), 12) for col in housedata))
730
+ f.write(prefix + _row_values(row_fmt, data2write[i, :]) + "\n")
731
+
732
+ return str(outfile)