# This file is part of pelagos_py.
#
# Copyright 2025-2026 National Oceanography Centre and The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Class definition for deriving CTD variables."""
#### Mandatory imports ####
from pelagos_py.steps.base_step import BaseStep, register_step
from pelagos_py.utils.qc_handling import QCHandlingMixin, raw_name
#### Custom imports ####
from pelagos_py.utils.processing_utils import interpolate_by_time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from pelagos_py.utils import fig_spec
@register_step
[docs]
class InterpolateVariables(BaseStep, QCHandlingMixin):
"""
A processing step for interpolating data.
Fills gaps in each listed variable by linear interpolation in time. Samples
flagged with one of the variable's listed flags, and NaN samples, are gaps; filled
samples are flagged 8 (interpolated). Values before the first or after the last
real value are not filled. Meant for the coordinates (``LATITUDE``, ``LONGITUDE``):
measured variables are left on their own rows, and ``DEPTH_ADJUSTED`` is filled by
Derive CTD. See :doc:`/user_guide/Pelagos-py_POSITION`.
Parameters
----------
variables : dict
Variable name -> list of QC flags whose samples are treated as gaps.
max_interp_time : float, optional
Largest gap (minutes between the surrounding real values) that is filled.
``0``/``False``/``"off"`` fills gaps of any size. Default ``5.0``.
Examples
--------
Example config usage::
- name: "Interpolate Data"
parameters:
variables: # per variable, the QC flags treated as gaps to fill
LATITUDE: [3, 4, 9]
LONGITUDE: [3, 4, 9]
max_interp_time: 5.0
diagnostics: false
Filled samples are flagged 8 (interpolated).
"""
step_name = "Interpolate Data"
required_variables = ["TIME"]
provided_variables = []
uses_data_subset = True
variable_parameters = ["variables"]
parameter_schema = {
"variables": {
"type": dict,
"required": True,
"description": (
"Variables to interpolate, each with the QC flags whose samples are "
"treated as gaps (e.g. PRES: [3, 4, 9]). NaN samples are always gaps."
),
},
"max_interp_time": {
"type": [float, bool, str],
"default": 5.0,
"description": (
"Maximum time (minutes) from the nearest surrounding non-interpolated "
"point that a gap will be filled across, so interpolation only fills "
"small gaps rather than whole missing profiles. 0/False/off disables "
"the limit (fills gaps of any size)."
),
},
}
def __init__(self, name, parameters=None, diagnostics=False, context=None):
parameters = dict(parameters or {})
if "qc_handling_settings" in parameters:
raise ValueError(
f"[{name}] 'qc_handling_settings' is not used here: put the flags under 'variables'."
)
# `variables` is the mixin's flag_filter_settings under a simpler name
parameters["qc_handling_settings"] = {
"flag_filter_settings": dict(parameters.get("variables") or {})
}
super().__init__(name, parameters, diagnostics, context)
# consumed by the mixin above; keep it out of saved configs, which would reject it
self.parameters.pop("qc_handling_settings")
def run(self):
self.log("Interpolating variables...")
self.filter_qc()
variables = list(self.filter_settings)
max_interp_seconds = self._max_interp_seconds()
self.filled = {} # for the diagnostics plot
time = self.data["TIME"].values
for var in variables:
was_nan = np.isnan(self.data[var].values)
if (~was_nan).sum() < 2:
self.log_warn(
f"{var} has fewer than 2 valid values; skipping interpolation."
)
interpolated = interpolate_by_time(self.data[var].values, time)
if max_interp_seconds:
self._limit_gap_fill(time, interpolated, was_nan, max_interp_seconds)
filled = self.filled[var] = was_nan & np.isfinite(interpolated)
# Only filled samples change; flagged ones that stay unfilled keep their original value
values = self.data_copy[var].values.copy()
values[filled] = interpolated[filled]
self.data[var][:] = values
# set in place: xr.where would drop the attrs
self.data[f"{var}_QC"].values[filled] = 8
if self.diagnostics:
self.generate_diagnostics()
# Update the context with the enhanced dataset
self.context["data"].update(self.data)
return self.context
def _max_interp_seconds(self):
"""Resolve ``max_interp_time`` (minutes) to seconds, or None if disabled."""
value = self.max_interp_time
if isinstance(value, str):
text = value.strip().lower()
if text in ("off", "false", "no", "0", "0.0"):
return None
value = float(text)
if not value:
return None
return float(value) * 60
@staticmethod
def _limit_gap_fill(time, interpolated, was_nan, max_seconds):
"""Revert interior interpolated points back to NaN if their surrounding
gap (between the nearest non-interpolated points either side) exceeds
max_seconds. Leading/trailing NaNs are untouched (interpolate_by never
fills them)."""
valid_idx = np.flatnonzero(~was_nan)
if valid_idx.size == 0:
return
prev_valid = np.full(was_nan.shape, -1)
prev_valid[valid_idx] = valid_idx
np.maximum.accumulate(prev_valid, out=prev_valid)
next_valid = np.full(was_nan.shape, was_nan.size)
next_valid[valid_idx] = valid_idx
next_valid[::-1] = np.minimum.accumulate(next_valid[::-1])
interior = was_nan & (prev_valid >= 0) & (next_valid < was_nan.size)
gap_seconds = (
time[next_valid[interior]] - time[prev_valid[interior]]
) / np.timedelta64(1, "s")
too_far = np.flatnonzero(interior)[gap_seconds > max_seconds]
interpolated[too_far] = np.nan
def generate_diagnostics(self):
# first variable only
matplotlib.use("tkagg")
fig, axes = fig_spec.new_fig()
ax = axes[0][0]
plot_var = next(iter(self.filter_settings))
time = self.data["TIME"].values
values, was_nan = self.data[plot_var].values, self.filled[plot_var]
fig_spec.points(
ax,
time[~was_nan],
values[~was_nan],
color=fig_spec.CATEGORY[1],
label="original",
)
fig_spec.points(
ax,
time[was_nan],
values[was_nan],
color=fig_spec.CATEGORY[3],
label="interpolated",
)
fig_spec.style_axes(ax, ylabel=plot_var)
if raw_name(plot_var) in ("PRES", "DEPTH"):
ax.invert_yaxis()
fig_spec.x_axis(ax, time)
fig_spec.legend(ax)
fig_spec.finish(fig, suptitle=f"Interpolation: {plot_var}")
plt.show(block=True)