Skip to main content

Quality control

The QARTOD flag scheme

QARTOD (Quality Assurance of Real-Time Oceanographic Data) is a set of IOOS manuals that describe standard tests and a shared flag scheme:

Flag Meaning
1 PASS
2 NOT_EVALUATED
3 SUSPECT
4 FAIL
9 MISSING

A key principle is that flags annotate data, they never change it. Users decide what to exclude. I implemented four tests in base R, with unit tests for each.

Show code
# qartod.R
# Base-R implementations of four IOOS QARTOD tests, adapted for DAILY
# lightstation sea surface temperature (BCSOP_daily on CIOOS Pacific ERDDAP).
#
# QARTOD flag scheme (IOOS / UNESCO-IOC primary level flags):
#   1 = PASS            data passed the test
#   2 = NOT_EVALUATED   test could not be run (e.g., neighbours missing)
#   3 = SUSPECT         questionable, keep but review
#   4 = FAIL            data judged bad
#   9 = MISSING         no observation
#
# Important caveat: the QARTOD manuals were written mainly for real-time,
# high-frequency sensor data. Applying them to daily bucket samples is an
# adaptation, so every threshold below is a documented, tunable choice.
#
# All functions expect ONE station's data, sorted by date, with one row per
# day at most. Gaps are allowed: tests that need neighbours check that the
# neighbours are exactly one day away and otherwise return 2.

QC_PASS <- 1L; QC_NOT_EVAL <- 2L; QC_SUSPECT <- 3L; QC_FAIL <- 4L; QC_MISSING <- 9L

QC_FLAG_VALUES   <- c(1L, 2L, 3L, 4L, 9L)
QC_FLAG_MEANINGS <- "PASS NOT_EVALUATED SUSPECT FAIL MISSING"

# ---------------------------------------------------------------------------
# 1. Gross range test
#    FAIL    if outside the sensor / physical span
#    SUSPECT if outside the operator-defined (user) span
# ---------------------------------------------------------------------------
qc_gross_range <- function(x, fail_span, suspect_span) {
  flag <- rep(QC_PASS, length(x))
  flag[x < suspect_span[1] | x > suspect_span[2]] <- QC_SUSPECT
  flag[x < fail_span[1]    | x > fail_span[2]]    <- QC_FAIL
  flag[is.na(x)] <- QC_MISSING
  flag
}

# ---------------------------------------------------------------------------
# 2. Spike test
#    reference = mean of the previous and next values
#    spike     = |x[n] - reference|
#    SUSPECT if spike > suspect_threshold, FAIL if spike > fail_threshold
#    NOT_EVALUATED if either neighbour is missing or not exactly 1 day away
# ---------------------------------------------------------------------------
qc_spike <- function(x, date, suspect_threshold, fail_threshold) {
  n <- length(x)
  flag  <- rep(QC_NOT_EVAL, n)
  spike <- rep(NA_real_, n)
  if (n >= 3) {
    i <- 2:(n - 1)
    ok <- as.numeric(date[i] - date[i - 1]) == 1 & as.numeric(date[i + 1] - date[i]) == 1
    s  <- abs(x[i] - (x[i - 1] + x[i + 1]) / 2)
    s[!ok] <- NA
    spike[i] <- s
    ev <- !is.na(spike)
    flag[ev] <- QC_PASS
    flag[ev & spike > suspect_threshold] <- QC_SUSPECT
    flag[ev & spike > fail_threshold]    <- QC_FAIL
    # Neighbour adjustment (documented extension to QARTOD): one bad value
    # inflates the spike score of the good values beside it. A FAIL is kept
    # only if its spike is larger than both neighbours' spikes; otherwise it
    # is downgraded to SUSPECT.
    for (k in which(flag == QC_FAIL)) {
      nb <- spike[c(k - 1, k + 1)]
      if (any(!is.na(nb) & nb > spike[k])) flag[k] <- QC_SUSPECT
    }
  }
  flag[is.na(x)] <- QC_MISSING
  flag
}

# ---------------------------------------------------------------------------
# 3. Rate of change test (SUSPECT only, as in the QARTOD manuals)
#    SUSPECT if |x[n] - x[n-1]| > n_dev * SD of the trailing window
#    The trailing window is the previous `window_days` calendar days.
#    NOT_EVALUATED if the previous day is missing or the window has fewer
#    than `min_obs` observations.
# ---------------------------------------------------------------------------
qc_rate_of_change <- function(x, date, n_dev = 3, window_days = 30, min_obs = 10) {
  n <- length(x)
  flag <- rep(QC_NOT_EVAL, n)
  d <- as.numeric(date)
  for (k in seq_len(n)[-1]) {
    if (is.na(x[k]) || is.na(x[k - 1]) || (d[k] - d[k - 1]) != 1) next
    in_win <- d >= d[k] - window_days & d < d[k] & !is.na(x)
    if (sum(in_win) < min_obs) next
    s <- stats::sd(x[in_win])
    flag[k] <- if (abs(x[k] - x[k - 1]) > n_dev * s) QC_SUSPECT else QC_PASS
  }
  flag[is.na(x)] <- QC_MISSING
  flag
}

# ---------------------------------------------------------------------------
# 4. Flat line test
#    Counts how many consecutive daily values (ending at n) are identical
#    within `tolerance`. SUSPECT if run >= suspect_n, FAIL if run >= fail_n.
#    A gap in dates or a missing value resets the run.
#    Note: lightstation values are recorded to 0.1 degC, so short runs of
#    identical values are expected, especially in winter.
# ---------------------------------------------------------------------------
qc_flat_line <- function(x, date, suspect_n = 5, fail_n = 10, tolerance = 1e-6) {
  n <- length(x)
  run <- integer(n)
  d <- as.numeric(date)
  for (k in seq_len(n)) {
    if (is.na(x[k])) { run[k] <- 0L; next }
    if (k > 1 && !is.na(x[k - 1]) && (d[k] - d[k - 1]) == 1 &&
        abs(x[k] - x[k - 1]) <= tolerance) {
      run[k] <- run[k - 1] + 1L
    } else {
      run[k] <- 1L
    }
  }
  flag <- rep(QC_PASS, n)
  flag[run >= suspect_n] <- QC_SUSPECT
  flag[run >= fail_n]    <- QC_FAIL
  flag[is.na(x)] <- QC_MISSING
  flag
}

# ---------------------------------------------------------------------------
# Aggregate (primary) flag: the worst result across tests.
#   any FAIL -> 4; else any SUSPECT -> 3; else any PASS -> 1; else 2.
#   Missing observations are 9 regardless.
# ---------------------------------------------------------------------------
qc_aggregate <- function(..., x) {
  m <- cbind(...)
  agg <- apply(m, 1, function(r) {
    if (any(r == QC_FAIL))    return(QC_FAIL)
    if (any(r == QC_SUSPECT)) return(QC_SUSPECT)
    if (any(r == QC_PASS))    return(QC_PASS)
    QC_NOT_EVAL
  })
  agg[is.na(x)] <- QC_MISSING
  as.integer(agg)
}

# ---------------------------------------------------------------------------
# Run all tests for one station. `cfg` is the list defined in R/config.R.
# ---------------------------------------------------------------------------
qc_station <- function(df, value_col, cfg) {
  df <- df[order(df$date), ]
  x <- df[[value_col]]
  span <- cfg$gross_range$suspect_span_by_station[[unique(df$station)]]
  if (is.null(span)) span <- cfg$gross_range$suspect_span
  df$qc_gross_range <- qc_gross_range(x, cfg$gross_range$fail_span, span)
  df$qc_spike       <- qc_spike(x, df$date, cfg$spike$suspect, cfg$spike$fail)
  df$qc_rate_of_change <- qc_rate_of_change(x, df$date, cfg$rate_of_change$n_dev,
                                            cfg$rate_of_change$window_days,
                                            cfg$rate_of_change$min_obs)
  df$qc_flat_line   <- qc_flat_line(x, df$date, cfg$flat_line$suspect_n, cfg$flat_line$fail_n)
  df$qc_aggregate   <- qc_aggregate(df$qc_gross_range, df$qc_spike,
                                    df$qc_rate_of_change, df$qc_flat_line, x = x)
  df
}

How I tuned the tests

The QARTOD manuals were written mainly for high-frequency, real-time sensors. These are daily bucket samples, so I treated every threshold as a starting point, looked at what each test flagged, and adjusted where the flags didn’t match what a person would question. All settings are in R/config.R, and the decisions are logged in the README.

  • Gross range. I started with a suspect limit of 22 °C. All 47 values above it were at three Strait of Georgia stations (Chrome Island, Departure Bay, and Entrance Island), and they occurred on the same dates across stations in warm summers. A broken thermometer wouldn’t do that, so I raised the suspect limit to 26 °C for those stations only.
  • Spike. Each value is compared with the mean of the days either side. At Departure Bay in July 2024, a value of 8.1 between 18.8 and 17.8 was clearly an error, but it also made its good neighbour fail. I added a rule that a FAIL is downgraded to SUSPECT if a neighbouring value has a larger spike, and wrote a unit test for it.
  • Rate of change. Flags were spread evenly across stations and months, with no sign of a single faulty record, so I kept the defaults.
  • Flat line. The longest run was 8.5 °C for about 19 days at Race Rocks in February 2010. I kept the thresholds, but found that some runs reflect a change in recording precision (below).

The data provider notes that sampling near high tide creates a 14-day cycle in daily values. That adds real day-to-day variation, which is one reason the spike and rate of change thresholds are looser than they would be for a continuous sensor.

What the flags caught

Show code
test_labels <- c(qc_aggregate = "Aggregate (worst of the four)", qc_gross_range = "Gross range",
                 qc_spike = "Spike", qc_rate_of_change = "Rate of change", qc_flat_line = "Flat line")
readr::read_csv("data/processed/qc_summary.csv", show_col_types = FALSE) |>
  dplyr::mutate(test = factor(test_labels[test], levels = test_labels)) |>
  dplyr::arrange(test) |>
  dplyr::select(Test = test, PASS, SUSPECT, FAIL, NOT_EVALUATED, MISSING) |>
  knitr::kable(format.args = list(big.mark = ","))
Test PASS SUSPECT FAIL NOT_EVALUATED MISSING
Aggregate (worst of the four) 139,186 1,484 35 0 12,528
Gross range 140,705 0 0 0 12,528
Spike 132,853 231 3 7,618 12,528
Rate of change 134,727 951 0 5,027 12,528
Flat line 140,311 362 32 0 12,528

Race Rocks, 2014 to 2016, coloured by aggregate flag

About 1% of values were flagged: 1,484 SUSPECT and 35 FAIL out of roughly 140,700 observations. Two findings stood out:

  • A value checked against a second variable. At Nootka Point on 30 March 2022, temperature dropped to 4.6 °C between 9.5 and 11.3. A cold freshwater pulse could in theory cause that, but salinity rose that day rather than falling, so I kept the FAIL.
  • Recording precision varies. Values are normally recorded to 0.1 °C, so about 10% should be whole numbers by chance. In some station-years it was 30% to 65% (Egg Island 2004 to 2005, Chrome Island 2008 to 2011, Race Rocks 2009, and Nootka Point 1994 to 1995). This suggests periods of whole-degree recording, and it explains several flat-line flags. I didn’t alter any values; I documented it as a known issue so users can decide how to treat those periods.