Skip to content

MSstats+: Anomaly scores depend on unrelated precursors and on numberOfCores (one RNG stream shared across isolation forests) #224

Open

Description

@caleb-lindgren

This bug was identified and this report generated by AI. I reviewed its findings,
and they are accurate. --caleb-lindgren

Summary. With calculateAnomalyScores = TRUE, a precursor's
AnomalyScores - and through the weights in dataProcess, its protein's
summarized quantity - change when a precursor whose name sorts before it is
added to or removed from the input, and when the converter's numberOfCores
changes. The same input converted twice with the same settings gives
identical scores, so a single analysis is reproducible; two analyses that
share a precursor but differ in anything else do not give it the same score.

Versions. MSstatsConvert 1.22.1 and MSstats 4.20.0 (Bioconductor
RELEASE_3_23), R 4.5 and 4.6, Linux. The same code is on devel as of
1.23.5.

Cause. src/isolation_forest.cpp declares one generator at file scope,

std::mt19937 gen(42); // Fixed random seed for reproducibility

seeded once when the shared library loads, and every call to
calculate_anomaly_score draws its splits from it without reseeding.
.runAnomalyModel scores precursors one after another in name order inside
each worker, so the random numbers a precursor's forest gets depend on how
many were drawn for the precursors scored before it in that worker - that
is, on every earlier-sorting precursor in the input, and on how
parLapply splits the precursors among numberOfCores workers, each of
which starts its own stream at 42. So the results for a given precursor are not
reproducible if anything changes the sort order of the precursors.

Reproduction. Self-contained; needs only MSstatsConvert and data.table.

library(MSstatsConvert); library(data.table)

# .runAnomalyModel starts a socket cluster and never stops it, so R later
# warns "closing unused connection" at unpredictable points. Supplying the
# missing stopCluster on exit keeps that - a separate, smaller issue - out
# of the output below.
invisible(suppressMessages(trace(".runAnomalyModel",
  where = asNamespace("MSstatsConvert"),
  exit = quote(parallel::stopCluster(cl)), print = FALSE)))

set.seed(1)
runs <- sprintf("run%02d", 1:12)

# One protein's precursors in every run: n peptides, three fragments each.
make <- function(protein, n, prefix) rbindlist(lapply(seq_len(n), function(k) {
  s <- paste0(prefix, strrep("A", k), "K"); base <- runif(1, 12, 20)
  rbindlist(lapply(runs, function(r) { f <- 2^(base + rnorm(3, 0, 0.3))
    data.table(Run = r, Protein.Group = protein, Protein.Names = protein,
      Protein.Ids = protein, Stripped.Sequence = s, Modified.Sequence = s,
      Precursor.Charge = 2L, Precursor.Mz = 500 + k, Precursor.Id = paste0(s, "2"),
      Fr0Quantity = f[1], Fr1Quantity = f[2], Fr2Quantity = f[3],
      Fragment.Info = NA_character_, Q.Value = 1e-4, Global.Q.Value = 1e-4,
      Global.PG.Q.Value = 1e-4, PG.Q.Value = 1e-4, Lib.Q.Value = 1e-4,
      Lib.PG.Q.Value = 1e-4, Quantity.Quality = runif(1, 0.5, 1),
      PG.MaxLFQ.Quality = runif(1, 0.5, 1), deltaRT = rnorm(1, 0, 0.1)) }))
}))

test   <- make("PTEST", 4, "TEST")    # the protein whose scores we watch
others <- rbindlist(lapply(1:6, function(i) make(paste0("POTHER", i), 3, paste0("OTHER", i))))
early  <- make("PAAA", 3, "AAA")      # peptides that sort before TEST...
late   <- make("PZZZ", 3, "ZZZ")      # ...and after it
annot  <- data.table(Run = runs, Condition = rep(c("A", "B"), each = 6),
  BioReplicate = seq_along(runs))

