cwaves 2026.12.4__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.
cwaves/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """CWAVES : computation of CWAVE parameters from ocean wave / SAR spectra.
2
+
3
+ Public API
4
+ ----------
5
+ - :func:`cwaves.compute_cwaves` : **the single entry point**. Computes the CWAVE
6
+ parameters of a spectrum given as an ``xarray.DataArray`` on its native
7
+ wavenumber grid -- cartesian (``k_rg``/``k_az``, uniform or not, e.g. FFT or
8
+ sinh grids) or polar (``k``/``phi``), half plane (``k_rg >= 0``) or full
9
+ plane. The grid is detected from the coordinates (see :mod:`cwaves.grid`);
10
+ no resampling is performed.
11
+ - :func:`cwaves.compute_cwave_parameters` : historical ``xsar_slc`` signature,
12
+ kept for API conservativeness; delegates to :func:`cwaves.compute_cwaves`.
13
+ - :func:`cwaves.reconstruct_spectrum` : reconstruction of a spectrum from its
14
+ CWAVE parameters (maximum entropy, exact constraints, or linear).
15
+ - :func:`cwaves.compute_kernel` : the orthonormal CWAVE kernels.
16
+ - :func:`cwaves.gegenbauer_polynoms` / :func:`cwaves.harmonic_functions` :
17
+ the radial and angular factors of the kernels.
18
+ - :func:`cwaves.symmetrize_xspectrum` : standalone utility rebuilding the full
19
+ plane of a one-sided Hermitian cross-spectrum.
20
+ - :func:`cwaves.get_default_config` / :func:`cwaves.load_config` : the
21
+ ``cwave_*`` configuration (the ``cwave`` block can be passed as kwargs).
22
+ - :func:`cwaves.compute_cwaves_from_file` : CLI-level helper (``cwaves
23
+ --input-nc``) that detects the schema of a NetCDF file and calls
24
+ :func:`cwaves.compute_cwaves` on its spectrum.
25
+
26
+ Reference
27
+ ---------
28
+ J. Schulz-Stellenfleth, T. Konig, and S. Lehner, "An empirical approach for the
29
+ retrieval of integral ocean wave parameters from synthetic aperture radar data",
30
+ J. Geophys. Res., 112, C03019, 2007. doi:10.1029/2006JC003970
31
+ """
32
+
33
+ try: # version is generated by hatch-vcs at build time
34
+ from cwaves._version import __version__
35
+ except ImportError: # pragma: no cover - fallback for source checkout
36
+ __version__ = "0.0.0+unknown"
37
+
38
+ from cwaves.client import compute_cwaves_from_file
39
+ from cwaves.compute_cwaves import (
40
+ compute_cwave_parameters,
41
+ compute_cwaves,
42
+ compute_kernel,
43
+ gegenbauer_polynoms,
44
+ harmonic_functions,
45
+ )
46
+ from cwaves.config import get_default_config, load_config
47
+ from cwaves.reconstruct import reconstruct_spectrum
48
+ from cwaves.symmetrize_xspectra import symmetrize_xspectrum
49
+
50
+ __all__ = [
51
+ "compute_cwaves",
52
+ "compute_cwave_parameters",
53
+ "compute_kernel",
54
+ "compute_cwaves_from_file",
55
+ "reconstruct_spectrum",
56
+ "gegenbauer_polynoms",
57
+ "harmonic_functions",
58
+ "symmetrize_xspectrum",
59
+ "get_default_config",
60
+ "load_config",
61
+ "__version__",
62
+ ]
cwaves/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '2026.12.4'
22
+ __version_tuple__ = version_tuple = (2026, 12, 4)
23
+
24
+ __commit_id__ = commit_id = None
cwaves/client.py ADDED
@@ -0,0 +1,387 @@
1
+ """Command-line client: CWAVE parameters of a spectrum stored in a NetCDF file.
2
+
3
+ The client has **one** entry point, :func:`compute_cwaves_from_file` (CLI
4
+ ``cwaves --input-nc <file>``). It opens the file, **detects its schema**, extracts
5
+ the spectrum with its native wavenumber grid and hands it to the library entry
6
+ point :func:`cwaves.compute_cwaves`. No resampling is done: the library
7
+ integrates on the native grid (cartesian or polar, uniform or not).
8
+
9
+ Recognised schemas (detection is based on the variables present, never on the
10
+ file name):
11
+
12
+ * ``"xsp"`` -- a cross-spectrum file with ``xspectra_{lag}tau_Re`` /
13
+ ``xspectra_{lag}tau_Im`` and cartesian ``k_rg`` / ``k_az`` coordinates in
14
+ rad/m, one spectrum per ``time`` slice (e.g. SARWave L1B XSP WV).
15
+ * ``"polar"`` -- a polar spectrum ``oswPolSpec`` on ``oswK`` [rad/m] x
16
+ ``oswPhi`` [degrees] (e.g. ESA OCN WV), with ``oswPhi = 0`` along the range
17
+ axis (``k_rg = k cos(phi)``).
18
+
19
+ Files whose spectra live in NetCDF **groups** (tiled IW products, ``intraburst``
20
+ / ``interburst``) hold one spectrum per tile: they are rejected with an explicit
21
+ message pointing to the tile-wise script :mod:`cwaves.scripts.iw_cwaves_map`.
22
+ """
23
+
24
+ import argparse
25
+ import logging
26
+ import os
27
+ import sys
28
+ from typing import Any, cast
29
+
30
+ import h5py
31
+ import numpy as np
32
+ import xarray as xr
33
+
34
+ from cwaves.compute_cwaves import PARTS, compute_cwaves
35
+ from cwaves.config import get_default_config
36
+
37
+ logger = logging.getLogger("cwaves.client")
38
+
39
+ DEFAULT_LAG = 2
40
+
41
+ #: schema name -> human readable description (for messages and the CLI help)
42
+ SCHEMAS = {
43
+ "xsp": "cross-spectrum xspectra_{lag}tau_Re/Im on (k_rg, k_az) [rad/m]",
44
+ "polar": "polar spectrum oswPolSpec on (oswK [rad/m], oswPhi [deg])",
45
+ "ocn_cartesian": "OCN WV cross-spectrum oswCartSpecRe/Im on its native sinh "
46
+ "grid (oswKx / oswGroundRngSize, oswKy / oswAziSize [rad/m])",
47
+ }
48
+
49
+ #: spectrum used for an OCN WV file (both are stored in the product)
50
+ OCN_SPECTRA = ("cartesian", "polar")
51
+
52
+
53
+ def _setup_logging() -> None:
54
+ """Configure the ``cwaves.client`` logger to write INFO to stdout."""
55
+ handler = logging.StreamHandler(sys.stdout)
56
+ handler.setFormatter(
57
+ logging.Formatter(
58
+ "%(asctime)s [%(levelname)s] %(message)s", "%Y-%m-%d %H:%M:%S"
59
+ )
60
+ )
61
+ logger.handlers.clear()
62
+ logger.addHandler(handler)
63
+ logger.setLevel(logging.INFO)
64
+
65
+
66
+ def _root_content(input_nc: str | os.PathLike[str]) -> tuple[set[str], list[str]]:
67
+ """Return the root variable names and group names of a NetCDF file.
68
+
69
+ NetCDF-4 (HDF5) files are inspected with ``h5py`` (no data read); other
70
+ formats (NetCDF-3) fall back to ``xarray`` and have no groups.
71
+ """
72
+ try:
73
+ with h5py.File(input_nc, "r") as h5:
74
+ variables = {k for k, v in h5.items() if isinstance(v, h5py.Dataset)}
75
+ groups = [k for k, v in h5.items() if isinstance(v, h5py.Group)]
76
+ return variables, groups
77
+ except OSError:
78
+ with xr.open_dataset(input_nc) as ds:
79
+ return {str(v) for v in ds.variables}, []
80
+
81
+
82
+ def detect_schema(input_nc: str | os.PathLike[str]) -> str:
83
+ """Return the schema of a NetCDF file (``"xsp"`` or ``"polar"``).
84
+
85
+ Args:
86
+ input_nc: path to the NetCDF file.
87
+
88
+ Returns:
89
+ The schema name (a key of :data:`SCHEMAS`).
90
+
91
+ Raises:
92
+ FileNotFoundError: if the file does not exist.
93
+ ValueError: if the spectra are stored in groups (tiled product) or no
94
+ supported spectrum variable is found.
95
+ """
96
+ if not os.path.exists(input_nc):
97
+ raise FileNotFoundError(input_nc)
98
+ variables, groups = _root_content(input_nc)
99
+ if "oswPolSpec" in variables:
100
+ return "polar"
101
+ if any(v.startswith("xspectra_") and v.endswith("_Re") for v in variables):
102
+ return "xsp"
103
+ if groups:
104
+ raise ValueError(
105
+ f"{input_nc} stores its spectra in groups {groups} (tiled product, one "
106
+ "spectrum per tile): use the tile-wise script "
107
+ "`python -m cwaves.scripts.iw_cwaves_map`, or open the group yourself "
108
+ "and call cwaves.compute_cwaves on each tile spectrum."
109
+ )
110
+ raise ValueError(
111
+ f"no supported spectrum found in {input_nc}; expected one of: "
112
+ + "; ".join(SCHEMAS.values())
113
+ )
114
+
115
+
116
+ def _xsp_spectrum(
117
+ ds: xr.Dataset, lag: int, time_idx: int, pol_idx: int
118
+ ) -> xr.DataArray:
119
+ """Build the complex cross-spectrum of one ``time`` slice of an XSP file."""
120
+ real = ds[f"xspectra_{lag}tau_Re"].isel(time=time_idx, pol=pol_idx, drop=True)
121
+ imag = ds[f"xspectra_{lag}tau_Im"].isel(time=time_idx, pol=pol_idx, drop=True)
122
+ if f"{lag}tau" in real.dims: # average the lag pairs
123
+ real = real.mean(dim=f"{lag}tau")
124
+ imag = imag.mean(dim=f"{lag}tau")
125
+ spec = real + 1j * imag
126
+ return spec.assign_coords(
127
+ k_rg=ds["k_rg"].isel(time=time_idx), k_az=ds["k_az"].isel(time=time_idx)
128
+ ).rename(f"xspectra_{lag}tau")
129
+
130
+
131
+ #: backward-compatible private alias (used by the report / figure scripts)
132
+ _l1b_cross_spectrum = _xsp_spectrum
133
+
134
+
135
+ def polar_spectrum(ds: xr.Dataset, iaz: int = 0, ira: int = 0) -> xr.DataArray:
136
+ """Extract the polar spectrum ``oswPolSpec`` with ``k`` / ``phi`` coordinates.
137
+
138
+ Args:
139
+ ds: an opened dataset with ``oswPolSpec``, ``oswK`` [rad/m] and
140
+ ``oswPhi`` [degrees] (``oswPhi = 0`` along the range axis).
141
+ iaz: ``oswAzSize`` index of the tile.
142
+ ira: ``oswRaSize`` index of the tile.
143
+
144
+ Returns:
145
+ The polar spectrum, dims ``(phi, k)``, ``phi`` in radians.
146
+ """
147
+ pol = ds["oswPolSpec"].isel(oswAzSize=iaz, oswRaSize=ira).values # (phi, K)
148
+ k = np.asarray(ds["oswK"].values, dtype=float)
149
+ phi = np.deg2rad(np.asarray(ds["oswPhi"].values, dtype=float))
150
+ return xr.DataArray(
151
+ pol, dims=("phi", "k"), coords={"phi": phi, "k": k}, name="oswPolSpec"
152
+ )
153
+
154
+
155
+ def ocn_cartesian_spectrum(
156
+ ds: xr.Dataset, lag: int = DEFAULT_LAG, iaz: int = 0, ira: int = 0
157
+ ) -> xr.DataArray:
158
+ """OCN WV cartesian cross-spectrum on its native sinh grid, in rad/m.
159
+
160
+ The ESA OCN WV product stores ``oswCartSpecRe/Im`` (half plane,
161
+ ``k_rg >= 0``) on a sinh-spaced grid whose axes ``oswKx`` / ``oswKy`` are
162
+ **normalised wavenumbers** (unit ``m/m``: wavenumber in rad/m times the
163
+ size of the estimation area). The physical wavenumbers are therefore
164
+ ``oswKx / oswGroundRngSize`` and ``oswKy / oswAziSize``. Checked on 1800
165
+ S1A/S1C/S1D WV products (issue #12): the axes follow exactly
166
+ ``a * 32 * sinh(kappa / 32)`` (``oswJx`` / ``oswJy`` are their exact
167
+ derivatives) and the central step equals ``2 pi / (1024 * ground pixel)``
168
+ on both axes. No decompression / resampling is performed:
169
+ :func:`cwaves.compute_cwaves` integrates on the sinh grid with exact cell
170
+ areas.
171
+
172
+ Args:
173
+ ds: an opened OCN WV measurement dataset.
174
+ lag: ``oswLag`` index (default 2).
175
+ iaz: ``oswAzSize`` index of the cell.
176
+ ira: ``oswRaSize`` index of the cell.
177
+
178
+ Returns:
179
+ The complex cross-spectrum ``real + 1j * imag``, dims
180
+ ``(freq_line, freq_sample)`` with ``k_az`` / ``k_rg`` in rad/m.
181
+
182
+ Raises:
183
+ ValueError: if the product has no area sizes (e.g. OCN IW groups,
184
+ whose axes are already physical: use the IW map script) or the
185
+ spectrum is not finite.
186
+ """
187
+ for var in ("oswCartSpecRe", "oswCartSpecIm", "oswGroundRngSize", "oswAziSize"):
188
+ if var not in ds:
189
+ raise ValueError(
190
+ f"{var} not found: not an OCN WV measurement file (OCN IW tiles: "
191
+ "use python -m cwaves.scripts.iw_cwaves_map)"
192
+ )
193
+ cell = {"oswAzSize": iaz, "oswRaSize": ira}
194
+ real = ds["oswCartSpecRe"].isel(cell)
195
+ imag = ds["oswCartSpecIm"].isel(cell)
196
+ if "oswLag" in real.dims:
197
+ real = real.isel(oswLag=lag)
198
+ imag = imag.isel(oswLag=lag)
199
+ real = real.transpose("oswKyBinSize", "oswKxBinSize")
200
+ imag = imag.transpose("oswKyBinSize", "oswKxBinSize")
201
+ if not (np.isfinite(real).all() and np.isfinite(imag).all()):
202
+ raise ValueError("oswCartSpec contains NaN/inf (check the cell index)")
203
+ size_rg = float(ds["oswGroundRngSize"].isel(cell))
204
+ size_az = float(ds["oswAziSize"].isel(cell))
205
+ k_rg = np.asarray(ds["oswKx"].values, dtype=float) / size_rg
206
+ k_az = np.asarray(ds["oswKy"].values, dtype=float) / size_az
207
+ return xr.DataArray(
208
+ real.values + 1j * imag.values,
209
+ dims=("freq_line", "freq_sample"),
210
+ coords={"k_az": ("freq_line", k_az), "k_rg": ("freq_sample", k_rg)},
211
+ name=f"oswCartSpec_lag{lag}",
212
+ )
213
+
214
+
215
+ def compute_cwaves_from_file(
216
+ input_nc: str | os.PathLike[str],
217
+ lag: int = DEFAULT_LAG,
218
+ pol: int = 0,
219
+ ocn_spectrum: str = "cartesian",
220
+ **cwave: Any,
221
+ ) -> xr.DataArray:
222
+ """Compute the CWAVE parameters of the spectrum (spectra) stored in a file.
223
+
224
+ The schema is detected with :func:`detect_schema`; the spectrum is passed on
225
+ its native grid to :func:`cwaves.compute_cwaves`.
226
+
227
+ Args:
228
+ input_nc: path to the NetCDF file.
229
+ lag: cross-spectrum lag for the ``"xsp"`` schema (default 2 = 2-tau)
230
+ and ``oswLag`` index of the OCN WV cartesian cross-spectrum.
231
+ pol: polarization index for the ``"xsp"`` schema (default 0).
232
+ ocn_spectrum: for an OCN WV file, ``"cartesian"`` (default: the SAR
233
+ cross-spectrum ``oswCartSpec`` on its native sinh grid, see
234
+ :func:`ocn_cartesian_spectrum`) or ``"polar"`` (the inverted wave
235
+ spectrum ``oswPolSpec``).
236
+ **cwave: ``cwave_*`` parameters (defaults: packaged
237
+ ``default_config.yml``).
238
+
239
+ Returns:
240
+ The CWAVE parameters (``k_gp`` x ``phi_hf``, plus ``time`` for
241
+ ``"xsp"`` files). The ``schema`` attribute records the detected schema.
242
+ """
243
+ if ocn_spectrum not in OCN_SPECTRA:
244
+ raise ValueError(f"ocn_spectrum must be one of {OCN_SPECTRA}")
245
+ schema = detect_schema(input_nc)
246
+ if not cwave:
247
+ cwave = get_default_config()["cwave"]
248
+ with xr.open_dataset(input_nc) as ds:
249
+ logger.info("loaded %s (schema %r: %s)", input_nc, schema, SCHEMAS[schema])
250
+ if schema == "polar" and ocn_spectrum == "cartesian" and "oswCartSpecRe" in ds:
251
+ schema = "ocn_cartesian"
252
+ logger.info("OCN WV file: using %s", SCHEMAS[schema])
253
+ out = compute_cwaves(ocn_cartesian_spectrum(ds, lag=lag), **cwave)
254
+ elif schema == "polar":
255
+ out = compute_cwaves(polar_spectrum(ds), **cwave)
256
+ else:
257
+ re_var = f"xspectra_{lag}tau_Re"
258
+ if re_var not in ds:
259
+ raise ValueError(f"{re_var} not found in {input_nc}")
260
+ results = [
261
+ compute_cwaves(_xsp_spectrum(ds, lag, t, pol), **cwave)
262
+ for t in range(ds.sizes["time"])
263
+ ]
264
+ out = xr.concat(results, dim="time").assign_coords(
265
+ time=ds["sensing_time"].values
266
+ )
267
+ out.attrs.update(results[0].attrs)
268
+ out.name = "cwave_params"
269
+ out.attrs["schema"] = schema
270
+ logger.info(
271
+ "CWAVE parameters computed on the native %s grid (%s plane): %d (k_gp) x "
272
+ "%d (phi_hf)",
273
+ out.attrs.get("grid"),
274
+ out.attrs.get("coverage"),
275
+ out.sizes["k_gp"],
276
+ out.sizes["phi_hf"],
277
+ )
278
+ return cast("xr.DataArray", out)
279
+
280
+
281
+ def to_netcdf(cwave_params: xr.DataArray, path: str | os.PathLike[str]) -> None:
282
+ """Write CWAVE parameters to NetCDF (complex values split into re / im).
283
+
284
+ NetCDF has no complex type: complex parameters (``part="complex"``) are
285
+ written as two variables ``cwave_params_re`` and ``cwave_params_im``.
286
+ """
287
+ if np.iscomplexobj(cwave_params.values):
288
+ ds = xr.Dataset(
289
+ {
290
+ "cwave_params_re": np.real(cwave_params),
291
+ "cwave_params_im": np.imag(cwave_params),
292
+ },
293
+ attrs=cwave_params.attrs,
294
+ )
295
+ ds.to_netcdf(path)
296
+ else:
297
+ cwave_params.to_netcdf(path)
298
+
299
+
300
+ def _cwave_kwargs(args: argparse.Namespace) -> dict[str, Any]:
301
+ """Collect the ``cwave_*`` parameters (config defaults + CLI overrides)."""
302
+ cwave: dict[str, Any] = dict(get_default_config()["cwave"])
303
+ if args.cwave_wlmax is not None:
304
+ cwave["cwave_wlmax"] = args.cwave_wlmax
305
+ if args.cwave_wlmin is not None:
306
+ cwave["cwave_wlmin"] = args.cwave_wlmin
307
+ if args.cwave_nk is not None:
308
+ cwave["cwave_Nk"] = args.cwave_nk
309
+ if args.cwave_nphi is not None:
310
+ cwave["cwave_Nphi"] = args.cwave_nphi
311
+ return cwave
312
+
313
+
314
+ def _build_parser() -> argparse.ArgumentParser:
315
+ parser = argparse.ArgumentParser(
316
+ description="Compute the CWAVE parameters of the spectrum stored in a "
317
+ "NetCDF file (schema auto-detected: "
318
+ + "; ".join(f"{k} = {v}" for k, v in SCHEMAS.items())
319
+ + ")."
320
+ )
321
+ parser.add_argument("--input-nc", required=True, help="input NetCDF file")
322
+ parser.add_argument(
323
+ "--lag",
324
+ type=int,
325
+ choices=[1, 2],
326
+ default=DEFAULT_LAG,
327
+ help="cross-spectrum lag: xspectra_{lag}tau (xsp schema) or oswLag index "
328
+ "(OCN WV cartesian), default 2",
329
+ )
330
+ parser.add_argument(
331
+ "--ocn-spectrum",
332
+ choices=list(OCN_SPECTRA),
333
+ default="cartesian",
334
+ help="OCN WV file: cartesian cross-spectrum oswCartSpec on its native sinh "
335
+ "grid (default) or polar wave spectrum oswPolSpec",
336
+ )
337
+ parser.add_argument(
338
+ "--pol", type=int, default=0, help="xsp schema: polarization index (default 0)"
339
+ )
340
+ parser.add_argument(
341
+ "--part",
342
+ choices=list(PARTS),
343
+ default="modulus",
344
+ help="projected part: modulus (default, paper), real, imag (odd harmonics) "
345
+ "or complex (written as cwave_params_re / cwave_params_im)",
346
+ )
347
+ parser.add_argument("--output-nc", default=None, help="optional output NetCDF path")
348
+ parser.add_argument(
349
+ "--cwave-wlmax", type=float, default=None, help="maximum wavelength [m]"
350
+ )
351
+ parser.add_argument(
352
+ "--cwave-wlmin", type=float, default=None, help="minimum wavelength [m]"
353
+ )
354
+ parser.add_argument(
355
+ "--cwave-nk", type=int, default=None, help="number of Gegenbauer functions"
356
+ )
357
+ parser.add_argument(
358
+ "--cwave-nphi", type=int, default=None, help="number of harmonic functions"
359
+ )
360
+ return parser
361
+
362
+
363
+ def entrypoint(argv: list[str] | None = None) -> int:
364
+ """Command-line entry point (``cwaves``)."""
365
+ _setup_logging()
366
+ args = _build_parser().parse_args(argv)
367
+ try:
368
+ out = compute_cwaves_from_file(
369
+ args.input_nc,
370
+ lag=args.lag,
371
+ pol=args.pol,
372
+ ocn_spectrum=args.ocn_spectrum,
373
+ part=args.part,
374
+ **_cwave_kwargs(args),
375
+ )
376
+ except (KeyError, ValueError, OSError) as exc:
377
+ logger.error("failed to compute CWAVE parameters: %s", exc)
378
+ return 1
379
+ if args.output_nc is not None:
380
+ to_netcdf(out, args.output_nc)
381
+ logger.info("saved CWAVE parameters to %s", args.output_nc)
382
+ logger.info("CWAVE parameters: %s", dict(out.sizes))
383
+ return 0
384
+
385
+
386
+ if __name__ == "__main__":
387
+ raise SystemExit(entrypoint())