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,1333 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """The attributed second output -- a self-describing sibling of a faithful port product.
3
+
4
+ **Author instruction, 2026-09-17, verbatim:** *"you can create a second output with these
5
+ attributes - this will be the final output from our package once we are out of testing/validation -
6
+ and for new products like arm data where file byte comparisons are not needed at all."*
7
+
8
+ **The tension this resolves, and the half that must not move.** ``combine_sizedist.m:202-231``
9
+ defines ten variables and **zero global and zero variable attributes** -- measured, not assumed:
10
+ :func:`arrayprobe.combine._write` is a line-for-line port of that block and writes no
11
+ ``putAtt`` call at all, so ``Bin Midpoints`` reaches a recipient with no stated unit even though
12
+ ``sizeDist.m:1746`` states one for the variable it was copied from. That absence is part of the
13
+ output contract: byte-identity against the archived ORACLES products compares every dimension,
14
+ variable *and attribute* against a MATLAB file that has none, and fifteen validated flights plus the
15
+ whole layer-1 claim rest on that comparison. **Adding metadata to the faithful writer would break
16
+ the reproduction.** So this module never touches it. It opens the faithful file **read-only**,
17
+ copies every value verbatim into a new file beside it, and puts the metadata there.
18
+
19
+ **Why this is not bureaucracy.** This project's central criticism of ARM's own product is that a
20
+ recipient cannot re-derive it -- and *our*
21
+ combined file taken alone has the same property: it carries no engine, no profile, no threshold and
22
+ no reject configuration, because it carries nothing at all. The run's provenance lives in the
23
+ ``.call`` sidecar beside it (``src/arrayprobe/driver/run_flight.py:1855-1861``, "beside it,
24
+ never inside it"), which a recipient does not necessarily receive. This module folds the whole
25
+ sidecar into the file, so the attributed output travels alone and still answers "how was this
26
+ made".
27
+
28
+ **Value-preserving, and that is the property the tests assert.** Every variable is written with its
29
+ source dtype, its source dimension list in the source's own on-disk order, and values compared equal
30
+ by ``np.array_equal(..., equal_nan=True)``. Nothing is rescaled, renamed, reordered or transposed --
31
+ in particular this module takes no view on MATLAB dimension order and hand-rolls no
32
+ transpose (the port never hand-rolls a netCDF axis transpose): a verbatim structural
33
+ copy needs neither.
34
+ A derived quantity (a CF-decodable time coordinate, say) would be a *computed* addition and is
35
+ deliberately not written; see ``docs/developer/ATTRIBUTED_EXPORT.md`` §4 for what that would cost.
36
+
37
+ **No new dependency.** ``netCDF4`` and ``numpy`` are already this package's two hard requirements
38
+ (``pyproject.toml:32-35``). The output is NETCDF4: the NETCDF3_CLASSIC constraint exists to
39
+ match MATLAB's bare ``'clobber'`` default and does not apply to a
40
+ file with no MATLAB counterpart.
41
+
42
+ **ACDD, not CF; CF is not asserted.** The run record is also written under the six
43
+ ACDD-1.3 discovery names (:data:`ACDD_KEYS`: ``Conventions``, ``history``, ``source``,
44
+ ``processing_level``, ``product_version``, ``date_created``), each only where the faithful file
45
+ holds no attribute of that name, so a generic catalogue finds the engine and the stamp without
46
+ knowing the ``arrayprobe_`` prefix. ``Conventions`` claims ACDD-1.3 and this module's own
47
+ convention, never CF. CF is the obvious target and ``arrayprobe_enhancements.cf_export``
48
+ already does the CF work
49
+ for ``sd`` files -- but the port never imports ``enhancements_uiops/`` (enforced by
50
+ ``tests/test_no_enhancement_coupling.py``), and a ``Conventions = "CF-1.x"`` token this module
51
+ cannot verify would be a claim, not a fact: ``Time Vector`` is a MATLAB datenum, which has no
52
+ udunits ``days since <epoch>`` spelling that is correct without changing the value. So the file
53
+ declares its own versioned local convention (:data:`EXPORT_CONVENTION`) and states every
54
+ unit's provenance per variable. Formalising on CF is the author's call --
55
+ ``docs/developer/ATTRIBUTED_EXPORT.md`` §4.
56
+
57
+ **Nothing here is invented.** Every unit is the string ``sizeDist.m`` itself writes for the variable
58
+ the value was copied from, cited at ``file:line`` and re-asserted against
59
+ ``arrayprobe.sizedist._VARS`` from the other side by ``tests/test_attributed_export.py``. A product
60
+ shape this module has no sourced unit table for is **refused by name**, never exported with a
61
+ guessed unit.
62
+ """
63
+
64
+ from __future__ import annotations
65
+
66
+ import argparse
67
+ import dataclasses
68
+ import datetime as _dt
69
+ import hashlib
70
+ import re
71
+ import sys
72
+ from collections.abc import Iterable, Mapping, Sequence
73
+ from pathlib import Path
74
+ from typing import Literal, TypedDict
75
+
76
+ import numpy as np
77
+ from netCDF4 import Dataset
78
+
79
+ from . import ncio
80
+ from .tools.tas_sources import read_qc_sidecar
81
+
82
+ __all__ = [
83
+ "EXPORT_CONVENTION",
84
+ "AttributedExportError",
85
+ "MissingStampError",
86
+ "StampParseError",
87
+ "UnknownProductError",
88
+ "VariableAttributes",
89
+ "ProductShape",
90
+ "COMBINED_SIZEDIST",
91
+ "SHAPES",
92
+ "identify_shape",
93
+ "parse_stamp",
94
+ "parse_reject",
95
+ "parse_tagged_value",
96
+ "default_output_path",
97
+ "global_attributes",
98
+ "shared_attributes",
99
+ "stamp_shared_attributes",
100
+ "storage_options",
101
+ "export",
102
+ "main",
103
+ ]
104
+
105
+ #: This module's own output convention, versioned so a reader can tell which vintage of attribute
106
+ #: names it holds. Deliberately **not** ``CF-1.x``: see the module docstring, and
107
+ #: ``docs/developer/ATTRIBUTED_EXPORT.md`` §4 for why CF is not asserted.
108
+ EXPORT_CONVENTION = "arrayprobe-attributed-1.0"
109
+
110
+ #: Every attribute this module adds carries this prefix, so a reader can separate what the export
111
+ #: asserted from anything the source file already held (today: nothing -- the faithful combined
112
+ #: writer defines no attributes at all). The two exceptions are ``units`` and ``long_name``, which
113
+ #: are the variable attributes a recipient's tooling actually reads, and which are quoted from
114
+ #: ``sizeDist.m`` rather than asserted here.
115
+ ATTR_PREFIX = "arrayprobe_"
116
+
117
+ #: The ``Conventions`` value written when the faithful file states none. ACDD-1.3 is claimed
118
+ #: because the six discovery attributes in :data:`ACDD_KEYS` are written under ACDD's own names;
119
+ #: CF is still not claimed, for the reason the module docstring gives (``Time Vector`` has no
120
+ #: correct udunits spelling without changing its value).
121
+ ACDD_CONVENTIONS = f"ACDD-1.3, {EXPORT_CONVENTION}"
122
+
123
+ #: The unprefixed ACDD/CF global attributes the export adds, each only where the faithful file
124
+ #: does not already carry one under the same name. A name the faithful file does carry is copied
125
+ #: from it verbatim instead, so an attribute the engine wrote is never overwritten.
126
+ ACDD_KEYS = ("Conventions", "history", "source", "processing_level", "product_version",
127
+ "date_created")
128
+
129
+ #: ``src/arrayprobe/driver/run_flight.py:1855-1861``'s sidecar naming: ``<output>.call``.
130
+ CALL_SUFFIX = ".call"
131
+
132
+ #: What :func:`default_output_path` appends. See ``docs/developer/ATTRIBUTED_EXPORT.md``
133
+ #: §3 -- the current layout; it may change in a later release.
134
+ DEFAULT_SUFFIX = ".attributed.nc"
135
+
136
+ #: Analysis-ready encoding (the attributed output is also the cloud-optimised one). zlib
137
+ #: level 4 is the level ``arrayprobe_enhancements.arco_export`` chose by measurement (levels above
138
+ #: it cost time for little size); cited, not imported -- the port never imports
139
+ #: ``enhancements_uiops/``.
140
+ ANALYSIS_READY_COMPLEVEL: Literal[4] = 4
141
+
142
+ #: A dimension longer than this is chunked; a shorter one (a bin axis) is kept whole in each chunk.
143
+ ANALYSIS_READY_WHOLE_DIM = 256
144
+
145
+ #: Chunk length along a long dimension: one hour of the products' 1 Hz seconds, so a reader
146
+ #: pulling one leg of a flight decompresses about an hour of data rather than the whole variable.
147
+ ANALYSIS_READY_CHUNK = 3600
148
+
149
+ #: What the file says about its own encoding, under ``arrayprobe_encoding``.
150
+ ENCODING_ANALYSIS_READY = (
151
+ "analysis-ready: netCDF4/HDF5, every numeric variable zlib-compressed at level "
152
+ f"{ANALYSIS_READY_COMPLEVEL}, the byte-shuffle filter on integer variables only (measured to "
153
+ "hurt float data, arrayprobe_enhancements.arco_export), chunked to at most "
154
+ f"{ANALYSIS_READY_CHUNK} along any dimension longer than {ANALYSIS_READY_WHOLE_DIM} (one hour "
155
+ "of 1 Hz seconds) and whole along shorter ones. Lossless: every value, dtype and dimension "
156
+ "order is the faithful file's, so a chunk can be read over a network without the rest.")
157
+ ENCODING_PLAIN = "plain: netCDF4, contiguous and uncompressed (analysis_ready=False)"
158
+
159
+ #: What a Zarr store written by :func:`export_zarr` says about its own encoding.
160
+ ENCODING_ZARR = (
161
+ "zarr: a Zarr store converted from the analysis-ready netCDF4 export, every numeric variable "
162
+ f"chunked to at most {ANALYSIS_READY_CHUNK} along any dimension longer than "
163
+ f"{ANALYSIS_READY_WHOLE_DIM} (one hour of 1 Hz seconds) and whole along shorter ones, with "
164
+ "zarr's default lossless compressor; every value, dtype, dimension order and attribute is the "
165
+ "netCDF4 export's, and no _FillValue is added.")
166
+
167
+ #: The install extra :func:`export_zarr` needs; named in its error when zarr or xarray is missing.
168
+ ZARR_EXTRA = "zarr"
169
+
170
+ #: What a Parquet directory written by :func:`export_parquet` says about its own encoding.
171
+ ENCODING_PARQUET = (
172
+ "parquet: a directory of Parquet files converted from the netCDF4 export, one file per "
173
+ "distinct dimension tuple in long form (one int64 index column per dimension, values "
174
+ "flattened in C order) and scalars in scalars.parquet; every value, dtype and attribute is "
175
+ "the netCDF4 export's, in a tabular layout rather than the same layout.")
176
+
177
+ #: The install extra :func:`export_parquet` needs; named in its error when pyarrow is missing.
178
+ PARQUET_EXTRA = "parquet"
179
+
180
+ #: ``matlab_compat.datenum(1970, 1, 1)``, measured 2026-09-17 in this environment, not looked up:
181
+ #: a ``Time Vector`` value ``v`` is ``(v - 719529.0) * 86400`` seconds since 1970-01-01T00:00:00Z.
182
+ #: Written into the file so a recipient can convert without knowing MATLAB's calendar, and asserted
183
+ #: against :func:`arrayprobe.matlab_compat.datenum` itself -- a different place -- by the tests.
184
+ DATENUM_UNIX_EPOCH_DAYS = 719529.0
185
+
186
+
187
+ class AttributedExportError(RuntimeError):
188
+ """Base class for every refusal this module raises."""
189
+
190
+
191
+ class MissingStampError(AttributedExportError):
192
+ """The faithful file carries no ``.call`` sidecar, so its configuration is unknown.
193
+
194
+ Refused rather than exported with the provenance block left blank, for exactly the reason
195
+ ``scripts/run_flight.py``'s :class:`UnverifiableProvenance` refuses an unstamped input: a file
196
+ that *looks* attributed but states nothing about how it was made is worse than no file, because
197
+ a reader cannot tell the difference. ``accept_unstamped=True`` overrides, and then the export
198
+ says so in ``arrayprobe_call_stamp`` rather than staying silent about it.
199
+ """
200
+
201
+
202
+ class StampParseError(AttributedExportError, ValueError):
203
+ """A ``.call`` line that does not parse as ``key=value`` pairs."""
204
+
205
+
206
+ class UnknownProductError(AttributedExportError, ValueError):
207
+ """A netCDF file whose variables match no :data:`SHAPES` entry.
208
+
209
+ Refused rather than copied with guessed units. Adding a shape means sourcing each variable's
210
+ unit from the MATLAB that writes it, at ``file:line`` -- see :data:`COMBINED_SIZEDIST`.
211
+ """
212
+
213
+
214
+ @dataclasses.dataclass(frozen=True)
215
+ class VariableAttributes:
216
+ """One variable's attributes, and where each came from.
217
+
218
+ ``units`` is a udunits-legal spelling of what the value *is*. ``source_units`` is the string
219
+ ``sizeDist.m`` itself writes for the variable this one was copied from, kept verbatim where it
220
+ differs from ``units`` -- the string is the thing under suspicion (the same reason
221
+ ``arrayprobe_enhancements.cf_export`` keeps ``arrayprobe_source_units``), and dropping it would
222
+ hide the discrepancy rather than record it. ``basis`` says how the unit was established:
223
+ *read* (quoted from a cited line) or *derived* (computed from cited lines, with the arithmetic
224
+ shown).
225
+ """
226
+
227
+ units: str
228
+ long_name: str
229
+ basis: str
230
+ source_units: str | None = None
231
+
232
+
233
+ @dataclasses.dataclass(frozen=True)
234
+ class ProductShape:
235
+ """One recognised faithful-product shape and its sourced attribute table."""
236
+
237
+ name: str
238
+ writer: str
239
+ """The MATLAB block that writes this product, ``file:line``."""
240
+ variables: Mapping[str, VariableAttributes]
241
+ time_convention: str = ""
242
+ """How this shape's time variable is encoded, written as ``arrayprobe_time_convention``."""
243
+ missing_value_convention: str = ""
244
+ """How this shape marks a missing value, written as ``arrayprobe_missing_value_convention``."""
245
+
246
+ def matches(self, names: Iterable[str]) -> bool:
247
+ """Whether ``names`` is exactly this shape's variable set.
248
+
249
+ Set equality, not a subset test: a file holding a variable this shape has no sourced unit
250
+ for must be refused, not exported with that one variable silently unlabelled.
251
+ """
252
+ return set(names) == set(self.variables)
253
+
254
+
255
+ # Named by file and lineage, never by a repository path: these strings are written into every
256
+ # attributed file, and no user's install holds the source tree they were read in.
257
+ _UIOOPS_SD = "ORACLES-variant sizeDist.m"
258
+ _COMBINE = "ORACLES-variant combine_sizedist.m"
259
+
260
+ #: The ten variables ``combine_sizedist.m:202-231`` writes (``arrayprobe.combine._write``), each
261
+ #: with the unit of the ``sd`` variable it is built from.
262
+ #:
263
+ #: **Every row is sourced, none is guessed.** ``sizeDist.m``'s own
264
+ #: ``netcdf.putAtt(...,'units',...)`` lines were read directly in the ORACLES-variant ``sizeDist.m``
265
+ #: (the tree that processed the real ORACLES products), and
266
+ #: the variable-to-variable correspondence is ``arrayprobe.combine._READ_VARS`` /
267
+ #: ``MATLAB_VARID``, itself pinned against the MATLAB's hard-coded ``netcdf.getVar`` indices by
268
+ #: ``tests/test_combine.py``.
269
+ COMBINED_SIZEDIST: dict[str, VariableAttributes] = {
270
+ "Time Vector": VariableAttributes(
271
+ units="days",
272
+ long_name="MATLAB datenum time vector",
273
+ basis=(
274
+ "derived. The sd `time` this is built from is HHMMSS (sizeDist.m:1732), but "
275
+ "combine_sizedist.m:95-120 converts it to a MATLAB datenum in days "
276
+ "(arrayprobe.combine:214-223: `datenum(year, month, day) + time_of_day`), so the "
277
+ "source unit string does not describe this variable. Measured in this environment: "
278
+ f"matlab_compat.datenum(1970,1,1) == {DATENUM_UNIX_EPOCH_DAYS!r}; see the global "
279
+ "attribute arrayprobe_datenum_unix_epoch_days for the conversion."
280
+ ),
281
+ source_units="HHMMSS (sd `time`; NOT this variable -- see basis)",
282
+ ),
283
+ "Bin Minimum": VariableAttributes(
284
+ units="mm", long_name="bin minimum size",
285
+ basis=f"read. {_UIOOPS_SD}:1736 'millimeter', on sd `bin_min`, copied unchanged by "
286
+ f"{_COMBINE}:62-65 (arrayprobe.combine:162).",
287
+ source_units="millimeter"),
288
+ "Bin Maximum": VariableAttributes(
289
+ units="mm", long_name="bin maximum size",
290
+ basis=f"read. {_UIOOPS_SD}:1741 'millimeter', on sd `bin_max`, copied unchanged by "
291
+ f"{_COMBINE}:62-65 (arrayprobe.combine:163).",
292
+ source_units="millimeter"),
293
+ "Bin Midpoints": VariableAttributes(
294
+ units="mm", long_name="bin midpoint size",
295
+ basis=f"read. {_UIOOPS_SD}:1746 'millimeter', on sd `bin_mid`, copied unchanged by "
296
+ f"{_COMBINE}:62-65 (arrayprobe.combine:164). This is the variable whose missing unit "
297
+ f"in the faithful file is the reason this attributed export exists.",
298
+ source_units="millimeter"),
299
+ "Bin Width": VariableAttributes(
300
+ units="mm", long_name="bin width",
301
+ basis=f"read. {_UIOOPS_SD}:1751 'millimeter', on sd `bin_dD`, copied unchanged by "
302
+ f"{_COMBINE}:62-65 (arrayprobe.combine:165).",
303
+ source_units="millimeter"),
304
+ "Mean Area Ratio": VariableAttributes(
305
+ units="1", long_name="mean area ratio per size bin",
306
+ basis=f"read. {_UIOOPS_SD}:1834 '1', on sd `mean_area_ratio` (varid21), concatenated "
307
+ f"unchanged by {_COMBINE}:70-71 (arrayprobe.combine:178).",
308
+ source_units="1"),
309
+ "Counts": VariableAttributes(
310
+ units="1", long_name="accepted particle count per size bin",
311
+ basis=f"read. {_UIOOPS_SD}:1829 '1', on sd `count` (varid20), concatenated unchanged by "
312
+ f"{_COMBINE}:70-71 (arrayprobe.combine:177).",
313
+ source_units="1"),
314
+ "Size Distribution cm-3": VariableAttributes(
315
+ units="cm-3", long_name="number concentration per size bin",
316
+ basis=(
317
+ f"derived, and the arithmetic checks out to the name the MATLAB gave the variable. "
318
+ f"sd `conc_minR` is 'cm-4' ({_UIOOPS_SD}:1757), i.e. cm-3 per cm of size; `bin_dD` is "
319
+ f"'millimeter' ({_UIOOPS_SD}:1751). {_COMBINE}:47-50 (arrayprobe.combine:173) writes "
320
+ f"(conc_minR / 10) * bin_dD, and dividing by 10 is exactly the mm->cm conversion "
321
+ f"(0.1 cm/mm), so cm-4 * cm = cm-3."),
322
+ source_units="cm-4 (sd `conc_minR`, before the bin-width multiplication)"),
323
+ "Number Concentration cm-3": VariableAttributes(
324
+ units="cm-3", long_name="total number concentration",
325
+ basis=f"read. {_UIOOPS_SD}:1772 'cm-3', on sd `n` (varid8), concatenated unchanged by "
326
+ f"{_COMBINE}:66-69 (arrayprobe.combine:179).",
327
+ source_units="cm-3"),
328
+ "Reject Ratio": VariableAttributes(
329
+ units="1", long_name="fraction of particles rejected",
330
+ basis=(
331
+ f"read, with the spelling corrected. {_UIOOPS_SD}:1807 writes '100/100' on sd "
332
+ f"`Reject_ratio` (varid15), concatenated unchanged by {_COMBINE}:66-69 "
333
+ f"(arrayprobe.combine:180). '100/100' is not udunits-legal and is UIOPS's own spelling "
334
+ f"of a dimensionless ratio; it is kept verbatim in arrayprobe_source_units rather than "
335
+ f"discarded."),
336
+ source_units="100/100"),
337
+ }
338
+
339
+ COMBINED_SHAPE = ProductShape(
340
+ name="combined_sizedist",
341
+ writer=f"{_COMBINE}:202-231 (arrayprobe.combine._write)",
342
+ variables=COMBINED_SIZEDIST,
343
+ time_convention=(
344
+ "Time Vector is a MATLAB datenum in days (combine_sizedist.m:95-120), not the HHMMSS "
345
+ "the sd files carry. Seconds since 1970-01-01T00:00:00Z = "
346
+ "(Time Vector - arrayprobe_datenum_unix_epoch_days) * 86400."),
347
+ missing_value_convention=(
348
+ "Missing seconds are IEEE-754 NaN in the float64 payload, with no _FillValue attribute "
349
+ "-- the faithful writer's own convention (combine_sizedist.m:124-148 pads the 1 Hz "
350
+ "grid with NaN; arrayprobe.combine:245-250). No _FillValue is added here, because "
351
+ "adding one would change what a masking reader returns."),
352
+ )
353
+
354
+ #: Every product shape this module can attribute. One today. A shape is added by sourcing each
355
+ #: variable's unit from the MATLAB that writes it -- never by copying a neighbouring table.
356
+ SHAPES: tuple[ProductShape, ...] = (COMBINED_SHAPE,)
357
+
358
+ #: The SODA-2 engine's citation, exactly as its author provided it.
359
+ SODA2_CITATION = (
360
+ "Aaron Bansemer. (2026). abansemer/soda2: v2.26.0 (Version v2.26.0) [Computer software]. "
361
+ "Zenodo. https://doi.org/10.5281/zenodo.18331418")
362
+
363
+ _SODA2_WRITER = "arrayprobe_soda2/export_ncdf.py"
364
+ #: The three time variables every SODA-2 PSD file carries (export_ncdf.py:490-499).
365
+ SODA2_TIME_VARIABLES = ("elapsed_time", "base_time", "time")
366
+
367
+
368
+ def is_soda2_psd(names: Iterable[str],
369
+ global_attrs: Mapping[str, object] | None = None) -> bool:
370
+ """Whether a file is a SODA-2 size-distribution netCDF: the writer's ``Source`` global
371
+ (export_ncdf.py:464), or its three time variables together (export_ncdf.py:490-499)."""
372
+ if global_attrs is not None and global_attrs.get("Source") == "SODA-2 OAP Processing Software":
373
+ return True
374
+ return set(SODA2_TIME_VARIABLES) <= set(names)
375
+
376
+
377
+ def _soda2_variable(name: str, source_attrs: Mapping[str, object]) -> VariableAttributes:
378
+ """One SODA-2 variable's attributes, from ``export_ncdf.py``'s own tables (imported, never
379
+ retyped). A variable the writer labels inline (the time block, ``bin_atts``) keeps the writer's
380
+ own text, cited to that block. A tag the writer marks ``Unknown`` is refused."""
381
+ from arrayprobe_soda2 import export_ncdf as w
382
+
383
+ units = source_attrs.get("units")
384
+ long_name = source_attrs.get("long_name")
385
+ if name in w._MAIN_SIMPLE:
386
+ ln, un, _ = w._MAIN_SIMPLE[name]
387
+ return VariableAttributes(un, ln, f"read: {_SODA2_WRITER}:251-261 (_MAIN_SIMPLE)")
388
+ if name in w._BULK_SIMPLE:
389
+ ln, un = w._BULK_SIMPLE[name]
390
+ return VariableAttributes(un, ln, f"read: {_SODA2_WRITER}:263-278 (_BULK_SIMPLE)")
391
+ if name in w._LWC:
392
+ return VariableAttributes(str(units), w._LWC[name],
393
+ f"read: {_SODA2_WRITER}:280-284 (_LWC); units as written")
394
+ if name in w._IWC:
395
+ return VariableAttributes(str(units), w._IWC[name],
396
+ f"read: {_SODA2_WRITER}:281-284 (_IWC); units as written")
397
+ if units is None or long_name is None or "Unknown" in (units, long_name):
398
+ raise UnknownProductError(
399
+ f"SODA-2 variable {name!r} carries no sourced unit (the writer labels an unrecognised "
400
+ f"numeric tag 'Unknown', {_SODA2_WRITER}:573-576); refusing rather than exporting a "
401
+ f"guessed unit")
402
+ if name in SODA2_TIME_VARIABLES:
403
+ basis = f"read: {_SODA2_WRITER}:490-499 (the time block, soda2_export_ncdf.pro:74-91)"
404
+ else:
405
+ basis = f"read: {_SODA2_WRITER}:527-576 (bin_atts and the per-bin tags, as written)"
406
+ return VariableAttributes(str(units), str(long_name), basis)
407
+
408
+
409
+ def soda2_shape(variables: Mapping[str, Mapping[str, object]]) -> ProductShape:
410
+ """The shape of one SODA-2 PSD file. Its variable set depends on the run's tags and options
411
+ (export_ncdf.py:540-630), so the shape is built per file rather than fixed."""
412
+ return ProductShape(
413
+ name="soda2_psd",
414
+ writer=f"{_SODA2_WRITER}:389-660 (soda2_export_ncdf)",
415
+ variables={n: _soda2_variable(n, a) for n, a in variables.items()},
416
+ time_convention=(
417
+ "time is 'seconds from midnight of start date'; elapsed_time is 'seconds since "
418
+ "<flight date> <start time> +0000'; base_time is 'seconds since 01/01/1970' -- the "
419
+ "writer's own units strings (arrayprobe_soda2/export_ncdf.py:491-499)."),
420
+ missing_value_convention=(
421
+ "The SODA-2 writer sets no _FillValue (arrayprobe_soda2/export_ncdf.py creates every "
422
+ "variable without one); values are copied verbatim."),
423
+ )
424
+
425
+
426
+ def identify_shape(names: Iterable[str]) -> ProductShape:
427
+ """Which :data:`SHAPES` entry a file's variable names are, or :class:`UnknownProductError`."""
428
+ names = list(names)
429
+ for shape in SHAPES:
430
+ if shape.matches(names):
431
+ return shape
432
+ known = ", ".join(s.name for s in SHAPES)
433
+ missing = sorted(set(COMBINED_SIZEDIST) - set(names))
434
+ extra = sorted(set(names) - set(COMBINED_SIZEDIST))
435
+ raise UnknownProductError(
436
+ f"no sourced attribute table for a file holding {sorted(names)!r}; known shapes: {known}. "
437
+ f"Against {COMBINED_SHAPE.name} this file is missing {missing!r} and holds {extra!r} "
438
+ f"besides. Refusing rather than exporting with guessed units -- add a ProductShape whose "
439
+ f"every unit is quoted from the MATLAB that writes it, at file:line "
440
+ f"(arrayprobe.attributed_export.COMBINED_SIZEDIST is the worked example).")
441
+
442
+
443
+ # ---------------------------------------------------------------------------
444
+ # The .call sidecar
445
+ # ---------------------------------------------------------------------------
446
+
447
+ #: A stamp key: an identifier at the start of the line or after whitespace, followed by ``=``.
448
+ #: The whitespace requirement is what keeps ``reject=(rej_hollow=0,max_edge_img_ar=4)`` one value
449
+ #: instead of three keys -- the inner ``=`` signs are preceded by ``(`` or ``,``, never by a space
450
+ #: (``src/arrayprobe/driver/run_flight.py:1571-1574`` builds that fragment with
451
+ #: ``",".join(...)``). It is **not** sufficient on its own: the S4c combine stamp nests a whole
452
+ #: space-separated stamp inside ``inputs_built_with=(...)``
453
+ #: (``src/arrayprobe/driver/run_flight.py:3600-3603``), whose inner keys *are* preceded by
454
+ #: spaces. :func:`_paren_depths` is what tells those apart from real keys.
455
+ _STAMP_KEY = re.compile(r"(?:^|\s)([A-Za-z_][A-Za-z0-9_.]*)=")
456
+
457
+ #: ``regimes.ResolvedField.render()``'s output: ``"<value> (<source>)"`` where ``<source>`` is
458
+ #: ``default`` (``stock`` in stamps written before 2026-10-16; both are read), ``regime:<name>``
459
+ #: or ``user:<path>`` (``regimes.py:196-199``). The value half has no
460
+ #: space, the tag half is parenthesised, which is why a threshold survives :func:`parse_stamp`
461
+ #: as one value and is split here rather than there.
462
+ _TAGGED = re.compile(r"^(?P<value>\S+)\s+\((?P<source>[^)]*)\)$")
463
+
464
+ #: The stamp keys whose value is a ``ResolvedField.render()`` string (see
465
+ #: ``src/arrayprobe/driver/run_flight.py:1063-1073``). Each becomes two attributes: the
466
+ #: number, and the provenance tag -- never blurred into one, which is the blurring this split exists
467
+ #: to prevent.
468
+ TAGGED_KEYS: tuple[str, ...] = ("area_ratio_z", "default_int_arr_thresh")
469
+
470
+
471
+ def _paren_depths(text: str) -> list[int]:
472
+ """``depths[i]`` = how many ``(`` are still open immediately **before** ``text[i]``.
473
+
474
+ Unbalanced parentheses are refused rather than guessed at: a stray ``)`` or an unclosed ``(``
475
+ means the nesting this function exists to read cannot be read, and a depth map computed from
476
+ it would silently make every key after the imbalance part of somebody else's value. Every
477
+ fragment the driver writes is balanced (``run_flight._combine_stamp``, ``thresholds_stamp``,
478
+ ``reject=(...)``), so an imbalance is a defect somewhere, not a shape to accommodate.
479
+ """
480
+ depths: list[int] = []
481
+ level = 0
482
+ for i, ch in enumerate(text):
483
+ depths.append(level)
484
+ if ch == "(":
485
+ level += 1
486
+ elif ch == ")":
487
+ level -= 1
488
+ if level < 0:
489
+ raise StampParseError(
490
+ f".call stamp has a ')' with no matching '(' at offset {i} in {text!r}; "
491
+ f"refusing to parse a stamp whose nesting cannot be read")
492
+ if level:
493
+ raise StampParseError(
494
+ f".call stamp leaves {level} '(' unclosed in {text!r}; refusing to parse a stamp "
495
+ f"whose nesting cannot be read")
496
+ return depths
497
+
498
+
499
+ def parse_stamp(stamp: str) -> dict[str, str]:
500
+ """A ``.call`` line -> its **top-level** ``key=value`` pairs, in the order written.
501
+
502
+ Values may contain spaces (``area_ratio_z=0.5 (default)``), nested ``=`` signs
503
+ (``reject=(rej_hollow=0,...)``) and a whole nested stamp
504
+ (``inputs_built_with=(engine=3.1.4 profile=... default_int_arr_thresh=6e-06 (default))``), so
505
+ this is not a ``split()``: each key's value runs to the start of the next key **at paren depth
506
+ zero**. A duplicated key is refused rather than resolved by a last-wins rule --
507
+ ``sd_call_label``'s own docstring (``src/arrayprobe/driver/run_flight.py:1667-1670``) records a
508
+ doubled ``engine=`` as a real defect class, and silently keeping one of two contradictory
509
+ values is how a stamp stops meaning anything.
510
+
511
+ **The nested stamp stays nested, and the outer level wins.** ``engine`` and ``profile`` appear
512
+ both at the top level and inside ``inputs_built_with``; they are different facts and must not
513
+ collide. The top-level keys describe *this* product; ``inputs_built_with`` is the provenance of
514
+ the files it was stitched from (``run_flight._combine_stamp``), so it is returned as one value
515
+ -- parenthesised, exactly as written; strip the outer ``()`` and call this function again if
516
+ you want the inputs' own fields (``parse_nested`` does that). Promoting the inner keys
517
+ would either overwrite the outer ones or trip the duplicate guard; both are wrong, and in an
518
+ earlier version that promotion is exactly what happened: ``inputs_built_with`` truncated to
519
+ ``'(engine=3.1.4'``, ``iat_file``/``profile``/``tree`` were silently the *inputs'* values under
520
+ the product's own names, and the closing paren landed on the last value, where
521
+ :func:`parse_tagged_value` finally raised and ``--attributed`` skipped every real product.
522
+
523
+ A value that itself contains a space-separated ``word=`` (a Windows path with a space in it,
524
+ say) would split wrongly here. That is why :func:`global_attributes` writes the raw line
525
+ verbatim as well: the parsed keys are a convenience, the raw line is the record.
526
+ """
527
+ text = stamp.strip()
528
+ if not text:
529
+ raise StampParseError("empty .call stamp")
530
+ depths = _paren_depths(text)
531
+ hits = [hit for hit in _STAMP_KEY.finditer(text) if depths[hit.start()] == 0]
532
+ if not hits:
533
+ raise StampParseError(f"no key=value pair in .call stamp {text!r}")
534
+ if hits[0].start() != 0:
535
+ raise StampParseError(
536
+ f".call stamp begins with {text[:hits[0].start()]!r}, which is not a key=value pair")
537
+ out: dict[str, str] = {}
538
+ for i, hit in enumerate(hits):
539
+ end = hits[i + 1].start() if i + 1 < len(hits) else len(text)
540
+ key = hit.group(1)
541
+ if key in out:
542
+ raise StampParseError(
543
+ f"key {key!r} appears twice in .call stamp {text!r}; refusing to pick one")
544
+ out[key] = text[hit.end():end].strip()
545
+ return out
546
+
547
+
548
+ def parse_nested(value: str) -> dict[str, str]:
549
+ """``"(engine=3.1.4 profile=X ...)"`` -> that nested stamp's own key=value pairs.
550
+
551
+ The one nested stamp today is ``inputs_built_with`` (``run_flight._combine_stamp``). This is
552
+ offered so a reader can get at the inputs' configuration **deliberately**, under its own name,
553
+ instead of having those fields silently promoted into the product's own namespace -- which is
554
+ the defect this whole paren-aware pass exists to undo. Nothing in :func:`global_attributes`
555
+ calls it: the export writes the fragment verbatim, because which of the two ``profile=`` values
556
+ a downstream reader wants is the reader's decision, not this module's.
557
+ """
558
+ inner = value.strip()
559
+ if not (inner.startswith("(") and inner.endswith(")")):
560
+ raise StampParseError(f"nested stamp {value!r} is not parenthesised")
561
+ return parse_stamp(inner[1:-1])
562
+
563
+
564
+ def parse_reject(value: str) -> dict[str, str]:
565
+ """``"(rej_hollow=0,max_edge_img_ar=4)"`` -> ``{"rej_hollow": "0", ...}``.
566
+
567
+ The fragment is built off the :class:`~arrayprobe_uiops.reject_core.RejectConfig` dataclass's
568
+ fields
569
+ (``src/arrayprobe/driver/run_flight.py:1552-1554``, "read off the dataclass, so a field
570
+ added later enters the stamp without anyone remembering to add it"), so this parses whatever
571
+ is there rather than a fixed field list -- a field added upstream reaches the exported file
572
+ with no edit here.
573
+ """
574
+ inner = value.strip()
575
+ if not (inner.startswith("(") and inner.endswith(")")):
576
+ raise StampParseError(f"reject fragment {value!r} is not parenthesised")
577
+ inner = inner[1:-1].strip()
578
+ if not inner:
579
+ return {}
580
+ fields: dict[str, str] = {}
581
+ for part in inner.split(","):
582
+ if "=" not in part:
583
+ raise StampParseError(f"reject field {part!r} is not key=value")
584
+ k, v = part.split("=", 1)
585
+ fields[k.strip()] = v.strip()
586
+ return fields
587
+
588
+
589
+ def parse_tagged_value(value: str) -> tuple[float, str]:
590
+ """``"0.5 (regime:liquid-warm)"`` -> ``(0.5, "regime:liquid-warm")``.
591
+
592
+ Both halves are returned because both are needed and neither implies the other: the number
593
+ without the tag cannot be told apart from a value someone typed, and the tag without the number
594
+ says nothing about what ran (``regimes.ResolvedField``'s own docstring: "three different
595
+ epistemic objects that must never be blurred").
596
+ """
597
+ hit = _TAGGED.match(value.strip())
598
+ if hit is None:
599
+ raise StampParseError(
600
+ f"threshold value {value!r} is not ResolvedField.render()'s '<value> (<source>)' shape")
601
+ try:
602
+ number = float(hit.group("value"))
603
+ except ValueError as exc: # pragma: no cover -- a non-numeric threshold is not reachable today
604
+ raise StampParseError(f"threshold value {value!r} has a non-numeric value half") from exc
605
+ return number, hit.group("source")
606
+
607
+
608
+ def read_stamp(source: Path) -> str | None:
609
+ """The ``.call`` line beside ``source``, or ``None``. Mirrors ``run_flight.read_stamp``."""
610
+ sidecar = Path(str(source) + CALL_SUFFIX)
611
+ if not sidecar.exists():
612
+ return None
613
+ return sidecar.read_text().strip()
614
+
615
+
616
+ # ---------------------------------------------------------------------------
617
+ # The export
618
+ # ---------------------------------------------------------------------------
619
+
620
+ def default_output_path(source: Path | str) -> Path:
621
+ """``<source><DEFAULT_SUFFIX>`` -- beside the faithful file, same stem, new suffix.
622
+
623
+ This is the current layout and may change in a later release
624
+ (``docs/developer/ATTRIBUTED_EXPORT.md`` §3). Co-location keeps the
625
+ correspondence obvious in a directory listing and makes the pair sort adjacently; the ``.nc``
626
+ ending says NETCDF4 where the faithful archived product says ``.cdf``; and nothing about the
627
+ faithful file's own name changes, which matters because every validated comparison addresses it
628
+ by name.
629
+ """
630
+ return Path(str(source) + DEFAULT_SUFFIX)
631
+
632
+
633
+ def sha256_of(path: Path | str, *, chunk: int = 1 << 20) -> str:
634
+ """The file's SHA-256, streamed. Written into the export so the attributed file names the
635
+ exact faithful bytes it describes -- the pair can be separated and still re-associated."""
636
+ digest = hashlib.sha256()
637
+ # `Path.open`, never a bare `open`: `arrayprobe.ncio` defines an `open` of its own (MATLAB's
638
+ # `netcdf.open`, carrying a ruff A001 exemption), and this module imports that module, so a
639
+ # later `from .ncio import open` would silently turn a byte read into a netCDF call.
640
+ with Path(path).open("rb") as fh:
641
+ while True:
642
+ block = fh.read(chunk)
643
+ if not block:
644
+ break
645
+ digest.update(block)
646
+ return digest.hexdigest()
647
+
648
+
649
+ def _package_version() -> str:
650
+ from . import __version__ as version # local import: keeps module import cheap and cycle-free
651
+ return str(version)
652
+
653
+
654
+ # The basis written beside an engine read from a stamp that does not name one.
655
+ ENGINE_INFERRED_BASIS = (
656
+ "inferred, not stamped: this .call predates 2026-09-15, when every v3.1.4 stamp "
657
+ "began naming its own engine (run_flight._engine_prefix). "
658
+ "run_flight._stamps_equivalent reads the absence of engine= as engine=3.1.4; "
659
+ "this export reads it the same way.")
660
+
661
+
662
+ def shared_attributes(
663
+ *,
664
+ engine: str | None,
665
+ engine_basis: str | None = None,
666
+ sd_configuration: str | None = None,
667
+ enhancements: Sequence[str] = (),
668
+ enhancements_record: str | None = None,
669
+ tas_qc: dict | None = None,
670
+ ) -> dict[str, object]:
671
+ """The run-level block every product of one run carries, identical in each.
672
+
673
+ The attributed combined (:func:`global_attributes`) and the faithful ARM copy of the port's
674
+ ``sd`` (:func:`stamp_shared_attributes`) each keep their own ``arrayprobe_call_stamp`` and
675
+ ``arrayprobe_stage``; what they share is this: the engine, the ``sd``-level configuration
676
+ (``arrayprobe_inputs_built_with``, the ``sd`` stamp in parentheses -- a combined's stamp
677
+ carries it under that key, the ARM copy reads it from its ``sd``), the enhancements applied
678
+ and their record, the airspeed QC summary and the package version. ``engine=None`` (an
679
+ unstamped source) and ``sd_configuration=None`` leave those keys out rather than invent them.
680
+ """
681
+ atts: dict[str, object] = {
682
+ f"{ATTR_PREFIX}package_version": _package_version(),
683
+ f"{ATTR_PREFIX}enhancements_applied": ",".join(enhancements) if enhancements else "none",
684
+ f"{ATTR_PREFIX}enhancements_basis": (
685
+ "none by construction when the producer is the port: 'the port is the faithful "
686
+ "reproduction and nothing else' (the package's rule that enhancements live outside "
687
+ "the port), "
688
+ "enforced by tests/test_no_enhancement_coupling.py. scripts/run_flight.py applies "
689
+ "corrections only to SEPARATE <stem>.enh.* products (named in their own .call), "
690
+ "never to the faithful file this export reads. A non-port chain must name what it "
691
+ "applied through this exporter's `enhancements` argument."),
692
+ }
693
+ if enhancements_record is not None:
694
+ # The producing chain's own record, verbatim text read from its sidecar by the
695
+ # caller -- nothing here imports the enhancements package.
696
+ atts[f"{ATTR_PREFIX}enhancements_record"] = enhancements_record
697
+ if tas_qc is not None:
698
+ # Which seconds were sized with a substituted or default TAS, read from the source's
699
+ # <product>.tasqc.json -- the run log is not the only record of it.
700
+ for key, value in tas_qc.items():
701
+ atts[f"{ATTR_PREFIX}{key}"] = value
702
+ else:
703
+ atts[f"{ATTR_PREFIX}tas_qc"] = (
704
+ "absent: the source carries no .tasqc.json, either because the run named no TAS "
705
+ "source (probe housekeeping TAS throughout) or because it predates the record "
706
+ "(2026-09-23). Which seconds took a default TAS is not established here.")
707
+ if engine is not None:
708
+ atts[f"{ATTR_PREFIX}engine"] = engine
709
+ if engine_basis is not None:
710
+ atts[f"{ATTR_PREFIX}engine_basis"] = engine_basis
711
+ if sd_configuration is not None:
712
+ atts[f"{ATTR_PREFIX}inputs_built_with"] = f"({sd_configuration})"
713
+ return atts
714
+
715
+
716
+ def _shared_from_stamp(stamp: str | None, *, nested: bool, **kw) -> dict[str, object]:
717
+ """:func:`shared_attributes` for a product whose ``.call`` is ``stamp``. ``nested``: the
718
+ ``sd`` configuration is the stamp's ``inputs_built_with=(...)`` (a combined); otherwise it
719
+ is the stamp itself (the stamp of an ``sd``, or of a copy of one)."""
720
+ if stamp is None:
721
+ return shared_attributes(engine=None, **kw)
722
+ keys = parse_stamp(stamp)
723
+ sd_configuration: str | None = stamp.strip()
724
+ if nested:
725
+ inner = keys.get("inputs_built_with", "").strip()
726
+ sd_configuration = (inner[1:-1] if inner.startswith("(") and inner.endswith(")")
727
+ else None)
728
+ return shared_attributes(engine=keys.get("engine", "3.1.4"),
729
+ engine_basis=None if "engine" in keys else ENGINE_INFERRED_BASIS,
730
+ sd_configuration=sd_configuration, **kw)
731
+
732
+
733
+ def global_attributes(
734
+ stamp: str | None,
735
+ *,
736
+ source_path: Path | str,
737
+ source_sha256: str,
738
+ source_bytes: int,
739
+ shape: ProductShape,
740
+ files_stitched: int | None = None,
741
+ enhancements: Sequence[str] = (),
742
+ export_time: str | None = None,
743
+ enhancements_record: str | None = None,
744
+ tas_qc: dict | None = None,
745
+ existing_attributes: Mapping[str, object] | None = None,
746
+ ) -> dict[str, object]:
747
+ """Every global attribute the export writes, as a plain dict.
748
+
749
+ ``existing_attributes`` are the faithful file's own global attributes. Each name in
750
+ :data:`ACDD_KEYS` that it holds is carried over verbatim rather than replaced
751
+ (:func:`acdd_attributes`).
752
+
753
+ Separated from :func:`export` so the block can be asserted without writing a file, and so a
754
+ caller assembling a product by another route can write the identical block. The run-level
755
+ part is :func:`shared_attributes`, placed here so the set and order of keys is unchanged; the
756
+ rest (source file and hash, product shape, fidelity note, time and missing-value
757
+ conventions, the exploded stamp) belongs to this file alone.
758
+
759
+ ``stamp`` is the raw ``.call`` line. It is written **verbatim** as
760
+ ``arrayprobe_call_stamp`` *and* exploded into one attribute per key: the verbatim line is the
761
+ record (nothing can be lost to a parsing edge case), the exploded keys are what a reader's
762
+ tooling can actually filter on. Any key this module does not recognise is still written, under
763
+ its own name -- so a stamp key added later reaches the file without an edit here.
764
+ """
765
+ shared = _shared_from_stamp(stamp, nested=True, enhancements=enhancements,
766
+ enhancements_record=enhancements_record, tas_qc=tas_qc)
767
+ now = export_time or _dt.datetime.now(_dt.UTC).isoformat(timespec="seconds")
768
+ p = ATTR_PREFIX
769
+ atts: dict[str, object] = {
770
+ f"{p}export_convention": EXPORT_CONVENTION,
771
+ f"{p}export_module": "arrayprobe.attributed_export",
772
+ f"{p}package_version": shared[f"{p}package_version"],
773
+ f"{p}export_time": now,
774
+ f"{p}source_file": Path(source_path).name,
775
+ f"{p}source_sha256": source_sha256,
776
+ f"{p}source_bytes": int(source_bytes),
777
+ f"{p}source_writer": shape.writer,
778
+ f"{p}product_shape": shape.name,
779
+ f"{p}fidelity_note": (
780
+ "This file is NOT the byte-comparison artefact. The faithful file named in "
781
+ "arrayprobe_source_file is: it carries zero attributes because the MATLAB that defines "
782
+ "its format writes zero attributes (combine_sizedist.m:202-231, measured), and every "
783
+ "validated-flight comparison is made against it. This file holds the same values and "
784
+ "adds metadata; use it to read the data, use the faithful file to compare bytes."),
785
+ f"{p}time_convention": shape.time_convention,
786
+ f"{p}datenum_unix_epoch_days": DATENUM_UNIX_EPOCH_DAYS,
787
+ f"{p}missing_value_convention": shape.missing_value_convention,
788
+ f"{p}enhancements_applied": shared[f"{p}enhancements_applied"],
789
+ f"{p}enhancements_basis": shared[f"{p}enhancements_basis"],
790
+ }
791
+ if files_stitched is not None:
792
+ atts[f"{p}files_stitched"] = int(files_stitched)
793
+ placed_later = (f"{p}engine", f"{p}engine_basis", f"{p}inputs_built_with")
794
+ for key, value in shared.items(): # the enhancements record and the airspeed QC
795
+ if key not in atts and key not in placed_later:
796
+ atts[key] = value
797
+
798
+ if stamp is None:
799
+ atts[f"{p}call_stamp"] = (
800
+ "ABSENT -- the faithful file carried no .call sidecar and the export was run with "
801
+ "accept_unstamped=True. The engine, profile, thresholds and reject configuration that "
802
+ "produced it are NOT established. Stated rather than left blank.")
803
+ atts.update(acdd_attributes(atts, stamp=None, source_path=source_path,
804
+ source_sha256=source_sha256, shape=shape, created=now,
805
+ existing=existing_attributes))
806
+ return atts
807
+
808
+ atts[f"{p}call_stamp"] = stamp
809
+ keys = parse_stamp(stamp)
810
+ for key, value in keys.items():
811
+ if key == "reject":
812
+ atts[f"{p}reject"] = value
813
+ for field, field_value in parse_reject(value).items():
814
+ atts[f"{p}reject_{field}"] = field_value
815
+ elif key in TAGGED_KEYS:
816
+ number, tag = parse_tagged_value(value)
817
+ atts[f"{p}{key}"] = number
818
+ atts[f"{p}{key}_source"] = tag
819
+ else:
820
+ atts[f"{p}{key}"] = value
821
+ # src/arrayprobe/driver/run_flight.py:1925-1928: a v3.1.4 stamp written before 2026-09-15 has
822
+ # no `engine=` key, and `_stamps_equivalent` reads that absence as engine=3.1.4; the shared
823
+ # block reads it the same way and says so. The update adds only that inferred engine and its
824
+ # basis, at the end; every other shared key is already in place with an equal value.
825
+ for key, value in shared.items():
826
+ atts.setdefault(key, value)
827
+ atts.update(acdd_attributes(atts, stamp=stamp, source_path=source_path,
828
+ source_sha256=source_sha256, shape=shape, created=now,
829
+ existing=existing_attributes))
830
+ return atts
831
+
832
+
833
+ def acdd_attributes(
834
+ atts: Mapping[str, object],
835
+ *,
836
+ stamp: str | None,
837
+ source_path: Path | str,
838
+ source_sha256: str,
839
+ shape: ProductShape,
840
+ created: str,
841
+ existing: Mapping[str, object] | None = None,
842
+ ) -> dict[str, object]:
843
+ """The ACDD/CF discovery attributes (:data:`ACDD_KEYS`), built from the run record.
844
+
845
+ ``atts`` is the prefixed block :func:`global_attributes` has already assembled; every value
846
+ here is read from it or from the stamp, never asserted afresh. A name present in ``existing``
847
+ (the faithful file's own globals) is returned with the faithful file's value, unchanged.
848
+ """
849
+ p = ATTR_PREFIX
850
+ version = str(atts[f"{p}package_version"])
851
+ name = Path(source_path).name
852
+ engine = atts.get(f"{p}engine")
853
+ if stamp is None:
854
+ record = "run record ABSENT (no .call sidecar beside the faithful file)"
855
+ source = ("arrayprobe; the engine that produced the faithful file is not established "
856
+ "(no .call sidecar)")
857
+ else:
858
+ record = f"run record (.call, verbatim): {stamp}"
859
+ source = (f"arrayprobe engine={engine}; the full run record is the attribute "
860
+ f"{p}call_stamp")
861
+ ours: dict[str, object] = {
862
+ "Conventions": ACDD_CONVENTIONS,
863
+ "history": (f"{created} arrayprobe.attributed_export {version}: attributed copy of "
864
+ f"{name} (sha256 {source_sha256}), values unchanged; {record}"),
865
+ "source": source,
866
+ "processing_level": f"{shape.name}, as written by {shape.writer}",
867
+ "product_version": version,
868
+ "date_created": created,
869
+ }
870
+ held = dict(existing or {})
871
+ return {key: (held[key] if key in held else ours[key]) for key in ACDD_KEYS}
872
+
873
+
874
+ def stamp_shared_attributes(target: Path | str, sd: Path | str,
875
+ combined: Path | str | None = None, *,
876
+ enhancements: Sequence[str] = (),
877
+ enhancements_record: str | None = None) -> dict[str, object]:
878
+ """Write :func:`shared_attributes` into ``target``, a product made from the port's ``sd``.
879
+
880
+ ``target`` is opened read-write and only global attributes are set. With ``combined`` (the
881
+ run's combined product, OUTPUT 2's source), the block is the combined's -- its ``.call`` and
882
+ its ``.tasqc.json``, including the merged-parts key the per-``sd`` record lacks -- so OUTPUT 3
883
+ carries exactly OUTPUT 2's run-level block. Without
884
+ it, the block is read from ``sd``. Either source is only read. ``enhancements`` and
885
+ ``enhancements_record`` name the corrections the run applied (a stamp does not), so the
886
+ enhanced lineage's block is built whole rather than patched afterwards. Returns the block
887
+ written.
888
+ """
889
+ enh = {"enhancements": tuple(enhancements), "enhancements_record": enhancements_record}
890
+ if combined is not None:
891
+ combined = Path(combined)
892
+ block = _shared_from_stamp(read_stamp(combined), nested=True,
893
+ tas_qc=read_qc_sidecar(combined), **enh)
894
+ else:
895
+ sd = Path(sd)
896
+ block = _shared_from_stamp(read_stamp(sd), nested=False, tas_qc=read_qc_sidecar(sd),
897
+ **enh)
898
+ with Dataset(str(target), "r+") as ds:
899
+ for key, value in block.items():
900
+ ds.setncattr(key, value)
901
+ return block
902
+
903
+
904
+ class StorageOptions(TypedDict, total=False):
905
+ """The ``createVariable`` keywords :func:`storage_options` may return, typed as netCDF4's own
906
+ signature takes them, so a call site needs no cast."""
907
+
908
+ zlib: bool
909
+ complevel: Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
910
+ shuffle: bool
911
+ chunksizes: list[int]
912
+
913
+
914
+ def storage_options(dtype: np.dtype, sizes: Sequence[int], *,
915
+ analysis_ready: bool = True) -> StorageOptions:
916
+ """``createVariable`` storage keywords for one variable: empty (contiguous, uncompressed) when
917
+ ``analysis_ready`` is off, and for a variable that cannot be compressed losslessly here -- a
918
+ scalar, a zero-length dimension, or a non-numeric type. Storage only: no keyword returned here
919
+ changes a value, a dtype or a dimension order."""
920
+ dtype = np.dtype(dtype)
921
+ if (not analysis_ready or not sizes or any(n == 0 for n in sizes)
922
+ or dtype.kind not in "biuf"):
923
+ return {}
924
+ chunks = [n if n <= ANALYSIS_READY_WHOLE_DIM else min(n, ANALYSIS_READY_CHUNK)
925
+ for n in sizes]
926
+ return {"zlib": True, "complevel": ANALYSIS_READY_COMPLEVEL,
927
+ "shuffle": dtype.kind in "biu", "chunksizes": chunks}
928
+
929
+
930
+ def export(
931
+ source: Path | str,
932
+ out: Path | str | None = None,
933
+ *,
934
+ stamp: str | None = None,
935
+ accept_unstamped: bool = False,
936
+ enhancements: Sequence[str] = (),
937
+ export_time: str | None = None,
938
+ enhancements_record: str | None = None,
939
+ analysis_ready: bool = True,
940
+ ) -> Path:
941
+ """Write the attributed sibling of the faithful product ``source``. Returns the path written.
942
+
943
+ ``source`` is opened read-only and is never modified -- asserted by
944
+ ``tests/test_attributed_export.py`` hashing it either side of this call. ``stamp`` defaults to
945
+ the ``.call`` sidecar beside it; absent, the export is refused unless ``accept_unstamped``.
946
+
947
+ ``enhancements`` names what a non-port producer applied. Empty (the default) writes
948
+ ``enhancements_applied = "none"``, which is the port's own case by construction.
949
+
950
+ ``export_time`` pins the timestamp, for tests that compare two exports byte for byte -- the same
951
+ reason ``creation_time=`` exists on the faithful writers.
952
+
953
+ ``analysis_ready`` (default on) writes each variable chunked and losslessly compressed
954
+ (:func:`storage_options`), so the file is the cloud-optimised form as well as the attributed
955
+ one; ``False`` writes it contiguous and uncompressed. Either way every value is unchanged, and
956
+ the file states which under ``arrayprobe_encoding``.
957
+ """
958
+ source = Path(source)
959
+ out = Path(out) if out is not None else default_output_path(source)
960
+ if out.resolve() == source.resolve():
961
+ raise AttributedExportError(
962
+ f"refusing to write the attributed export over the faithful file {source}; the whole "
963
+ f"point of this module is that the faithful bytes do not move")
964
+
965
+ # A SODA-2 run's record is the JSON stamp `<stem>.pbp.call` beside its `<stem>.nc`.
966
+ soda2_call = source.with_suffix(".pbp.call")
967
+ soda2_record = (soda2_call.read_text(encoding="utf-8") if soda2_call.is_file() else None)
968
+ if stamp is None:
969
+ stamp = read_stamp(source)
970
+ if stamp is None and soda2_record is None and not accept_unstamped:
971
+ raise MissingStampError(
972
+ f"{source.name} carries no {CALL_SUFFIX} sidecar, so the engine, profile, "
973
+ f"thresholds and reject configuration that produced it are unknown. An attributed "
974
+ f"file that states nothing about its own provenance is worse than none, because a "
975
+ f"reader cannot tell the difference. Pass accept_unstamped=True to export anyway "
976
+ f"(the file then says so), or restore the sidecar.")
977
+
978
+ src = Dataset(str(source), "r")
979
+ try:
980
+ src.set_auto_maskandscale(False) # raw values, ncio.get_var's policy -- NaN stays NaN
981
+ src_globals = {k: src.getncattr(k) for k in src.ncattrs()}
982
+ soda2 = is_soda2_psd(src.variables, src_globals)
983
+ if soda2:
984
+ shape = soda2_shape({n: {k: v.getncattr(k) for k in v.ncattrs()}
985
+ for n, v in src.variables.items()})
986
+ else:
987
+ shape = identify_shape(src.variables)
988
+ files_stitched = (len(src.dimensions["files_stitched"])
989
+ if "files_stitched" in src.dimensions else None)
990
+ atts = global_attributes(
991
+ stamp,
992
+ source_path=source,
993
+ source_sha256=sha256_of(source),
994
+ source_bytes=source.stat().st_size,
995
+ shape=shape,
996
+ files_stitched=files_stitched,
997
+ enhancements=enhancements,
998
+ export_time=export_time,
999
+ enhancements_record=enhancements_record,
1000
+ tas_qc=read_qc_sidecar(source),
1001
+ existing_attributes={k: src.getncattr(k) for k in src.ncattrs()},
1002
+ )
1003
+ # Before the ACDD discovery block, which stays the last thing written (the order
1004
+ # tests/test_config_outputs.py pins).
1005
+ if soda2:
1006
+ atts[f"{ATTR_PREFIX}engine"] = "soda2"
1007
+ atts[f"{ATTR_PREFIX}engine_citation"] = SODA2_CITATION
1008
+ if soda2_record is not None:
1009
+ atts[f"{ATTR_PREFIX}run_record"] = soda2_record
1010
+ atts["references"] = SODA2_CITATION
1011
+ atts["source"] = f"arrayprobe engine=soda2; {SODA2_CITATION}"
1012
+ acdd = {key: atts.pop(key) for key in ACDD_KEYS if key in atts}
1013
+ atts[f"{ATTR_PREFIX}encoding"] = (ENCODING_ANALYSIS_READY if analysis_ready
1014
+ else ENCODING_PLAIN)
1015
+ atts.update(acdd)
1016
+ dst = Dataset(str(out), "w", format="NETCDF4")
1017
+ try:
1018
+ dst.set_auto_maskandscale(False)
1019
+ dst.setncatts(atts)
1020
+ for name, dim in src.dimensions.items():
1021
+ # `files_stitched` is used by no variable -- "the only record of how many files
1022
+ # went into the product" (arrayprobe.combine:332-333). Carried over as a dimension
1023
+ # *and* surfaced as an attribute above, because a bare dimension is easy to miss.
1024
+ dst.createDimension(name, None if dim.isunlimited() else len(dim))
1025
+ for name, var in src.variables.items():
1026
+ spec = shape.variables[name]
1027
+ # Verbatim: same dtype, same dimension list, same order. No transpose is performed
1028
+ # or implied -- see the module docstring.
1029
+ new = dst.createVariable(
1030
+ name, var.dtype, var.dimensions,
1031
+ **storage_options(var.dtype, [len(src.dimensions[d]) for d in var.dimensions],
1032
+ analysis_ready=analysis_ready))
1033
+ new.set_auto_maskandscale(False)
1034
+ # ncio's own helper, not a second suppression invented here: netCDF4 1.7.4's
1035
+ # Variable.__setitem__ sets .shape on the incoming array in place, which NumPy 2.5
1036
+ # deprecates, and it fires for a perfectly shaped input (ncio.py:118-138).
1037
+ with ncio._quiet_netcdf4_setitem():
1038
+ new[...] = np.asarray(var[...])
1039
+ new.units = spec.units
1040
+ new.long_name = spec.long_name
1041
+ new.setncattr(f"{ATTR_PREFIX}units_basis", spec.basis)
1042
+ if spec.source_units is not None:
1043
+ new.setncattr(f"{ATTR_PREFIX}source_units", spec.source_units)
1044
+ # Any attribute the source variable carries that this export does not itself set
1045
+ # is copied verbatim, after the ones it does set. `_FillValue` can only be set at
1046
+ # creation; it is skipped here rather than re-created with a different meaning.
1047
+ written = set(new.ncattrs())
1048
+ for key in var.ncattrs():
1049
+ if key not in written and key != "_FillValue":
1050
+ new.setncattr(key, var.getncattr(key))
1051
+ finally:
1052
+ dst.close()
1053
+ finally:
1054
+ src.close()
1055
+ return out
1056
+
1057
+
1058
+ def default_zarr_path(attributed_nc: Path | str) -> Path:
1059
+ """``<attributed_nc>`` with a trailing ``.nc`` replaced by ``.zarr`` (appended otherwise)."""
1060
+ attributed_nc = Path(attributed_nc)
1061
+ if attributed_nc.suffix == ".nc":
1062
+ return attributed_nc.with_suffix(".zarr")
1063
+ return attributed_nc.with_name(attributed_nc.name + ".zarr")
1064
+
1065
+
1066
+ def export_zarr(attributed_nc: Path | str, store: Path | str | None = None) -> Path:
1067
+ """Opt-in: copy the attributed netCDF4 export ``attributed_nc`` into a Zarr store.
1068
+
1069
+ netCDF4 stays the default output; this is a second, optional encoding of the same file. Every
1070
+ variable's values, dtype and dimension order are carried unchanged, and every global and
1071
+ variable attribute verbatim, except the global ``arrayprobe_encoding``, which is overwritten
1072
+ with :data:`ENCODING_ZARR`. The file is read with CF decoding, masking, scaling and time
1073
+ decoding all off, so no value is reinterpreted: NaN stays NaN and no ``_FillValue`` is added.
1074
+ Chunks follow :func:`storage_options`' rule. Needs the ``[zarr]`` extra (zarr and xarray),
1075
+ imported here and nowhere at module level. Refuses to write over an existing ``store``.
1076
+ """
1077
+ try:
1078
+ import xarray as xr
1079
+ import zarr # noqa: F401 -- imported only to fail early with the extra's name
1080
+ except ImportError as exc:
1081
+ raise AttributedExportError(
1082
+ f"the Zarr writer needs zarr and xarray, which are not installed ({exc}). Install "
1083
+ f"them with `pip install arrayprobe[{ZARR_EXTRA}]`; netCDF4, the default output, "
1084
+ f"needs neither.") from exc
1085
+ attributed_nc = Path(attributed_nc)
1086
+ store = Path(store) if store is not None else default_zarr_path(attributed_nc)
1087
+ if store.exists():
1088
+ raise AttributedExportError(
1089
+ f"refusing to write the Zarr store over an existing path {store}; remove or rename "
1090
+ f"it first")
1091
+ with xr.open_dataset(attributed_nc, engine="netcdf4", decode_cf=False, mask_and_scale=False,
1092
+ decode_times=False, decode_coords=False) as ds:
1093
+ ds = ds.load()
1094
+ encoding: dict[str, dict[str, object]] = {}
1095
+ for name, var in ds.variables.items():
1096
+ var.encoding = {}
1097
+ enc: dict[str, object] = {}
1098
+ chunks = storage_options(var.dtype, list(var.shape)).get("chunksizes")
1099
+ if isinstance(chunks, list):
1100
+ enc["chunks"] = tuple(chunks)
1101
+ if "_FillValue" not in var.attrs:
1102
+ # xarray otherwise writes a NaN fill for floats; ``None`` adds no _FillValue. One the
1103
+ # source itself wrote stays in the attributes, verbatim.
1104
+ enc["_FillValue"] = None
1105
+ encoding[str(name)] = enc
1106
+ ds.attrs[f"{ATTR_PREFIX}encoding"] = ENCODING_ZARR
1107
+ ds.to_zarr(store, mode="w-", encoding=encoding, consolidated=False)
1108
+ return store
1109
+
1110
+
1111
+ def default_parquet_path(attributed_nc: Path | str) -> Path:
1112
+ """``<attributed_nc>`` with a trailing ``.nc`` replaced by ``.parquet`` (appended otherwise);
1113
+ the path is a directory holding one Parquet file per dimension tuple."""
1114
+ attributed_nc = Path(attributed_nc)
1115
+ if attributed_nc.suffix == ".nc":
1116
+ return attributed_nc.with_suffix(".parquet")
1117
+ return attributed_nc.with_name(attributed_nc.name + ".parquet")
1118
+
1119
+
1120
+ #: The per-particle dimension of a proc (S3, ``imgProc_sm``) file: one entry per particle.
1121
+ PARTICLE_DIM = "time"
1122
+
1123
+
1124
+ def _export_particles_parquet(proc_nc: Path, out: Path | None, pa, pq) -> Path:
1125
+ """``layout="particles"``: one Parquet file, one row per particle of a proc file.
1126
+
1127
+ Every variable on ``(time,)`` is a column; a variable on ``(time, k)`` becomes ``k`` columns
1128
+ ``name[1]`` .. ``name[k]`` (MATLAB's 1-based column index). Variables on no particle axis
1129
+ (``bin_count``) are not particle columns and are left out. Values are read with masking and
1130
+ scaling off, dtypes kept. Schema metadata carries the source's SHA-256, its ``.call`` stamp
1131
+ (``None`` when it has none) and every variable's attributes as JSON."""
1132
+ import json
1133
+
1134
+ import netCDF4
1135
+ import numpy as np
1136
+
1137
+ out = out if out is not None else proc_nc.with_name(proc_nc.name + ".particles.parquet")
1138
+ if out.exists():
1139
+ raise AttributedExportError(
1140
+ f"refusing to write the Parquet particle table over an existing path {out}")
1141
+ columns: dict[str, object] = {}
1142
+ var_attrs: dict[str, object] = {}
1143
+ with netCDF4.Dataset(proc_nc, "r") as ds:
1144
+ ds.set_auto_maskandscale(False)
1145
+ if PARTICLE_DIM not in ds.dimensions:
1146
+ raise AttributedExportError(
1147
+ f"{proc_nc} has no {PARTICLE_DIM!r} dimension; layout='particles' needs a proc "
1148
+ f"(per-particle) file")
1149
+ n = len(ds.dimensions[PARTICLE_DIM])
1150
+ for name, var in ds.variables.items():
1151
+ if not var.dimensions or var.dimensions[0] != PARTICLE_DIM:
1152
+ continue
1153
+ values = np.asarray(var[...])
1154
+ if values.ndim == 1:
1155
+ columns[name] = values
1156
+ elif values.ndim == 2:
1157
+ for j in range(values.shape[1]):
1158
+ columns[f"{name}[{j + 1}]"] = values[:, j]
1159
+ else:
1160
+ raise AttributedExportError(
1161
+ f"variable {name!r} has {values.ndim} dimensions; a particle row holds at "
1162
+ f"most a 2-D (particle, k) variable")
1163
+ var_attrs[name] = {k: (lambda v: v.tolist() if hasattr(v, "tolist") else v)(
1164
+ var.getncattr(k)) for k in var.ncattrs()}
1165
+ table = pa.table(columns)
1166
+ assert table.num_rows == n, (table.num_rows, n)
1167
+ meta = {
1168
+ f"{ATTR_PREFIX}layout": "particles",
1169
+ f"{ATTR_PREFIX}source_sha256": sha256_of(proc_nc),
1170
+ f"{ATTR_PREFIX}source_name": proc_nc.name,
1171
+ f"{ATTR_PREFIX}call_stamp": json.dumps(read_stamp(proc_nc)),
1172
+ f"{ATTR_PREFIX}var_attrs": json.dumps(var_attrs),
1173
+ }
1174
+ pq.write_table(table.replace_schema_metadata(meta), out)
1175
+ return out
1176
+
1177
+
1178
+ def export_parquet(attributed_nc: Path | str, out: Path | str | None = None, *,
1179
+ layout: str = "dimensions") -> Path:
1180
+ """Opt-in: copy the attributed netCDF4 export ``attributed_nc`` into Parquet files.
1181
+
1182
+ ``layout="particles"`` (opt-in; the default ``"dimensions"`` is unchanged) instead takes a
1183
+ proc (S3, per-particle) file and writes one Parquet file, default
1184
+ ``<proc>.particles.parquet``, with one row per particle: see
1185
+ :func:`_export_particles_parquet`.
1186
+
1187
+ netCDF4 stays the default output. Parquet is tabular, so ``out`` is a directory with one
1188
+ file per distinct dimension tuple, ``<dimA>__<dimB>.parquet``, in long form: one int64 index
1189
+ column per dimension, named after it, then one column per variable on that tuple, its values
1190
+ flattened in C order with the dtype kept. Scalars go to ``scalars.parquet`` (one row). Global
1191
+ and per-variable attributes are JSON in each file's schema metadata
1192
+ (``arrayprobe_global_attrs``, ``arrayprobe_var_attrs``), with ``arrayprobe_encoding`` set to
1193
+ :data:`ENCODING_PARQUET`. The file is read with masking and scaling off. A dtype pyarrow
1194
+ cannot hold raises, naming the variables. Needs the ``[parquet]`` extra (pyarrow), imported
1195
+ here and nowhere at module level. Refuses to write over an existing ``out``.
1196
+ """
1197
+ try:
1198
+ import pyarrow as pa
1199
+ import pyarrow.parquet as pq
1200
+ except ImportError as exc:
1201
+ raise AttributedExportError(
1202
+ f"the Parquet writer needs pyarrow, which is not installed ({exc}). Install it with "
1203
+ f"`pip install arrayprobe[{PARQUET_EXTRA}]`; netCDF4, the default output, needs "
1204
+ f"neither.") from exc
1205
+ if layout == "particles":
1206
+ return _export_particles_parquet(Path(attributed_nc),
1207
+ Path(out) if out is not None else None, pa, pq)
1208
+ if layout != "dimensions":
1209
+ raise AttributedExportError(
1210
+ f"unknown Parquet layout {layout!r}; use 'dimensions' (default) or 'particles'")
1211
+ import json
1212
+
1213
+ import netCDF4
1214
+ import numpy as np
1215
+
1216
+ attributed_nc = Path(attributed_nc)
1217
+ out = Path(out) if out is not None else default_parquet_path(attributed_nc)
1218
+ if out.exists():
1219
+ raise AttributedExportError(
1220
+ f"refusing to write the Parquet directory over an existing path {out}; remove or "
1221
+ f"rename it first")
1222
+
1223
+ def _jsonable(value: object) -> object:
1224
+ if isinstance(value, np.ndarray):
1225
+ return value.tolist()
1226
+ if isinstance(value, np.generic):
1227
+ return value.item()
1228
+ return value
1229
+
1230
+ groups: dict[tuple[str, ...], dict[str, tuple[np.ndarray, dict[str, object]]]] = {}
1231
+ with netCDF4.Dataset(attributed_nc, "r") as ds:
1232
+ ds.set_auto_maskandscale(False)
1233
+ global_attrs = {k: _jsonable(ds.getncattr(k)) for k in ds.ncattrs()}
1234
+ global_attrs[f"{ATTR_PREFIX}encoding"] = ENCODING_PARQUET
1235
+ sizes = {name: len(dim) for name, dim in ds.dimensions.items()}
1236
+ for name, var in ds.variables.items():
1237
+ attrs = {k: _jsonable(var.getncattr(k)) for k in var.ncattrs()}
1238
+ groups.setdefault(tuple(var.dimensions), {})[name] = (np.asarray(var[...]), attrs)
1239
+ out.mkdir(parents=True)
1240
+ for dims, members in groups.items():
1241
+ shape = tuple(sizes[d] for d in dims)
1242
+ columns: dict[str, object] = {}
1243
+ if dims:
1244
+ index = np.indices(shape, dtype=np.int64).reshape(len(dims), -1)
1245
+ for d, col in zip(dims, index, strict=True):
1246
+ columns[d] = col
1247
+ for name, (values, _attrs) in members.items():
1248
+ if name in columns:
1249
+ if dims == (name,):
1250
+ # A coordinate variable (``time`` on ``time``): its values replace the
1251
+ # int64 index column, whose position the row order already carries.
1252
+ columns[name] = values.reshape(-1)
1253
+ continue
1254
+ raise AttributedExportError(
1255
+ f"variable {name!r} has the same name as one of its dimensions' index "
1256
+ f"columns; the Parquet layout cannot hold both")
1257
+ columns[name] = values.reshape(-1) if dims else values.reshape(1)
1258
+ try:
1259
+ table = pa.table(columns)
1260
+ except (pa.ArrowInvalid, pa.ArrowNotImplementedError, pa.ArrowTypeError) as exc:
1261
+ raise AttributedExportError(
1262
+ f"pyarrow cannot hold a variable on dimensions {dims} "
1263
+ f"({', '.join(members)}): {exc}") from exc
1264
+ meta = {
1265
+ f"{ATTR_PREFIX}global_attrs": json.dumps(global_attrs),
1266
+ f"{ATTR_PREFIX}var_attrs": json.dumps({n: a for n, (_v, a) in members.items()}),
1267
+ f"{ATTR_PREFIX}dims": json.dumps(list(dims)),
1268
+ f"{ATTR_PREFIX}encoding": ENCODING_PARQUET,
1269
+ }
1270
+ table = table.replace_schema_metadata(meta)
1271
+ fname = ("__".join(dims) if dims else "scalars") + ".parquet"
1272
+ pq.write_table(table, out / fname)
1273
+ return out
1274
+
1275
+
1276
+ def main(argv: Sequence[str] | None = None) -> int:
1277
+ """``python -m arrayprobe.attributed_export FAITHFUL.cdf [OUT.nc] [--zarr] [--parquet]``."""
1278
+ parser = argparse.ArgumentParser(
1279
+ prog="python -m arrayprobe.attributed_export",
1280
+ description=("Write a self-describing sibling of a faithful port product: same values, "
1281
+ "plus the whole .call sidecar and a sourced unit on every variable. The "
1282
+ "faithful file is opened read-only and never modified."))
1283
+ parser.add_argument("source", help="the faithful product (its .call sidecar is read too)")
1284
+ parser.add_argument("out", nargs="?", default=None,
1285
+ help=f"output path (default: <source>{DEFAULT_SUFFIX})")
1286
+ parser.add_argument("--accept-unstamped", action="store_true",
1287
+ help="export a product with no .call sidecar; the file records that its "
1288
+ "provenance is not established")
1289
+ parser.add_argument("--enhancements", default="",
1290
+ help="comma-separated names of enhancements the producing chain applied; "
1291
+ "empty (the default) means none, which is the port's own case")
1292
+ parser.add_argument("--plain", action="store_true",
1293
+ help="write contiguous, uncompressed variables instead of the default "
1294
+ "analysis-ready (chunked, losslessly compressed) encoding; the "
1295
+ "values are identical either way")
1296
+ parser.add_argument("--zarr", action="store_true",
1297
+ help="also write a Zarr store beside the netCDF4 export (<out> with .nc "
1298
+ "replaced by .zarr), same values and attributes; needs the [zarr] "
1299
+ "extra")
1300
+ parser.add_argument("--parquet", action="store_true",
1301
+ help="also write a directory of Parquet files beside the netCDF4 export "
1302
+ "(<out> with .nc replaced by .parquet), one long-form file per "
1303
+ "dimension tuple, attributes as schema metadata; needs the "
1304
+ "[parquet] extra")
1305
+ args = parser.parse_args(argv)
1306
+ names = tuple(n.strip() for n in args.enhancements.split(",") if n.strip())
1307
+ if not Path(args.source).is_file():
1308
+ # Checked first: a mistyped path otherwise failed as "carries no .call sidecar".
1309
+ print(f"{parser.prog}: not a file: {args.source}", file=sys.stderr)
1310
+ return 2
1311
+ try:
1312
+ written = export(args.source, args.out, accept_unstamped=args.accept_unstamped,
1313
+ enhancements=names, analysis_ready=not args.plain)
1314
+ netcdf = written
1315
+ if args.zarr:
1316
+ print(f"wrote {written}")
1317
+ written = export_zarr(netcdf)
1318
+ if args.parquet:
1319
+ print(f"wrote {written}")
1320
+ written = export_parquet(netcdf)
1321
+ except AttributedExportError as exc:
1322
+ # One line, exit 2, as every other refusal on the command line; the library keeps
1323
+ # raising. MissingStampError's text names the keyword, so the flag is added here.
1324
+ hint = (" On the command line that is --accept-unstamped."
1325
+ if isinstance(exc, MissingStampError) else "")
1326
+ print(f"{parser.prog}: {exc}{hint}", file=sys.stderr)
1327
+ return 2
1328
+ print(f"wrote {written}")
1329
+ return 0
1330
+
1331
+
1332
+ if __name__ == "__main__": # pragma: no cover -- exercised through main() in the tests
1333
+ raise SystemExit(main())