Skip to contents

This tutorial answers four questions on one small simulation: which coordinates to read factors in, what the posterior uncertainty means, how a sample-group contrast translates into feature units, and how to fit and filter nonnegative gene programs. The simulated sample is the independent unit; there is no real biology. Get started defines view, activity, effects and offset.

Coordinates

A fit has one reconstruction but many equivalent coordinate systems. "raw" keeps flashier’s own scaling. "ldf" (the default) gives unit-norm factors with the scale on one side. "rms" gives every activity column unit root-mean-square so activities are comparable across factors. Pick one and keep its activity and effects together.

library(flashier.utils)
set.seed(17)
A <- matrix(rnorm(80), 40, 2)
B <- matrix(rnorm(24), 12, 2)
X <- tcrossprod(A, B) + matrix(rnorm(480, sd = .2), 40, 12)
dimnames(X) <- list(paste0("s", 1:40), paste0("g", 1:12))
fit <- flashier::flash(X, greedy_Kmax = 2, nullcheck = FALSE,
  ebnm_fn = ebnm::ebnm_normal, backfit = TRUE, verbose = 0)
raw <- standardize_factors(fit, sample_side = "rows", scaling = "raw",
                           feature_scale = "simulated_intensity")
view <- standardize_factors(fit, sample_side = "rows", scaling = "rms",
                            feature_scale = "simulated_intensity")
stopifnot(max(abs(tcrossprod(raw$activity, raw$effects) -
                  tcrossprod(view$activity, view$effects))) < 1e-8)
library(ggplot2)
activity_long <- rbind(cbind(scaling = "raw", as.data.frame(as.table(raw$activity))),
                       cbind(scaling = "rms", as.data.frame(as.table(view$activity))))
names(activity_long)[2:4] <- c("sample", "factor", "activity")
ggplot(activity_long, aes(factor, activity)) + geom_boxplot(outlier.shape = NA) +
  geom_point(position = position_jitter(width = 0.15, height = 0, seed = 1), size = 1, alpha = 0.6) +
  facet_wrap(~scaling) + theme_minimal()
Boxplots of activity per factor under raw and RMS scaling. Raw spreads differ between F1 and F2; RMS makes them equal.

Activity of all 40 simulated samples per factor in raw and RMS coordinates (points) with a box summary. Same fit, same reconstruction, different units; RMS forces unit root-mean-square per factor.

RMS scaling changes factor units while preserving their product. LDF scaling also preserves the product, with its diagonal absorbed on exactly one side. Always use the matching activity/effect pair and retain view$offset when reconstructing an affine model: sweep(tcrossprod(A, B), 2, offset, "+"). Do not mix coefficients or posterior draws from different bases.

Conditional uncertainty

Posterior standard deviations come from the native fit, expressed in the coordinates of the view you pass.

effect_sd <- factor_uncertainty(fit, side = "effects", sample_side = "rows",
                                representation = view)
ggplot(effect_sd, aes(feature, estimate)) +
  geom_pointrange(aes(ymin = estimate - posterior.sd, ymax = estimate + posterior.sd)) +
  geom_hline(yintercept = 0, linetype = 2) + facet_wrap(~factor) + theme_minimal()
Point ranges of each feature effect plus or minus one posterior standard deviation, one panel per factor. Ranges are narrow relative to the effects.

Feature effects for the 12 simulated genes with ± 1 posterior SD, conditional on the estimated priors and fitted rank (mean-field, typically too narrow). Not a regression standard error.

head(factor_uncertainty(fit, side = "activity", sample_side = "rows",
                        representation = view))
##   sample factor    estimate
## 1     s1     F1  0.58487310
## 2     s2     F1  0.18818541
## 3     s3     F1  0.20769915
## 4     s4     F1  0.11505738
## 5     s5     F1 -1.31618942
## 6     s6     F1  0.07681596
##                                                           basis_id posterior.sd
## 1 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a   0.05527547
## 2 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a   0.05527547
## 3 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a   0.05527547
## 4 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a   0.05527547
## 5 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a   0.05527547
## 6 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a   0.05527547
##            lfsr             uncertainty_type    status reason
## 1  1.826856e-26 conditional_variational_ebmf supported   <NA>
## 2  3.314797e-04 conditional_variational_ebmf supported   <NA>
## 3  8.581749e-05 conditional_variational_ebmf supported   <NA>
## 4  1.869436e-02 conditional_variational_ebmf supported   <NA>
## 5 1.280308e-125 conditional_variational_ebmf supported   <NA>
## 6  8.231389e-02 conditional_variational_ebmf supported   <NA>

