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.
- arrayprobe/__init__.py +219 -0
- arrayprobe/__main__.py +19 -0
- arrayprobe/_v314_lazy.py +48 -0
- arrayprobe/ai_ready.py +212 -0
- arrayprobe/attributed_export.py +1333 -0
- arrayprobe/authordefaults.py +267 -0
- arrayprobe/cli.py +3510 -0
- arrayprobe/combine.py +12 -0
- arrayprobe/compare.py +950 -0
- arrayprobe/config.py +1239 -0
- arrayprobe/constants.py +12 -0
- arrayprobe/count_closure.py +204 -0
- arrayprobe/diagnostic_views.py +769 -0
- arrayprobe/diode_report.py +265 -0
- arrayprobe/driver/__init__.py +5 -0
- arrayprobe/driver/_load_record.py +331 -0
- arrayprobe/driver/preflight_inputs.py +250 -0
- arrayprobe/driver/reprocess.py +553 -0
- arrayprobe/driver/run_flight.py +8166 -0
- arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
- arrayprobe/dropsize.py +519 -0
- arrayprobe/friendly.py +206 -0
- arrayprobe/geometry/__init__.py +77 -0
- arrayprobe/geometry/min_rectangle.py +92 -0
- arrayprobe/intarr.py +12 -0
- arrayprobe/intarr_analysis.py +16 -0
- arrayprobe/intarr_plots.py +12 -0
- arrayprobe/inventory.py +129 -0
- arrayprobe/jit_kernels.py +344 -0
- arrayprobe/lwc.py +44 -0
- arrayprobe/masks.py +349 -0
- arrayprobe/matio.py +410 -0
- arrayprobe/matlab_compat.py +13 -0
- arrayprobe/ncio.py +26 -0
- arrayprobe/particle.py +55 -0
- arrayprobe/particle_perimeter.py +12 -0
- arrayprobe/products.py +78 -0
- arrayprobe/profiles.py +179 -0
- arrayprobe/provenance.py +21 -0
- arrayprobe/py.typed +11 -0
- arrayprobe/readers/__init__.py +9 -0
- arrayprobe/readers/dmt.py +603 -0
- arrayprobe/readers/mask_csv.py +12 -0
- arrayprobe/readers/pms.py +12 -0
- arrayprobe/readers/sea.py +433 -0
- arrayprobe/readers/tasinfo.py +12 -0
- arrayprobe/regimes.py +507 -0
- arrayprobe/render.py +728 -0
- arrayprobe/reproduce_report.py +149 -0
- arrayprobe/review_agreement.py +135 -0
- arrayprobe/review_sampling.py +327 -0
- arrayprobe/run_page.py +624 -0
- arrayprobe/sample_area.py +12 -0
- arrayprobe/selector.py +206 -0
- arrayprobe/sizing.py +151 -0
- arrayprobe/time_convert.py +12 -0
- arrayprobe/timing_closure.py +141 -0
- arrayprobe/tools/__init__.py +27 -0
- arrayprobe/tools/make_demo_flight.py +1089 -0
- arrayprobe/tools/make_tas_file.py +760 -0
- arrayprobe/tools/probe_comparison.py +569 -0
- arrayprobe/tools/synthetic_truth.py +698 -0
- arrayprobe/tools/tas_sources.py +705 -0
- arrayprobe/triage_context.py +488 -0
- arrayprobe/triage_server.py +5215 -0
- arrayprobe/tune/__init__.py +15 -0
- arrayprobe/tune/diodes.py +400 -0
- arrayprobe/tune/distributions.py +300 -0
- arrayprobe/tune/sample.py +243 -0
- arrayprobe/tune/score.py +230 -0
- arrayprobe/tune/settings.py +354 -0
- arrayprobe/validate_by_condition.py +208 -0
- arrayprobe/validation_report.py +166 -0
- arrayprobe-0.1.0.dist-info/METADATA +260 -0
- arrayprobe-0.1.0.dist-info/RECORD +189 -0
- arrayprobe-0.1.0.dist-info/WHEEL +5 -0
- arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
- arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
- arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
- arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
- arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
- arrayprobe_soda2/__init__.py +131 -0
- arrayprobe_soda2/angles.py +143 -0
- arrayprobe_soda2/aspect_ratio.py +541 -0
- arrayprobe_soda2/backfill.py +100 -0
- arrayprobe_soda2/binary_dof.py +181 -0
- arrayprobe_soda2/buildindex.py +113 -0
- arrayprobe_soda2/decompress_dmt.py +285 -0
- arrayprobe_soda2/enhancement_hooks.py +275 -0
- arrayprobe_soda2/export_ascii.py +732 -0
- arrayprobe_soda2/export_ncdf.py +683 -0
- arrayprobe_soda2/export_ncdf_raf.py +396 -0
- arrayprobe_soda2/fillholes.py +161 -0
- arrayprobe_soda2/find_radius.py +105 -0
- arrayprobe_soda2/findsize.py +407 -0
- arrayprobe_soda2/fit_poisson.py +170 -0
- arrayprobe_soda2/fix2dimage.py +63 -0
- arrayprobe_soda2/fixraking.py +162 -0
- arrayprobe_soda2/fixstuckbits.py +146 -0
- arrayprobe_soda2/hvps4_read_frame.py +121 -0
- arrayprobe_soda2/jit_kernels.py +152 -0
- arrayprobe_soda2/label_blobs.py +177 -0
- arrayprobe_soda2/min_circle_fast.py +320 -0
- arrayprobe_soda2/particlesort.py +703 -0
- arrayprobe_soda2/pbp_writer.py +558 -0
- arrayprobe_soda2/poisson_spot_correct.py +183 -0
- arrayprobe_soda2/princomp.py +107 -0
- arrayprobe_soda2/probespecs.py +361 -0
- arrayprobe_soda2/process_2d.py +1364 -0
- arrayprobe_soda2/process_2d_parallel.py +626 -0
- arrayprobe_soda2/process_hk.py +512 -0
- arrayprobe_soda2/processbuffer_2dc.py +155 -0
- arrayprobe_soda2/processbuffer_cip.py +213 -0
- arrayprobe_soda2/processbuffer_f2dc.py +139 -0
- arrayprobe_soda2/processbuffer_spec.py +441 -0
- arrayprobe_soda2/processbuffer_tail.py +350 -0
- arrayprobe_soda2/pth_readers.py +245 -0
- arrayprobe_soda2/py.typed +11 -0
- arrayprobe_soda2/read2dbuffer.py +371 -0
- arrayprobe_soda2/reject.py +246 -0
- arrayprobe_soda2/reprocess_pbp.py +156 -0
- arrayprobe_soda2/sample_area.py +264 -0
- arrayprobe_soda2/save_writer.py +480 -0
- arrayprobe_soda2/sea.py +324 -0
- arrayprobe_soda2/spec_absolutepointers.py +109 -0
- arrayprobe_soda2/spec_decompress.py +203 -0
- arrayprobe_soda2/spec_index.py +476 -0
- arrayprobe_soda2/spec_read_frame.py +286 -0
- arrayprobe_soda2/spec_read_hk.py +301 -0
- arrayprobe_soda2/spec_readint.py +127 -0
- arrayprobe_soda2/timeconv.py +77 -0
- arrayprobe_soda2/update_op.py +101 -0
- arrayprobe_uiops/__init__.py +45 -0
- arrayprobe_uiops/combine.py +192 -0
- arrayprobe_uiops/combine_fork.py +359 -0
- arrayprobe_uiops/constants.py +830 -0
- arrayprobe_uiops/decode_naming.py +113 -0
- arrayprobe_uiops/diode_mask.py +250 -0
- arrayprobe_uiops/engine_absence.py +41 -0
- arrayprobe_uiops/export_oap.py +325 -0
- arrayprobe_uiops/geometry_core.py +366 -0
- arrayprobe_uiops/habit.py +749 -0
- arrayprobe_uiops/habit_core.py +248 -0
- arrayprobe_uiops/hollow_size_rule.py +376 -0
- arrayprobe_uiops/imgproc.py +2081 -0
- arrayprobe_uiops/imgproc_core.py +275 -0
- arrayprobe_uiops/intarr.py +167 -0
- arrayprobe_uiops/intarr_analysis.py +569 -0
- arrayprobe_uiops/intarr_plots.py +119 -0
- arrayprobe_uiops/jit_kernels.py +430 -0
- arrayprobe_uiops/lwc.py +70 -0
- arrayprobe_uiops/matlab_compat.py +860 -0
- arrayprobe_uiops/measure.py +346 -0
- arrayprobe_uiops/min_circle.py +204 -0
- arrayprobe_uiops/min_ellipse.py +161 -0
- arrayprobe_uiops/min_rectangle.py +200 -0
- arrayprobe_uiops/ncar_2dc_timing.py +100 -0
- arrayprobe_uiops/ncio.py +810 -0
- arrayprobe_uiops/oap_read.py +228 -0
- arrayprobe_uiops/particle.py +51 -0
- arrayprobe_uiops/particle_perimeter.py +94 -0
- arrayprobe_uiops/particle_physics.py +199 -0
- arrayprobe_uiops/pecan_params.py +134 -0
- arrayprobe_uiops/probe_cases.py +298 -0
- arrayprobe_uiops/product_sanity.py +337 -0
- arrayprobe_uiops/profile.py +71 -0
- arrayprobe_uiops/profiles.py +756 -0
- arrayprobe_uiops/provenance.py +804 -0
- arrayprobe_uiops/py.typed +11 -0
- arrayprobe_uiops/qc.py +169 -0
- arrayprobe_uiops/readers/__init__.py +8 -0
- arrayprobe_uiops/readers/mask_csv.py +74 -0
- arrayprobe_uiops/readers/pms.py +239 -0
- arrayprobe_uiops/readers/tasinfo.py +57 -0
- arrayprobe_uiops/rect_ellipse.py +129 -0
- arrayprobe_uiops/register_image_assisted.py +25 -0
- arrayprobe_uiops/reject.py +501 -0
- arrayprobe_uiops/reject_core.py +220 -0
- arrayprobe_uiops/sample_area.py +93 -0
- arrayprobe_uiops/sizedist.py +1923 -0
- arrayprobe_uiops/sizedist_core.py +814 -0
- arrayprobe_uiops/sizedist_tables.py +642 -0
- arrayprobe_uiops/spec.py +1094 -0
- arrayprobe_uiops/spec_core.py +703 -0
- arrayprobe_uiops/stray_pixel.py +103 -0
- arrayprobe_uiops/tas.py +191 -0
- arrayprobe_uiops/time_convert.py +41 -0
- uiops/__init__.py +402 -0
- uiops/py.typed +11 -0
arrayprobe_uiops/ncio.py
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""MATLAB ``netcdf.*`` package semantics on top of netCDF4-python.
|
|
3
|
+
|
|
4
|
+
Reproduces the low-level MATLAB netCDF interface used by UIOOPS v3.1.4 so ported
|
|
5
|
+
call sites can be transliterated 1:1. Two semantics this module exists to
|
|
6
|
+
preserve:
|
|
7
|
+
|
|
8
|
+
**(1) The dimension reversal.** MATLAB stores arrays fastest-varying-dimension
|
|
9
|
+
first and reverses the dimension list when it calls the C API. Verified three
|
|
10
|
+
independent ways (design doc §1.2): ``read_binary_SPEC.m:44-56`` declares ``data``
|
|
11
|
+
as ``[ImgRowlen(8) ImgBlocklen(1700) time]``, and the shipped
|
|
12
|
+
``2DS.20151205_subset1.V.cdf`` holds it as ``('time','ImgBlocklen','ImgRowlen')``
|
|
13
|
+
with shape ``(1000, 1700, 8)``.
|
|
14
|
+
|
|
15
|
+
The reversal lives in exactly one place here -- :func:`_c_order` and
|
|
16
|
+
:func:`_c_order_index` -- and every public entry point routes through it.
|
|
17
|
+
Callers pass MATLAB-order arguments and get MATLAB-shaped arrays back. **There is
|
|
18
|
+
no public way to hand-roll a transpose, deliberately.**
|
|
19
|
+
|
|
20
|
+
A corollary worth internalizing: the ``'`` at a MATLAB call site and the dim
|
|
21
|
+
reversal *cancel*. Anywhere MATLAB writes ``X'`` into a 2-D netCDF variable
|
|
22
|
+
(``imgProc_sm.m:885,929``; ``sizeDist.m:2104-2154``; ``read_binary_DMT.m:202``;
|
|
23
|
+
``read_binary_SEA.m:211``; ``IntArrAnalysis.m:293``), Python writes ``X``
|
|
24
|
+
unchanged in ``(time, other)`` order. So does ``permute(X,[3 2 1])`` at
|
|
25
|
+
``sizeDist.m:2110,2117,2136,2142``.
|
|
26
|
+
|
|
27
|
+
**(2) Raw versus masked reads.** MATLAB's low-level ``netcdf.getVar`` returns RAW
|
|
28
|
+
values -- no ``_FillValue`` masking, no ``scale_factor``/``add_offset``.
|
|
29
|
+
netCDF4-python masks by default *even when no ``_FillValue`` attribute exists*.
|
|
30
|
+
:func:`get_var` therefore forces masking off, while :func:`ncread` -- the
|
|
31
|
+
high-level MATLAB function, used at ``imgProc_sm.m:169-170,184-185`` -- keeps it
|
|
32
|
+
on. Two functions, two policies; this is the single most important behavioural
|
|
33
|
+
distinction in the module.
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
MATLAB source of truth: ``UIOPS-v3.1.4/joefinlon-UIOPS-ba5e67c/``.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import contextlib
|
|
42
|
+
import os
|
|
43
|
+
import warnings
|
|
44
|
+
from collections.abc import Iterable, Iterator
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
from typing import Any, Literal, cast
|
|
47
|
+
|
|
48
|
+
import numpy as np
|
|
49
|
+
import numpy.typing as npt
|
|
50
|
+
from netCDF4 import Dataset, Variable
|
|
51
|
+
|
|
52
|
+
from . import provenance
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"NC_UNLIMITED",
|
|
56
|
+
"NC_GLOBAL",
|
|
57
|
+
"MATLAB_NC_TYPES",
|
|
58
|
+
"NC_FILL",
|
|
59
|
+
"get_constant",
|
|
60
|
+
"NcFile",
|
|
61
|
+
"create",
|
|
62
|
+
"open",
|
|
63
|
+
"def_dim",
|
|
64
|
+
"def_var",
|
|
65
|
+
"put_att",
|
|
66
|
+
"end_def",
|
|
67
|
+
"inq_dim",
|
|
68
|
+
"inq_var_id",
|
|
69
|
+
"get_var",
|
|
70
|
+
"put_var",
|
|
71
|
+
"close",
|
|
72
|
+
"ncread",
|
|
73
|
+
"read_image_record",
|
|
74
|
+
"write_record_block",
|
|
75
|
+
"put_provenance",
|
|
76
|
+
"read_provenance",
|
|
77
|
+
"provenance_of",
|
|
78
|
+
"engine_of",
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# --------------------------------------------------------------------------
|
|
83
|
+
# Constants
|
|
84
|
+
# --------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
NC_UNLIMITED = 0
|
|
87
|
+
"""``netcdf.getConstant('NC_UNLIMITED')`` -- ``imgProc_sm.m:214``,
|
|
88
|
+
``read_binary_SPEC.m:44,61``."""
|
|
89
|
+
|
|
90
|
+
NC_GLOBAL = -1
|
|
91
|
+
"""``netcdf.getConstant('NC_GLOBAL')`` -- ``imgProc_sm.m:218``,
|
|
92
|
+
``sizeDist.m:1807``, ``IntArrAnalysis.m:249``."""
|
|
93
|
+
|
|
94
|
+
MATLAB_NC_TYPES: dict[str, type | str] = {
|
|
95
|
+
# 'byte' is SIGNED int8. Confirmed empirically: month/day/hour/minute/second/
|
|
96
|
+
# wkday all report int8 in all three shipped probe files. Guessing uint8 here
|
|
97
|
+
# silently corrupts every date field. read_binary_SPEC.m:49-53.
|
|
98
|
+
"byte": np.int8,
|
|
99
|
+
"short": np.int16, # read_binary_SPEC.m:48 -> year
|
|
100
|
+
"int": np.int32, # read_binary_SPEC.m:56 -> data
|
|
101
|
+
"float": np.float32, # never used in UIOOPS; mapping is unambiguous
|
|
102
|
+
"double": np.float64, # read_binary_SEA.m:39-47; all of sizeDist.m:1874-2089
|
|
103
|
+
# NC_CHAR. No defVar(...,'char',...) site exists in UIOOPS or the ORACLES
|
|
104
|
+
# variant; measured under Octave's netcdf package instead
|
|
105
|
+
# (octave_oracle/run_defvar_char_bank.py): xtype 2, one byte per element,
|
|
106
|
+
# unwritten elements NUL (0), which netCDF4-python reads as dtype 'S1'.
|
|
107
|
+
"char": "S1",
|
|
108
|
+
}
|
|
109
|
+
"""MATLAB ``defVar`` type strings to numpy dtypes (``'S1'`` for ``'char'``).
|
|
110
|
+
|
|
111
|
+
The ``'char'`` mapping is measured, not assumed: Octave's ``netcdf.defVar(...,'char',...)``
|
|
112
|
+
writes ``NC_CHAR``, and the port's write is asserted byte for byte against that file
|
|
113
|
+
(``tests/test_ncio_char.py``, golden ``tests/data/defvar_char_octave_golden.json``).
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
NC_FILL: dict[str, int | float] = {
|
|
117
|
+
"byte": -127, # NC_FILL_BYTE
|
|
118
|
+
"short": -32767, # NC_FILL_SHORT
|
|
119
|
+
"int": -2147483647, # NC_FILL_INT
|
|
120
|
+
"float": 9.9692099683868690e36, # NC_FILL_FLOAT
|
|
121
|
+
"double": 9.9692099683868690e36, # NC_FILL_DOUBLE
|
|
122
|
+
}
|
|
123
|
+
"""netCDF-3 default fill values.
|
|
124
|
+
|
|
125
|
+
UIOOPS never writes ``_FillValue``, never calls ``defVarFill`` and never calls
|
|
126
|
+
``setFill`` (design doc §1.6), so unwritten records carry exactly these. They are
|
|
127
|
+
what :func:`get_var` returns *raw*, and what :func:`ncread` masks.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
_NC_FORMATS = ("NETCDF3_CLASSIC", "NETCDF3_64BIT_OFFSET", "NETCDF4_CLASSIC", "NETCDF4")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@contextlib.contextmanager
|
|
134
|
+
def _quiet_netcdf4_setitem() -> Iterator[None]:
|
|
135
|
+
"""Suppress one third-party DeprecationWarning around netCDF4 assignment.
|
|
136
|
+
|
|
137
|
+
``netCDF4 1.7.4``'s ``Variable.__setitem__`` sets ``.shape`` on the incoming
|
|
138
|
+
array in place, which NumPy 2.5 deprecates. It fires even for a perfectly
|
|
139
|
+
contiguous, exactly-shaped input, so it cannot be avoided from this side --
|
|
140
|
+
only by moving a pin, which we are not doing for a warning.
|
|
141
|
+
|
|
142
|
+
Scoped to the two assignment sites rather than filtered globally, so a
|
|
143
|
+
deprecation raised by *our own* code still surfaces, and so a test suite may
|
|
144
|
+
run under ``warnings.simplefilter('error')``. Revisit when netCDF4 releases
|
|
145
|
+
a NumPy 2.5-clean version; see ``requirements.txt``.
|
|
146
|
+
"""
|
|
147
|
+
with warnings.catch_warnings():
|
|
148
|
+
warnings.filterwarnings(
|
|
149
|
+
"ignore",
|
|
150
|
+
message="Setting the shape on a NumPy array has been deprecated",
|
|
151
|
+
category=DeprecationWarning,
|
|
152
|
+
)
|
|
153
|
+
yield
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def get_constant(name: str) -> int:
|
|
157
|
+
"""``netcdf.getConstant(name)`` for the two constants UIOOPS uses."""
|
|
158
|
+
try:
|
|
159
|
+
return {"NC_UNLIMITED": NC_UNLIMITED, "NC_GLOBAL": NC_GLOBAL}[name]
|
|
160
|
+
except KeyError:
|
|
161
|
+
raise ValueError(
|
|
162
|
+
f"netcdf.getConstant({name!r}): UIOPS uses only NC_UNLIMITED and "
|
|
163
|
+
"NC_GLOBAL (design doc §1.1). Add it here with its call site if a "
|
|
164
|
+
"later stage genuinely needs another."
|
|
165
|
+
) from None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# --------------------------------------------------------------------------
|
|
169
|
+
# The dimension reversal -- the ONLY place it happens
|
|
170
|
+
# --------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
def _c_order(seq: Iterable[Any]) -> tuple[Any, ...]:
|
|
173
|
+
"""MATLAB dimension order (fastest first) -> C/on-disk order (slowest first).
|
|
174
|
+
|
|
175
|
+
Its own inverse, so it also converts back. Every reversal in this module
|
|
176
|
+
goes through here or through :func:`_c_order_index`.
|
|
177
|
+
"""
|
|
178
|
+
return tuple(seq)[::-1]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _c_order_index(start: npt.ArrayLike, count: npt.ArrayLike) -> tuple[slice, ...]:
|
|
182
|
+
"""MATLAB ``start``/``count`` vectors -> a C-order tuple of slices.
|
|
183
|
+
|
|
184
|
+
``start`` is **0-based everywhere** in UIOOPS. Evidence: ``imgProc_sm.m:452-453``
|
|
185
|
+
initializes ``w=-1; wstart=0;`` before feeding ``:873``, and ``sizeDist.m:686``
|
|
186
|
+
writes ``start_all = find(startindex)-1;`` -- explicitly converting 1-based
|
|
187
|
+
``find`` results to 0-based netCDF starts.
|
|
188
|
+
"""
|
|
189
|
+
s = np.atleast_1d(np.asarray(start, dtype=np.int64))
|
|
190
|
+
c = np.atleast_1d(np.asarray(count, dtype=np.int64))
|
|
191
|
+
if s.shape != c.shape:
|
|
192
|
+
raise ValueError(f"start and count must have equal length, got {s.shape} and {c.shape}")
|
|
193
|
+
return tuple(
|
|
194
|
+
slice(int(a), int(a) + int(n))
|
|
195
|
+
for a, n in zip(_c_order(s), _c_order(c), strict=True)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _as_char_array(data: str | npt.ArrayLike) -> np.ndarray:
|
|
200
|
+
"""A MATLAB char argument to ``putVar`` -> an ``'S1'`` array in MATLAB shape.
|
|
201
|
+
|
|
202
|
+
A Python ``str`` is a MATLAB char row (``1xN``), as ``netcdf.putVar(ncid,vid,'wxyz')``
|
|
203
|
+
passes it; an array of ``'S1'`` or one-character ``'U1'`` elements is a char matrix
|
|
204
|
+
already in MATLAB order, so ``names'`` at the call site stays a transpose here too.
|
|
205
|
+
A MATLAB char is one byte on disk (``NC_CHAR``), so each character must encode to
|
|
206
|
+
one Latin-1 byte.
|
|
207
|
+
"""
|
|
208
|
+
if isinstance(data, str):
|
|
209
|
+
return np.array([c.encode("latin-1") for c in data], dtype="S1").reshape(1, -1)
|
|
210
|
+
arr = np.asarray(data)
|
|
211
|
+
if arr.dtype.kind == "U":
|
|
212
|
+
if arr.dtype.itemsize > 4:
|
|
213
|
+
raise ValueError("a char putVar takes one character per element, not strings")
|
|
214
|
+
return np.char.encode(arr, "latin-1").astype("S1")
|
|
215
|
+
if arr.dtype.kind == "S":
|
|
216
|
+
if arr.dtype.itemsize > 1:
|
|
217
|
+
raise ValueError("a char putVar takes one character per element, not strings")
|
|
218
|
+
return arr.astype("S1")
|
|
219
|
+
raise TypeError(f"a char variable takes str or 'S1'/'U1' data, got {arr.dtype}")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _to_matlab_shape(arr: np.ndarray) -> np.ndarray:
|
|
223
|
+
"""Reverse the axes and apply MATLAB's shape conventions.
|
|
224
|
+
|
|
225
|
+
MATLAB arrays are always at least 2-D and drop **trailing** singleton
|
|
226
|
+
dimensions. So ``getVar(f,id,[0,0,i-1],[8,1700,1])`` is ``8x1700``, not
|
|
227
|
+
``8x1700x1``, and a whole 1-D variable of length ``N`` comes back ``Nx1`` --
|
|
228
|
+
a column. The column part matters more than it looks: ``sizeDist.m:815``
|
|
229
|
+
(``[0;diff(Time_in_seconds)]``) and ``:713`` (``[diff(start_all); ...]``) are
|
|
230
|
+
vertical concatenations, which only typecheck on columns (a MATLAB-compatibility gap, and §T3
|
|
231
|
+
of the design doc).
|
|
232
|
+
"""
|
|
233
|
+
out = np.transpose(arr)
|
|
234
|
+
while out.ndim > 2 and out.shape[-1] == 1:
|
|
235
|
+
out = out.reshape(out.shape[:-1])
|
|
236
|
+
while out.ndim < 2:
|
|
237
|
+
out = out.reshape(out.shape + (1,))
|
|
238
|
+
return out
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _from_matlab_shape(arr: np.ndarray, target_shape: tuple[int, ...]) -> np.ndarray:
|
|
242
|
+
"""Inverse of :func:`_to_matlab_shape` for writes.
|
|
243
|
+
|
|
244
|
+
``target_shape`` is the C-order shape of the destination region, so the
|
|
245
|
+
MATLAB-shaped ``arr`` is reversed and then reshaped onto it. This is where
|
|
246
|
+
the ``X'`` at a MATLAB ``putVar`` call site cancels against the reversal.
|
|
247
|
+
"""
|
|
248
|
+
out = np.transpose(np.asarray(arr))
|
|
249
|
+
if out.shape == target_shape:
|
|
250
|
+
# Contiguous, because netCDF4 1.7.4 reshapes a non-contiguous input
|
|
251
|
+
# in-place and NumPy 2.5 deprecates that.
|
|
252
|
+
return np.ascontiguousarray(out)
|
|
253
|
+
# MATLAB pads to 2-D and drops trailing singletons, so a shape mismatch is
|
|
254
|
+
# legitimate whenever the element count agrees -- e.g. a 1x1 write into a
|
|
255
|
+
# scalar hyperslab, or an (N,1) column into a 1-D region of length N.
|
|
256
|
+
if out.size != int(np.prod(target_shape, dtype=np.int64)):
|
|
257
|
+
raise ValueError(
|
|
258
|
+
f"cannot write an array of shape {np.shape(arr)} (MATLAB order) into a "
|
|
259
|
+
f"region of on-disk shape {target_shape}"
|
|
260
|
+
)
|
|
261
|
+
return np.ascontiguousarray(out.reshape(target_shape))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# --------------------------------------------------------------------------
|
|
265
|
+
# The file handle
|
|
266
|
+
# --------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
class NcFile:
|
|
269
|
+
"""A MATLAB ``ncid``.
|
|
270
|
+
|
|
271
|
+
MATLAB identifies dimensions and variables by **integer IDs assigned in
|
|
272
|
+
creation order**, and UIOOPS relies on that: ``imgProc_sm.m:205-206`` reads
|
|
273
|
+
dimension 0 (``time``) and dimension 2 (``ImgBlocklen``) by number alone,
|
|
274
|
+
never by name. A bare :class:`netCDF4.Dataset` has no such numbering, so this
|
|
275
|
+
class keeps it -- along with the mask/scale policy and the define-mode state.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
def __init__(self, ds: Dataset, *, define_mode: bool):
|
|
279
|
+
self._ds = ds
|
|
280
|
+
self._dim_names: list[str] = list(ds.dimensions)
|
|
281
|
+
self._var_names: list[str] = list(ds.variables)
|
|
282
|
+
self._in_define = define_mode
|
|
283
|
+
for var in ds.variables.values():
|
|
284
|
+
var.set_auto_maskandscale(False)
|
|
285
|
+
|
|
286
|
+
# -- properties ------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
@property
|
|
289
|
+
def dataset(self) -> Dataset:
|
|
290
|
+
"""The underlying :class:`netCDF4.Dataset`.
|
|
291
|
+
|
|
292
|
+
For tests and for :mod:`tools.compare_nc`. Ported call sites must not
|
|
293
|
+
reach through it -- that is how a hand-rolled transpose gets in.
|
|
294
|
+
"""
|
|
295
|
+
return self._ds
|
|
296
|
+
|
|
297
|
+
@property
|
|
298
|
+
def in_define_mode(self) -> bool:
|
|
299
|
+
"""Whether the file is still in netCDF define mode.
|
|
300
|
+
|
|
301
|
+
NETCDF3_CLASSIC has the two-mode discipline MATLAB's ``netcdf.*``
|
|
302
|
+
surface exposes: dimensions, variables and attributes are created in
|
|
303
|
+
define mode, data is written in data mode, and ``netcdf.endDef``
|
|
304
|
+
crosses over one way. netCDF4-python hides that, so it is tracked here
|
|
305
|
+
instead and ``_require_define`` raises on a define-mode call made after
|
|
306
|
+
the crossing -- the same error MATLAB would give, rather than a silent
|
|
307
|
+
success that would let a call order the MATLAB cannot express pass
|
|
308
|
+
review.
|
|
309
|
+
"""
|
|
310
|
+
return self._in_define
|
|
311
|
+
|
|
312
|
+
# -- definition ------------------------------------------------------
|
|
313
|
+
|
|
314
|
+
def def_dim(self, name: str, length: int) -> int:
|
|
315
|
+
"""``netcdf.defDim(ncid,name,length)``; ``length == NC_UNLIMITED`` (0) is a
|
|
316
|
+
record dimension. Returns the 0-based dimension ID."""
|
|
317
|
+
self._require_define("defDim")
|
|
318
|
+
self._ds.createDimension(name, None if length == NC_UNLIMITED else int(length))
|
|
319
|
+
self._dim_names.append(name)
|
|
320
|
+
return len(self._dim_names) - 1
|
|
321
|
+
|
|
322
|
+
def def_var(
|
|
323
|
+
self,
|
|
324
|
+
name: str,
|
|
325
|
+
xtype: str,
|
|
326
|
+
dimids: npt.ArrayLike,
|
|
327
|
+
*,
|
|
328
|
+
chunksizes: npt.ArrayLike | None = None,
|
|
329
|
+
) -> int:
|
|
330
|
+
"""``netcdf.defVar(ncid,name,xtype,dimids)`` with ``dimids`` in MATLAB order.
|
|
331
|
+
|
|
332
|
+
**This is the only place the reversal happens on write.**
|
|
333
|
+
``read_binary_SPEC.m:56`` passes ``[dimid1 dimid2 dimid0]`` =
|
|
334
|
+
``[ImgRowlen ImgBlocklen time]`` and the file holds
|
|
335
|
+
``('time','ImgBlocklen','ImgRowlen')``.
|
|
336
|
+
|
|
337
|
+
``chunksizes`` mirrors ``netcdf.defVarChunking(ncid,varid,'CHUNKED',chunkSizes)``:
|
|
338
|
+
MATLAB order, like ``dimids``, reversed by the same :func:`_c_order`, so no caller
|
|
339
|
+
transposes it by hand. ``None`` (the default) passes nothing to
|
|
340
|
+
``createVariable`` and leaves the library's default chunking, exactly as before
|
|
341
|
+
the keyword existed. A value on a classic-model file, which has no chunks, or
|
|
342
|
+
one whose length differs from ``dimids``'s, raises :class:`ValueError`.
|
|
343
|
+
"""
|
|
344
|
+
self._require_define("defVar")
|
|
345
|
+
try:
|
|
346
|
+
dtype = MATLAB_NC_TYPES[xtype]
|
|
347
|
+
except KeyError:
|
|
348
|
+
raise ValueError(
|
|
349
|
+
f"unknown MATLAB netCDF type {xtype!r}; UIOPS uses only "
|
|
350
|
+
f"{sorted(MATLAB_NC_TYPES)} (design doc §1.4)"
|
|
351
|
+
) from None
|
|
352
|
+
ids = np.atleast_1d(np.asarray(dimids, dtype=np.int64))
|
|
353
|
+
names = tuple(self._dim_names[int(i)] for i in _c_order(ids))
|
|
354
|
+
extra: dict[str, Any] = {}
|
|
355
|
+
if chunksizes is not None:
|
|
356
|
+
if self._ds.data_model not in ("NETCDF4", "NETCDF4_CLASSIC"):
|
|
357
|
+
raise ValueError(
|
|
358
|
+
f"defVarChunking on variable {name!r}: a {self._ds.data_model} file "
|
|
359
|
+
"has no chunks; chunksizes needs a NETCDF4 or NETCDF4_CLASSIC file"
|
|
360
|
+
)
|
|
361
|
+
sizes = [int(n) for n in np.atleast_1d(np.asarray(chunksizes, dtype=np.int64))]
|
|
362
|
+
if len(sizes) != len(ids):
|
|
363
|
+
raise ValueError(
|
|
364
|
+
f"defVarChunking on variable {name!r}: {len(sizes)} chunk sizes for "
|
|
365
|
+
f"{len(ids)} dimensions"
|
|
366
|
+
)
|
|
367
|
+
extra["chunksizes"] = tuple(_c_order(sizes))
|
|
368
|
+
# Annotated because ``createVariable`` is generic in its element type and
|
|
369
|
+
# mypy cannot solve the type variable from a runtime ``dtype`` looked up
|
|
370
|
+
# out of ``MATLAB_NC_TYPES``. ``Variable`` (i.e. ``Variable[Any]``) is
|
|
371
|
+
# exactly what it returns; nothing here depends on the element type.
|
|
372
|
+
var: Variable = self._ds.createVariable(name, dtype, names, **extra)
|
|
373
|
+
var.set_auto_maskandscale(False)
|
|
374
|
+
self._var_names.append(name)
|
|
375
|
+
return len(self._var_names) - 1
|
|
376
|
+
|
|
377
|
+
def put_att(self, varid: int, name: str, value: Any) -> None:
|
|
378
|
+
"""``netcdf.putAtt(ncid,varid,name,value)``; ``varid`` may be
|
|
379
|
+
:data:`NC_GLOBAL`.
|
|
380
|
+
|
|
381
|
+
Attribute names contain spaces (``'Creation Time'``, ``'SA Method'``,
|
|
382
|
+
``'Dmax Definition'``) and the ``Units``/``units`` case is inconsistent
|
|
383
|
+
between ``imgProc_sm.m`` and ``sizeDist.m``. Both are part of the output
|
|
384
|
+
contract -- written verbatim, never normalized.
|
|
385
|
+
"""
|
|
386
|
+
self._require_define("putAtt")
|
|
387
|
+
target = self._ds if varid == NC_GLOBAL else self._ds.variables[self._var_names[varid]]
|
|
388
|
+
target.setncattr(name, value)
|
|
389
|
+
|
|
390
|
+
def end_def(self) -> None:
|
|
391
|
+
"""``netcdf.endDef(ncid)``.
|
|
392
|
+
|
|
393
|
+
netCDF4-python leaves define mode implicitly, so this changes no bytes --
|
|
394
|
+
but it flips the state that makes a ``putVar``-before-``endDef`` (or a
|
|
395
|
+
``putAtt``-after-) fail here exactly as it fails in MATLAB. UIOOPS never
|
|
396
|
+
calls ``reDef``, so the one-way transition is faithful.
|
|
397
|
+
"""
|
|
398
|
+
self._in_define = False
|
|
399
|
+
|
|
400
|
+
# -- inquiry ---------------------------------------------------------
|
|
401
|
+
|
|
402
|
+
def inq_dim(self, dimid: int) -> tuple[str, int]:
|
|
403
|
+
"""``[name,len] = netcdf.inqDim(ncid,dimid)``.
|
|
404
|
+
|
|
405
|
+
``imgProc_sm.m:205-206`` calls this with the bare numbers 2 and 0.
|
|
406
|
+
"""
|
|
407
|
+
name = self._dim_names[dimid]
|
|
408
|
+
return name, len(self._ds.dimensions[name])
|
|
409
|
+
|
|
410
|
+
def inq_var_id(self, name: str) -> int:
|
|
411
|
+
"""``netcdf.inqVarID(ncid,name)``."""
|
|
412
|
+
try:
|
|
413
|
+
return self._var_names.index(name)
|
|
414
|
+
except ValueError:
|
|
415
|
+
raise KeyError(
|
|
416
|
+
f"netcdf.inqVarID: no variable {name!r} in {self._ds.filepath()}"
|
|
417
|
+
) from None
|
|
418
|
+
|
|
419
|
+
def variable(self, varid: int) -> Variable:
|
|
420
|
+
"""The underlying netCDF4 ``Variable``, with mask/scale already off.
|
|
421
|
+
|
|
422
|
+
For the fused helpers below and for structural assertions in tests. Not
|
|
423
|
+
for ported call sites: reaching for the on-disk array is how a hand-rolled
|
|
424
|
+
transpose gets back in.
|
|
425
|
+
"""
|
|
426
|
+
var = self._ds.variables[self._var_names[varid]]
|
|
427
|
+
var.set_auto_maskandscale(False)
|
|
428
|
+
return var
|
|
429
|
+
|
|
430
|
+
# -- data motion -----------------------------------------------------
|
|
431
|
+
|
|
432
|
+
def get_var(
|
|
433
|
+
self,
|
|
434
|
+
varid: int,
|
|
435
|
+
start: npt.ArrayLike | None = None,
|
|
436
|
+
count: npt.ArrayLike | None = None,
|
|
437
|
+
) -> np.ndarray:
|
|
438
|
+
"""``netcdf.getVar`` -- all three signatures UIOOPS uses.
|
|
439
|
+
|
|
440
|
+
``start``/``count`` are 0-based and in MATLAB dimension order; the return
|
|
441
|
+
is in MATLAB dimension order and shape. Auto mask/scale is **OFF**, so
|
|
442
|
+
unwritten records come back as the raw :data:`NC_FILL` values, which is
|
|
443
|
+
what MATLAB hands the caller.
|
|
444
|
+
"""
|
|
445
|
+
var = self.variable(varid)
|
|
446
|
+
if start is None and count is None:
|
|
447
|
+
raw = var[...]
|
|
448
|
+
elif start is None or count is None:
|
|
449
|
+
raise ValueError("netcdf.getVar takes start and count together or neither")
|
|
450
|
+
else:
|
|
451
|
+
raw = var[_c_order_index(start, count)]
|
|
452
|
+
return _to_matlab_shape(np.asarray(raw))
|
|
453
|
+
|
|
454
|
+
def put_var(self, varid: int, *args: Any) -> None:
|
|
455
|
+
"""``netcdf.putVar`` -- all three signatures UIOOPS uses.
|
|
456
|
+
|
|
457
|
+
``put_var(vid, data)`` writes a whole variable; ``put_var(vid, start,
|
|
458
|
+
count, data)`` writes a hyperslab. ``data`` is MATLAB-ordered, so
|
|
459
|
+
``imgProc_sm.m:885``::
|
|
460
|
+
|
|
461
|
+
netcdf.putVar(f, vid, [0 wstart], [2 w-wstart+1], images.position')
|
|
462
|
+
|
|
463
|
+
transliterates as ``put_var(vid, [0, wstart], [2, n], position)`` with
|
|
464
|
+
``position`` of shape ``(2, n)``, landing on disk as ``(time, 2)``.
|
|
465
|
+
"""
|
|
466
|
+
if self._in_define:
|
|
467
|
+
raise RuntimeError(
|
|
468
|
+
"netcdf.putVar before netcdf.endDef: the file is still in define "
|
|
469
|
+
"mode (MATLAB raises NC_EINDEFINE). Call end_def() first."
|
|
470
|
+
)
|
|
471
|
+
var = self.variable(varid)
|
|
472
|
+
if var.dtype == np.dtype("S1"):
|
|
473
|
+
args = args[:-1] + (_as_char_array(args[-1]),)
|
|
474
|
+
if len(args) == 1:
|
|
475
|
+
(data,) = args
|
|
476
|
+
arr = np.asarray(data)
|
|
477
|
+
if var.shape == ():
|
|
478
|
+
with _quiet_netcdf4_setitem():
|
|
479
|
+
var[...] = arr
|
|
480
|
+
else:
|
|
481
|
+
# An unlimited dimension reports its CURRENT length, which is 0 on
|
|
482
|
+
# a freshly created file, so size the region from the data instead.
|
|
483
|
+
region = tuple(var.shape)
|
|
484
|
+
if 0 in region:
|
|
485
|
+
region = _c_order(np.shape(arr))
|
|
486
|
+
with _quiet_netcdf4_setitem():
|
|
487
|
+
var[...] = _from_matlab_shape(arr, tuple(region))
|
|
488
|
+
elif len(args) == 3:
|
|
489
|
+
start, count, data = args
|
|
490
|
+
index = _c_order_index(start, count)
|
|
491
|
+
target = tuple(sl.stop - sl.start for sl in index)
|
|
492
|
+
with _quiet_netcdf4_setitem():
|
|
493
|
+
var[index] = _from_matlab_shape(np.asarray(data), target)
|
|
494
|
+
else:
|
|
495
|
+
raise TypeError(
|
|
496
|
+
"netcdf.putVar takes (varid, data) or (varid, start, count, data); "
|
|
497
|
+
f"got {len(args)} data argument(s)"
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
# -- lifecycle -------------------------------------------------------
|
|
501
|
+
|
|
502
|
+
def close(self) -> None:
|
|
503
|
+
"""``netcdf.close(ncid)``. Idempotent, so a double close in a ported
|
|
504
|
+
error path does not mask the original failure."""
|
|
505
|
+
if not self._ds.isopen():
|
|
506
|
+
return
|
|
507
|
+
self._ds.close()
|
|
508
|
+
|
|
509
|
+
def _require_define(self, what: str) -> None:
|
|
510
|
+
if not self._in_define:
|
|
511
|
+
raise RuntimeError(
|
|
512
|
+
f"netcdf.{what} after netcdf.endDef: the file has left define mode "
|
|
513
|
+
"(MATLAB raises NC_ENOTINDEFINE). UIOPS never calls netcdf.reDef, so "
|
|
514
|
+
"every definition belongs before end_def()."
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
def __enter__(self) -> NcFile:
|
|
518
|
+
return self
|
|
519
|
+
|
|
520
|
+
def __exit__(self, *exc: object) -> None:
|
|
521
|
+
self.close()
|
|
522
|
+
|
|
523
|
+
def __repr__(self) -> str:
|
|
524
|
+
state = "define" if self._in_define else "data"
|
|
525
|
+
return f"<NcFile {self._ds.filepath()!r} mode={state} vars={len(self._var_names)}>"
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
# --------------------------------------------------------------------------
|
|
529
|
+
# Module-level functions mirroring the MATLAB names
|
|
530
|
+
# --------------------------------------------------------------------------
|
|
531
|
+
|
|
532
|
+
def create(
|
|
533
|
+
filename: str | os.PathLike[str],
|
|
534
|
+
mode: str = "clobber",
|
|
535
|
+
*,
|
|
536
|
+
format: str = "NETCDF3_CLASSIC",
|
|
537
|
+
) -> NcFile:
|
|
538
|
+
"""``netcdf.create(filename,'clobber')``.
|
|
539
|
+
|
|
540
|
+
Every creation site in UIOOPS passes a bare ``'clobber'`` and no format, so
|
|
541
|
+
MATLAB's default ``NC_FORMAT_CLASSIC`` applies -- confirmed from the magic
|
|
542
|
+
bytes of the three shipped probe files (``b'CDF\\x01'``). Default preserved
|
|
543
|
+
here, **including its failure mode**: NETCDF3_CLASSIC caps a non-record
|
|
544
|
+
variable at 2 GiB and ``imgProc_sm.m`` writes ~40 record variables, so a large
|
|
545
|
+
flight fails at ``putVar`` exactly as MATLAB's would. ``format=`` is the
|
|
546
|
+
escape hatch, never the default.
|
|
547
|
+
"""
|
|
548
|
+
if mode != "clobber":
|
|
549
|
+
raise ValueError(
|
|
550
|
+
f"netcdf.create mode {mode!r}: every UIOPS creation site passes "
|
|
551
|
+
"'clobber' (design doc §1.1); 'noclobber' is unexercised"
|
|
552
|
+
)
|
|
553
|
+
if format not in _NC_FORMATS:
|
|
554
|
+
raise ValueError(f"unknown netCDF format {format!r}; expected one of {_NC_FORMATS}")
|
|
555
|
+
# The ``cast`` is discharged by the guard immediately above, not asserted on
|
|
556
|
+
# faith: netCDF4 types ``format=`` as a ``Literal`` of five names and
|
|
557
|
+
# ``_NC_FORMATS`` is a four-element subset of exactly those names, so any
|
|
558
|
+
# value reaching this line is already one of them. Keeping the parameter a
|
|
559
|
+
# plain ``str`` is deliberate -- the ValueError above is the port's own
|
|
560
|
+
# documented error for a bad format, and a ``Literal`` annotation would move
|
|
561
|
+
# that rejection from runtime (where MATLAB's would also be) to type-check
|
|
562
|
+
# time, which callers passing a computed string would never see.
|
|
563
|
+
fmt = cast("Literal['NETCDF3_CLASSIC', 'NETCDF3_64BIT_OFFSET', "
|
|
564
|
+
"'NETCDF4_CLASSIC', 'NETCDF4']", format)
|
|
565
|
+
return NcFile(Dataset(filename, "w", format=fmt), define_mode=True)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def open(filename: str | os.PathLike[str], mode: str = "nowrite") -> NcFile: # noqa: A001 -- MATLAB name
|
|
569
|
+
"""``netcdf.open(filename,'nowrite')``.
|
|
570
|
+
|
|
571
|
+
Reads both NETCDF3_CLASSIC and NETCDF3_64BIT_OFFSET: the probe files UIOOPS
|
|
572
|
+
writes are classic, but ``flightData_20151205.cdf`` -- an *input*, produced
|
|
573
|
+
outside UIOOPS and consumed at ``imgProc_sm.m:169-170`` -- is 64-bit offset.
|
|
574
|
+
"""
|
|
575
|
+
if mode not in ("nowrite", "write"):
|
|
576
|
+
raise ValueError(f"netcdf.open mode {mode!r}: UIOPS uses only 'nowrite'")
|
|
577
|
+
return NcFile(Dataset(filename, "r" if mode == "nowrite" else "a"), define_mode=False)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def def_dim(ncid: NcFile, name: str, length: int) -> int:
|
|
581
|
+
"""``netcdf.defDim`` -- see :meth:`NcFile.def_dim`."""
|
|
582
|
+
return ncid.def_dim(name, length)
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def def_var(
|
|
586
|
+
ncid: NcFile,
|
|
587
|
+
name: str,
|
|
588
|
+
xtype: str,
|
|
589
|
+
dimids: npt.ArrayLike,
|
|
590
|
+
*,
|
|
591
|
+
chunksizes: npt.ArrayLike | None = None,
|
|
592
|
+
) -> int:
|
|
593
|
+
"""``netcdf.defVar`` with ``dimids`` (and ``chunksizes``, when given) in MATLAB
|
|
594
|
+
order -- see :meth:`NcFile.def_var`."""
|
|
595
|
+
return ncid.def_var(name, xtype, dimids, chunksizes=chunksizes)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def put_att(ncid: NcFile, varid: int, name: str, value: Any) -> None:
|
|
599
|
+
"""``netcdf.putAtt`` -- see :meth:`NcFile.put_att`."""
|
|
600
|
+
ncid.put_att(varid, name, value)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def end_def(ncid: NcFile) -> None:
|
|
604
|
+
"""``netcdf.endDef`` -- see :meth:`NcFile.end_def`."""
|
|
605
|
+
ncid.end_def()
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def inq_dim(ncid: NcFile, dimid: int) -> tuple[str, int]:
|
|
609
|
+
"""``netcdf.inqDim`` -- see :meth:`NcFile.inq_dim`."""
|
|
610
|
+
return ncid.inq_dim(dimid)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def inq_var_id(ncid: NcFile, name: str) -> int:
|
|
614
|
+
"""``netcdf.inqVarID`` -- see :meth:`NcFile.inq_var_id`."""
|
|
615
|
+
return ncid.inq_var_id(name)
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def get_var(
|
|
619
|
+
ncid: NcFile,
|
|
620
|
+
varid: int,
|
|
621
|
+
start: npt.ArrayLike | None = None,
|
|
622
|
+
count: npt.ArrayLike | None = None,
|
|
623
|
+
) -> np.ndarray:
|
|
624
|
+
"""``netcdf.getVar`` -- see :meth:`NcFile.get_var`. Raw, unmasked."""
|
|
625
|
+
return ncid.get_var(varid, start, count)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def put_var(ncid: NcFile, varid: int, *args: Any) -> None:
|
|
629
|
+
"""``netcdf.putVar`` -- see :meth:`NcFile.put_var`."""
|
|
630
|
+
ncid.put_var(varid, *args)
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def close(ncid: NcFile) -> None:
|
|
634
|
+
"""``netcdf.close`` -- see :meth:`NcFile.close`."""
|
|
635
|
+
ncid.close()
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
# --------------------------------------------------------------------------
|
|
639
|
+
# The high-level shim -- opposite masking policy, deliberately separate
|
|
640
|
+
# --------------------------------------------------------------------------
|
|
641
|
+
|
|
642
|
+
def ncread(filename: str | os.PathLike[str], varname: str) -> np.ndarray:
|
|
643
|
+
"""MATLAB ``ncread(filename,varname)``.
|
|
644
|
+
|
|
645
|
+
MATLAB dimension order, like :func:`get_var`, but with ``_FillValue`` masking
|
|
646
|
+
and ``scale_factor``/``add_offset`` **applied** -- the opposite policy, which
|
|
647
|
+
is why this is a separate function rather than a flag. Returns a masked array
|
|
648
|
+
when the file gives cause to mask.
|
|
649
|
+
|
|
650
|
+
Provenance: ``imgProc_sm.m:169-170,184-185`` (TAS and Time from the flight-data
|
|
651
|
+
file); ``run_imgProc_Munich.m:16-24,32-34``; ``run_sizeDist_Munich.m:25-28``.
|
|
652
|
+
"""
|
|
653
|
+
with Dataset(filename, "r") as ds:
|
|
654
|
+
var = ds.variables[varname]
|
|
655
|
+
var.set_auto_maskandscale(True)
|
|
656
|
+
raw = var[...]
|
|
657
|
+
if np.ma.isMaskedArray(raw):
|
|
658
|
+
return np.ma.masked_array(
|
|
659
|
+
_to_matlab_shape(raw.data),
|
|
660
|
+
mask=_to_matlab_shape(np.ma.getmaskarray(raw)),
|
|
661
|
+
)
|
|
662
|
+
return _to_matlab_shape(np.asarray(raw))
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
# --------------------------------------------------------------------------
|
|
666
|
+
# Fused idioms -- so orientation-sensitive call sites are never re-derived
|
|
667
|
+
# --------------------------------------------------------------------------
|
|
668
|
+
|
|
669
|
+
def read_image_record(ncid: NcFile, varid: int, i: int, n_bytes: int, n_slices: int) -> np.ndarray:
|
|
670
|
+
"""``imgProc_sm.m:489-495`` fused into one call.
|
|
671
|
+
|
|
672
|
+
MATLAB reads ``temp = netcdf.getVar(f,varid,[0,0,i-1],[8,1700,1])`` (``8x1700``)
|
|
673
|
+
and immediately does ``data(:,:) = temp';`` -- so what the rest of
|
|
674
|
+
``imgProc_sm.m`` calls ``data`` is ``1700x8``, i.e. ``ds['data'][i,:,:]`` with
|
|
675
|
+
no transpose at all. ``i`` here is the **0-based** record index.
|
|
676
|
+
|
|
677
|
+
Returns ``(n_slices, n_bytes)``. Orientation check: the 2DS boundary word
|
|
678
|
+
(``imgProc_sm.m:159``) fills a whole 8-element slice, so all-43690 runs lie
|
|
679
|
+
along the last axis.
|
|
680
|
+
"""
|
|
681
|
+
temp = ncid.get_var(varid, [0, 0, i], [n_bytes, n_slices, 1])
|
|
682
|
+
return np.ascontiguousarray(temp.T)
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
# --------------------------------------------------------------------------
|
|
686
|
+
# Provenance carried BY THE BYTES -- the provenance stamp, opt-in, default off
|
|
687
|
+
# --------------------------------------------------------------------------
|
|
688
|
+
|
|
689
|
+
def put_provenance(
|
|
690
|
+
ncid: NcFile,
|
|
691
|
+
*,
|
|
692
|
+
engine: str,
|
|
693
|
+
# REQUIRED, not defaulted: `profile=None` is a legal and meaningful value here
|
|
694
|
+
# -- an S2 stamp names no profile because neither the SEA nor the DMT reader
|
|
695
|
+
# reads one -- but it must be STATED. A default cannot distinguish "absent by
|
|
696
|
+
# design" from "the caller forgot", which is the whole point of
|
|
697
|
+
# tests/test_profile_is_never_defaulted.py, and that check caught this module
|
|
698
|
+
# propagating the anti-pattern across four signatures on 2026-09-18.
|
|
699
|
+
profile: str | None,
|
|
700
|
+
stage: str | None = None,
|
|
701
|
+
extra: dict[str, str] | None = None,
|
|
702
|
+
) -> dict[str, str]:
|
|
703
|
+
"""Write :func:`arrayprobe.provenance.attrs_for`'s global attributes into ``ncid``.
|
|
704
|
+
|
|
705
|
+
**Opt-in, and nothing in the port calls it.** Adding a global attribute changes the file's
|
|
706
|
+
bytes, and the layer-1 comparison is not hypothetical about that:
|
|
707
|
+
the image-processing oracle test asserts
|
|
708
|
+
``a.ncattrs() == b.ncattrs()`` against the
|
|
709
|
+
MATLAB-written oracle, so a writer that stamped by default would fail that test on its first
|
|
710
|
+
run -- and would shift every tracked ``.call`` fixture and every archived comparison in the
|
|
711
|
+
same commit. A writer opts in by calling this; the default stays "writes exactly what MATLAB
|
|
712
|
+
wrote", which is the claim the whole project rests on.
|
|
713
|
+
|
|
714
|
+
Define mode, like every other ``putAtt``: call it before :meth:`NcFile.end_def`. Returns the
|
|
715
|
+
attributes written, so a caller can pass the identical values to
|
|
716
|
+
:func:`arrayprobe.provenance.write` and have the sidecar and the attribute agree by
|
|
717
|
+
construction -- both texts come from ``provenance.stamp_text``.
|
|
718
|
+
|
|
719
|
+
``alongside the .call sidecar rather than instead of it``: this does **not** write a sidecar.
|
|
720
|
+
The two carriers are written by two calls on purpose, because a product may legitimately have
|
|
721
|
+
one and not the other (an older product has only the sidecar; a hardlinked copy has only the
|
|
722
|
+
attribute), and :func:`provenance_of` is what reads whichever exist.
|
|
723
|
+
"""
|
|
724
|
+
attrs = provenance.attrs_for(engine=engine, profile=profile, stage=stage, extra=extra)
|
|
725
|
+
for name, value in attrs.items():
|
|
726
|
+
ncid.put_att(NC_GLOBAL, name, value)
|
|
727
|
+
return attrs
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def read_provenance(filename: str | os.PathLike[str]) -> provenance.Stamp | None:
|
|
731
|
+
"""The stamp ``filename`` carries **in its own bytes**, or ``None`` if it carries none.
|
|
732
|
+
|
|
733
|
+
Survives a rename, a copy and a hardlink, which is the entire reason it exists: a ``.call``
|
|
734
|
+
sidecar is keyed by filename, so a hardlinked name carries no sidecar stamp (observed
|
|
735
|
+
for a 1.25 GB CIP product). One implementation, in the v3.5 engine:
|
|
736
|
+
:func:`arrayprobe_uiops.provenance.read_in_file_stamp`.
|
|
737
|
+
"""
|
|
738
|
+
return provenance.read_in_file_stamp(filename)
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def provenance_of(filename: str | Path) -> provenance.Stamp:
|
|
742
|
+
"""Both carriers, reconciled -- raising rather than choosing when they disagree.
|
|
743
|
+
|
|
744
|
+
Reads the attribute inside ``filename`` and the ``.call`` sidecar beside it, and:
|
|
745
|
+
|
|
746
|
+
* raises :class:`arrayprobe.provenance.ProvenanceDisagreement` when both state a field and
|
|
747
|
+
state it differently -- **the guard that provenance carried in the file exists
|
|
748
|
+
for**. Neither carrier outranks the other, so there is no tie to break: one of them
|
|
749
|
+
describes a run that did not write these bytes;
|
|
750
|
+
* returns the attribute's stamp when only it exists (the hardlink case);
|
|
751
|
+
* returns the sidecar's stamp when only it exists (every product written before today);
|
|
752
|
+
* raises :class:`arrayprobe.provenance.Unstamped` when neither exists.
|
|
753
|
+
|
|
754
|
+
Agreement is field-by-field over the fields **both** carriers state, so a sidecar that records
|
|
755
|
+
no engine and an attribute that names one is agreement, not conflict -- see
|
|
756
|
+
:func:`arrayprobe.provenance.disagreements`.
|
|
757
|
+
"""
|
|
758
|
+
inside = read_provenance(filename)
|
|
759
|
+
beside = provenance.read(filename)
|
|
760
|
+
differences = provenance.disagreements(beside, inside)
|
|
761
|
+
if differences:
|
|
762
|
+
raise provenance.ProvenanceDisagreement(Path(filename), differences)
|
|
763
|
+
if inside is not None:
|
|
764
|
+
return inside
|
|
765
|
+
if beside is not None:
|
|
766
|
+
return beside
|
|
767
|
+
raise provenance.Unstamped(filename)
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def engine_of(filename: str | Path) -> str:
|
|
771
|
+
"""The engine that wrote ``filename``, from **either** carrier, or a refusal.
|
|
772
|
+
|
|
773
|
+
:func:`arrayprobe.provenance.engine_of` asks the sidecar alone, so it cannot answer for a
|
|
774
|
+
renamed, copied or hardlinked product. This asks the bytes first and the sidecar second, and
|
|
775
|
+
is otherwise the same contract: it never returns a default, never infers an engine from a
|
|
776
|
+
date, a filename or a neighbouring file, and raises
|
|
777
|
+
|
|
778
|
+
* :class:`~arrayprobe.provenance.ProvenanceDisagreement` when the carriers conflict,
|
|
779
|
+
* :class:`~arrayprobe.provenance.Unstamped` when neither exists,
|
|
780
|
+
* :class:`~arrayprobe.provenance.EngineUnrecorded` when what exists does not say --
|
|
781
|
+
which is still the honest answer for every product written before 2026-09-18.
|
|
782
|
+
"""
|
|
783
|
+
stamp = provenance_of(filename)
|
|
784
|
+
if stamp.engine is None:
|
|
785
|
+
raise provenance.EngineUnrecorded(filename, stamp)
|
|
786
|
+
return stamp.engine
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def write_record_block(ncid: NcFile, varid: int, start: int, block: npt.ArrayLike) -> None:
|
|
790
|
+
"""``imgProc_sm.m:873-929`` fused: append ``block`` at 0-based record ``start``.
|
|
791
|
+
|
|
792
|
+
``block`` is in **C/on-disk order** (time first) because the MATLAB ``'`` at
|
|
793
|
+
those call sites has already been absorbed -- that is the whole point of the
|
|
794
|
+
cancellation noted in the module docstring. Passing a MATLAB-order array here
|
|
795
|
+
is the one easy mistake, so the shape is checked against the variable's
|
|
796
|
+
trailing dimensions.
|
|
797
|
+
"""
|
|
798
|
+
arr = np.asarray(block)
|
|
799
|
+
var = ncid.variable(varid)
|
|
800
|
+
trailing = tuple(var.shape[1:])
|
|
801
|
+
n = arr.shape[0] if arr.ndim else 1
|
|
802
|
+
expected = (n,) + trailing
|
|
803
|
+
if arr.shape != expected:
|
|
804
|
+
raise ValueError(
|
|
805
|
+
f"write_record_block expects C/on-disk order {expected} for variable "
|
|
806
|
+
f"{var.name!r}, got {arr.shape}. If you have a MATLAB-order array, use "
|
|
807
|
+
"put_var(ncid, varid, start, count, data) instead."
|
|
808
|
+
)
|
|
809
|
+
with _quiet_netcdf4_setitem():
|
|
810
|
+
var[start:start + n, ...] = arr
|