NPX and QC
Before you test a single protein in an Olink dataset, you need to know what an NPX value means and which values and samples to trust. This page works through both on the public Olink Explore data of the MGH COVID-19 cohort of Filbin et al. 2021, deposited on Mendeley Data under CC BY 4.0, and shows which standard checks the public file cannot support. The Olink NPX format page describes the columns of a full export.
Read the workbook into the long layout
Section titled “Read the workbook into the long layout”The NPX workbook is wide, with one row per plasma sample and one column per OlinkID. The
Public ID reads <subject>_D<day>, and Day is 0, 3, 7 or E, a sample drawn at a
clinical deterioration. Assay names, panels, UniProt accessions and LODs sit in sheet 2A
of Supplemental Table 2, so the code joins them on the OlinkID. In the clinical workbook,
Acuity max is the worst state within 28 days, where 1 is death, 2 intubation, 3 oxygen,
4 a hospital stay without oxygen and 5 discharge.
The data below come from Bánk Fenyves’s version 2 deposit for Filbin and colleagues’ 2021 study, under CC BY 4.0. This lesson reshapes the NPX workbook, joins assay and clinical annotations, and computes the displayed quality summaries.
suppressPackageStartupMessages({ library(readxl) library(dplyr) library(tidyr) library(ggplot2)})
mgh_dir <- "/opt/data/mgh_covid_olink"dir.create("outputs", showWarnings = FALSE)
# The NPX workbook writes a missing value as the text "NA".npx_wide <- read_excel( file.path(mgh_dir, "olink_proteomics.xlsx"), na = "NA")# Sheet 2A starts with a title row, so the header is on row 2.assay_table <- read_excel( file.path(mgh_dir, "supplemental_table_2_olink_assays.xlsx"), sheet = "2A-Olink-Assay", skip = 1)cat(sprintf( "wide table: %d rows, %d columns\n", nrow(npx_wide), ncol(npx_wide)))cat(sprintf("assay table: %d assays\n", nrow(assay_table)))day_counts <- table(npx_wide$Day)cat(sprintf( "Day %s: %d samples\n", names(day_counts), as.integer(day_counts)), sep = "")
# One row per sample and assay, the layout of an Olink export.npx <- npx_wide |> rename(SampleID = `Public ID`) |> pivot_longer( starts_with("OID"), names_to = "OlinkID", values_to = "NPX" ) |> inner_join(assay_table, by = "OlinkID") |> select( SampleID, Day, OlinkID, UniProt, Assay, Panel, Panel_Version, MissingFreq, LOD, NPX )cat(sprintf("long table: %d rows\n", nrow(npx)))cat(sprintf("missing NPX: %d\n", sum(is.na(npx$NPX))))print(as.data.frame(head(npx, 3)), digits = 4)
clinical <- read_excel( file.path(mgh_dir, "clinical_metadata.xlsx"), sheet = "Subject-level metadata") |> transmute( subject = as.character(`Public ID`), COVID, acuity_max = `Acuity max` )# A Public ID is <subject>_D<day>, so the subject is the part before "_".npx <- npx |> mutate(subject = sub("_.*$", "", SampleID)) |> left_join(clinical, by = "subject")
olink_subjects <- unique(npx$subject)cat(sprintf("subjects with NPX: %d\n", length(olink_subjects)))cat(sprintf( "subjects with NPX and no clinical row: %d\n", sum(!olink_subjects %in% clinical$subject)))cat(sprintf( "clinical subjects with no NPX: %s\n", paste(setdiff(clinical$subject, olink_subjects), collapse = ", ")))
# Day 0 holds one sample per subject.day0 <- npx |> filter(Day == "0")day0_samples <- day0 |> distinct(SampleID, COVID, acuity_max)covid_pos <- day0_samples$COVID == 1cat(sprintf("Day 0 samples: %d\n", nrow(day0_samples)))cat(sprintf(" COVID negative: %d\n", sum(!covid_pos)))cat(sprintf( " COVID positive, Acuity max 1 or 2: %d\n", sum(covid_pos & day0_samples$acuity_max <= 2)))cat(sprintf( " COVID positive, Acuity max 3 to 5: %d\n", sum(covid_pos & day0_samples$acuity_max >= 3)))wide table: 784 rows, 1431 columnsassay table: 1429 assaysDay 0: 383 samplesDay 3: 219 samplesDay 7: 139 samplesDay E: 43 sampleslong table: 1120336 rowsmissing NPX: 18 SampleID Day OlinkID UniProt Assay Panel Panel_Version1 1_D0 0 OID20321 O00584 RNASET2 CARDIOMETABOLIC 12 1_D0 0 OID20206 Q07108 CD69 CARDIOMETABOLIC 13 1_D0 0 OID20195 P35754 GLRX CARDIOMETABOLIC 1 MissingFreq LOD NPX1 0.03 1.422 4.1972 0.04 1.099 5.5313 0.06 2.056 1.901subjects with NPX: 383subjects with NPX and no clinical row: 0clinical subjects with no NPX: 180Day 0 samples: 383 COVID negative: 78 COVID positive, Acuity max 1 or 2: 109 COVID positive, Acuity max 3 to 5: 196import jsonimport pathlib
import matplotlib.pyplot as pltimport pandas as pd
MGH_DIR = pathlib.Path("/opt/data/mgh_covid_olink")OUTPUTS = pathlib.Path("outputs")OUTPUTS.mkdir(exist_ok=True)
# The NPX workbook writes a missing value as the text "NA".npx_wide = pd.read_excel( MGH_DIR / "olink_proteomics.xlsx", na_values=["NA"], keep_default_na=False,)# Day mixes numbers and the letter E, so read every value as text.npx_wide["Day"] = npx_wide["Day"].astype(str)# Sheet 2A starts with a title row, so the header is on row 2.assay_table = pd.read_excel( MGH_DIR / "supplemental_table_2_olink_assays.xlsx", sheet_name="2A-Olink-Assay", skiprows=1,)rows, columns = npx_wide.shapeprint(f"wide table: {rows} rows, {columns} columns")print(f"assay table: {len(assay_table)} assays")for day, count in npx_wide["Day"].value_counts().sort_index().items(): print(f"Day {day}: {count} samples")
# One row per sample and assay, the layout of an Olink export.olink_ids = [name for name in npx_wide.columns if name.startswith("OID")]npx = ( npx_wide.rename(columns={"Public ID": "SampleID"}) .melt( id_vars=["SampleID", "Day"], value_vars=olink_ids, var_name="OlinkID", value_name="NPX", ) .merge(assay_table, on="OlinkID", how="inner"))npx = npx[[ "SampleID", "Day", "OlinkID", "UniProt", "Assay", "Panel", "Panel_Version", "MissingFreq", "LOD", "NPX",]]print(f"long table: {len(npx)} rows")print(f"missing NPX: {npx['NPX'].isna().sum()}")first_rows = npx[npx["SampleID"] == "1_D0"].head(3)print(first_rows.to_string(index=False, line_width=80))
clinical = pd.read_excel( MGH_DIR / "clinical_metadata.xlsx", sheet_name="Subject-level metadata")clinical = pd.DataFrame({ "subject": clinical["Public ID"].astype(int).astype(str), "COVID": clinical["COVID"], "acuity_max": clinical["Acuity max"],})# A Public ID is <subject>_D<day>, so the subject is the part before "_".npx["subject"] = npx["SampleID"].str.split("_").str[0]npx = npx.merge(clinical, on="subject", how="left")
olink_subjects = npx["subject"].unique()no_clinical = ~pd.Series(olink_subjects).isin(clinical["subject"])no_npx = sorted(set(clinical["subject"]) - set(olink_subjects))print(f"subjects with NPX: {len(olink_subjects)}")print(f"subjects with NPX and no clinical row: {no_clinical.sum()}")print(f"clinical subjects with no NPX: {', '.join(no_npx)}")
# Day 0 holds one sample per subject.day0 = npx[npx["Day"] == "0"]day0_samples = day0.drop_duplicates("SampleID")covid_pos = day0_samples["COVID"] == 1print(f"Day 0 samples: {len(day0_samples)}")print(f" COVID negative: {(~covid_pos).sum()}")severe = covid_pos & (day0_samples["acuity_max"] <= 2)print(f" COVID positive, Acuity max 1 or 2: {severe.sum()}")other = covid_pos & (day0_samples["acuity_max"] >= 3)print(f" COVID positive, Acuity max 3 to 5: {other.sum()}")wide table: 784 rows, 1431 columnsassay table: 1429 assaysDay 0: 383 samplesDay 3: 219 samplesDay 7: 139 samplesDay E: 43 sampleslong table: 1120336 rowsmissing NPX: 18SampleID Day OlinkID UniProt Assay Panel Panel_Version \ 1_D0 0 OID20321 O00584 RNASET2 CARDIOMETABOLIC 1 1_D0 0 OID20206 Q07108 CD69 CARDIOMETABOLIC 1 1_D0 0 OID20195 P35754 GLRX CARDIOMETABOLIC 1
MissingFreq LOD NPX 0.03 1.4223 4.1968 0.04 1.0986 5.5310 0.06 2.0558 1.9006subjects with NPX: 383subjects with NPX and no clinical row: 0clinical subjects with no NPX: 180Day 0 samples: 383 COVID negative: 78 COVID positive, Acuity max 1 or 2: 109 COVID positive, Acuity max 3 to 5: 196The 784 samples come from 383 subjects, and the later days thin out because Filbin et al. sampled COVID-19 patients again only while they stayed in hospital. Of the 1,120,336 rows of the long table, 18 have no NPX. Subject 180 has clinical data but no NPX, and the paper reports Day 0 data for 383 patients with one assay outlier excluded. Day 0 holds one sample per subject, and the rest of this page uses it. It counts 78 subjects without COVID-19, 109 COVID-19 patients who died or were intubated, and 196 who were not.
What an NPX value is
Section titled “What an NPX value is”NPX is Olink’s relative unit on a log2 scale, so one NPX step is roughly a doubling of the protein. It is relative to the assay as well as to the run, as the What is proteomics page explains. This cohort shows it directly, because Olink Explore places CXCL8, IL6 and TNF in all four panels for quality control, as Filbin et al. describe.
# One assay across subjects: IL6 on the Inflammation panel.il6 <- day0 |> filter(OlinkID == "OID20563")spread <- quantile(il6$NPX, c(0.05, 0.95), names = FALSE)cat(sprintf( "IL6 Day 0: 5th percentile %.2f NPX, 95th percentile %.2f NPX\n", spread[1], spread[2]))cat(sprintf( "a gap of %.2f NPX, about a %.0f-fold difference\n", diff(spread), 2^diff(spread)))
# One protein, four assays: CXCL8, IL6 and TNF sit in every panel.inflammation_copy <- day0 |> filter(Assay %in% c("CXCL8", "IL6", "TNF"), Panel == "INFLAMMATION") |> select(SampleID, Assay, inflammation_npx = NPX)shared_assays <- day0 |> inner_join(inflammation_copy, by = c("SampleID", "Assay")) |> group_by(Assay, Panel, OlinkID) |> summarise( median_npx = median(NPX), below_lod = mean(NPX < LOD), r_inflammation = cor(NPX, inflammation_npx), .groups = "drop" ) |> arrange(Assay, Panel)cat("Assay Panel OlinkID median below LOD r\n")cat(sprintf( "%-6s %-16s %s %7.2f %10.3f %6.3f\n", shared_assays$Assay, shared_assays$Panel, shared_assays$OlinkID, shared_assays$median_npx, shared_assays$below_lod, shared_assays$r_inflammation), sep = "")IL6 Day 0: 5th percentile 2.38 NPX, 95th percentile 7.99 NPXa gap of 5.62 NPX, about a 49-fold differenceAssay Panel OlinkID median below LOD rCXCL8 CARDIOMETABOLIC OID20153 3.14 0.016 0.990CXCL8 INFLAMMATION OID20631 6.50 0.000 1.000CXCL8 NEUROLOGY OID20997 6.62 0.000 0.995CXCL8 ONCOLOGY OID21430 5.63 0.000 0.997IL6 CARDIOMETABOLIC OID20101 5.68 0.010 0.993IL6 INFLAMMATION OID20563 5.39 0.021 1.000IL6 NEUROLOGY OID20911 5.68 0.010 0.995IL6 ONCOLOGY OID21276 5.83 0.008 0.996TNF CARDIOMETABOLIC OID20074 1.46 0.084 0.890TNF INFLAMMATION OID20473 1.77 0.003 1.000TNF NEUROLOGY OID20848 1.75 0.587 0.905TNF ONCOLOGY OID21237 1.21 0.131 0.906def agreement_with_inflammation(group): """Summarize one copy of a shared assay on Day 0.
Args: group: The Day 0 rows of one assay copy, with an inflammation_npx column that holds the NPX of the Inflammation panel copy.
Returns: A Series with the median NPX, the share of values below LOD and the Pearson correlation with the Inflammation panel copy. """ return pd.Series({ "median_npx": group["NPX"].median(), "below_lod": (group["NPX"] < group["LOD"]).mean(), "r_inflammation": group["NPX"].corr(group["inflammation_npx"]), })
# One assay across subjects: IL6 on the Inflammation panel.il6 = day0.loc[day0["OlinkID"] == "OID20563", "NPX"]low, high = il6.quantile([0.05, 0.95])print( f"IL6 Day 0: 5th percentile {low:.2f} NPX, " f"95th percentile {high:.2f} NPX")gap = high - lowprint(f"a gap of {gap:.2f} NPX, about a {2 ** gap:.0f}-fold difference")
# One protein, four assays: CXCL8, IL6 and TNF sit in every panel.is_shared = day0["Assay"].isin(["CXCL8", "IL6", "TNF"])inflammation_copy = day0.loc[ is_shared & (day0["Panel"] == "INFLAMMATION"), ["SampleID", "Assay", "NPX"],].rename(columns={"NPX": "inflammation_npx"})shared_assays = ( day0[is_shared] .merge(inflammation_copy, on=["SampleID", "Assay"]) .groupby(["Assay", "Panel", "OlinkID"]) .apply(agreement_with_inflammation) .reset_index())print("Assay Panel OlinkID median below LOD r")for row in shared_assays.itertuples(): print( f"{row.Assay:<6} {row.Panel:<16} {row.OlinkID} " f"{row.median_npx:7.2f} {row.below_lod:10.3f} " f"{row.r_inflammation:6.3f}" )IL6 Day 0: 5th percentile 2.38 NPX, 95th percentile 7.99 NPXa gap of 5.62 NPX, about a 49-fold differenceAssay Panel OlinkID median below LOD rCXCL8 CARDIOMETABOLIC OID20153 3.14 0.016 0.990CXCL8 INFLAMMATION OID20631 6.50 0.000 1.000CXCL8 NEUROLOGY OID20997 6.62 0.000 0.995CXCL8 ONCOLOGY OID21430 5.63 0.000 0.997IL6 CARDIOMETABOLIC OID20101 5.68 0.010 0.993IL6 INFLAMMATION OID20563 5.39 0.021 1.000IL6 NEUROLOGY OID20911 5.68 0.010 0.995IL6 ONCOLOGY OID21276 5.83 0.008 0.996TNF CARDIOMETABOLIC OID20074 1.46 0.084 0.890TNF INFLAMMATION OID20473 1.77 0.003 1.000TNF NEUROLOGY OID20848 1.75 0.587 0.905TNF ONCOLOGY OID21237 1.21 0.131 0.906Within one assay, NPX behaves like a log concentration. IL6 on the Inflammation panel spans 5.62 NPX from the 5th to the 95th percentile of the Day 0 samples, about a 49-fold range. Across assays it does not. The four CXCL8 assays order the 383 samples almost identically, with r of 0.990 or more against the Inflammation copy, yet their medians run from 3.14 NPX on the Cardiometabolic panel to 6.62 NPX on the Neurology panel. Compare samples within an assay, and never read a higher NPX on one assay as more protein than a lower NPX on another.
TNF agrees less, with r from 0.890 to 0.906, and its Neurology copy has a share of 0.587 of its Day 0 values below LOD. For an analysis by protein, keep one copy of each, or a correction for multiple testing counts IL6 four times. The Inflammation copies are the ones to keep, with at most 0.021 of their values below LOD.
What the public file leaves out
Section titled “What the public file leaves out”A full Olink export also carries a plate ID and a QC flag for each sample. Filbin et al.
describe negative controls run in triplicate on each plate to set the background and the
LOD, and on intensity normalized Explore data the LOD differs from plate to plate, as
Olink’s
LOD tutorial
describes. The R tab passes the Day 0 table to check_npx(), the validator that other
OlinkAnalyze functions run first. The Python tab compares the column names with the list
that the
OlinkAnalyze vignette
gives for read_npx().
# The columns that read_npx() returns for an Olink export.export_columns <- c( "SampleID", "OlinkID", "UniProt", "Assay", "MissingFreq", "Panel", "Panel_Version", "PlateID", "QC_Warning", "LOD", "NPX")cat(sprintf( "export columns missing here: %s\n", paste(setdiff(export_columns, names(npx)), collapse = ", ")))lod_values <- npx |> distinct(OlinkID, LOD) |> count(OlinkID)cat(sprintf("LOD values per assay: %d\n", max(lod_values$n)))
# check_npx() validates a table before the other OlinkAnalyze functions.checked <- try(OlinkAnalyze::check_npx(day0), silent = TRUE)cat(paste0(conditionMessage(attr(checked, "condition")), "\n"))export columns missing here: PlateID, QC_WarningLOD values per assay: 1✖ There are no column names associated with the following keys:* "plate_id": One of "PlateID", "plateid", or "plate_id".* "qc_warning": One of "QC_Warning", "SampleQC", "qc_warning", or "sample_qc".ℹ Please ensure presence of columns above in dataset `df`. If columns are present and the column name does not match one of the expected ones, please use argument `preferred_names` to point to the correct column.# The columns that read_npx() returns for an Olink export.export_columns = [ "SampleID", "OlinkID", "UniProt", "Assay", "MissingFreq", "Panel", "Panel_Version", "PlateID", "QC_Warning", "LOD", "NPX",]missing_columns = [name for name in export_columns if name not in npx]print(f"export columns missing here: {', '.join(missing_columns)}")lod_values = npx.drop_duplicates(["OlinkID", "LOD"])["OlinkID"]print(f"LOD values per assay: {lod_values.value_counts().max()}")export columns missing here: PlateID, QC_WarningLOD values per assay: 1check_npx() stops on the missing plate and QC columns, and so does olink_qc_plot(),
which calls it. Its preferred_names argument can point to a column with another name,
but nothing can supply a plate ID that was never exported.
| Missing | What it allows | What remains |
|---|---|---|
QC_Warning |
Drop the samples that failed Olink’s internal controls | The distribution of each sample, at the end of this page |
PlateID |
Test for a plate effect | The design, since Filbin et al. allocated samples randomly onto plates based on disease outcome grouping |
| LOD per plate | Call each value against the LOD of its own plate | One LOD per assay |
Values below LOD
Section titled “Values below LOD”Olink reports a value below LOD as a number, not a blank, so the code compares each NPX
with the LOD of its assay. The OlinkAnalyze vignette defines MissingFreq as the
frequency of samples below LOD, which makes it a check on the join.
# Olink reports values below LOD, so count them per assay.per_assay <- npx |> group_by(OlinkID, Assay, Panel, MissingFreq) |> summarise(below_lod = mean(NPX < LOD, na.rm = TRUE), .groups = "drop")measured <- npx |> filter(!is.na(NPX))cat(sprintf( "values below LOD: %d of %d, a share of %.4f\n", sum(measured$NPX < measured$LOD), nrow(measured), mean(measured$NPX < measured$LOD)))
per_panel <- per_assay |> group_by(Panel) |> summarise(assays = n(), over_half = sum(below_lod > 0.5)) |> inner_join( measured |> group_by(Panel) |> summarise(below_lod = mean(NPX < LOD)), by = "Panel" )cat("Panel assays below LOD assays over 0.5\n")cat(sprintf( "%-16s %6d %10.4f %16d\n", per_panel$Panel, per_panel$assays, per_panel$below_lod, per_panel$over_half), sep = "")
most_below <- per_assay |> arrange(desc(below_lod), OlinkID) |> head(3)cat(sprintf( "%s %-7s %-16s %.3f below LOD, MissingFreq %.2f\n", most_below$OlinkID, most_below$Assay, most_below$Panel, most_below$below_lod, most_below$MissingFreq), sep = "")
# MissingFreq is the share below LOD that the authors' export recorded.none_below <- per_assay |> filter(below_lod == 0)cat(sprintf( "correlation with MissingFreq: %.4f\n", cor(per_assay$below_lod, per_assay$MissingFreq)))cat(sprintf( "median of MissingFreq minus the share: %.4f\n", median(per_assay$MissingFreq - per_assay$below_lod)))cat(sprintf( "assays with no value below LOD: %d, smallest MissingFreq %.2f\n", nrow(none_below), min(none_below$MissingFreq)))
# The rule on this page: drop an assay with more than half below LOD.kept <- per_assay |> filter(below_lod <= 0.5)cat(sprintf( "assays kept: %d, dropped: %d\n", nrow(kept), nrow(per_assay) - nrow(kept)))values below LOD: 207906 of 1120318, a share of 0.1856Panel assays below LOD assays over 0.5CARDIOMETABOLIC 368 0.1324 46INFLAMMATION 365 0.1877 70NEUROLOGY 328 0.2385 81ONCOLOGY 368 0.1895 62OID20833 IVD NEUROLOGY 1.000 below LOD, MissingFreq 0.99OID20432 ARNT INFLAMMATION 0.999 below LOD, MissingFreq 0.94OID20888 KLB NEUROLOGY 0.997 below LOD, MissingFreq 0.98correlation with MissingFreq: 0.9989median of MissingFreq minus the share: 0.0300assays with no value below LOD: 661, smallest MissingFreq 0.03assays kept: 1170, dropped: 259def count_over_half(shares): """Count the assays with more than half of their values below LOD.
Args: shares: A Series with the share below LOD of each assay.
Returns: The number of shares above 0.5. """ return int((shares > 0.5).sum())
# Olink reports values below LOD, so count them per assay.measured = npx[npx["NPX"].notna()].copy()measured["below_lod"] = measured["NPX"] < measured["LOD"]per_assay = measured.groupby( ["OlinkID", "Assay", "Panel", "MissingFreq"], as_index=False)["below_lod"].mean()print( f"values below LOD: {measured['below_lod'].sum()} of {len(measured)}, " f"a share of {measured['below_lod'].mean():.4f}")
per_panel = per_assay.groupby("Panel").agg( assays=("OlinkID", "size"), over_half=("below_lod", count_over_half),)per_panel["below_lod"] = measured.groupby("Panel")["below_lod"].mean()print("Panel assays below LOD assays over 0.5")for row in per_panel.reset_index().itertuples(): print( f"{row.Panel:<16} {row.assays:6d} {row.below_lod:10.4f} " f"{row.over_half:16d}" )
most_below = per_assay.sort_values( ["below_lod", "OlinkID"], ascending=[False, True]).head(3)for row in most_below.itertuples(): print( f"{row.OlinkID} {row.Assay:<7} {row.Panel:<16} " f"{row.below_lod:.3f} below LOD, MissingFreq {row.MissingFreq:.2f}" )
# MissingFreq is the share below LOD that the authors' export recorded.none_below = per_assay[per_assay["below_lod"] == 0]missingfreq_r = per_assay["below_lod"].corr(per_assay["MissingFreq"])offset = (per_assay["MissingFreq"] - per_assay["below_lod"]).median()print(f"correlation with MissingFreq: {missingfreq_r:.4f}")print(f"median of MissingFreq minus the share: {offset:.4f}")print( f"assays with no value below LOD: {len(none_below)}, " f"smallest MissingFreq {none_below['MissingFreq'].min():.2f}")
# The rule on this page: drop an assay with more than half below LOD.kept = per_assay[per_assay["below_lod"] <= 0.5]print(f"assays kept: {len(kept)}, dropped: {len(per_assay) - len(kept)}")values below LOD: 207906 of 1120318, a share of 0.1856Panel assays below LOD assays over 0.5CARDIOMETABOLIC 368 0.1324 46INFLAMMATION 365 0.1877 70NEUROLOGY 328 0.2385 81ONCOLOGY 368 0.1895 62OID20833 IVD NEUROLOGY 1.000 below LOD, MissingFreq 0.99OID20432 ARNT INFLAMMATION 0.999 below LOD, MissingFreq 0.94OID20888 KLB NEUROLOGY 0.997 below LOD, MissingFreq 0.98correlation with MissingFreq: 0.9989median of MissingFreq minus the share: 0.0300assays with no value below LOD: 661, smallest MissingFreq 0.03assays kept: 1170, dropped: 259A share of 0.1856 of the measured values sits below LOD, from 0.1324 on the
Cardiometabolic panel to 0.2385 on the Neurology panel. The share of each assay tracks
MissingFreq with a correlation of 0.9989. MissingFreq still runs higher, by a median
of 0.0300, and the 661 assays with no value below LOD in this file all show 0.03 or more.
The supplement does not say which wells the authors’ export counted, so this file cannot
explain the offset.
The LOD tutorial argues for keeping values below LOD, since they tend to converge across groups and are unlikely to add false positives. They keep their NPX here. The rule on this page removes assays instead. An assay with more than half of its values below LOD measures background in most samples, and testing it adds to the multiple testing correction with little chance of a finding. The rule drops 259 assays and keeps 1,170. If you expect a protein in one group only, apply the rule within each group and keep an assay that passes in any of them.
Sample IDs with a suffix
Section titled “Sample IDs with a suffix”Seven Public IDs end in .1 or .2, and the workbook does not say why. The code compares
the samples that share a subject and a day, next to the Day 0 and Day 3 samples of one
subject.
#' Compare the NPX values of two samples across all assays.#'#' @param npx Long NPX table with SampleID, OlinkID and NPX columns.#' @param first_id SampleID of the first sample.#' @param second_id SampleID of the second sample.#' @return A list with the Pearson correlation and the median absolute#' difference over the assays that both samples measured.ComparePair <- function(npx, first_id, second_id) { first <- npx |> filter(SampleID == first_id) |> select(OlinkID, NPX) second <- npx |> filter(SampleID == second_id) |> select(OlinkID, NPX) pair <- inner_join(first, second, by = "OlinkID") |> na.omit() list( r = cor(pair$NPX.x, pair$NPX.y), median_abs_diff = median(abs(pair$NPX.x - pair$NPX.y)) )}
samples <- npx |> distinct(SampleID, Day, subject) |> mutate(visit = sub("\\.[0-9]+$", "", SampleID)) |> add_count(visit, name = "samples_in_visit") |> arrange(visit, SampleID)suffixed <- samples |> filter(SampleID != visit)cat(sprintf( "IDs with a suffix: %s\n", paste(suffixed$SampleID, collapse = ", ")))alone <- suffixed |> filter(samples_in_visit == 1)cat(sprintf( "the only sample of its visit: %s\n", paste(alone$SampleID, collapse = ", ")))repeated <- samples |> filter(samples_in_visit > 1)for (visit_id in unique(repeated$visit)) { ids <- repeated$SampleID[repeated$visit == visit_id] pair <- ComparePair(npx, ids[1], ids[2]) cat(sprintf( "%-9s %-9s r = %.3f, median absolute difference %.2f NPX\n", ids[1], ids[2], pair$r, pair$median_abs_diff ))}
# Keep the first sample of each visit and give it the visit ID.first_samples <- samples |> distinct(visit, .keep_all = TRUE)npx_visit <- npx |> semi_join(first_samples, by = "SampleID") |> mutate(SampleID = sub("\\.[0-9]+$", "", SampleID))cat(sprintf("visits: %d\n", nrow(first_samples)))visit_counts <- table(first_samples$Day)cat(sprintf( "Day %s: %d visits\n", names(visit_counts), as.integer(visit_counts)), sep = "")
# For scale: the Day 0 and Day 3 samples of one subject.day3_subjects <- first_samples$subject[first_samples$Day == "3"]within_subject <- npx_visit |> filter(subject %in% day3_subjects, Day %in% c("0", "3")) |> select(subject, Day, OlinkID, NPX) |> pivot_wider(names_from = Day, values_from = NPX, names_prefix = "day_") |> group_by(subject) |> summarise(r = cor(day_0, day_3, use = "complete.obs"))cat(sprintf( "Day 0 against Day 3, %d subjects: median r = %.3f\n", nrow(within_subject), median(within_subject$r)))IDs with a suffix: 154_D7.1, 321_D7.1, 321_D7.2, 344_DE.1, 344_DE.2, 43_D7.1, 59_D3.1the only sample of its visit: 154_D7.1, 43_D7.1321_D7.1 321_D7.2 r = 0.950, median absolute difference 0.37 NPX344_DE.1 344_DE.2 r = 0.915, median absolute difference 0.70 NPX59_D3 59_D3.1 r = 0.991, median absolute difference 0.14 NPXvisits: 781Day 0: 383 visitsDay 3: 218 visitsDay 7: 138 visitsDay E: 42 visitsDay 0 against Day 3, 218 subjects: median r = 0.928def compare_pair(npx, first_id, second_id): """Compare the NPX values of two samples across all assays.
Args: npx: Long NPX table with SampleID, OlinkID and NPX columns. first_id: SampleID of the first sample. second_id: SampleID of the second sample.
Returns: A tuple of the Pearson correlation and the median absolute difference over the assays that both samples measured. """ first = npx.loc[npx["SampleID"] == first_id, ["OlinkID", "NPX"]] second = npx.loc[npx["SampleID"] == second_id, ["OlinkID", "NPX"]] pair = first.merge(second, on="OlinkID").dropna() correlation = pair["NPX_x"].corr(pair["NPX_y"]) median_abs_diff = (pair["NPX_x"] - pair["NPX_y"]).abs().median() return correlation, median_abs_diff
samples = npx[["SampleID", "Day", "subject"]].drop_duplicates()samples["visit"] = samples["SampleID"].str.replace( r"\.[0-9]+$", "", regex=True)samples["samples_in_visit"] = samples.groupby("visit")["SampleID"].transform( "size")samples = samples.sort_values(["visit", "SampleID"])suffixed = samples[samples["SampleID"] != samples["visit"]]print(f"IDs with a suffix: {', '.join(suffixed['SampleID'])}")alone = suffixed[suffixed["samples_in_visit"] == 1]print(f"the only sample of its visit: {', '.join(alone['SampleID'])}")repeated = samples[samples["samples_in_visit"] > 1]for visit_id, group in repeated.groupby("visit", sort=False): first_id, second_id = group["SampleID"].iloc[:2] correlation, median_abs_diff = compare_pair(npx, first_id, second_id) print( f"{first_id:<9} {second_id:<9} r = {correlation:.3f}, " f"median absolute difference {median_abs_diff:.2f} NPX" )
# Keep the first sample of each visit and give it the visit ID.first_samples = samples.drop_duplicates("visit")npx_visit = npx[npx["SampleID"].isin(first_samples["SampleID"])].copy()npx_visit["SampleID"] = npx_visit["SampleID"].str.replace( r"\.[0-9]+$", "", regex=True)print(f"visits: {len(first_samples)}")for day, count in first_samples["Day"].value_counts().sort_index().items(): print(f"Day {day}: {count} visits")
# For scale: the Day 0 and Day 3 samples of one subject.day3_subjects = first_samples.loc[first_samples["Day"] == "3", "subject"]wide_by_day = { day: npx_visit[ (npx_visit["Day"] == day) & npx_visit["subject"].isin(day3_subjects) ].pivot(index="OlinkID", columns="subject", values="NPX") for day in ["0", "3"]}within_subject = wide_by_day["0"].corrwith(wide_by_day["3"])print( f"Day 0 against Day 3, {len(within_subject)} subjects: " f"median r = {within_subject.median():.3f}")IDs with a suffix: 154_D7.1, 321_D7.1, 321_D7.2, 344_DE.1, 344_DE.2, 43_D7.1, 59_D3.1the only sample of its visit: 154_D7.1, 43_D7.1321_D7.1 321_D7.2 r = 0.950, median absolute difference 0.37 NPX344_DE.1 344_DE.2 r = 0.915, median absolute difference 0.70 NPX59_D3 59_D3.1 r = 0.991, median absolute difference 0.14 NPXvisits: 781Day 0: 383 visitsDay 3: 218 visitsDay 7: 138 visitsDay E: 42 visitsDay 0 against Day 3, 218 subjects: median r = 0.92843_D7.1 and 154_D7.1 are the only sample of their visit, so their suffix goes.
59_D3 and 59_D3.1 agree at r = 0.991, closer than the Day 0 and Day 3 samples of a
typical subject at a median r of 0.928, so they behave like one draw measured twice.
344_DE.1 and 344_DE.2 agree at r = 0.915, so they behave like two draws. The rule here
keeps the first sample of each visit in sort order and drops its suffix, which leaves 781
visits. No suffixed ID is a Day 0 sample. A longitudinal analysis of the event samples
should ask the study team which draw each one is.
Samples that stand apart
Section titled “Samples that stand apart”With no QC flag, the distribution of each sample is the remaining sample check.
olink_qc_plot() plots the IQR of a sample’s NPX values against its median for each
panel, and marks a sample 3 standard deviations or more from the panel mean on either
axis, as the
OlinkAnalyze reference manual
describes. The function cannot run on this table, so both tabs apply its rule to the 383
Day 0 samples with all 1,429 assays.
# The rule of olink_qc_plot(): within a panel, a sample is an outlier when# its median or its IQR lies 3 SD or more from the mean over all samples.sample_qc <- day0 |> group_by(Panel, SampleID, acuity_max) |> summarise( iqr = IQR(NPX, na.rm = TRUE), sample_median = median(NPX, na.rm = TRUE), .groups = "drop" ) |> group_by(Panel) |> mutate( median_low = mean(sample_median) - 3 * sd(sample_median), median_high = mean(sample_median) + 3 * sd(sample_median), iqr_low = mean(iqr) - 3 * sd(iqr), iqr_high = mean(iqr) + 3 * sd(iqr), outlier = !(sample_median > median_low & sample_median < median_high & iqr > iqr_low & iqr < iqr_high) ) |> ungroup()per_panel_qc <- sample_qc |> group_by(Panel) |> summarise(samples = n(), outliers = sum(outlier))cat(sprintf( "%-16s %d samples, %d outliers\n", per_panel_qc$Panel, per_panel_qc$samples, per_panel_qc$outliers), sep = "")
flagged <- sample_qc |> filter(outlier) |> count(SampleID, acuity_max, name = "panels") |> arrange(desc(panels), SampleID)cat(sprintf("samples flagged in any panel: %d\n", nrow(flagged)))cat(sprintf( "%-7s in %d of 4 panels, Acuity max %d\n", flagged$SampleID, flagged$panels, flagged$acuity_max), sep = "")cat(sprintf( "flagged with Acuity max 1 or 2: %d of %d\n", sum(flagged$acuity_max <= 2), nrow(flagged)))cat(sprintf( "all Day 0 samples with Acuity max 1 or 2: %d of %d\n", sum(day0_samples$acuity_max <= 2), nrow(day0_samples)))iqr_by_acuity <- sample_qc |> group_by(acuity_max) |> summarise(mean_iqr = mean(iqr))cat(sprintf( "mean IQR at Acuity max %d: %.2f NPX\n", iqr_by_acuity$acuity_max, iqr_by_acuity$mean_iqr), sep = "")CARDIOMETABOLIC 383 samples, 9 outliersINFLAMMATION 383 samples, 6 outliersNEUROLOGY 383 samples, 9 outliersONCOLOGY 383 samples, 4 outlierssamples flagged in any panel: 15334_D0 in 4 of 4 panels, Acuity max 2265_D0 in 3 of 4 panels, Acuity max 4116_D0 in 2 of 4 panels, Acuity max 5200_D0 in 2 of 4 panels, Acuity max 4201_D0 in 2 of 4 panels, Acuity max 1202_D0 in 2 of 4 panels, Acuity max 1210_D0 in 2 of 4 panels, Acuity max 3257_D0 in 2 of 4 panels, Acuity max 1270_D0 in 2 of 4 panels, Acuity max 2343_D0 in 2 of 4 panels, Acuity max 1206_D0 in 1 of 4 panels, Acuity max 221_D0 in 1 of 4 panels, Acuity max 3221_D0 in 1 of 4 panels, Acuity max 1238_D0 in 1 of 4 panels, Acuity max 2292_D0 in 1 of 4 panels, Acuity max 2flagged with Acuity max 1 or 2: 10 of 15all Day 0 samples with Acuity max 1 or 2: 132 of 383mean IQR at Acuity max 1: 3.05 NPXmean IQR at Acuity max 2: 3.00 NPXmean IQR at Acuity max 3: 2.89 NPXmean IQR at Acuity max 4: 2.85 NPXmean IQR at Acuity max 5: 2.80 NPXthresholds <- sample_qc |> distinct(Panel, median_low, median_high, iqr_low, iqr_high)qc_plot <- ggplot(sample_qc, aes(sample_median, iqr)) + geom_vline( data = thresholds, aes(xintercept = median_low), linetype = "dashed", colour = "grey55" ) + geom_vline( data = thresholds, aes(xintercept = median_high), linetype = "dashed", colour = "grey55" ) + geom_hline( data = thresholds, aes(yintercept = iqr_low), linetype = "dashed", colour = "grey55" ) + geom_hline( data = thresholds, aes(yintercept = iqr_high), linetype = "dashed", colour = "grey55" ) + geom_point(aes(colour = outlier), size = 1.6, alpha = 0.85) + scale_colour_manual( values = c(`FALSE` = "#a8a6a0", `TRUE` = "#eb6834"), labels = c(`FALSE` = "within 3 SD", `TRUE` = "outlier"), name = NULL ) + facet_wrap(vars(Panel), scales = "free") + labs( x = "Sample median, NPX", y = "Sample IQR, NPX", title = sprintf( "MGH Day 0 plasma, %d samples: IQR against median in each panel", nrow(day0_samples) ) ) + theme_minimal(base_size = 11) + theme(legend.position = "top", panel.grid.minor = element_blank())ggsave( "outputs/olink-npx-qc_iqr_median_r.png", qc_plot, width = 9, height = 6.5, dpi = 120, bg = "white")
# The gate compares these values with the Python tab.metrics <- list( wide_rows = nrow(npx_wide), wide_columns = ncol(npx_wide), assays = nrow(assay_table), long_rows = nrow(npx), missing_npx = sum(is.na(npx$NPX)), day0_samples = nrow(day0_samples), covid_negative = sum(!covid_pos), severe = sum(covid_pos & day0_samples$acuity_max <= 2), il6_p05 = spread[1], il6_p95 = spread[2], cxcl8_cardiometabolic_median = shared_assays$median_npx[ shared_assays$OlinkID == "OID20153" ], tnf_neurology_r = shared_assays$r_inflammation[ shared_assays$OlinkID == "OID20848" ], below_lod_share = mean(measured$NPX < measured$LOD), assays_over_half = sum(per_panel$over_half), missingfreq_correlation = cor(per_assay$below_lod, per_assay$MissingFreq), assays_none_below = nrow(none_below), assays_kept = nrow(kept), suffixed_ids = nrow(suffixed), visits = nrow(first_samples), within_subject_median_r = median(within_subject$r), outlier_points = sum(sample_qc$outlier), outlier_samples = nrow(flagged), outliers_severe = sum(flagged$acuity_max <= 2))jsonlite::write_json( metrics, "outputs/olink-npx-qc_metrics_r.json", auto_unbox = TRUE, digits = NA)
def interquartile_range(values): """Return the interquartile range of a Series, ignoring missing values.
Args: values: A pandas Series of NPX values.
Returns: The 75th percentile minus the 25th percentile. """ return values.quantile(0.75) - values.quantile(0.25)
# The rule of olink_qc_plot(): within a panel, a sample is an outlier when# its median or its IQR lies 3 SD or more from the mean over all samples.sample_qc = ( day0.groupby(["Panel", "SampleID", "acuity_max"]) .agg( iqr=("NPX", interquartile_range), sample_median=("NPX", "median"), ) .reset_index())by_panel = sample_qc.groupby("Panel")for column in ["sample_median", "iqr"]: center = by_panel[column].transform("mean") width = 3 * by_panel[column].transform("std") sample_qc[f"{column}_low"] = center - width sample_qc[f"{column}_high"] = center + widthinside = ( (sample_qc["sample_median"] > sample_qc["sample_median_low"]) & (sample_qc["sample_median"] < sample_qc["sample_median_high"]) & (sample_qc["iqr"] > sample_qc["iqr_low"]) & (sample_qc["iqr"] < sample_qc["iqr_high"]))sample_qc["outlier"] = ~insideper_panel_qc = sample_qc.groupby("Panel", as_index=False).agg( samples=("outlier", "size"), outliers=("outlier", "sum"))for row in per_panel_qc.itertuples(): print(f"{row.Panel:<16} {row.samples} samples, {row.outliers} outliers")
flagged = ( sample_qc[sample_qc["outlier"]] .groupby(["SampleID", "acuity_max"]) .size() .reset_index(name="panels") .sort_values(["panels", "SampleID"], ascending=[False, True]))print(f"samples flagged in any panel: {len(flagged)}")for row in flagged.itertuples(): print( f"{row.SampleID:<7} in {row.panels} of 4 panels, " f"Acuity max {row.acuity_max:.0f}" )flagged_severe = int((flagged["acuity_max"] <= 2).sum())print(f"flagged with Acuity max 1 or 2: {flagged_severe} of {len(flagged)}")day0_severe = int((day0_samples["acuity_max"] <= 2).sum())print( f"all Day 0 samples with Acuity max 1 or 2: " f"{day0_severe} of {len(day0_samples)}")iqr_by_acuity = sample_qc.groupby("acuity_max")["iqr"].mean()for acuity, mean_iqr in iqr_by_acuity.items(): print(f"mean IQR at Acuity max {acuity:.0f}: {mean_iqr:.2f} NPX")CARDIOMETABOLIC 383 samples, 9 outliersINFLAMMATION 383 samples, 6 outliersNEUROLOGY 383 samples, 9 outliersONCOLOGY 383 samples, 4 outlierssamples flagged in any panel: 15334_D0 in 4 of 4 panels, Acuity max 2265_D0 in 3 of 4 panels, Acuity max 4116_D0 in 2 of 4 panels, Acuity max 5200_D0 in 2 of 4 panels, Acuity max 4201_D0 in 2 of 4 panels, Acuity max 1202_D0 in 2 of 4 panels, Acuity max 1210_D0 in 2 of 4 panels, Acuity max 3257_D0 in 2 of 4 panels, Acuity max 1270_D0 in 2 of 4 panels, Acuity max 2343_D0 in 2 of 4 panels, Acuity max 1206_D0 in 1 of 4 panels, Acuity max 221_D0 in 1 of 4 panels, Acuity max 3221_D0 in 1 of 4 panels, Acuity max 1238_D0 in 1 of 4 panels, Acuity max 2292_D0 in 1 of 4 panels, Acuity max 2flagged with Acuity max 1 or 2: 10 of 15all Day 0 samples with Acuity max 1 or 2: 132 of 383mean IQR at Acuity max 1: 3.05 NPXmean IQR at Acuity max 2: 3.00 NPXmean IQR at Acuity max 3: 2.89 NPXmean IQR at Acuity max 4: 2.85 NPXmean IQR at Acuity max 5: 2.80 NPXcolors = {False: "#a8a6a0", True: "#eb6834"}labels = {False: "within 3 SD", True: "outlier"}figure, axes = plt.subplots(2, 2, figsize=(9, 6.5))for ax, (panel, group) in zip(axes.flat, sample_qc.groupby("Panel")): for is_outlier in [False, True]: points = group[group["outlier"] == is_outlier] ax.scatter( points["sample_median"], points["iqr"], s=14, alpha=0.85, color=colors[is_outlier], label=labels[is_outlier], ) first = group.iloc[0] for column in ["sample_median_low", "sample_median_high"]: ax.axvline(first[column], color="#8c8b86", linestyle="--", lw=1) for column in ["iqr_low", "iqr_high"]: ax.axhline(first[column], color="#8c8b86", linestyle="--", lw=1) ax.set_title(panel, fontsize=10) ax.set_xlabel("Sample median, NPX") ax.set_ylabel("Sample IQR, NPX") ax.spines[["top", "right"]].set_visible(False)axes.flat[0].legend(frameon=False, loc="upper left")figure.suptitle( f"MGH Day 0 plasma, {len(day0_samples)} samples: " "IQR against median in each panel", x=0.02, ha="left",)figure.tight_layout()figure.savefig(OUTPUTS / "olink-npx-qc_iqr_median_python.png", dpi=120)
# The gate compares these values with the R tab.metrics = { "wide_rows": rows, "wide_columns": columns, "assays": len(assay_table), "long_rows": len(npx), "missing_npx": int(npx["NPX"].isna().sum()), "day0_samples": len(day0_samples), "covid_negative": int((~covid_pos).sum()), "severe": int(severe.sum()), "il6_p05": float(low), "il6_p95": float(high), "cxcl8_cardiometabolic_median": float(shared_assays.loc[ shared_assays["OlinkID"] == "OID20153", "median_npx" ].iloc[0]), "tnf_neurology_r": float(shared_assays.loc[ shared_assays["OlinkID"] == "OID20848", "r_inflammation" ].iloc[0]), "below_lod_share": float(measured["below_lod"].mean()), "assays_over_half": int(per_panel["over_half"].sum()), "missingfreq_correlation": float(missingfreq_r), "assays_none_below": len(none_below), "assays_kept": len(kept), "suffixed_ids": len(suffixed), "visits": len(first_samples), "within_subject_median_r": float(within_subject.median()), "outlier_points": int(sample_qc["outlier"].sum()), "outlier_samples": len(flagged), "outliers_severe": flagged_severe,}(OUTPUTS / "olink-npx-qc_metrics_python.json").write_text( json.dumps(metrics, indent=2) + "\n")
The rule flags 15 samples, and 334_D0 in all four panels. In the figure every flag sits
on the high side, with a wide IQR, a high median, or both. Check who they are before you
drop them. 10 of the 15 come from subjects who died or were intubated, against 132 of all
383 Day 0 samples, and the mean IQR rises at each step from 2.80 NPX at Acuity max 5 to
3.05 NPX at Acuity max 1. Filbin et al. read intracellular proteins in plasma as the
contents of dying cells, and a patient with heavy tissue damage would carry more of them,
which lifts many low assays at once. In this cohort, part of what the outlier plot shows
is disease severity.
Olink’s outlier vignette calls the 3 SD lines guidelines rather than strict thresholds. With nothing that points to a technical cause, this page keeps all 15 samples and lists them above, so a later analysis can check whether a result depends on them.
Where this goes wrong
Section titled “Where this goes wrong”- Without
na = "NA", readxl reads the IFNG, GCG and MUC16 columns as text, and the pivot to the long layout fails on the mix of number and text columns. - Code that treats values below LOD as missing throws away the low end of every assay, a share of 0.1856 of the measured values here.
- In a disease cohort, the samples that the 3 SD rule flags can be the sickest patients. Check the clinical data of every flagged sample before you remove one.
Next steps
Section titled “Next steps”Bridging plates and projects shows how to put two
NPX projects on one scale, and
Differential abundance tests the Day 0 proteins
between groups. The code for this page is in guides/proteomics/olink-npx-qc/ of the
companion repository.
Scientific references
Section titled “Scientific references”The OlinkAnalyze package by Nevola and colleagues supplies the functions for the analysis of Olink proteomic data.
Further reading
Section titled “Further reading”The Olink limit of detection tutorial explains the negative-control calculation and the treatment of values below LOD. It supplies the assay context for the counts on this page.
The Olink outlier tutorial describes sample median and interquartile-range diagnostics. Use these diagnostics to investigate flagged samples alongside their clinical and technical records.