Keep the native fit for posterior moments and sampling; a representation alone contains coordinates, not a posterior sampler. Native uncertainty is conditional on estimated priors. It is neither a downstream regression standard error nor uncertainty about the biological identity of a factor.

Group contrast in feature units

First summarize and contrast factor activity by a metadata column.

metadata <- data.frame(sample = rownames(X), donor = rownames(X),
                       group = rep(c("A", "B"), each = 20))
plot_factor_activity(view, metadata = metadata, group = "group", style = "distribution")
Boxplots of activity by group A and B for each factor.

Activity by sample group. The descriptive contrast below summarizes these distributions.

head(summarize_factor_activity(view, metadata, by = "group", unit_col = "donor"))
##   group factor  n n_units        mean        sd      median        q25
## 1     A     F1 20      20 -0.50255494 0.6701953 -0.36179429 -1.1439219
## 2     A     F2 20      20  0.04804205 1.0477028  0.21795580 -0.5983661
## 3     B     F1 20      20  0.46411915 1.0786582  0.44052837 -0.3091902
## 4     B     F2 20      20  0.05111094 1.0012006  0.09609645 -0.6636017
##          q75                                                         basis_id
## 1 0.08637632 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 2 0.92513956 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 3 0.85924594 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 4 0.68389739 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
contrast <- compare_factor_groups(view, metadata, group = "group",
                                  contrast = c("A", "B"), unit_col = "donor")
names(contrast)
## [1] "factor_contrast"   "feature_contrast"  "counts"           
## [4] "analysis_metadata"

c("A", "B") means A minus B. Group summaries are descriptive and default to observation weighting; cells are not automatically balanced by donor. Threshold summaries use resolved activity coordinates. Display normalization must not silently redefine an inferential threshold.

Then test each factor against the design and push the fitted coefficient back through the effects to get a per-feature contrast.

association <- test_factor_association(view, metadata, formula = ~group, engine = "lm",
                            unit_col = "donor", independence = "independent")
reconstructed <- backproject_contrast(view, association$table,
  input = "coefficients", factor_basis = view$manifest, term = "groupB")
head(reconstructed$effects)
##   feature contrast    estimate
## 1      g1   groupB  1.58806979
## 2      g2   groupB -0.32408254
## 3      g3   groupB -0.61926407
## 4      g4   groupB -0.33113088
## 5      g5   groupB  2.07011928
## 6      g6   groupB -0.01872848
##                                                           basis_id
## 1 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 2 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 3 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 4 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 5 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
## 6 7b8e93cda7a16b50ebde9e0ba6833652995d2ce884521554bf22625b509cd25a
ggplot(reconstructed$effects, aes(feature, estimate)) + geom_col() +
  geom_hline(yintercept = 0) + theme_minimal() + labs(y = "B − A")
Bar chart of the backprojected B minus A contrast per feature.

Backprojected group contrast per simulated gene in simulated intensity units (B minus A; 20 independent samples per group). Point estimates only; no uncertainty is attached.

Here groupB means B minus A, opposite to the descriptive contrast above. Backprojection multiplies feature effects by factor coefficients; offsets cancel in a same-model contrast. Point coefficients alone supply no uncertainty. Use a full coefficient covariance or compatible draws when justified; factor posterior SDs cannot substitute for either. Repeated observations require an appropriate repeated-unit model, not an independent-cell test.

For observed feature contrasts, validate_backprojection() requires matching contrast direction, covariates, weighting and feature units. It reports descriptive agreement, not independent biological validation. Named scientific arguments are preferred; see function references for complete controls.

Choose ebnm_fn, S and var_type

Choose ebnm_fn from the support your measurements require. Nonnegative activities can pair with signed effects in Gaussian EBMF. A Poisson topic model instead models nonnegative counts with mixed memberships. S specifies supplied noise; var_type decides which residual variances the Gaussian model estimates. S = .5, var_type = NULL fixes supplied noise. S = .5, var_type = 0 also estimates residual variance. max_factors is the EBMF greedy upper bound; GBCD uses its distinct kmax argument. Initialization and backfit affect the numerical optimum, so compare seeds without treating agreement as calibration.

