"""L2A to L2B: geophysical products in their own files.
An L2B product holds products derived from one L2A product, one group per
file (:data:`hypso.io.naming.L2B_GROUPS`), as PACE OCI's suites: ``BGC``
holds chlorophyll-a and suspended matter, ``IOP`` absorption, scattering,
backscattering and Kd. Like PACE's OC_AOP suite, the L2A keeps Rrs and the
AC tool's aerosol optical depth. An L2B file has 2D variables only, no band cube; per-wavelength quantities are separate
variables (``aph_443``, ``bbp_443``), as in NASA's OC_IOP files. It keeps
the L2A's geometry, ``pixel_flags``, grid and metadata, so it can be
regridded, windowed and read by Satpy like any other level. File names:
``...L2B.<GROUP>.<source>.nc``, where the source is the algorithm (e.g.
``oc4``) or the AC tool whose own product it is (e.g. ``polymer``). An
OC-SMART run thus writes ``L2A.RRS`` (Rrs, aod), ``L2B.BGC``, ``L2B.IOP``
and ``L2A.AUX``.
The AC tool's other per-band outputs (OC-SMART's Lt, Lr, Lrc, Lwp, tg_sol,
tg_sen, ...) go to another file next to the L2A, ``...L2A.AUX.<method>.nc``
(:func:`split_intermediates`), built the same way: 2D variables only, one per
quantity and band (``Lt_434``), with the L2A's geometry and flags.
"""
import re
import numpy as np
import xarray as xr
from hypso.io.naming import L2B_GROUPS, _check_token
from hypso.io.product import GRID_DIMS, GRID_MAPPING, _GEOMETRY_ATTRS, spatial_dims
from hypso.io.provenance import add_step
from hypso.masks.flags import FLAGS_NAME
[docs]
def make_l2b(tree: xr.DataTree, group: str, source: str, variables: dict, parameters: dict = None) -> xr.DataTree:
"""An L2B tree from an L2A tree and the derived variables.
Parameters
----------
tree : xarray.DataTree
The L2A product the variables were derived from.
group : str
Product group, a key of :data:`hypso.io.naming.L2B_GROUPS`.
source : str
Algorithm or tool, e.g. ``"oc4"`` or ``"polymer"`` (a file-name token).
variables : dict
``{name: xarray.DataArray or (array, attrs)}``, each of the product's
spatial shape; attributes should include ``units`` and ``long_name``.
parameters : dict, optional
Recorded in the ``l2b_<group>_<source>`` provenance step.
Returns
-------
xarray.DataTree
"""
if tree.attrs.get("processing_level") != "L2A":
raise ValueError(f"L2B products are derived from L2A, got {tree.attrs.get('processing_level')}")
if group not in L2B_GROUPS:
raise ValueError(f"unknown L2B group {group!r}; known: {sorted(L2B_GROUPS)}")
_check_token("source", source)
if not variables:
raise ValueError("no variables")
root = tree.to_dataset(inherit=False)
dims = spatial_dims(root)
keep = [n for n in root.data_vars if n in _GEOMETRY_ATTRS or n in ("crs_wgs84", GRID_MAPPING, FLAGS_NAME)]
out = root[keep]
out = out.drop_vars([c for c in out.coords if c not in GRID_DIMS])
shape = tuple(root.sizes[d] for d in dims)
for name, value in variables.items():
data, attrs = (value.values, dict(value.attrs)) if isinstance(value, xr.DataArray) else value
data = np.asarray(data)
if data.shape != shape:
raise ValueError(f"{name!r} has shape {data.shape}, expected {shape}")
if name in out:
raise ValueError(f"{name!r} is a geometry or flag variable")
out[name] = xr.Variable(dims, data, attrs)
out.attrs = dict(root.attrs)
out.attrs.update(processing_level="L2B", l2b_group=group, l2b_source=source)
from hypso.io.product import INTERMEDIATES_NODE
result = tree.copy()
result.dataset = out
if INTERMEDIATES_NODE in result.children: # the L2A's AC intermediates belong to its L2A.AUX file
del result[INTERMEDIATES_NODE]
input_source = tree.encoding.get("source")
result.encoding.pop("source", None)
add_step(result, f"l2b_{group.lower()}_{source}", input_file=input_source or "L2A (in memory)",
parameters={"group": group, "source": source, "variables": " ".join(variables), **(parameters or {})})
return result
# The AC tools' own geophysical products, by variable name, and their L2B group.
# Anything else an AC tool returns (e.g. Polymer's logfb, Rgli, Rnir, OC-SMART's
# aod_<nm>) describes the correction and stays in the L2A, as aot does in PACE's
# OC_AOP suite. The tools' flag variables (`*_flags`)
# stay in the L2A and are also copied into each L2B, for quality screening.
_TOOL_PRODUCT_GROUPS = (
("BGC", re.compile(r"^(chla|chl_.*|chlor_a.*|ndci|spm.*|tsm.*|tur_.*|t_dogliotti.*|t_nechad.*)$",
re.IGNORECASE)),
# per-band IOPs, <quantity>_<nm> (OC-SMART's aph, adg, bbp, apg, bp; QAA's a, bbp), and Kd
("IOP", re.compile(r"^((a|aph|adg|apg|bbp|bb|bp)_\d+|kd.*)$", re.IGNORECASE)),
)
[docs]
def derive(tree: xr.DataTree, group: str, algorithm: str = None) -> xr.DataTree:
"""An L2B tree from one of the package's algorithms on an L2A.
Parameters
----------
tree : xarray.DataTree
An L2A tree; most algorithms need ``Rrs`` (``L2A.RRS.*``).
group : str
L2B group, ``"BGC"`` or ``"IOP"``.
algorithm : str, optional
See :data:`hypso.processing.l2b_algorithms.ALGORITHMS`; default the
group's default (BGC: ``"oci"``, IOP: ``"qaa"``).
Returns
-------
xarray.DataTree
``...L2B.<group>.<algorithm>``.
"""
from hypso.io.product import product_name
from hypso.processing.l2b_algorithms import ALGORITHMS, default_algorithm
if tree.attrs.get("processing_level") != "L2A":
raise ValueError(f"L2B products are derived from L2A, got {tree.attrs.get('processing_level')}")
algorithm = algorithm or default_algorithm(group)
if (group, algorithm) not in ALGORITHMS:
raise ValueError(f"no algorithm {algorithm!r} for {group}; available: "
f"{sorted(a for g, a in ALGORITHMS if g == group)}")
function, inputs, reference, _ = ALGORITHMS[(group, algorithm)]
name = product_name(tree)
if name not in inputs:
raise ValueError(f"{group} {algorithm} needs an L2A with {' or '.join(inputs)}, this one has {name} "
f"(e.g. derive from an L2A.RRS product: Polymer, OC-SMART, ACOLITE L2W)")
cube = tree.dataset[name]
outputs = function(cube.values, cube["radiation_wavelength"].values)
variables = {var: (values.astype(np.float32), {**attrs, "algorithm": algorithm, "reference": reference})
for var, (values, attrs) in outputs.items()}
return make_l2b(tree, group, algorithm, variables,
parameters={"algorithm": algorithm, "reference": reference, "input_variable": name})