# 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 quality control steps."""
#### Mandatory imports ####
from pelagos_py.steps.base_step import BaseStep, register_step
from pelagos_py.steps import QC_CLASSES
from pelagos_py.utils.qc_handling import (
QC_COMBINATRIX,
adjusted_name,
prefer_adjusted,
resolve_pass_flag,
)
#### Custom imports ####
import xarray as xr
import numpy as np
import pandas as pd
import json
def _flag_summary(flags):
counts = np.bincount(flags.astype(np.int64), minlength=10)
stats = pd.Series(flags).describe().round(5).to_dict()
return {i: int(counts[i]) for i in range(10)}, stats
def _split_test_settings(settings):
# `diagnostics` is a per-test override, not a QC parameter
return {k: v for k, v in settings.items() if k != "diagnostics"}, settings.get(
"diagnostics"
)
@register_step
[docs]
class ApplyQC(BaseStep):
"""
Step to apply quality control tests to the dataset.
Inherits properties from BaseStep (see base_step.py).
"""
step_name = "Apply QC"
parameter_schema = {
"qc_settings": {
"type": dict,
"required": True,
"description": (
"Mapping of QC test name -> that test's settings. Each test is run "
"in order and merges its flags into the dataset's _QC columns."
),
},
}
[docs]
def organise_flags(self, new_flags, overwrite=False):
"""
Method for taking in new flags (new_flags) and cross checking against existing flags (self.flag_store), including upgrading flags when necessary, following ARGO flagging standards.
With ``overwrite`` the new flags replace the stored ones outright (tests that merge themselves, e.g. visual qc).
See Wong et al. 2025 pp. 106 (http://dx.doi.org/10.13155/33951) and Mancini et al. 2021 pp. 43-44 for additional ARGO flag definitions.
Combinatrix logic:
0: No QC performed, the initial flag.
1: Good data. No adjustment needed.
2: Probably good data.
3: Probably bad data that are potentially correctable.
4: Bad data that are not correctable.
5: Value changed.
6, 7: Not used.
8: Estimated by interpolation, extrapolation, or other algorithm.
9: Missing value.
The combinatrix defines flagging priority when merging in new flags. The flag value itself acts as a kind of index.
As an example, if an existing flag is 2 (probably good data) and a new flag is 4 (bad data), the resulting flag will be 4.
2 (probably good data) + 4 (bad data) -> 4 (bad data)
3 (probably bad data) + 5 (value changed) -> 3 (probably bad data)
parameters
----------
new_flags : xarray.Dataset
Dataset containing new QC flag variables to be merged into the existing flag store.
"""
# Update existing flag columns
flag_columns_to_update = set(new_flags.data_vars) & set(
self.flag_store.data_vars
)
for column_name in flag_columns_to_update:
new = new_flags[column_name].values
if not overwrite:
new = QC_COMBINATRIX[self.flag_store[column_name], new]
self.flag_store[column_name][:] = new
# Add new QC flag columns if they dont already exist
flag_columns_to_add = set(new_flags.data_vars) - set(self.flag_store.data_vars)
if len(flag_columns_to_add) > 0:
for column_name in flag_columns_to_add:
self.flag_store[column_name] = new_flags[column_name]
[docs]
def run(self):
"""
Run the Apply QC step.
raises
------
KeyError
If no QC operations are specified, or if requested QC tests are invalid.
ValueError
If no data is found in context.
"""
# Defining the order of operations
if len(self.qc_settings.keys()) == 0:
raise KeyError(
"[Apply QC] No QC operations were specified in an ApplyQC step."
)
else:
# Check requested QC tests against valid tests
invalid_requests = set(self.qc_settings.keys()) - set(QC_CLASSES.keys())
if invalid_requests:
raise KeyError(
f"[Apply QC] The following requested QC tests could not be found: {invalid_requests}"
)
queued_qc = [QC_CLASSES.get(key) for key in self.qc_settings.keys()]
# Check if the data is in the context
self.check_data()
full_data = self.context["data"]
global_parameters = self.context.get("global_parameters") or {}
self.pass_flag = resolve_pass_flag(global_parameters.get("pass_flag"))
resolved_settings = prefer_adjusted(self.qc_settings, set(full_data.variables))
if resolved_settings != self.qc_settings:
self.log(
f"Resolved variable names (preferring _ADJUSTED):{json.dumps(resolved_settings)}",
console=False,
)
self.qc_settings = resolved_settings
# Try and fetch the qc history from context and update it
qc_history = self.context.setdefault("qc_history", {})
# Collect all of the required varible names and qc outputs for each test
all_required_variables = set({})
test_qc_outputs_cols = set({})
for test in queued_qc:
if hasattr(test, "dynamic"):
# Initialise the test to check its dynamic attributes
test_params, _ = _split_test_settings(self.qc_settings[test.qc_name])
test_instance = test(None, **test_params)
all_required_variables.update(test_instance.required_variables)
test_qc_outputs_cols.update(test_instance.qc_outputs)
del test_instance
else:
all_required_variables.update(test.required_variables)
test_qc_outputs_cols.update(test.qc_outputs)
# Check that the required variables for the test are in the dataset.
# Use full_data.variables (data vars + coordinates), not .keys() (data
# vars only), so a required variable stored as a coordinate (e.g. TIME,
# LATITUDE, LONGITUDE) is not falsely reported as missing.
present = set(full_data.variables)
# Static names like DEPTH count as present through their _ADJUSTED version.
resolved_required = set(
prefer_adjusted(list(all_required_variables), present)
)
if not resolved_required.issubset(present):
self.halt(
f"The data is missing variables: ({resolved_required - present}) which are required for running QC '{test.qc_name}'."
f" Make sure that the variables are present in the data, or remove tests from the order."
)
# Deep-copy only what this call touches: every test's required_variables
# (each test self-scopes to these, including dynamic tests above), plus
# the QC output columns themselves and the variable each flags (needed to
# build masks for outputs that don't exist yet, see mia_qc/base below).
subset_names = set(all_required_variables) | set(test_qc_outputs_cols)
# Tests resolve hard-coded names (e.g. DEPTH) to their _ADJUSTED version themselves.
subset_names.update(adjusted_name(var) for var in all_required_variables)
subset_names.update(var[:-3] for var in test_qc_outputs_cols)
subset_names.add("TIME") # diagnostics plot against time
subset_vars = [name for name in subset_names if name in full_data.variables]
data = full_data[subset_vars].copy(deep=True)
# The dashboard runs each test as its own step; tests still read the pre-step flags
test_data = data
flags_before = self.context.pop("qc_flags_before", None)
if flags_before is not None:
test_data = data.drop_vars(
[name for name in data.data_vars if name.endswith("_QC")]
)
test_data = test_data.assign(
{
name: flags_before[name]
for name in subset_vars
if name in flags_before
}
)
# Fetch existing flags from the data and create a place to store them
existing_flags = [
flag_col for flag_col in data.data_vars if flag_col in test_qc_outputs_cols
]
self.flag_store = xr.Dataset(coords={"N_MEASUREMENTS": data["N_MEASUREMENTS"]})
if len(existing_flags) > 0:
self.log(f"Found existing flags columns {set(existing_flags)} in data.")
self.flag_store = data[existing_flags].fillna(9).astype(np.int8)
other_existing_qc = set(
[var for var in data.data_vars if var.endswith("_QC")]
) - set(test_qc_outputs_cols)
if any(other_existing_qc):
# File-only: this set can be large and repeats every QC step.
self.logger.info(
"%s pre-existing QC column(s) left untouched by this step: %s",
len(other_existing_qc),
", ".join(sorted(other_existing_qc)),
extra={"console": False},
)
# Initialize the missing flag columns
mia_qc = test_qc_outputs_cols - set(data.data_vars)
base = [var[:-3] for var in mia_qc]
if not set(base).issubset(
set(data.keys())
): # Confirm that the required QC columns exist
raise KeyError(
f"[Apply QC] The data is missing: ({set(base) - set(data.keys())}), which is/are defined in the config as a variable to flag or use during one of the tests."
f" Double check the configuration file and make sure all variable parameters (like 'also flag' [CHLA]) are present in the data."
)
data_subset = data[base]
masks = xr.where(data_subset.isnull(), 9, 0).astype(np.int8)
masks = masks.rename({var: f"{var}_QC" for var in base})
self.flag_store.update(masks)
# Run through all of the QC steps and add the flags to flag_store
for qc_qc_name, qc_test_settings in self.qc_settings.items():
qc_test_params, test_diagnostics = _split_test_settings(qc_test_settings)
if test_diagnostics is None:
test_diagnostics = self.diagnostics
self.log(
f"Applying: {qc_qc_name}"
) # print(f"[Apply QC] Applying: {qc_qc_name}")
qc_test_instance = QC_CLASSES[qc_qc_name](test_data, **qc_test_params)
qc_test_instance.pass_flag = self.pass_flag
overwrite = qc_test_instance.overwrite_flags
if overwrite: # the test merges against the store itself
qc_test_instance.existing_flags = self.flag_store
returned_flags = (
qc_test_instance.return_qc()
) # Runs the test, returns the flags
self.organise_flags(returned_flags, overwrite=overwrite)
# Update QC history
for flagged_var in returned_flags.data_vars:
# Track percent of flags no longer 0 (following ARGO convention)
var_flags = returned_flags[flagged_var]
percent_flagged = (var_flags.to_numpy() != 0).sum() / len(var_flags)
if percent_flagged == 0:
self.log_warn(
f"All flags for {flagged_var} remain 0 after {qc_qc_name}"
)
# else: # TODO: Add 'verbose' log option if needed. Might not need to happen at this point.
# self.log(f"{percent_flagged*100:.2f}% of {flagged_var} points accounted for by {qc_qc_name}")
qc_history.setdefault(flagged_var, []).append(
(qc_qc_name, percent_flagged)
)
# Write additional QC details to _QC variable attributes
# TODO: Find where columns are initialized, or just run on non-QC'd datasets
parent_attrs = data[flagged_var[:-3]].attrs
attrs = self.flag_store[flagged_var].attrs
attrs["quality_control_conventions"] = "Argo standard flags"
attrs["valid_min"] = 0
attrs["valid_max"] = 9
attrs["flag_values"] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
attrs["flag_meanings"] = (
"NO_QC, GOOD, PROB_GOOD, PROB_BAD, BAD, VALUE_CHANGED, NOT_USED, NOT_USED, ESTIMATED, MISSING"
)
parent_long_name = parent_attrs.get("long_name")
if parent_long_name is None:
self.log_warn(
f"'{flagged_var[:-3]}' has no 'long_name' attribute; QC flag variable "
f"'{flagged_var}' will be missing its 'long_name' too."
)
else:
attrs["long_name"] = f"{parent_long_name} quality flag"
parent_standard_name = parent_attrs.get("standard_name")
if parent_standard_name is not None:
attrs["standard_name"] = f"{parent_standard_name}_flag"
attr_test = qc_qc_name.replace(" ", "_").lower()
counts, stats = _flag_summary(var_flags.to_numpy())
attrs[f"{attr_test}_flag_cts"] = json.dumps(counts)
attrs[f"{attr_test}_stats"] = json.dumps(stats)
attrs[f"{attr_test}_params"] = json.dumps(qc_test_params)
# Can get indices of 3/4 with np.where(var_flags.to_numpy() == 3)[0] for future reference
# Diagnostic plotting. Never let a diagnostic-only error abort QC;
# this matters when the report writer force-enables diagnostics to
# capture plots for every test.
if test_diagnostics:
# plot the merged flags after this test, not just this test's output
for col in returned_flags.data_vars:
for holder in (
qc_test_instance.data,
getattr(qc_test_instance, "flags", None),
):
if holder is not None and col in holder:
holder[col] = self.flag_store[col]
try:
qc_test_instance.plot_diagnostics()
except Exception as exc: # noqa: BLE001 - diagnostics must not be fatal
self.log_warn(
f"Diagnostic plotting failed for QC test '{qc_qc_name}': {exc}"
)
# Once finished, remove the test instance from memory
del qc_test_instance
# Append the flags from self.flag_store to the xarray data and push back into context
for flag_column in self.flag_store.data_vars:
if (self.flag_store[flag_column] == 0).all():
self.log_warn(
f"{flag_column} is all 0 after running all QC steps. Check intended QC variables and test requirements."
)
elif (self.flag_store[flag_column] == 0).any():
n_zero = int((self.flag_store[flag_column] == 0).sum())
self.log_warn(
f"{flag_column} (length={len(self.flag_store[flag_column])}) has {n_zero} zero QC values following all QC steps."
)
data[flag_column] = (
("N_MEASUREMENTS",),
self.flag_store[flag_column].to_numpy().astype(np.int8),
)
data[flag_column].attrs = self.flag_store[flag_column].attrs.copy()
# data is a subset of context["data"]; merge rather than replace so
# variables outside the subset (e.g. other tests' untouched _QC columns)
# aren't dropped.
self.context["data"].update(data)
self.context["qc_history"] = qc_history
return self.context