Jiadong Mao’s EBNMF workshop explains EBNM shrinkage, prior families, EBMF, topic models and GBCD. Use those explanations alongside the original package manuals. No workshop code or prose is copied here; its repository has no identified license.

Filter cells by total GP membership

ImmGenT-GP section 5 removes cells with excessive total maximum-scaled membership. Each pass recomputes GP maxima after removal. The pipeline uses 12 passes and cutoff 10. Ziang Zhang / AgueroZZ provided the workflow; per-script authorship is unresolved. This package independently implements that rule without copying upstream code.

nonnegative_fit <- fit_ebmf(X, "rows", max_factors = 2,
  ebnm_fn = list(ebnm::ebnm_point_exponential, ebnm::ebnm_normal),
  nullcheck = FALSE, backfit = TRUE, seed = 18, verbose = 0)
filtered <- filter_cells_by_total_membership(nonnegative_fit, max_val = 10, numiter = 12)
filtered$removed_samples
## character(0)
ggplot(filtered$history, aes(iteration, remaining)) + geom_step() + geom_point() +
  scale_x_continuous(breaks = filtered$history$iteration) +
  expand_limits(y = 0) + theme_minimal() + labs(y = "samples remaining")
Step chart of samples remaining after each of the twelve filtering passes.

Samples remaining after each discrete pass (steps, not a continuous trend). The count stops changing once no sample exceeds the cutoff.

Activities must be nonnegative. Signed feature effects remain valid. The result contains matched sample activities and feature effects with unchanged retained reconstruction. The original fit stays unchanged. Selected-cell PVE and posterior uncertainty require separate analysis. This threshold selects broad GP membership; it does not establish poor cell quality.

Fit GBCD programs

GBCD fits cell covariance before estimating gene signatures with fixed memberships. Yusha Liu, Peter Carbonetto, Jason Willwerscheid and Matthew Stephens wrote gbcd. This adapter calls their engine. Install the audited optional version outside package builds:

remotes::install_github("stephenslab/gbcd@670e3afb50236303ddf99db33a3394abd4a711bd")

Supply normalized natural-log expression. Declare its preprocessing explicitly. The wrapper performs no normalization. kmax controls upstream initialization; it does not cap final rank. The memory preflight predicts upstream allocation branches, but cannot guarantee a peak-memory bound.

programs <- fit_gbcd_programs(X, "rows", kmax = 5,
  feature_scale = "natural_log",
  preprocessing = list(scope = "within_dataset",
    description = "log1p library-size normalized counts", log_base = "e"))
view <- programs$representation
factor_features(view, "GEP1", select = "distinctive")
plot_factor_features(view, "GEP1")
programs$signatures
programs$diagnostics
factor_provenance(result = programs)

Factors are named GEP1, GEP2, … (gene expression programs). effect and log2_fc describe EB-SNMF point estimates. z_score and lfsr (local false sign rate) come from separate gene-wise linear regression followed by ashr. These statistics condition on estimated memberships. They do not measure uncertainty in learning those memberships. Unavailable statistics remain NA. Native FLASH PVE and posterior sampling remain unavailable for this representation.

The upstream Baseline label remains a varying factor. It is never converted to a constant offset. Output sorting loses prior lineage, so every returned activity support stays unknown. Default projection priors cannot be inferred.

Grade-of-membership differential expression

Workshop section 5.5 uses fastTopics::de_analysis() for grade-of-membership (GoM) DE. That method requires count data and nonnegative memberships whose rows sum to one. test_gom_de() calls it after checking both inputs, with a required seed. It estimates topic expression with fixed memberships and reports least-extreme log2 fold changes with conditional uncertainty. See the original fastTopics manual and package authors Peter Carbonetto, Kevin Luo, Kushal Dey and Matthew Stephens. Abhishek Sarkar and other contributors also receive credit in the package. factor_features(select = "distinctive") instead ranks descriptive coefficient margins in the supplied factor basis. Those margins have no GoM DE lfsr. GBCD’s separate LM/ash statistics also differ from count-based GoM DE.

Credits

Native FLASH and EBNM authors are credited in Get started. Group contrasts and reconstruction adapt David Zemmour / Zemmour Lab workflows. Regression uses R Core’s stats::lm; the coordinate and reconstruction checks and the ggplot2 figures are independently implemented. See factor_provenance() and full credits.