# 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(s) for flagging stuck, static, or otherwise unchanged data (which should be changing)."""
#### Mandatory imports ####
import numpy as np
import pandas as pd
from pelagos_py.steps.base_qc import BaseQC, register_qc
from pelagos_py.utils.qc_handling import 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 stuck_value_qc(BaseQC):
"""
Target Variable: Any
Flag Number: 4 (bad)
Variables Flagged: Any
Checks that successive measurements are not frozen.
EXAMPLE
-------
::
- name: "Apply QC"
parameters:
qc_settings:
stuck value qc:
variables: {PRES: 4, LATITUDE: 100}
also_flag: {PRES: [CNDC, TEMP], LATITUDE: [LONGITUDE]}
plot: [PRES, LATITUDE]
diagnostics: true
"""
qc_name = "stuck value 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 -> max allowed run of identical values, e.g. {'PRES': 4}.",
},
"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).",
},
}
def __init__(self, data, **kwargs):
super().__init__(data, **kwargs)
self.required_variables = list(set(self.variables.keys()))
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
self.data = self.data[self.keep_vars()]
# Generate the variable-specific flags
for var, n_stuck in self.variables.items():
# remove nans
var_data = self.data[var].dropna(dim="N_MEASUREMENTS")
# each sample gets the length of the run of identical values it is in
values = pd.Series(var_data.values)
run_id = (values != values.shift()).cumsum()
run_length = values.groupby(run_id).transform("size").to_numpy()
stuck_value_mask = np.where(run_length > n_stuck, 4, self.pass_flag)
# Insert the flags into the QC column
nan_mask = np.isnan(self.data[var])
self.data[f"{var}_QC"] = (
["N_MEASUREMENTS"],
np.where(nan_mask, 9, self.pass_flag),
)
self.data[f"{var}_QC"][np.where(~nan_mask)] = stuck_value_mask
# 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"))
fig_spec.style_axes(ax, title=f"{var} Stuck Value Test", 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)