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,683 @@
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_ncdf.pro`` (462 lines) -- SODA-2's own netCDF
4
+ size-distribution export, ported bug-for-bug.
5
+
6
+ Vendored source, read whole: ``SODA2/abansemer-soda2-afcea15/
7
+ soda2_export_ncdf.pro``, plus ``compute_area.pro`` (40) and
8
+ ``compute_meanar.pro`` (22), which only this export calls. The bulk
9
+ properties reuse Y1's :func:`arrayprobe_soda2.export_ascii.compute_bulk_simple`
10
+ (and through it ``mmdiam``/``mvdiam``/``meandiam``/``unnormalize``);
11
+ ``sfm2hms`` and the ``/REVERSE_OFFSET`` ``HH:MM:SS`` builder reuse
12
+ :mod:`arrayprobe_soda2.pbp_writer`; ``soda2_parsedate``/``julday`` reuse
13
+ :mod:`arrayprobe_soda2.timeconv`. Oracle: ``gdl_oracle/
14
+ run_soda2_export_ncdf_bank.py`` (unmodified ``.pro`` under GDL), golden
15
+ ``tests/data/gdl_soda2_export_ncdf_golden.json``.
16
+
17
+ **Who calls it.** Not the driver: ``soda2_process_2d.pro`` never calls this
18
+ routine (its only exports are the PBP files, ``:688-718``, and
19
+ ``soda2_export_ascii``, ``:722-726``). The one caller in the vendored tree is
20
+ the GUI, ``soda2_export.pro:39-44``: ``restore`` a ``.dat`` SAVE file, then
21
+ ``soda2_export_ncdf, data, outfile=outdir + <basename>.nc``. So the port's
22
+ input is the ``data`` structure that SAVE file holds -- which is
23
+ :class:`arrayprobe_soda2.process_2d.ProcessData`, field for field
24
+ (``soda2_process_2d.pro:678-687``) -- and there is no driver call site to
25
+ wire.
26
+
27
+ **Format.** ``ncdf_create(outfile, /clobber)`` (`:15`) with no
28
+ ``/NETCDF4_FORMAT`` keyword is a classic netCDF-3 file: ``NETCDF3_CLASSIC``,
29
+ no compression, fixed-size ``Time`` dimension.
30
+
31
+ **Reading of IDL semantics the port reproduces (each pinned by a bank case):**
32
+
33
+ - ``data`` is a positional argument, hence by reference: `:22`'s
34
+ ``data = create_struct(data, 'endbins', ...)`` replaces the *caller's*
35
+ variable with one carrying a new ``ENDBINS`` tag, and `:69` writes
36
+ ``'none'`` into the caller's own ``op`` for every empty-string field. The
37
+ port reproduces the second on the caller's ``op`` dict and the first on a
38
+ caller ``dict`` (a :class:`ProcessData` has no slot to add, so there it is
39
+ the returned file, not the object, that carries it).
40
+ - Every ``op`` field becomes a global attribute holding only its **first
41
+ element** (`:70`, ``data.op.(i)[0]``), in the field's own IDL type.
42
+ - Every variable is ``/float`` (`:177`, `:377`), whatever the tag's type.
43
+ - IDL lists dimensions fastest-first, so ``[xdimid, ydimid]`` is the
44
+ netCDF variable ``(Vector<n>, Time)``; the port writes ``arr.T`` for a
45
+ ``[ntimes, nbins]`` array. Never hand-rolled elsewhere -- here only.
46
+ - An attribute value whose IDL type is INT (``size(/TYPE) eq 2``) is
47
+ written ``/LONG`` (NC_INT) (`:179-180`); a global attribute is not
48
+ (`:70`), so an INT ``op`` field is NC_SHORT.
49
+ - `:160` tests ``'INTENDDBINS'`` (double D), so ``INTENDBINS`` never matches
50
+ and falls to ``ELSE``: its dimension is defined (`:40-43`) but no
51
+ variable is ever written on it. Reproduced.
52
+
53
+ **Refused by name** (not reached by any caller in the vendored tree):
54
+ ``pthfile`` (`:392-457`, ``restore`` of an IDL SAVE into the local ``data``
55
+ -- :class:`PthfileNotPorted`); ``noskip=1`` on a non-numeric tag whose
56
+ element count equals ``n_elements(data.time)`` (`:167-170` would
57
+ ``ncdf_varput`` a string or structure -- :class:`NoskipNonNumericNotPorted`).
58
+
59
+ Imports nothing from ``arrayprobe``/``arrayprobe_uiops``.
60
+ """
61
+ from __future__ import annotations
62
+
63
+ import dataclasses
64
+ import datetime as _dt
65
+ from collections.abc import Mapping, MutableMapping
66
+ from pathlib import Path
67
+ from typing import Any
68
+
69
+ import numpy as np
70
+
71
+ from .export_ascii import compute_bulk_simple
72
+ from .pbp_writer import _idl_hms_string, engine_attrs, sfm2hms
73
+ from .pth_readers import pth_suffix
74
+ from .spec_index import julday
75
+ from .timeconv import soda2_parsedate
76
+
77
+ __all__ = [
78
+ "DimensionNameInUse",
79
+ "MinsizeBinstartOutOfRange",
80
+ "NoskipNonNumericNotPorted",
81
+ "PthfileNotPorted",
82
+ "compute_area",
83
+ "compute_meanar",
84
+ "idl_sfm2hms",
85
+ "soda2_export_ncdf",
86
+ "write_run_psd",
87
+ ]
88
+
89
+
90
+ class PthfileNotPorted(NotImplementedError):
91
+ """``soda2_export_ncdf.pro:392-457`` -- ``pthfile`` makes the routine
92
+ ``restore`` an IDL SAVE file into its own local ``data`` (and so, by
93
+ reference, into the caller's). No caller in the vendored tree passes it
94
+ (``soda2_export.pro:43`` does not)."""
95
+
96
+
97
+ class NoskipNonNumericNotPorted(NotImplementedError):
98
+ """``soda2_export_ncdf.pro:167-170`` with ``noskip=1`` on a tag that is a
99
+ string or structure but has ``n_elements(data.time)`` elements: IDL would
100
+ multiply it by ``1.0`` and ``ncdf_varput`` it. Not ported."""
101
+
102
+
103
+ class DimensionNameInUse(RuntimeError):
104
+ """``soda2_export_ncdf.pro:30-42`` names every bin dimension
105
+ ``'Vector'+n_elements(...)``, so two different axes of the same length
106
+ get the same name. The driver's interarrival axis has 40 midbins and 41
107
+ endbins (``soda2_process_2d.pro:53-57``), so a size axis of 39, 40 or 41
108
+ bins collides: measured under GDL (case ``vector_collision``),
109
+ ``NCDF_DIMDEF: (NC_ERROR=-42)`` halts at `:38` with the file open."""
110
+
111
+
112
+ class MinsizeBinstartOutOfRange(IndexError):
113
+ """``soda2_export_ncdf.pro:195-202`` -- ``i100``/``i200``/``i1000`` is
114
+ ``min(where(data.op.endbins ge N))``: ``-1`` when no edge reaches ``N``,
115
+ and equal to ``numbins`` when only the *last* edge does. Either way
116
+ ``compute_bulk_simple`` cannot run: the ``-1`` case halts three frames
117
+ down in ``mmdiam.pro:12`` (``fltarr(0)``, the same halt measured for
118
+ ``soda2_export_ascii``'s ``minsize_above_bins``; SODA-2 register entry S7-b), the
119
+ ``numbins`` case on a ``[binstart:binstop]`` subscript with
120
+ ``low > high``. The port raises here, before calling it; the bank pins
121
+ that GDL halts too."""
122
+
123
+
124
+ # ---------------------------------------------------------------------------
125
+ # Call tree not already ported
126
+ # ---------------------------------------------------------------------------
127
+
128
+ def idl_sfm2hms(sfm: float) -> int:
129
+ """``sfm2hms.pro`` exactly: ``long(sfm)``, then ``10000*hour +
130
+ 100*minute + sec`` with **no** wrap at 86400 s -- 86401 s is
131
+ ``240001``. This name delegates to :func:`arrayprobe_soda2.pbp_writer.sfm2hms`, so the two
132
+ cannot drift apart. `:56-57` feed it
133
+ ``min``/``max(data.time)``, which do cross midnight (bank case
134
+ ``past_midnight``; ``run_soda2_sfm2hms_bank.py``)."""
135
+ return sfm2hms(sfm)
136
+
137
+
138
+ def _idl_total_nan(x: np.ndarray) -> np.float32:
139
+ """IDL ``total(x, /nan)`` on a FLOAT array: a sequential single-precision
140
+ sum in IDL's memory order (first index fastest), NaN skipped.
141
+ ``numpy.nansum`` sums pairwise in C order and differs by an ULP (bank
142
+ cases ``full_driver_shape``/``precip_full``, ``AREA``/``AREA200``)."""
143
+ flat = np.asarray(x, dtype=np.float32).ravel(order="F")
144
+ flat = flat[~np.isnan(flat)]
145
+ return np.cumsum(flat, dtype=np.float32)[-1] if flat.size else np.float32(0.0)
146
+
147
+
148
+ def compute_meanar(spec2d: np.ndarray, armidbins: np.ndarray) -> np.ndarray:
149
+ """``compute_meanar.pro`` (22 lines). ``spec2d`` ``[ntimes, nbins,
150
+ narbins]``; returns FLOAT ``[ntimes, nbins]``, 0 where a size bin holds
151
+ nothing."""
152
+ s = np.asarray(spec2d, dtype=np.float32)
153
+ ar = np.asarray(armidbins, dtype=np.float32)
154
+ meanar = np.zeros(s.shape[:2], dtype=np.float32)
155
+ for i in range(s.shape[0]):
156
+ for j in range(s.shape[1]):
157
+ tot = _idl_total_nan(s[i, j, :])
158
+ if tot > 0:
159
+ meanar[i, j] = _idl_total_nan(s[i, j, :] * ar) / tot
160
+ return meanar
161
+
162
+
163
+ def compute_area(data: Mapping[str, Any], binstart: int = 0) -> dict[str, np.ndarray]:
164
+ """``compute_area.pro`` (40 lines). ``data`` is the upper-cased tag
165
+ mapping :func:`soda2_export_ncdf` builds. Returns ``area`` (FLOAT
166
+ ``[ntimes]``, 1/m) and ``asd`` (FLOAT ``[ntimes, nbins]``)."""
167
+ op = {str(k).lower(): v for k, v in data["OP"].items()}
168
+ spec2d = np.asarray(data["SPEC2D"], dtype=np.float32)
169
+ ntimes, nbins_s, narbins = spec2d.shape
170
+ area = np.zeros(ntimes, dtype=np.float32)
171
+ endbins = np.asarray(op["endbins"], dtype=np.float32)
172
+ numbins = len(endbins) - 1
173
+ midbins = (endbins[0:numbins] + endbins[1:numbins + 1]) / np.float32(2.0)
174
+ arend = np.asarray(_idl_value(op["arendbins"]))
175
+ armidbins = (arend[:-1] + arend[1:]) / 2.0 # the op field's own type
176
+ pi = np.float32(np.pi)
177
+ sa = np.asarray(data["SA"], dtype=np.float32)
178
+ agrid = np.zeros((nbins_s, narbins), dtype=np.float32)
179
+ sagrid = np.zeros((nbins_s, narbins), dtype=np.float32)
180
+ for i in range(nbins_s):
181
+ agrid[i, :] = pi / np.float32(4) * (midbins[i] / np.float32(1.0e6)) ** 2 * armidbins
182
+ sagrid[i, :] = sa[i]
183
+ asd = np.zeros((ntimes, nbins_s), dtype=np.float32)
184
+ tas = np.asarray(data["TAS"])
185
+ act = np.asarray(data["ACTIVETIME"])
186
+ for i in range(ntimes):
187
+ svgrid = sagrid * tas[i] * act[i] # IDL promotion: FLOAT unless tas is DOUBLE
188
+ if tas[i] > 0:
189
+ with np.errstate(divide="ignore", invalid="ignore"):
190
+ fullgrid = agrid[binstart:, :] * spec2d[i, binstart:, :] / svgrid[binstart:, :]
191
+ for j in range(fullgrid.shape[0]):
192
+ asd[i, binstart + j] = _idl_total_nan(fullgrid[j, :])
193
+ area[i] = _idl_total_nan(fullgrid)
194
+ return {"area": area, "asd": asd}
195
+
196
+
197
+ # ---------------------------------------------------------------------------
198
+ # IDL -> netCDF typing
199
+ # ---------------------------------------------------------------------------
200
+
201
+ def _idl_value(value: Any) -> Any:
202
+ """A Python value as the IDL type it stands for. numpy values keep their
203
+ dtype (the caller's own IDL type, as ``pbp_writer``'s B5 convention);
204
+ a Python ``int`` is an IDL integer literal (INT if it fits, else LONG);
205
+ a Python ``float`` is DOUBLE; ``str`` stays a string."""
206
+ if isinstance(value, str | np.str_):
207
+ return str(value)
208
+ if isinstance(value, bool | np.bool_):
209
+ return np.int16(value)
210
+ if isinstance(value, int):
211
+ return np.int16(value) if -32768 <= value <= 32767 else np.int32(value)
212
+ if isinstance(value, float):
213
+ return np.float64(value)
214
+ arr = np.asarray(value)
215
+ if arr.dtype.kind in "US":
216
+ return arr.astype(str)
217
+ if arr.dtype == np.int64:
218
+ # A list of Python ints: an IDL array literal of INT/LONG.
219
+ return arr.astype(np.int16 if np.all(np.abs(arr) <= 32767) else np.int32)
220
+ return arr
221
+
222
+
223
+ def _first(value: Any) -> Any:
224
+ """IDL ``v[0]`` on a scalar or an array."""
225
+ v = _idl_value(value)
226
+ if isinstance(v, str):
227
+ return v
228
+ arr = np.asarray(v)
229
+ return arr.ravel()[0] if arr.ndim else arr[()]
230
+
231
+
232
+ def _put_att(target: Any, name: str, value: Any, *, long_int: bool) -> None:
233
+ """``ncdf_attput``: strings as NC_CHAR; numbers in their own type, INT
234
+ raised to NC_INT when the call carries ``/LONG`` (`:179-180`)."""
235
+ v = _idl_value(value)
236
+ if isinstance(v, str):
237
+ target.setncattr(name, v)
238
+ return
239
+ arr = np.asarray(v)
240
+ if arr.dtype.kind == "U":
241
+ target.setncattr(name, str(arr.ravel()[0]))
242
+ return
243
+ if long_int and arr.dtype == np.int16:
244
+ arr = arr.astype(np.int32)
245
+ target.setncattr(name, arr if arr.ndim else arr[()])
246
+
247
+
248
+ # ---------------------------------------------------------------------------
249
+ # Per-tag tables (`:104-172`, `:248-372`)
250
+ # ---------------------------------------------------------------------------
251
+
252
+ _MAIN_SIMPLE = {
253
+ "SA": ("Sample Area", "m2", "size"),
254
+ "COUNT_ACCEPTED": ("Count Accepted", "#", "time"),
255
+ "TAS": ("True Air speed used", "m/s", "time"),
256
+ "ACTIVETIME": ("Probe activity time", "s", "time"),
257
+ "MIDBINS": ("Size Bin Mid-points", "micrometers", "size"),
258
+ "ENDBINS": ("Size Bin End-points", "micrometers", "sizeend"),
259
+ "INTMIDBINS": ("Interarrival Bin Mid-points", "s", "int"),
260
+ # `:160` spells it 'INTENDDBINS', so the real INTENDBINS tag never matches.
261
+ "INTENDDBINS": ("Interarrival Bin End-points", "s", "intend"),
262
+ }
263
+
264
+ _BULK_SIMPLE: dict[str, tuple[str, str]] = {
265
+ "AREA": ("Projected Particle Area, All Particles", "1/m"),
266
+ "AREA100": ("Projected Particle Area, Particles Larger than 100um in Diameter", "1/m"),
267
+ "AREA200": ("Projected Particle Area, Particles Larger than 200um in Diameter", "1/m"),
268
+ "AREA1000": ("Projected Particle Area, Particles Larger than 1000um in Diameter", "1/m"),
269
+ "MVD": ("Median Volume Diameter, All Particles", "micrometers"),
270
+ "MND": ("Mean Diameter, All Particles", "micrometers"),
271
+ "DMASS": ("Mass-weighted Diameter, All Particles", "micrometers"),
272
+ "NT": ("Total Number Concentration, All Particles", "#/m3"),
273
+ }
274
+ for _n in ("100", "200", "1000"):
275
+ _gt = f"Particles Larger than {_n}um in Diameter"
276
+ _BULK_SIMPLE[f"MVD{_n}"] = (f"Median Volume Diameter, {_gt}", "micrometers")
277
+ _BULK_SIMPLE[f"MND{_n}"] = (f"Mean Diameter, {_gt}", "micrometers")
278
+ _BULK_SIMPLE[f"DMASS{_n}"] = (f"Mass-weighted Diameter, {_gt}", "micrometers")
279
+ _BULK_SIMPLE[f"NT{_n}"] = (f"Total Number Concentration, {_gt}", "#/m3")
280
+
281
+ _LWC = {"LWC": "Liquid Water Content"}
282
+ _IWC = {"IWC": "Ice Water Content"}
283
+ for _n in ("100", "200", "1000"):
284
+ _LWC[f"LWC{_n}"] = f"Liquid Water Content, Particles Larger than {_n}um in Diameter"
285
+ _IWC[f"IWC{_n}"] = f"Ice Water Content, Particles Larger than {_n}um in Diameter"
286
+
287
+
288
+ def _tags(data: Any) -> dict[str, Any]:
289
+ """``tag_names(data)`` with values, in declaration order, upper-cased.
290
+ A :class:`ProcessData` contributes its IDL fields only (``pbp_csv_path``
291
+ is port tooling, not a ``data`` tag)."""
292
+ if dataclasses.is_dataclass(data) and not isinstance(data, type):
293
+ return {f.name.upper(): getattr(data, f.name) for f in dataclasses.fields(data)
294
+ if f.name != "pbp_csv_path"}
295
+ return {str(k).upper(): v for k, v in data.items()}
296
+
297
+
298
+ def _n_elements(v: Any) -> int:
299
+ if isinstance(v, str):
300
+ return 1
301
+ if dataclasses.is_dataclass(v) or isinstance(v, Mapping):
302
+ return 1
303
+ return int(np.asarray(v).size)
304
+
305
+
306
+ def _is_numeric(v: Any) -> bool:
307
+ if isinstance(v, str) or dataclasses.is_dataclass(v) or isinstance(v, Mapping):
308
+ return False
309
+ return np.asarray(v).dtype.kind in "biuf"
310
+
311
+
312
+ def _min_where_ge(endbins: np.ndarray, threshold: float) -> int:
313
+ idx = np.nonzero(endbins >= threshold)[0]
314
+ return int(idx.min()) if idx.size else -1
315
+
316
+
317
+ def _bulk_checked(conc1d: np.ndarray, endbins: np.ndarray, binstart: int,
318
+ line: str) -> dict[str, np.ndarray]:
319
+ numbins = len(endbins) - 1
320
+ if binstart < 0 or binstart > numbins - 1:
321
+ raise MinsizeBinstartOutOfRange(
322
+ f"soda2_export_ncdf.pro:{line}: binstart={binstart} for {numbins} bins "
323
+ f"(endbins up to {float(endbins[-1])}) -- compute_bulk_simple halts")
324
+ return compute_bulk_simple(conc1d, endbins, binstart=binstart)
325
+
326
+
327
+ # ---------------------------------------------------------------------------
328
+ # soda2_export_ncdf
329
+ # ---------------------------------------------------------------------------
330
+
331
+ #: The airspeed record's convention, written as ``arrayprobe_tas_qc_convention``.
332
+ TAS_QC_CONVENTION = "arrayprobe-soda2-tas-qc/1"
333
+
334
+ #: The ``op.pth`` suffixes ``soda2_process_2d.pro:128-172`` reads (``process_2d.py``'s branch);
335
+ #: any other suffix leaves ``got_pth = 0`` and the probe's own airspeed is used.
336
+ _PTH_SUFFIXES = ("dat", "sav", "txt", "csv", "nc")
337
+
338
+
339
+ def _hms_ranges(seconds: list[int]) -> str:
340
+ """Consecutive seconds-from-midnight as ``HHMMSS-HHMMSS`` runs, comma-separated."""
341
+ runs: list[tuple[int, int]] = []
342
+ for s in sorted(set(seconds)):
343
+ if runs and s == runs[-1][1] + 1:
344
+ runs[-1] = (runs[-1][0], s)
345
+ else:
346
+ runs.append((s, s))
347
+ return ", ".join(f"{idl_sfm2hms(a):06d}" if a == b
348
+ else f"{idl_sfm2hms(a):06d}-{idl_sfm2hms(b):06d}" for a, b in runs)
349
+
350
+
351
+ def tas_qc_attrs(tags: Mapping[str, Any], op: Mapping[str, Any]) -> dict[str, Any]:
352
+ """The airspeed data-quality record for one SODA-2 export, as global attributes.
353
+
354
+ Not IDL output: written beside ``arrayprobe_engine``/``arrayprobe_profile`` so the file says
355
+ where its airspeed came from, and which seconds had none. A second whose ``TAS`` is not
356
+ positive gets no concentration (``process_2d.py:1095`` leaves ``conc1d`` at 0), so those
357
+ zeros are missing data, not clear air. No variable changes.
358
+ """
359
+ opl = {str(k).lower(): v for k, v in op.items()}
360
+ pth = str(_first(opl.get("pth", "")) or "")
361
+ fixed = float(_first(opl.get("fixedtas", 0.0)) or 0.0)
362
+ # Case-sensitive, as process_2d's own suffix test is: a ``.CSV`` is not read.
363
+ suffix = pth_suffix(pth)
364
+ if pth and pth != "none" and suffix in _PTH_SUFFIXES:
365
+ source = f"pth file ({suffix})"
366
+ elif pth and pth != "none":
367
+ source = f"probe (op.pth suffix {suffix or 'none'!r} is not read)"
368
+ elif fixed > 0:
369
+ source = f"fixedtas {fixed:g} m/s (a constant, not a measurement)"
370
+ else:
371
+ source = "probe"
372
+ time = np.asarray(tags["TIME"], dtype=np.float64).ravel()
373
+ tas = np.asarray(tags["TAS"], dtype=np.float64).ravel()
374
+ bad = ~(np.isfinite(tas) & (tas > 0))
375
+ missing = [int(t) for t in time[bad]]
376
+ n, total = len(missing), int(time.size)
377
+ return {
378
+ "arrayprobe_tas_qc_convention": TAS_QC_CONVENTION,
379
+ "arrayprobe_tas_source": source,
380
+ "arrayprobe_tas_seconds_total": total,
381
+ "arrayprobe_tas_nonpositive_count": n,
382
+ "arrayprobe_tas_nonpositive_ranges": _hms_ranges(missing) if n else "none",
383
+ "arrayprobe_tas_uncertainty": (
384
+ f"{n} of {total} seconds had no positive airspeed; their concentrations are 0 "
385
+ "because no sample volume could be formed, not because no particle was seen."
386
+ if n else "every second had a positive airspeed"),
387
+ }
388
+
389
+
390
+ def soda2_export_ncdf(
391
+ data: Any,
392
+ outfile: str,
393
+ *,
394
+ pthfile: str | None = None,
395
+ lite: int = 0,
396
+ noskip: int = 0,
397
+ date_created: str | None = None,
398
+ stamp_profile: str | None = None,
399
+ ) -> str:
400
+ """``soda2_export_ncdf.pro`` (462 lines). ``data`` is a
401
+ :class:`~arrayprobe_soda2.process_2d.ProcessData` or a mapping of IDL
402
+ tag name to value in IDL declaration order; ``data['op']``/``data.op``
403
+ is a mapping of ``op`` field to value, types as :func:`_idl_value`
404
+ reads them. ``[ntimes, nbins]`` arrays are row-per-time, as
405
+ ``ProcessData`` holds them. ``date_created`` overrides ``systime()``
406
+ (`:64`, non-deterministic) for tests. Returns ``outfile``."""
407
+ import netCDF4
408
+
409
+ if pthfile is not None:
410
+ raise PthfileNotPorted(
411
+ "soda2_export_ncdf.pro:392-457: pthfile (restore of an IDL SAVE) is not ported")
412
+ lite = int(lite)
413
+ noskip = int(noskip)
414
+
415
+ tags = _tags(data)
416
+ op: MutableMapping[str, Any] = tags["OP"]
417
+ opl = {str(k).lower(): k for k in op} # lower-case -> the caller's own key
418
+ opnames = [str(k).upper() for k in op]
419
+
420
+ def opget(name: str) -> Any:
421
+ return op[opl[name]]
422
+
423
+ time = np.asarray(tags["TIME"])
424
+ ntimes = int(time.size)
425
+
426
+ # `:21-24` -- the caller's `data` gains an ENDBINS tag (by reference).
427
+ if "ENDBINS" in opnames and "ENDBINS" not in tags:
428
+ tags["ENDBINS"] = opget("endbins")
429
+ if isinstance(data, MutableMapping) and not dataclasses.is_dataclass(data):
430
+ data["endbins"] = opget("endbins")
431
+
432
+ Path(outfile).unlink(missing_ok=True) # /clobber
433
+ ds = netCDF4.Dataset(outfile, "w", format="NETCDF3_CLASSIC")
434
+ try:
435
+ ds.createDimension("Time", ntimes) # `:27`
436
+ dimname: dict[str, str] = {"time": "Time"}
437
+
438
+ def dimdef(key: str, n: int, line: str) -> None:
439
+ name = f"Vector{n}"
440
+ if name in ds.dimensions:
441
+ raise DimensionNameInUse(
442
+ f"soda2_export_ncdf.pro:{line}: NCDF_DIMDEF: (NC_ERROR=-42) -- "
443
+ f"dimension {name!r} is already defined")
444
+ dimname[key] = name
445
+ ds.createDimension(name, n)
446
+
447
+ if "ENDBINS" in opnames: # `:28-34`
448
+ ne = _n_elements(opget("endbins"))
449
+ dimdef("size", ne - 1, "31")
450
+ dimdef("sizeend", ne, "33")
451
+ if "INTMIDBINS" in tags: # `:36-39`
452
+ dimdef("int", _n_elements(tags["INTMIDBINS"]), "38")
453
+ if "INTENDBINS" in tags: # `:40-43`
454
+ dimdef("intend", _n_elements(tags["INTENDBINS"]), "42")
455
+ if "ARENDBINS" in tags: # `:45-48` (tests `tags`, reads `data.op`)
456
+ dimdef("ar", _n_elements(opget("arendbins")) - 1, "47")
457
+
458
+ date = soda2_parsedate(str(opget("date")))
459
+ days1970 = int(date.julday) - julday(1, 1, 1970) # `:53`
460
+ flightdate = f"{date.month}/{date.day}/{date.year}"
461
+ starttime = _idl_hms_string(idl_sfm2hms(float(np.min(time))))
462
+ stoptime = _idl_hms_string(idl_sfm2hms(float(np.max(time))))
463
+
464
+ # `:63-71` -- global attributes.
465
+ ds.setncattr("Source", "SODA-2 OAP Processing Software")
466
+ ds.setncattr("DateCreated", date_created if date_created is not None
467
+ else _dt.datetime.now().ctime())
468
+ ds.setncattr("FlightDate", flightdate)
469
+ if "DATE_PROCESSED" in tags:
470
+ ds.setncattr("DateProcessed", str(tags["DATE_PROCESSED"]))
471
+ ds.setncattr("TimeInterval", f"{starttime}-{stoptime}")
472
+ for key, name in zip(list(op.keys()), opnames, strict=True):
473
+ first = _first(op[key])
474
+ if isinstance(first, str) and first == "":
475
+ # `:69` -- written into the caller's own op (by reference).
476
+ v = op[key]
477
+ if isinstance(v, str):
478
+ op[key] = "none"
479
+ else:
480
+ arr = np.asarray(v).astype(object)
481
+ arr.ravel()[0] = "none"
482
+ op[key] = arr.astype(str)
483
+ first = "none"
484
+ _put_att(ds, name, first, long_int=False)
485
+ # In-file provenance (author, 2026-09-24) -- not IDL output; see pbp_writer.engine_attrs.
486
+ for name, value in engine_attrs(stamp_profile).items():
487
+ ds.setncattr(name, value)
488
+ for name, value in tas_qc_attrs(tags, op).items():
489
+ ds.setncattr(name, value)
490
+
491
+ # `:74-91` -- the three time variables.
492
+ v = ds.createVariable("elapsed_time", "f8", ("Time",))
493
+ v.setncattr("long_name", "Elapsed time")
494
+ v.setncattr("units", f"seconds since {date.year}-{date.month}-{date.day} {starttime} +0000")
495
+ vb = ds.createVariable("base_time", "f8", ())
496
+ vb.setncattr("long_name", "Base time")
497
+ vb.setncattr("units", "seconds since 01/01/1970")
498
+ vt = ds.createVariable("time", "f8", ("Time",))
499
+ vt.setncattr("long_name", "Time")
500
+ vt.setncattr("units", "seconds from midnight of start date")
501
+ vt[:] = time
502
+ # `:89` data.time[0] + LONG: IDL keeps a FLOAT time FLOAT (a DOUBLE
503
+ # one DOUBLE), so a FLOAT data.time loses the seconds of base_time.
504
+ t0 = time.ravel()[0]
505
+ base: np.floating[Any]
506
+ if time.dtype == np.float32:
507
+ base = np.float32(t0) + np.float32(days1970 * 86400)
508
+ else:
509
+ base = np.float64(t0) + np.float64(days1970 * 86400)
510
+ vb.assignValue(base)
511
+ v[:] = time - time.ravel()[0]
512
+
513
+ def write_var(tagname: str, dims: tuple[str, ...], atts: list[tuple[str, Any]],
514
+ value: Any) -> None:
515
+ # `:176-188`: reuse a same-named variable if one exists.
516
+ ncdims = tuple(dimname[d] for d in reversed(dims))
517
+ var = ds.variables[tagname] if tagname in ds.variables else \
518
+ ds.createVariable(tagname, "f4", ncdims)
519
+ for aname, aval in atts:
520
+ _put_att(var, aname, aval, long_int=True)
521
+ # `:187` currentdata*1.0 then ncdf_varput into a FLOAT variable:
522
+ # every input type lands as float32 (round-to-nearest).
523
+ arr = np.asarray(value).astype(np.float32)
524
+ var[:] = np.ascontiguousarray(arr.T) if arr.ndim == 2 else arr
525
+
526
+ endbins_raw = _idl_value(opget("endbins")) if "endbins" in opl else None
527
+
528
+ def bin_atts(long_name: str, units: str, *,
529
+ parameterization: str | None = None) -> list[tuple[str, Any]]:
530
+ eb = np.asarray(endbins_raw)
531
+ binwidth = eb[1:] - eb[:-1]
532
+ out: list[tuple[str, Any]] = [("long_name", long_name), ("units", units)]
533
+ if parameterization is not None:
534
+ out.append(("parameterization", parameterization))
535
+ out.append(("Bin_midpoints", _idl_value(tags["MIDBINS"])))
536
+ out.append(("Bin_endpoints", eb))
537
+ out.append(("Bin_width", binwidth))
538
+ out.append(("Bin_units", "micrometers"))
539
+ return out
540
+
541
+ # `:94-190` -- main structure tags.
542
+ dims: tuple[str, ...]
543
+ for tag, value in list(tags.items()):
544
+ if tag in _MAIN_SIMPLE:
545
+ ln, un, dim = _MAIN_SIMPLE[tag]
546
+ dims = (dim,)
547
+ if lite == 1 and len(dims) > 1:
548
+ continue
549
+ write_var(tag, dims, [("long_name", ln), ("units", un)], value)
550
+ elif tag in ("CONC1D", "SPEC1D"):
551
+ if lite == 1:
552
+ continue
553
+ if tag == "CONC1D":
554
+ atts = bin_atts("Particle Concentration Per Size Bin, "
555
+ "Normalized by Bin Width", "#/m4")
556
+ name = "CONCENTRATION"
557
+ else:
558
+ atts = bin_atts("Particle Count Per Size Bin", "#")
559
+ name = "COUNTS"
560
+ write_var(name, ("time", "size"), atts, value)
561
+ elif tag in ("INTSPEC_ALL", "INTSPEC_ACCEPTED"):
562
+ if lite == 1:
563
+ continue
564
+ ieb = _idl_value(tags["INTENDBINS"])
565
+ which = "All Particles" if tag == "INTSPEC_ALL" else "Accepted Particles"
566
+ atts = [("long_name", f"Particle Count Per Interarrival Bin, {which}"),
567
+ ("units", "#"), ("Bin_endpoints", ieb),
568
+ ("Bin_width", np.asarray(ieb)[1:] - np.asarray(ieb)[:-1]),
569
+ ("Bin_units", "seconds")]
570
+ write_var(tag, ("time", "int"), atts, value)
571
+ else: # ELSE, `:164-171`
572
+ if noskip == 1 and _n_elements(value) == ntimes and tag != "TIME":
573
+ if not _is_numeric(value):
574
+ raise NoskipNonNumericNotPorted(
575
+ f"soda2_export_ncdf.pro:167-170: noskip on non-numeric tag {tag}")
576
+ write_var(tag, ("time",),
577
+ [("long_name", "Unknown"), ("units", "Unknown")], value)
578
+
579
+ # `:193-235` -- bulk properties.
580
+ if "ENDBINS" in opnames and float(np.max(np.asarray(opget("endbins")))) > 100:
581
+ conc1d = tags["CONC1D"]
582
+ eb = np.asarray(opget("endbins"), dtype=np.float32)
583
+ bulkall = compute_bulk_simple(conc1d, eb, binstart=0)
584
+ i100 = _min_where_ge(eb, 100)
585
+ bulk100 = _bulk_checked(conc1d, eb, i100, "195-196")
586
+ i200 = _min_where_ge(eb, 200)
587
+ bulk200 = _bulk_checked(conc1d, eb, i200, "197-198")
588
+ got_precip = 0
589
+ if str(opget("probetype")) != "MERGED" and float(_first(opget("res"))) >= 100:
590
+ got_precip = 1
591
+ i1000 = _min_where_ge(eb, 1000)
592
+ bulk1000 = _bulk_checked(conc1d, eb, i1000, "201-202")
593
+ bulk: dict[str, Any] = {k.upper(): v for k, v in bulkall.items()}
594
+ if "SPEC2D_ASPR" in tags:
595
+ arend = np.asarray(_idl_value(opget("arendbins")))
596
+ armid = (arend[:-1] + arend[1:]) / 2.0 # `:205`
597
+ meanar = compute_meanar(tags["SPEC2D"], armid)
598
+ meanaspr = compute_meanar(tags["SPEC2D_ASPR"], armid)
599
+ area = compute_area(tags)
600
+ bulk.update({"AREA": area["area"], "MEANAR": meanar,
601
+ "MEANASPR": meanaspr, "ASD": area["asd"]})
602
+ if got_precip == 0:
603
+ area100 = compute_area(tags, binstart=i100)
604
+ area200 = compute_area(tags, binstart=i200)
605
+ for n, b, a in (("100", bulk100, area100), ("200", bulk200, area200)):
606
+ bulk.update({f"NT{n}": b["nt"], f"MND{n}": b["mnd"], f"MVD{n}": b["mvd"],
607
+ f"DMASS{n}": b["dmass"], f"IWC{n}": b["iwc"],
608
+ f"AREA{n}": a["area"], f"LWC{n}": b["lwc"]})
609
+ else:
610
+ area1000 = compute_area(tags, binstart=i1000)
611
+ bulk.update({"NT1000": bulk1000["nt"], "MND1000": bulk1000["mnd"],
612
+ "MVD1000": bulk1000["mvd"], "DMASS1000": bulk1000["dmass"],
613
+ "IWC1000": bulk1000["iwc"], "AREA1000": area1000["area"],
614
+ "LWC1000": bulk1000["lwc"]})
615
+ else:
616
+ parts = ((("100", bulk100), ("200", bulk200)) if got_precip == 0
617
+ else (("1000", bulk1000),))
618
+ for n, b in parts:
619
+ bulk.update({f"NT{n}": b["nt"], f"MND{n}": b["mnd"], f"MVD{n}": b["mvd"],
620
+ f"DMASS{n}": b["dmass"], f"IWC{n}": b["iwc"], f"LWC{n}": b["lwc"]})
621
+ else:
622
+ bulk = dict(tags) # `:235` -- CDP/FSSP: bulk variables already in data
623
+
624
+ water = int(_first(opget("water")))
625
+ for tag, value in bulk.items(): # `:238-390`
626
+ dims = ("time",)
627
+ if tag in _LWC:
628
+ if water == 0:
629
+ continue
630
+ atts = [("long_name", _LWC[tag]), ("units", "gram/m3")]
631
+ name = tag
632
+ elif tag in _IWC:
633
+ atts = [("long_name", _IWC[tag]), ("units", "gram/m3"),
634
+ ("parameterization", "Brown and Francis 1995")]
635
+ name = tag
636
+ elif tag in _BULK_SIMPLE:
637
+ ln, un = _BULK_SIMPLE[tag]
638
+ atts = [("long_name", ln), ("units", un)]
639
+ name = tag
640
+ elif tag in ("MEANAR", "MEANASPR"):
641
+ word = "Area" if tag == "MEANAR" else "Aspect"
642
+ atts = [("long_name", f"Mean {word} Ratio Per Size Bin"), ("units", "unitless"),
643
+ ("Bin_midpoints", _idl_value(tags["MIDBINS"])),
644
+ ("Bin_endpoints", np.asarray(endbins_raw)),
645
+ ("Bin_units", "micrometers")]
646
+ dims = ("time", "size")
647
+ name = "MEAN_AREARATIO" if tag == "MEANAR" else "MEAN_ASPECTRATIO"
648
+ elif tag == "ASD":
649
+ atts = bin_atts("Projected Area Per Size Bin, Not Normalized by Bin Width", "1/m")
650
+ dims = ("time", "size")
651
+ name = "ASD"
652
+ elif tag == "MSD":
653
+ atts = bin_atts("Calculated Mass Per Size Bin, Not Normalized by Bin Width", "g/m3",
654
+ parameterization="Brown and Francis 1995")
655
+ dims = ("time", "size")
656
+ name = "MSD"
657
+ else:
658
+ continue
659
+ if lite == 1 and len(dims) > 1:
660
+ continue
661
+ write_var(name, dims, atts, value)
662
+ finally:
663
+ ds.close()
664
+ return str(outfile)
665
+
666
+
667
+ def write_run_psd(data: Any, *, outdir: str | None = None,
668
+ date_created: str | None = None) -> str:
669
+ """Write the size-distribution netCDF ``<stem>.nc`` of a finished run.
670
+
671
+ ``data`` is the :class:`~arrayprobe_soda2.process_2d.ProcessData` that
672
+ ``soda2_process_2d`` returns, the struct the IDL driver saves at
673
+ ``soda2_process_2d.pro:729-731``. The file is :func:`soda2_export_ncdf`
674
+ on that struct, unchanged, named as ``soda2_filename.pro`` names the
675
+ SAVE file with ``.nc`` for ``.dat`` -- the PSD file NCAR's pipeline makes
676
+ by restoring the SAVE file and calling ``soda2_export_ncdf, data``.
677
+ ``outdir`` defaults to ``op.outdir``. Returns the path written."""
678
+ from .pbp_writer import pbp_filename
679
+
680
+ op = _tags(data)["OP"]
681
+ lower = {str(k).lower(): v for k, v in op.items()}
682
+ outfile = pbp_filename(op, str(lower["shortname"]), extension=".nc", outdir=outdir)
683
+ return soda2_export_ncdf(data, outfile, date_created=date_created)