# 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.
"""QC test for flagging using spike/despike detection methods."""
#### Mandatory imports ####
import numpy as np
import pandas as pd
from pelagos_py.steps.base_qc import BaseQC, register_qc
from pelagos_py.utils.processing_utils import profile_indices
from pelagos_py.utils.qc_handling import (
calculation_flags_for,
propagate_flags,
raw_name,
)
#### Custom imports ####
import matplotlib.pyplot as plt
import xarray as xr
import matplotlib
from pelagos_py.utils import fig_spec
@register_qc
[docs]
class spike_qc(BaseQC):
"""
Target Variable: Any
Flag Number: 4 (bad)
Variables Flagged: Any
Checks for spikes by comparing each value to a rolling median: values whose
residual exceeds the standard deviation of the residuals times the variable's
sensitivity are flagged.
EXAMPLE
-------
::
- name: "Apply QC"
parameters:
qc_settings:
spike qc:
variables: {PRES: 2, LATITUDE: 1}
also_flag: {PRES: [CNDC, TEMP], LATITUDE: [LONGITUDE]}
plot: [PRES, LATITUDE]
window_size: 10
diagnostics: true
"""
qc_name = "spike qc"
# Specify if test target variable is user-defined (if True, __init__ has to be redefined)
dynamic = True
parameter_schema = {
"variables": {
"type": dict,
"required": True,
"description": "Mapping of variable -> spike sensitivity, e.g. {'PRES': 2}.",
},
"also_flag": {
"type": dict,
"default": {},
"description": "Propagate a variable's flags onto other variables.",
},
"plot": {
"type": list,
"default": [],
"description": "Variables to plot in diagnostics (default: every tested variable).",
},
"window_size": {
"type": int,
"default": 7,
"description": "Rolling-median window size used for spike detection.",
},
}
def __init__(self, data, **kwargs):
super().__init__(data, **kwargs)
self.required_variables = list(set(self.variables.keys())) + ["PROFILE_NUMBER"]
self.qc_outputs = list(
set(f"{var}_QC" for var in self.required_variables)
| set(f"{var}_QC" for var in sum(self.also_flag.values(), []))
)
[docs]
def return_qc(self):
# Subset the data, keeping any existing _QC so already-bad samples can be
# excluded from the baseline below.
self.data = self.data[self.keep_vars(*(f"{v}_QC" for v in self.variables))]
# Generate the variable-specific flags
groups = profile_indices(self.data["PROFILE_NUMBER"].values)
self._untested = {}
for var, sensitivity in self.variables.items():
spike_qc = np.full(len(self.data[var]), 0)
values = self.data[var].values
qc_flags = (
self.data[f"{var}_QC"].values if f"{var}_QC" in self.data else None
)
untested = 0
# Apply the checks across individual profiles
for indices in self.log_progress(
groups.values(), desc=f"[{var}]", unit="prof", total=len(groups)
):
profile = values[indices]
missing = np.isnan(profile)
# Usable = not NaN and not already flagged bad/missing; only these
# inform the baseline, so prior-bad spikes can't bias detection.
usable = ~missing
if qc_flags is not None:
usable &= ~np.isin(qc_flags[indices], calculation_flags_for(var))
var_data = profile[usable]
if len(var_data) < self.window_size:
untested += 1 # left 0: Apply QC's merge keeps the existing flag
continue
# Calculate the residules from the running median of the data
rolling_median = (
pd.Series(var_data)
.rolling(window=self.window_size, center=True)
.median()
.to_numpy()
)
residules = var_data - rolling_median
# Define the residule threshold
threshold = np.nanstd(residules) * sensitivity
# Apply the threshold to residules to get the flags
spike_flags = np.where(
(np.abs(residules) > threshold), 4, self.pass_flag
)
# NaNs are missing (9); excluded/usable points start good (1).
# Excluded points stay 1 so Apply QC's combinatrix keeps their
# existing (worse) flag; usable points take their spike result.
profile_flags = np.where(missing, 9, self.pass_flag)
profile_flags[usable] = spike_flags
spike_qc[indices] = profile_flags
self._untested[var] = (untested, len(groups))
if untested:
self.log_warn(
f"{untested} of {len(groups)} profiles have fewer than {self.window_size} "
f"usable {var} points (window_size) and were not tested."
)
# Add the flags to the data
self.data[f"{var}_QC"] = (["N_MEASUREMENTS"], spike_qc)
# Broadcast the QC found for var into variables specified by "also_flag"
if extra_vars := self.also_flag.get(var):
for extra_var in extra_vars:
base = self.data.get(
f"{extra_var}_QC", xr.zeros_like(self.data[f"{var}_QC"])
)
self.data[f"{extra_var}_QC"] = (
["N_MEASUREMENTS"],
propagate_flags(base, self.data[f"{var}_QC"]),
)
# Select just the flags
self.flags = self.data[
[var_qc for var_qc in self.data.data_vars if "_QC" in var_qc]
]
return self.flags
[docs]
def plot_diagnostics(self):
matplotlib.use("tkagg")
plot_vars = self.plot or list(self.variables)
# Plot the QC output
fig, axes = fig_spec.new_fig(nrows=len(plot_vars), sharex=True)
x = fig_spec.x_time(self.data)
for ax, var in zip(axes[:, 0], plot_vars):
# Check that the user specified var exists in the test set
if f"{var}_QC" not in self.qc_outputs:
self.log_warn(
f"Cannot plot {var}_QC as it was not included in this test."
)
continue
fig_spec.flag_points(ax, x, self.data[var], self.data[f"{var}_QC"])
ylabel = fig_spec.axis_label(var, self.data[var].attrs.get("units"))
untested, total = self._untested.get(var, (0, 0))
title = f"{var} Spike Test"
if untested:
title += (
f" — {untested} of {total} profiles untested (< window_size points)"
)
fig_spec.style_axes(ax, title=title, ylabel=ylabel)
if raw_name(var) in ("PRES", "DEPTH"):
ax.invert_yaxis()
fig_spec.legend(ax, title="Flags")
fig_spec.x_axis(axes[-1][0], x)
fig_spec.finish(fig)
plt.show(block=True)