# PTEST's anomaly scores from one conversion, in a fixed row order.
scores <- function(input, cores = 1) {
  x <- as.data.table(DIANNtoMSstatsFormat(as.data.frame(input), annotation = annot,
    MBR = FALSE, quantificationColumn = "auto", calculateAnomalyScores = TRUE,
    anomalyModelFeatures = c("Quantity.Quality", "PG.MaxLFQ.Quality", "deltaRT"),
    anomalyModelFeatureTemporal = c("mean_decrease", "mean_decrease", "dispersion_increase"),
    runOrder = data.table(Run = runs, Order = seq_along(runs)),
    numberOfCores = cores, use_log_file = FALSE, verbose = FALSE))
  x <- x[ProteinName == "PTEST"]
  setorder(x, PeptideSequence, FragmentIon, Run)
  x$AnomalyScores
}

baseline <- scores(rbind(test, others))
cases <- list(
  "the same input, converted again"          = function() scores(rbind(test, others)),
  "plus a protein sorting BEFORE PTEST"      = function() scores(rbind(test, others, early)),
  "plus a protein sorting AFTER PTEST"       = function() scores(rbind(test, others, late)),
  "the same input, numberOfCores = 2"        = function() scores(rbind(test, others), 2)
)

cat("MSstatsConvert", as.character(packageVersion("MSstatsConvert")), "\n\n")
cat("PTEST's own rows are identical in every case below, so none of its",
  length(baseline), "anomaly\nscores should change from the baseline conversion.\n\n")
cat(sprintf("%-38s %18s  %s\n", "case", "PTEST scores moved", "expected 0"))
for (name in names(cases)) {
  moved <- sum(abs(cases[[name]]() - baseline) > 1e-12, na.rm = TRUE)
  cat(sprintf("%-38s %10d of %3d  %s\n", name, moved, length(baseline),
    if (moved == 0) "ok" else "CHANGED"))
}

With 1.22.1 as released it prints:

MSstatsConvert 1.22.1

PTEST's own rows are identical in every case below, so none of its 144 anomaly
scores should change from the baseline conversion.

case                                   PTEST scores moved  expected 0
the same input, converted again                 0 of 144  ok
plus a protein sorting BEFORE PTEST           138 of 144  CHANGED
plus a protein sorting AFTER PTEST              0 of 144  ok
the same input, numberOfCores = 2             138 of 144  CHANGED

Where the added protein's rows go in the input makes no difference; where
its peptides sort does, because the converter orders precursors by name
before modelling them.

A second, smaller issue: the anomaly model's cluster is never stopped.
.runAnomalyModel calls parallel::makeCluster(cores) and returns without
stopCluster, so every conversion with anomaly scores leaves a worker process
and its socket behind, and R later prints closing unused connection warnings
at unpredictable points when it garbage-collects them. The reproduction above
adds the missing call with trace(); without it, those warnings interleave
with its output. The fix is one line after the makeCluster:

cl = parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cl), add = TRUE)

Impact. Not a correctness problem in any single analysis: every forest
is still a valid isolation forest, and its Monte Carlo error is present
whatever the seed. The problem is that this error is redrawn, arbitrarily,
whenever anything upstream changes - the search database, an FDR or
contaminant filter, the sample set, or the core count used for tuning - so
it does not cancel when two analyses are compared, and results cannot be
reproduced across those changes. This came up for us when we were comparing
results on the same data with and without some peptides excluded; we planned to
use non-excluded peptides as a baseline between the two MSstats+ runs, since
they shouldn't change, but they actually did change due to this bug.

Suggested fix. Reseed per forest, so a precursor's scores depend on its
own data only:

@@ -170,6 +170,10 @@ DataFrame calculate_anomaly_score(
         int max_depth
 ) {
     
+    // Reseeded per call, so a PSM's forest depends on its own data only
+    // and not on how many PSMs were scored before it in this process.
+    gen.seed(42);
+
     std::vector<std::unordered_map<std::string, double>> data = convert_dataframe(df);

With this, every line of the reproduction prints 0 and ok, at any
numberOfCores. A seed argument passed from R - or one derived from the
precursor's identifier - would also let users vary the seed to see the
forest's own Monte Carlo error, which a fixed per-forest seed hides.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions