Robustness checks for an EBMF fit
Source:vignettes/articles/robustness-checks.Rmd
robustness-checks.RmdRun these checks before you give a factor a biological name. Each one is a short chunk on one simulated fit, with what a bad result looks like. The checks do not replace replication across donors or datasets. Get started defines view, activity and effects.
library(flashier.utils)
set.seed(17)
activity_truth <- cbind(c(rep(3, 12), rep(0.3, 12)), c(rep(0.3, 12), rep(3, 12))) +
matrix(runif(48, 0, 0.4), 24, 2)
effect_truth <- cbind(c(2, 1.7, 1.4, 1.1, -0.6, -1.2, rep(0.1, 6)),
c(rep(-0.15, 6), 2, 1.7, 1.4, 1.1, -0.8, -1.2))
X <- tcrossprod(activity_truth, effect_truth) + matrix(rnorm(288, sd = 0.1), 24, 12)
dimnames(X) <- list(sprintf("s%02d", 1:24), sprintf("g%02d", 1:12))
metadata <- data.frame(sample = rownames(X), donor = rep(sprintf("d%02d", 1:12), each = 2),
group = rep(c("A", "B"), each = 12))
fit <- fit_ebmf(X, "rows", max_factors = 4, S = 0.1, var_type = 0L,
ebnm_fn = list(ebnm::ebnm_point_exponential, ebnm::ebnm_normal),
backfit = TRUE, nullcheck = TRUE, seed = 1, verbose = 0,
feature_scale = "simulated_intensity", independent_unit = "donor")
view <- standardize_factors(fit, prior_support = c(activity = "nonnegative", effects = "signed"))
library(ggplot2)
plot_congruence <- function(m, threshold = 0.9) {
d <- as.data.frame(as.table(m)); names(d) <- c("reference", "target", "congruence")
ggplot(d, aes(target, reference, fill = abs(congruence) >= threshold)) + geom_tile() +
geom_text(aes(label = round(congruence, 2))) +
scale_fill_manual(values = c(`TRUE` = "#0072B2", `FALSE` = "grey85"), name = "accepted") +
theme_minimal() + coord_fixed()
}plot_congruence() is a six-line helper used by checks 2,
6 and 7: a tile is coloured when its absolute congruence clears the
threshold.
1. Did the optimizer finish, and does the rank ceiling bind?
c(rank = fit$n_factors, max_factors = 4, elbo = fit$elbo,
maxiter_reached = isTRUE(flashier::flash_fit(fit)[["maxiter.reached"]]))
#> rank max_factors elbo maxiter_reached
#> 2.00000 4.00000 -49.11596 0.00000
plot_factor_pve(fit)
PVE per factor. Two factors, below the ceiling of four.
Bad signs: maxiter_reached is TRUE, a
native warning about convergence, or rank equal to
max_factors. A fit at the ceiling has not chosen its rank;
raise max_factors and refit. Tiny PVE factors are
candidates for noise, not automatically wrong. Keep the native warnings;
do not rerun until they disappear.
2. Does another seed find the same programs?
fit2 <- fit_ebmf(X, "rows", max_factors = 4, S = 0.1, var_type = 0L,
ebnm_fn = list(ebnm::ebnm_point_exponential, ebnm::ebnm_normal),
backfit = TRUE, nullcheck = TRUE, seed = 2, verbose = 0,
feature_scale = "simulated_intensity")
agreement <- factor_replicability(fit, fit2, min_congruence = 0.9)
plot_congruence(agreement$congruence_matrix)
Congruence between seeds. Coloured tiles clear 0.9.
agreement$matches[, c("reference_factor", "target_factor", "congruence", "status")]
#> reference_factor target_factor congruence status
#> 1 F1 F1 1 accepted
#> 2 F2 F2 1 acceptedfactor_replicability() matches factors by Tucker
congruence of their effect vectors with one-to-one assignment. Bad
signs: an unmatched_reference row, or congruence below your
threshold for a factor you plan to interpret. Seed agreement is
initialization sensitivity on fixed data. It does not show the program
survives a change of cells.
3. Is a factor carried by a handful of samples?
A <- factor_activity(view)
effective_n <- colSums(A)^2 / colSums(A^2)
top5_share <- apply(A, 2, function(a) sum(sort(a, decreasing = TRUE)[1:5]) / sum(a))
round(rbind(effective_n, top5_share), 2)
#> F1 F2
#> effective_n 13.72 12.09
#> top5_share 0.40 0.43
labels <- data.frame(factor = names(effective_n), estimate = max(A) * 1.1,
label = sprintf("n_eff = %.1f", effective_n))
ggplot(factor_activity(view, format = "long"), aes(factor, estimate)) +
geom_point(position = position_jitter(width = 0.15, height = 0, seed = 1)) +
geom_text(data = labels, aes(label = label)) + theme_minimal()
Activity of each of the 24 simulated samples per factor (jittered horizontally only). A factor carried by a handful of samples shows a few high dots over a floor near zero; here each factor has about 12 effective samples.
Effective sample count is (sum a)^2 / sum a^2 for
nonnegative activity. Bad signs: an effective count near 1 to 3, or most
activity mass in five samples. Such a factor can match well across seeds
and still vanish when those samples are left out. In the EBMF versus
cNMF case study, high concentration co-occurred with poor subsample
matches for the rare HLA/CD74 factors.
4. How wide is the conditional uncertainty?
intervals <- factor_intervals(fit, side = "effects", representation = view,
factors = "F1", nsamp = 2000, seed = 3)
ggplot(intervals, aes(feature, mean)) +
geom_pointrange(aes(ymin = lower, ymax = upper)) +
geom_hline(yintercept = 0, linetype = 2) + theme_minimal()
Equal-tail 95% intervals from 2000 posterior draws for every F1 feature effect, conditional on the estimated priors and rank. An interval that crosses the dashed zero line is a feature you cannot call.
intervals[intervals$feature %in% c("g01", "g05", "g07"),
c("feature", "mean", "lower", "upper", "prob_zero")]
#> feature mean lower upper prob_zero
#> 1 g01 2.359801 2.144224 2.566512 0
#> 5 g05 -2.844926 -3.068896 -2.613697 0
#> 7 g07 22.642728 22.428887 22.856498 0Posterior standard deviations and intervals are conditional on the
estimated priors and on the fitted rank. Mean-field intervals are
typically too narrow: in one rank-1 simulation, intervals for non-null
effects covered 0.67 to 0.91 of the true values at a nominal 0.95, while
effects that were truly zero were excluded at the nominal rate. Bad
signs: an interval that crosses zero for an effect you want to call, or
prob_zero near one. Good signs here do not substitute for
regression standard errors or biological replication.
5. Do the programs survive leaving donors out?
stability <- factor_stability(X, fit, metadata, unit_col = "donor", seed = 4, B = 8,
scheme = "subsample", fraction = 0.75, min_congruence = 0.9)
stability$summary[, c("factor", "n_successful", "n_matched", "recovery_rate",
"recovery_rate_all_requested", "median_congruence", "q025_congruence")]
#> factor n_successful n_matched recovery_rate recovery_rate_all_requested
#> 1 F1 8 8 1.00 1.00
#> 2 F2 8 6 0.75 0.75
#> median_congruence q025_congruence
#> 1 0.9977882 0.9123930
#> 2 0.9997669 0.9982926
stability_long <- rbind(
data.frame(factor = stability$summary$factor, panel = "recovery rate (8 refits)",
value = stability$summary$recovery_rate, lower = NA, upper = NA),
data.frame(factor = stability$summary$factor, panel = "congruence: median, 2.5% to 97.5%",
value = stability$summary$median_congruence,
lower = stability$summary$q025_congruence, upper = stability$summary$q975_congruence))
stability_long$panel <- factor(stability_long$panel, unique(stability_long$panel))
ggplot(stability_long, aes(factor, value)) +
geom_pointrange(aes(ymin = lower, ymax = upper), na.rm = TRUE) +
geom_hline(data = data.frame(panel = "congruence: median, 2.5% to 97.5%", y = 0.9),
aes(yintercept = y), linetype = 2) +
facet_wrap(~panel) + scale_y_continuous(limits = c(0, 1)) + theme_minimal() +
labs(y = NULL)
Recovery across eight donor-subsample refits (nine of twelve donors each). Left: fraction of refits in which the factor was recovered. Right: congruence of the recovered factor, median and empirical 2.5 to 97.5% range over refits. Refits share data and are not independent replicates.
factor_stability() refits on resampled biological units
and reports how often each reference factor is recovered. Use
scheme = "subsample" so no duplicated rows bias the
empirical Bayes priors. Bad signs: a recovery rate well below one, or
failed replicates. Report recovery_rate_all_requested,
which counts refits that lost the factor entirely;
recovery_rate leaves those out. With
min_congruence set, the congruence quantiles describe match
quality among the recovered refits only and cannot fall below the
threshold, so the recovery rate, not a low quantile, shows instability
(n_matched counts the refits behind the quantiles). Eight
replicates illustrate the call; use tens to hundreds for a real
estimate.
6. Does a different prior tell the same story?
fit_other <- tryCatch(fit_ebmf(X, "rows", max_factors = 4, S = 0.1, var_type = 0L,
ebnm_fn = list(ebnm::ebnm_point_exponential, ebnm::ebnm_point_normal),
backfit = TRUE, nullcheck = TRUE, seed = 1, verbose = 0,
feature_scale = "simulated_intensity"), error = conditionMessage)
if (is.character(fit_other)) fit_other else
plot_congruence(factor_replicability(fit, fit_other, min_congruence = 0.9)$congruence_matrix)
Congruence across effect priors, or the optimizer’s error message if that prior fails.
A program that only appears under one prior family is a modelling choice, not a finding. A prior whose optimizer fails on your data is also a result: record the message rather than retuning until it passes. Compare priors shows the full workflow with known truth and held-out prediction.
7. Does the noise model change the factors?
fit_genewise <- fit_ebmf(X, "rows", max_factors = 4, S = 0.1, var_type = 2L,
ebnm_fn = list(ebnm::ebnm_point_exponential, ebnm::ebnm_normal),
backfit = TRUE, nullcheck = TRUE, seed = 1, verbose = 0,
feature_scale = "simulated_intensity")
c(pooled = fit$n_factors, genewise = fit_genewise$n_factors)
#> pooled genewise
#> 2 2
plot_congruence(factor_replicability(fit, fit_genewise, min_congruence = 0.9)$congruence_matrix)
Congruence across noise models. Off-diagonal accepted tiles mean the order swapped, not that a factor was lost.
var_type = 0 pools one residual variance; 2
estimates one per feature and lets high-variance features absorb their
own noise. With a supplied S, the estimated variance is
added to S^2. Factor order can swap, as here; the matching
handles that. Bad signs: a rank change, or a factor with no accepted
counterpart. Report which setting you used.
8. Does metadata explain it, and on the right unit?
activity_long <- factor_activity(view, format = "long")
activity_meta <- merge(activity_long, metadata, by = "sample")
stopifnot("one metadata row per sample" = nrow(activity_meta) == nrow(activity_long))
donor_means <- aggregate(estimate ~ donor + group + factor, activity_meta, mean)
ggplot(activity_meta, aes(group, estimate)) +
geom_point(position = position_jitter(width = 0.1, height = 0, seed = 1), colour = "grey60", size = 1) +
geom_point(data = donor_means, shape = 18, size = 3) +
facet_wrap(~factor) + theme_minimal() + labs(y = "activity")
Activity by group. Small dots are samples (24); diamonds are donor means (12 donors, two samples each). The donor is the independent unit, so the diamonds are what a test may compare.
summarize_factor_activity(view, metadata, by = "group", unit_col = "donor")[,
c("group", "factor", "n", "n_units", "mean", "sd")]
#> group factor n n_units mean sd
#> 1 A F1 12 6 0.021170714 0.011478780
#> 2 A F2 12 6 0.288444592 0.011349293
#> 3 B F1 12 6 0.287556481 0.009082768
#> 4 B F2 12 6 0.001361598 0.003783817
tryCatch(test_factor_association(view, metadata, formula = ~group, engine = "lm",
unit_col = "donor", independence = "independent"),
error = conditionMessage)
#> [1] "Independent engine cannot test repeated records; aggregate explicitly or use dream with a donor random effect"Group summaries are descriptive. Two samples share each donor here,
so an independent-unit test on 24 samples is refused rather than run.
Bad signs: n much larger than n_units, or a
p-value from an independent engine on repeated samples. Use the
dream engine with the donor as a random effect, or
aggregate to one row per unit first.
test_factor_association(view, metadata, formula = ~ group + (1 | donor), engine = "dream",
unit_col = "donor", independence = "repeated")$table[,
c("factor", "term", "estimate", "p.value")]
#> factor term estimate p.value
#> 1 F1 groupB 0.2663858 3.778135e-14
#> 2 F2 groupB -0.2870830 5.540667e-29Held-out prediction on donors is in Compare priors.
Checklist
- Converged, rank below the ceiling, warnings recorded.
- Same programs across seeds.
- Effective sample count well above a handful.
- Intervals exclude zero for effects you name, with the underdispersion caveat.
- Recovery rate across unit resamples close to one.
- The same programs under a different prior.
- The same programs under a different noise model.
- Metadata association on the independent unit, not on repeated samples.
Credits
Native FLASH/flashier: Jason Willwerscheid, Peter Carbonetto, Wei Wang and Matthew Stephens. EBNM: Jason Willwerscheid, Matthew Stephens and Peter Carbonetto. Factor matching delegates to William Revelle’s psych and Kurt Hornik and Walter Böhm’s clue. The concentration check follows the EBMF versus cNMF adversarial review in this repository; the checks and figures (ggplot2, Hadley Wickham and contributors) are independently written. The PVE display follows the MOFA2 plotting workflow of Ricard Argelaguet, Damien Arnol, Danila Bredikhin and Britta Velten conceptually, with no source reused. See the full credits.