Filter features with controls and detection evidence
The controls define which ion features support a quantitative comparison. A reproducible background peak can pass a precision check, while a biologically interesting peak can fail because its measurements are too incomplete. We keep those decisions separate and retain every rejected feature with its reasons.
The main rules require detection in at least six of eight pooled QCs and raw QC CV no greater than 0.30. When a blank measurement exists, the observed biological-to-blank median ratio must be at least five. When every blank is undetected, a feature with an observed biological signal passes the blank rule under a separate status, while its ratio remains missing. The other retention rules still apply. We never replace undetected blanks with measured zero concentrations.
Declare the retained universe
Section titled “Declare the retained universe”The main retention-time window is 0.6 seconds through values strictly below 1,080 seconds. The deposited protocol places lithium-formate calibration near eighteen minutes. Primary preparation excludes a linked feature when its consensus apex or any original feature apex falls outside that window, and it preserves the exclusion evidence. The downstream check verifies the retained matrix’s consensus times.
Biological detection requires at least five of six plants in each species and five complete plot pairs. A pair is complete only when both plants have an observed area for that feature. Species-restricted detections remain descriptive results because filling the other species with small values would invent the quantitative contrast.
Both examples call the recorded shared calculations, then compare every feature decision and numeric QC value. The shared files remain visible in the companion directory beside the page runners.
The ratio scatter omits features whose blank ratio is missing. The complete tables and detection grid retain those features, including their explicit blank status.
The source data are Dietz and colleagues’ MTBLS865 deposit, released publicly by MetaboLights in 2020 under EMBL-EBI Terms of Use. The repository’s public data policy permits reuse, and its data guide permits modification. The source notice identifies the authors, original files, and this analysis’s selection and transformations.
library(ggplot2)library(jsonlite)library(patchwork)source("/shared/statistics.R")options(digits = 17)
data <- LoadFeatureData()quality <- SummarizeQuality(data, blank_minimum = 5, cv_maximum = 0.30)write.csv(quality, "outputs/feature_qc_r.csv", row.names = FALSE, na = "NA")restricted <- quality[quality$species_restricted, ]write.csv(restricted, "outputs/species_restricted_r.csv", row.names = FALSE, na = "NA")metrics <- list( features = nrow(quality), quality_retained = sum(quality$quality_retained), main_retained = sum(quality$main_retained), undetected_blank = sum(quality$blank_status == "undetected_blank"), species_restricted = nrow(restricted), rt_excluded = sum(!quality$rt_pass))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE)cat("Input features:", metrics$features, "\n")cat("Control-qualified and main retained features:", metrics$quality_retained, metrics$main_retained, "\n")cat("Features with no detected blank measurement:", metrics$undetected_blank, "\n")cat("Descriptive species-restricted features:", metrics$species_restricted, "\n")Input features: 96101Control-qualified and main retained features: 399 42Features with no detected blank measurement: 63369Descriptive species-restricted features: 51422ratio_plot <- ggplot(quality, aes(blank_ratio, qc_cv, color = main_retained)) + geom_point(size = 1.1, alpha = 0.5, na.rm = TRUE) + geom_vline(xintercept = 5, linetype = 2) + geom_hline(yintercept = 0.30, linetype = 2) + scale_x_log10(breaks = c(0.1, 1, 10, 100), labels = c("0.1", "1", "10", "100")) + scale_color_manual(values = c("#aab4bc", "#286b86")) + labs(x = "Observed biological / blank median", y = "Raw pooled-QC CV", color = "Main retained", title = "Blank and precision criteria") + theme_minimal(base_size = 11)grid <- as.data.frame(table( Dactylis = factor(quality$n_dactylis, levels = 0:6), Galium = factor(quality$n_galium, levels = 0:6)))fill_palette <- scales::col_numeric(c("#f3f6f7", "#286b86"), domain = range(grid$Freq))fill_rgb <- t(grDevices::col2rgb(fill_palette(grid$Freq))) / 255linear_rgb <- ifelse(fill_rgb <= 0.04045, fill_rgb / 12.92, ((fill_rgb + 0.055) / 1.055)^2.4)luminance <- as.vector(linear_rgb %*% c(0.2126, 0.7152, 0.0722))grid$label_color <- ifelse(luminance < 0.179, "white", "black")detection_plot <- ggplot(grid, aes(Dactylis, Galium, fill = Freq)) + geom_tile(color = "white") + geom_text(aes(label = Freq, color = label_color), size = 3) + scale_color_identity() + scale_fill_gradient(low = "#f3f6f7", high = "#286b86") + labs(x = "Dactylis plants detected", y = "Galium plants detected", fill = "Features", title = "All feature detection patterns") + theme_minimal(base_size = 11)ggsave("outputs/feature_qc_r.png", ratio_plot + detection_plot, width = 10.5, height = 4.6, dpi = 160, bg = "white")
import importlib.utilimport jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
spec = importlib.util.spec_from_file_location("metabo", "/shared/statistics.py")metabo = importlib.util.module_from_spec(spec)spec.loader.exec_module(metabo)data = metabo.load_feature_data()quality = metabo.summarize_quality(data, blank_minimum=5, cv_maximum=0.30)quality.to_csv("outputs/feature_qc_python.csv", index=False, na_rep="NA")restricted = quality.loc[quality["species_restricted"]]restricted.to_csv("outputs/species_restricted_python.csv", index=False, na_rep="NA")r_quality = pd.read_csv("outputs/feature_qc_r.csv", dtype={"feature_id": str})pd.testing.assert_frame_equal(quality, r_quality, check_dtype=False, rtol=1e-9, atol=1e-10)metrics = { "features": len(quality), "quality_retained": int(quality["quality_retained"].sum()), "main_retained": int(quality["main_retained"].sum()), "undetected_blank": int(quality["blank_status"].eq( "undetected_blank").sum()), "species_restricted": len(restricted), "rt_excluded": int((~quality["rt_pass"]).sum()),}Path("outputs/metrics_python.json").write_text(json.dumps(metrics, indent=2))print("Input features:", metrics["features"])print("Control-qualified and main retained features:", metrics["quality_retained"], metrics["main_retained"])print("Features with no detected blank measurement:", metrics["undetected_blank"])print("Descriptive species-restricted features:", metrics["species_restricted"])Input features: 96101Control-qualified and main retained features: 399 42Features with no detected blank measurement: 63369Descriptive species-restricted features: 51422figure, axes = plt.subplots(1, 2, figsize=(10.5, 4.6))for retained, color in [(False, "#aab4bc"), (True, "#286b86")]: rows = quality.loc[quality["main_retained"].eq(retained)] axes[0].scatter(rows["blank_ratio"], rows["qc_cv"], s=8, alpha=0.5, color=color, label=str(retained))axes[0].axvline(5, color="black", linestyle="--", linewidth=0.8)axes[0].axhline(0.30, color="black", linestyle="--", linewidth=0.8)axes[0].set_xscale("log")axes[0].set_xlabel("Observed biological / blank median")axes[0].set_ylabel("Raw pooled-QC CV")axes[0].set_title("Blank and precision criteria")axes[0].legend(title="Main retained", fontsize=8)grid = pd.crosstab(quality["n_galium"], quality["n_dactylis"])grid = grid.reindex(index=range(7), columns=range(7), fill_value=0)heat = axes[1].imshow(grid, origin="lower", cmap="Blues", aspect="equal")for row in range(7): for column in range(7): value = grid.iloc[row, column] rgb = np.asarray(heat.cmap(heat.norm(value))[:3]) linear_rgb = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4) luminance = linear_rgb @ np.array([0.2126, 0.7152, 0.0722]) text_color = "white" if luminance < 0.179 else "black" axes[1].text(column, row, str(value), color=text_color, ha="center", va="center", fontsize=8)axes[1].set_xticks(range(7))axes[1].set_yticks(range(7))axes[1].set_xlabel("Dactylis plants detected")axes[1].set_ylabel("Galium plants detected")axes[1].set_title("All feature detection patterns")figure.colorbar(heat, ax=axes[1], label="Features", shrink=0.8)figure.tight_layout()figure.savefig("outputs/feature_qc_python.png", dpi=160, facecolor="white")plt.close(figure)
The ratio plot omits undefined ratios, so it must be read with the undetected-blank count and the complete exclusion table. These criteria are declared choices for this example, not universal analytical standards. The differential lesson varies blank and QC thresholds while holding the primary normalization reference fixed.
Further reading
Section titled “Further reading”-
Broadhurst and colleagues on blank and pooled-QC assessment
The authors separate contamination checks from precision assessment and require reported acceptance criteria.
-
W3C contrast and relative luminance
The definition gives the sRGB conversion and luminance coefficients used to select heatmap label colors. Contrast concerns legibility and does not change feature eligibility.