Test QC drift before biological normalization
A drift correction must improve predictions for QC injections it did not use to fit the trend. Eight pooled QCs support a constrained linear assessment, not a flexible curve selected because it makes the biological groups separate. We preserve every feature’s correction decision before sample normalization.
The reference universe contains features that pass the primary control, retention-time, biological detection, and complete-pair rules. Species-restricted detections remain outside that normalization reference. Their asymmetric detection must not define different effective reference populations for the two species.
Require evidence for correction
Section titled “Require evidence for correction”For each feature with at least six detected QCs, the shared calculation fits log2 area against elapsed acquisition time. It compares leave-one-QC-out prediction error with an intercept-only model fitted to the same training injections. The correction requires at least a 10% reduction in mean squared prediction error.
Every biological injection must also fall inside that feature’s observed QC interval. Missing endpoint QCs can therefore prevent correction even when the full QC schedule surrounds the plants. Accepted corrections subtract the fitted slope relative to mean observed QC time, which preserves mean QC log2 area. Measurements outside that interval remain uncorrected.
Define the quotient reference
Section titled “Define the quotient reference”PQN uses the per-feature median biological intensity as its reference. Each biological injection receives the median of its positive observed feature-to-reference ratios. Dividing by that factor changes the sample scale while preserving missing observations.
The method assumes a stable reference distribution. It can remove a global biological shift, so the species comparison also reports no sample scaling, median scaling, and effects without accepted drift correction. Blanks and standard mixtures never enter the biological quotient calculation.
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)drift <- CorrectDrift(data)normalized <- NormalizeBiological(data, drift$corrected, quality$main_retained, method = "pqn")write.csv(drift$decisions, "outputs/drift_decisions_r.csv", row.names = FALSE, na = "NA")factor_table <- data.frame(injection_id = normalized$metadata$injection_id, pqn_factor = unname(normalized$factors))write.csv(factor_table, "outputs/pqn_factors_r.csv", row.names = FALSE)matrix_table <- data.frame(feature_id = data$features$feature_id, normalized$matrix, check.names = FALSE)write.csv(matrix_table, "outputs/normalized_r.csv", row.names = FALSE, na = "NA")complete <- quality$main_retained & rowSums(is.finite(normalized$matrix)) == ncol(normalized$matrix)stopifnot(sum(complete) >= 2L)pca <- prcomp(t(normalized$matrix[complete, , drop = FALSE]), center = TRUE, scale. = FALSE)variance <- pca$sdev^2 / sum(pca$sdev^2)stopifnot(all(is.finite(variance)))distances <- as.matrix(dist(t(normalized$matrix[complete, , drop = FALSE])))write.csv(distances, "outputs/sample_distances_r.csv", row.names = TRUE)metrics <- list( primary_reference_features = sum(quality$main_retained), accepted_drift_features = sum(drift$decisions$accepted), corrected_reference_features = sum(drift$decisions$accepted & quality$main_retained), pca_complete_features = sum(complete), pc1_variance = variance[1], pc2_variance = variance[2])write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)cat("Primary normalization reference features:", metrics$primary_reference_features, "\n")cat("Accepted QC trends among reference features:", metrics$corrected_reference_features, "\n")cat("Complete features used for PCA:", metrics$pca_complete_features, "\n")Primary normalization reference features: 42Accepted QC trends among reference features: 9Complete features used for PCA: 18decision <- drift$decisionserror_plot <- ggplot(decision, aes(mse_intercept, mse_linear, color = accepted)) + geom_point(size = 1.2, alpha = 0.5, na.rm = TRUE) + geom_abline(slope = 0.9, intercept = 0, linetype = 2) + scale_color_manual(values = c("#aab4bc", "#286b86")) + labs(x = "Held-out intercept-only MSE", y = "Held-out linear MSE", color = "Accepted", title = "QC prediction error") + theme_minimal(base_size = 11)scores <- data.frame(normalized$metadata, PC1 = pca$x[, 1], PC2 = pca$x[, 2])score_plot <- ggplot(scores, aes(PC1, PC2, color = species)) + geom_point(size = 3) + geom_text(aes(label = plot), vjust = -0.8, size = 3, show.legend = FALSE) + scale_color_manual(values = c("#286b86", "#b85c38")) + labs(x = sprintf("PC1, %.1f%%", variance[1] * 100), y = sprintf("PC2, %.1f%%", variance[2] * 100), title = "Complete retained features after PQN", color = "Species") + theme_minimal(base_size = 11) + theme(legend.position = "bottom")ggsave("outputs/normalization_drift_r.png", error_plot + score_plot, width = 11, height = 4.8, dpi = 160, bg = "white")
import importlib.utilimport jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy.spatial.distance import pdist, squareform
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)corrected, decision = metabo.correct_drift(data)matrix, factors, metadata = metabo.normalize_biological( data, corrected, quality["main_retained"].to_numpy(), method="pqn")decision.to_csv("outputs/drift_decisions_python.csv", index=False, na_rep="NA")factor_table = pd.DataFrame({"injection_id": metadata["injection_id"], "pqn_factor": factors})factor_table.to_csv("outputs/pqn_factors_python.csv", index=False)matrix_table = pd.DataFrame(matrix, columns=metadata["injection_id"])matrix_table.insert(0, "feature_id", data["features"]["feature_id"])matrix_table.to_csv("outputs/normalized_python.csv", index=False, na_rep="NA")tables = [("drift_decisions", decision), ("pqn_factors", factor_table), ("normalized", matrix_table)]for name, frame in tables: expected = pd.read_csv(f"outputs/{name}_r.csv", dtype={"feature_id": str}) pd.testing.assert_frame_equal(frame, expected, check_dtype=False, check_names=False, rtol=1e-8, atol=1e-10)complete = quality["main_retained"].to_numpy() & np.isfinite(matrix).all(axis=1)assert complete.sum() >= 2pca_input = matrix[complete].Tcentered = pca_input - pca_input.mean(axis=0)left, singular_values, right = np.linalg.svd(centered, full_matrices=False)scores = left[:, :2] * singular_values[:2]variance = singular_values ** 2 / np.sum(singular_values ** 2)assert np.isfinite(variance).all()distances = squareform(pdist(pca_input))r_distances = pd.read_csv("outputs/sample_distances_r.csv", index_col=0)np.testing.assert_allclose(distances, r_distances, rtol=1e-9, atol=1e-10)pd.DataFrame(distances, index=metadata["injection_id"], columns=metadata["injection_id"]).to_csv( "outputs/sample_distances_python.csv")metrics = { "primary_reference_features": int(quality["main_retained"].sum()), "accepted_drift_features": int(decision["accepted"].sum()), "corrected_reference_features": int((decision["accepted"] & quality["main_retained"]).sum()), "pca_complete_features": int(complete.sum()), "pc1_variance": float(variance[0]), "pc2_variance": float(variance[1]),}Path("outputs/metrics_python.json").write_text(json.dumps(metrics, indent=2))print("Primary normalization reference features:", metrics["primary_reference_features"])print("Accepted QC trends among reference features:", metrics["corrected_reference_features"])print("Complete features used for PCA:", metrics["pca_complete_features"])Primary normalization reference features: 42Accepted QC trends among reference features: 9Complete features used for PCA: 18figure, axes = plt.subplots(1, 2, figsize=(11, 4.8))for accepted, color in [(False, "#aab4bc"), (True, "#286b86")]: rows = decision.loc[decision["accepted"].eq(accepted)] axes[0].scatter(rows["mse_intercept"], rows["mse_linear"], s=8, alpha=0.5, color=color, label=str(accepted))maximum = decision["mse_intercept"].max()axes[0].plot([0, maximum], [0, 0.9 * maximum], color="black", linestyle="--", linewidth=0.8)axes[0].set_xlabel("Held-out intercept-only MSE")axes[0].set_ylabel("Held-out linear MSE")axes[0].set_title("QC prediction error")axes[0].legend(title="Accepted", fontsize=8)for species, color in zip(metabo.SPECIES, ["#286b86", "#b85c38"], strict=True): mask = metadata["species"].eq(species).to_numpy() axes[1].scatter(scores[mask, 0], scores[mask, 1], color=color, label=species, s=40)for number, plot in enumerate(metadata["plot"]): axes[1].annotate(plot, scores[number], xytext=(3, 4), textcoords="offset points", fontsize=8)axes[1].set_xlabel(f"PC1, {variance[0] * 100:.1f}%")axes[1].set_ylabel(f"PC2, {variance[1] * 100:.1f}%")axes[1].set_title("Complete retained features after PQN")axes[1].legend(fontsize=8, loc="best")figure.tight_layout()figure.savefig("outputs/normalization_drift_python.png", dpi=160, facecolor="white")plt.close(figure)
PCA uses complete retained features and does not impute a missing measurement. Axis signs can differ between implementations without changing sample distances or explained variance. Separation by species is a description of these measurements, not an additional test of the species coefficient.
Further reading
Section titled “Further reading”-
Dieterle and colleagues on probabilistic quotient normalization
The original abstract introduces a dilution estimate from test-to-reference quotients and reports NMR validation. It supplies method context without validating this LC-MS implementation.
-
Broadhurst and colleagues on QC signal correction
The guidance discusses regression-based signal correction and the placement of endpoint QCs. Its cross-validation discussion explains the risk of prediction outside observed QC times.