Package 'ALDEx3'

Title: Linear Models for Sequence Count Data
Description: Provides scalable linear and linear mixed effects models tailored for sequence count data analysis (e.g., analysis of 16S or RNA-seq data). Uses Dirichlet-multinomial sampling to quantify uncertainty in relative abundance or relative expression conditioned on observed count data. Implements scale models as a generalization of normalizations which account for uncertainty in scale (e.g., total abundances) as described in Nixon et al. (2025) <doi:10.1186/s13059-025-03609-3> and McGovern et al. (2026) <doi:10.1186/s40168-026-02377-x>.
Authors: Justin Silverman [aut, cre], Greg Gloor [aut], Kyle McGovern [aut, ctb]
Maintainer: Justin Silverman <[email protected]>
License: MIT + file LICENSE
Version: 1.7.0
Built: 2026-10-30 02:14:44 UTC
Source: https://github.com/jsilve24/aldex3

Help Index


ALDEx3 Linear Models

Description

Fit linear or linear mixed models to sequence count data while accounting for uncertainty in both composition and scale (total abundance).

For each of nsample Monte Carlo draws, aldex samples each sample's composition from a Dirichlet-multinomial posterior, samples its log2 scale from the scale model, and adds the two to obtain log2 abundances. It then fits the chosen model to every feature, adjusts the p-values across features within the draw, and averages estimates, standard errors and adjusted p-values over draws.

Usage

aldex(
  Y,
  X,
  data = NULL,
  method = "lm",
  nsample = 2000,
  scale = NULL,
  streamsize = 8000,
  n.cores = detectCores() - 1,
  return.pars = c("X", "estimate", "std.error", "df", "p.val", "p.val.adj", "logComp",
    "logScale"),
  p.adjust.method = "BH",
  test = NULL,
  onesided = FALSE,
  contrasts = NULL,
  ...
)

Arguments

Y

a D x N matrix of sequence counts, where D is the number of taxa or genes and N the number of samples.

X

a one-sided model formula (no response), used with data, or for method = "lm" a P x N numeric model matrix (P is the number of coefficients). For "blmm" and "lme4", the formula includes random effects in lme4 syntax, e.g. ~ treat + (1 | subject). For "nlme", give the fixed-effects formula here and the random effects through random in ....

data

a data frame with N rows, required when X is a formula.

method

(default "lm") the regression engine:

"lm"

fast ordinary linear regression.

"blmm"

ALDEx3's approximate linear mixed model, with lmerTest refits for draws that fail its checks (see Details).

"lme4"

a full lmerTest (lme4) mixed model fit to every draw.

"nlme"

an nlme mixed model; requires random and optionally accepts correlation (see lme).

nsample

number of Monte Carlo draws.

scale

A scale-model function, such as clr.sm, tss.sm, sample.sm, or coefficient.sm; alternatively, an N x nsample matrix of log2-scale draws. Additional arguments for a scale-model function are passed through .... See "Writing a custom scale model" in the Examples section for the required interface.

streamsize

(default 8000) size threshold for processing draws in chunks. Streaming occurs when D*N*nsample*8/100000 > streamsize, so the default corresponds to about 800 MB of response draws. Each chunk contains at most floor(streamsize*100000/(D*N*8)) draws. This is a heuristic, not a hard memory limit. Composition and scale draws are not returned when streaming. Set streamsize=Inf to disable streaming. BLMM fits a separate anchor per chunk, so changing this threshold can change its results slightly.

n.cores

(default detectCores()-1) Number of workers for mixed models. "lme4" and "nlme" distribute feature-draw fits across workers; "blmm" distributes features.

return.pars

what results should be returned, see return section below.

p.adjust.method

(default BH) The method for multiple hypothesis test correction. See p.adjust for all available methods.

test

inference selector. Defaults depend on method: "t.HC3" for "lm", "t.satterthwaite.adaptive" for "blmm", and "t" for "lme4" and "nlme". For lm, choose "t", "t.HC0", or "t.HC3"; for blmm, choose "t.satterthwaite.adaptive", "t.satterthwaite", or the deprecated "t.residual"; for lme4 and nlme, only "t" is supported. Names are case-sensitive.

onesided

(default FALSE) FALSE gives two-sided p-values; "lower" or "upper" gives one-sided p-values for the alternative that the estimate is negative or positive, respectively.

contrasts

optional numeric K x P matrix with one fixed-effect contrast per row. Its uniquely named columns must be the complete coefficient set and are reordered to the fitted design. Contrast rows have unique nonempty names, are finite and nonzero, and need not sum to zero or be independent. Contrasts require a full-rank fixed-effect design with positive residual degrees of freedom. They do not change composition or scale sampling or adjustment families. For BLMM, checks on an added contrast can cause further refinement or a refit, which can also change coefficient results slightly.

...

Additional scale-model arguments, such as gamma, s.mu, or c.mu. For method = "nlme", this may also include random or correlation.

Details

Scale models. Sequence counts determine the relative composition of each sample, but not its total abundance or scale. The scale argument tells ALDEx3 what is known about that missing quantity and how uncertain that knowledge is. Choose a scale model based on the information available:

  • Use sample.sm for external measurements such as flow cytometry, qPCR, or spike-ins for individual samples.

  • Use coefficient.sm when prior knowledge concerns a group difference, treatment effect, time trend, or another model term.

  • Use clr.sm when CLR normalization is a reasonable center but its implied scale differences are uncertain.

  • Use tss.sm when the starting assumption is no systematic scale difference between groups.

  • Write a custom scale-model function when the built-in models do not match the information available for the study. The "Writing a custom scale model" example below describes the required function interface and N x nsample output.

Linear models. For method = "lm", "t" uses the ordinary residual variance, "t.HC0" the White sandwich covariance, and "t.HC3" its leverage-corrected version.

BLMM. For each feature, BLMM fits one set of covariance parameters shared by all draws (the anchor). With the default "t.satterthwaite.adaptive", each draw then refines its own covariance fit from the anchor with at most eight steps, and its estimates, standard errors and Satterthwaite degrees of freedom are computed at that fit. A draw is accepted only if it passes numerical checks of convergence, curvature and stability of its inference; draws that fail are refit with lmerTest, and a warning reports how many. Fits with all covariance parameters at zero, or with whole zero columns of the covariance Cholesky factor, get local inference without a refit. The checks are numerical; they do not guarantee calibrated p-values. "t.satterthwaite" is the cheaper shared-anchor approximation used by default in ALDEx3 1.5.0-1.6.2. The deprecated "t.residual" uses residual degrees of freedom for accepted draws and warns once per call. If lmerTest cannot produce valid inference for a refit draw's contrast, that draw's p-values are NA with a warning; errors during fitting stop the analysis. BLMM chooses dense or sparse computation automatically. See vignette("ALDEx3-mixed-effects") for details.

Other mixed models. "lme4" uses lmerTest Satterthwaite inference for every draw; "nlme" uses its native denominator degrees of freedom.

Contrasts. Each contrast row tests H0:cTβ=0H_0: c^T\beta=0, using the full fitted coefficient covariance. These are linear hypotheses, not R's factor-coding contrasts. For nlme, a contrast may involve only coefficients with the same denominator degrees of freedom.

Multiple testing. Each coefficient and contrast is a separate adjustment family across features. Within each draw, p-values are adjusted with p.adjust.method and then averaged over draws; for two-sided tests this is done for each direction and the smaller result is reported. Use aldex.p.adjust on the fitted object to adjust several coefficients or contrasts as one family without refitting.

Value

An aldex list. X (P x N), streaming, method, the resolved test, p.adjust.method, and onesided are always recorded. Here P is the coefficient count, D the feature count, N the observation count, and S the Monte Carlo draw count. return.pars controls:

estimate, std.error, df

P x D x S arrays of fitted coefficients, within-fit standard errors, and degrees of freedom.

p.val, p.val.adj

P x D matrices of final raw and adjusted probabilities, respecting onesided and p.adjust.method.

logComp, logScale

D x N x S log2-composition draws and N x S log2-scale draws. These are not retained during streaming.

random.effects

Pr x D x S arrays of Pr random-effect variance and covariance terms, including residual variance, for mixed models.

When contrasts are requested, contrasts$matrix always records their reordered matrix. contrasts$estimate, contrasts$std.error, and contrasts$df have dimensions K x D x S; contrasts$p.val and contrasts$p.val.adj have dimensions K x D. K is the number of contrast rows. The same return.pars fields control coefficient and contrast results together. Names and singleton dimensions are retained. Use summary(fit, component = "contrasts") for stored contrast summaries; the default summary includes coefficients and contrasts.

Author(s)

Justin Silverman, Kyle McGovern

Examples

set.seed(15)
Y <- matrix(rpois(3 * 12, 50), 3, 12)
metadata <- data.frame(group = rep(c(0, 1), each = 6))
X <- model.matrix(~ group, metadata)
C <- matrix(c(0, 1), 1, dimnames = list("group difference", colnames(X)))
fit <- aldex(Y, ~ group, metadata, nsample = 8, scale = clr.sm,
             gamma = 0.2, contrasts = C)
summary(fit, component = "contrasts")


Y <- matrix(1:110, 10, 11)
condition <- c(rep(0, 5), rep(1, 6))
data <- data.frame(condition=condition)
## Use CLR as the center and allow coefficient-scale uncertainty of SD 0.5.
res <- aldex(Y, ~condition, data, nsample=2000, scale=clr.sm, gamma=0.5)

## Writing a custom scale model
## A custom model must return one log2-scale draw per sample and Monte
## Carlo replicate. Here, external_scale supplies a known value per sample.
known_scale <- function(X, logComp, external_scale) {
  nsample <- dim(logComp)[3]
  matrix(rep(external_scale, nsample), nrow=ncol(X), ncol=nsample)
}
res <- aldex(Y, ~condition, data, nsample=2000, scale=known_scale,
             external_scale=rep(0, ncol(Y)))

ALDEx3 Effect Diagnostics

Description

ALDEx2-inspired effect diagnostics for an ALDEx3 binary contrast

Usage

aldex.effect(object, contrast)

Arguments

object

An object returned by aldex.

contrast

The exact model coefficient or unambiguous binary data column to summarize.

Details

aldex.effect is a helper for effect-size diagnostics that Greg Gloor and ALDEx2 users commonly inspect when evaluating pairwise effects. It is not a replacement for summary.aldex, which reports model estimates, standard errors and adjusted p-values. This function summarizes a single binary ALDEx3 model contrast using Cohen's-d-based Monte Carlo diagnostics.

For a selected contrast row k, feature d, Monte Carlo draw s, and binary group indicators x = object$X[k, ], let B[d, s] be the fitted ALDEx3 coefficient stored in object$estimate[k, d, s]. Let logW[d, i, s] = object$logComp[d, i, s] + object$logScale[i, s] be the reconstructed log abundance for sample i. aldex.effect requires logComp and logScale, so it is unavailable when aldex streams large jobs and omits those arrays. For each feature and Monte Carlo draw, the pooled within-group variance is ((n0 - 1) * var(logW[d, x == 0, s]) + (n1 - 1) * var(logW[d, x == 1, s])) / (n0 + n1 - 2), where n0 and n1 are the group sizes.

The returned columns are calculated as follows:

  • estimate: the mean of B[d, s] over Monte Carlo draws.

  • pooled.SD: the mean of the pooled within-group standard deviation, ⁠sqrt(pooled variance)⁠, over Monte Carlo draws.

  • cohens.d: the mean of B[d, s] / pooled.SD[d, s] over Monte Carlo draws. This is Cohen's-d-based and is not the same as the historical robust ALDEx2 effect statistic based on between/within dispersion.

  • overlap: an ALDEx2-style directional uncertainty diagnostic. It counts the Monte Carlo Cohen's d draws below and above zero, smooths those two counts with a 0.5 pseudocount, converts them with the ALDEx/Aitchison mean, and returns the smaller smoothed sign probability. Values near 0 indicate that nearly all Monte Carlo effect draws have the same sign. Values near 0.5 indicate uncertainty about direction. overlap is not a p-value, a confidence interval probability, or a literal area of overlap between two density curves.

Value

A data.frame with columns parameter, entity, estimate, pooled.SD, cohens.d, and overlap.

Author(s)

Greg Gloor, Justin Silverman


Adjust p-values jointly across fitted coefficients and contrasts

Description

Recomputes multiple-testing adjustments from an existing ALDEx3 fit, without refitting or drawing new samples. Each group pools all features of its named coefficients or stored contrasts into one adjustment family.

Usage

aldex.p.adjust(object, groups = NULL, method = NULL, onesided = NULL)

Arguments

object

An object returned by aldex, retaining the per-draw estimate, std.error, and df arrays for coefficients and any requested contrasts. These arrays are returned by default, including during streaming. Composition and scale draws are not needed.

groups

A character vector of coefficient or contrast names for one family, or a list of character vectors for several disjoint families. Unlisted rows each retain a separate family across all features. NULL restores separate adjustment for every row. Use exact row names. Prefixes are not normally needed: a name that occurs only once among all coefficient and contrast rows can be used directly, for example groups = c("age_effect", "group_effect"). If both components have a row named "age", use "coefficient:age" or "contrast:age" to select the intended row. Either prefix may also be used when the name is unique. Qualified names take precedence over unqualified names. A row cannot occur twice. Intercepts are included only when explicitly named in a group.

method

A method accepted by p.adjust. By default, uses object$p.adjust.method, or "BH" if absent.

onesided

FALSE for two-sided inference, or "lower" or "upper" for a directional test. By default, uses object$onesided, or FALSE if absent. Fits made before version 1.6.1 did not record either setting: explicitly supply method and onesided if those fits used nondefault settings.

Details

Directional probabilities are reconstructed as pt(estimate / std.error, df) using both tails directly. For two-sided inference, each tail is doubled and capped at one. Adjustment pools the feature-by-row hypotheses in a group separately within each draw and direction, before averaging over draws and selecting the smaller directional aggregate. This preserves ALDEx3's aggregation procedure; applying p.adjust to the final p.val matrix would generally give different results.

Groups define the multiplicity families; separate groups do not provide a joint adjustment for their combined discovery list. Choose families from the scientific questions rather than from observed significance. The assumptions of the selected adjustment method still apply, and grouping does not establish a new FDR guarantee for Monte Carlo aggregated probabilities. Only contrasts already present in the fit can be included; this function does not construct new contrasts.

Value

A modified aldex object, with p.val and p.val.adj matrices for coefficients and stored contrasts. Raw probabilities change only if onesided changes. Estimates, standard errors, degrees of freedom, and draws are preserved. p.adjust.method, onesided, and p.adjust.groups record the settings; the latter is a list of fully qualified row names, including unlisted singleton families. Assign the result to keep it.

Choosing groups

Find the available coefficient names with rownames(fit$estimate) and stored contrast names with rownames(fit$contrasts$matrix). Use these exact names, including factor level suffixes where present.

groups = c("age", "group") puts all features for both named rows in one family. With D features, this is 2 * D hypotheses per draw and direction. A list creates separate families: for example, groups = list(c("age", "group"), c("early", "late")) creates two families of 2 * D hypotheses each. Rows not named in either family are still adjusted individually across their D features. These examples assume the names are unique across both components. A family may contain coefficients, contrasts, or both; prefixes only identify which row is meant and do not determine family membership.

See Also

aldex, summary.aldex

Examples

set.seed(16)
Y <- matrix(rpois(4 * 12, 50), 4, 12)
metadata <- data.frame(age = seq_len(12), group = rep(c(0, 1), each = 6))
C <- rbind(age_effect = c(0, 1, 0), group_effect = c(0, 0, 1))
colnames(C) <- colnames(model.matrix(~ age + group, metadata))
fit <- aldex(Y, ~ age + group, metadata, nsample = 8,
             scale = clr.sm, gamma = 0.2, contrasts = C)
rownames(fit$estimate)         # "(Intercept)", "age", "group"
rownames(fit$contrasts$matrix) # "age_effect", "group_effect"
# Unique contrast names need no prefix. Pool all four features from
# each of these two contrasts into one family of eight hypotheses.
joint <- aldex.p.adjust(fit, groups = c("age_effect", "group_effect"))
summary(joint, component = "contrasts")
# A family can also mix coefficients and stored contrasts.
mixed <- aldex.p.adjust(fit, groups = c("age", "group_effect"))
# Separate families for coefficients and contrasts.
separate <- aldex.p.adjust(fit, groups = list(
  c("age", "group"), c("age_effect", "group_effect")))
# If a contrast shares a coefficient name, identify which one you mean.
C.shared <- C
rownames(C.shared)[1] <- "age"
fit.shared <- aldex(Y, ~ age + group, metadata, nsample = 8,
                    scale = clr.sm, gamma = 0.2, contrasts = C.shared)
# "age" alone is now ambiguous. Select the contrast named "age":
joint.shared <- aldex.p.adjust(fit.shared,
  groups = c("contrast:age", "group_effect"))
# Select the coefficient instead, grouped with the other contrast:
mixed.shared <- aldex.p.adjust(fit.shared,
  groups = c("coefficient:age", "group_effect"))

Plot Method for ALDEx3 objects with pairwise comparisons

Description

Simple plots for an ALDEx3 object

Usage

aldex.plot(
  object,
  plot = c("volcano", "effect", "MA", "water"),
  contrast = NULL,
  threshold = 0.05,
  min.diff = 0.5,
  cohen = 0.5,
  sig.col = rgb(1, 0, 0, 0.5),
  water.show = 5,
  water.col = c("red", "blue"),
  water.names = TRUE,
  ...
)

Arguments

object

An object of class aldex

plot

type of plot (default='volcano')

contrast

the name of the comparison to plot, must be provided

threshold

FDR significance threshold (default=0.05)

min.diff

(default=0.5) used for MA (display), and waterfall (cutoff) plots

cohen

Cohen's d threshold for effect plot (slope)

sig.col

color for significant features

water.show

number features to show in waterfall plot

water.col

vector of colors for waterfall plot

water.names

logical, show names of features for waterfall plot

...

additional plot parameters (cex)

Details

Provides volcano, effect, MA and waterfall plots from an ALDEx3 object.

This method plots combinations of adjusted p-values from object$p.val.adj, posterior estimates, standard errors and log abundance values averaged across Monte Carlo samples. The result is returned as a single plot of the desired type. Effect plots use the ALDEx2-inspired diagnostics returned by aldex.effect. The contrast must identify exactly one binary model coefficient. Effect diagnostics and MA plots require logComp and logScale, which are not returned when aldex streams large jobs.

Value

the desired plot

Author(s)

Greg Gloor


CLR-based scale model

Description

Use this model when centered log-ratio (CLR) normalization is a reasonable starting point, but you do not want to assume that it recovers the sample scales exactly. For example, in a case-control study, CLR may provide a plausible center while gamma allows the true difference in total abundance between cases and controls to depart from that center.

Usage

clr.sm(X, logComp, gamma = 0.5)

Arguments

X

Model matrix passed automatically by aldex(). Rows are model coefficients and columns are samples.

logComp

Monte Carlo log-compositions passed automatically by aldex(), with dimensions features x samples x nsample.

gamma

Non-negative scalar. Standard deviation of the Gaussian random shift that relaxes the CLR assumption about scale. gamma = 0 yields the fixed CLR assumption. Larger values express less confidence in the CLR-implied differences between sample scales.

Details

Set gamma = 0 to use the CLR-implied scales without additional uncertainty. A value such as gamma = 0.5 allows each scale-model coefficient to vary with SD 0.5 on the log2 scale. Larger values express less confidence in the CLR assumption.

The uncertainty applies to model coefficients, not independently to every sample. Samples with the same covariate values therefore receive the same random shift in a Monte Carlo draw. This differs from sample.sm, which can draw a separate scale for each sample.

Value

A numeric matrix of dimension N x nsample giving Monte Carlo samples of the log-scale for each sample (rows) and each Monte Carlo draw (columns).

Author(s)

Justin Silverman

References

Nixon G, Gloor GB, Silverman JD (2025). "Incorporating scale uncertainty in microbiome and gene expression analysis as an extension of normalization". Genome Biology. doi:10.1186/s13059-025-03609-3

Examples

# Allow moderate uncertainty around CLR-implied scale differences.
Y <- matrix(seq_len(60), nrow = 10)
condition <- factor(c("control", "control", "control",
                      "case", "case", "case"))
fit <- aldex(Y, ~ condition, data.frame(condition), nsample = 20,
             scale = clr.sm, gamma = 0.5)

Scale model using prior information about groups or treatments

Description

Use this model when prior information describes a treatment, group, time, or other model coefficient rather than an individual sample. Samples with the same covariate values share the same scale shift in each Monte Carlo draw.

Usage

coefficient.sm(
  X,
  logComp,
  c.mu = NULL,
  c.cor = NULL,
  c.sd = NULL,
  c.cov = NULL
)

Arguments

X

Model matrix passed automatically by aldex(). Rows are model coefficients and columns are samples.

logComp

Monte Carlo log-compositions passed automatically by aldex(). This function uses the third dimension to determine the number of draws.

c.mu

Expected log2 scale change for each model coefficient, in the same order as the rows of X. Must have length P.

c.cor

Deprecated P x P covariance matrix for the fixed-effect coefficients. Use c.cov instead. Retained until ALDEx3 2.0.0.

c.sd

SD of the log2 scale change for each model coefficient. Must have length P; coefficients are treated as independent.

c.cov

A P x P covariance matrix for the model coefficients' log2 scale changes. Use this instead of c.sd when coefficient uncertainties are correlated.

Details

Suppose an effect plot from a control-versus-treatment experiment is centered near -8, even though prior knowledge suggests that most features should not change. One way to represent that knowledge is to shift the treatment samples upward by 8 log2 units relative to the controls. With control as the reference level, use c.mu = c(0, 8): the first value leaves the common intercept unchanged, and the second adds 8 to treatment. Setting c.sd = c(0, 0.5) expresses an SD of 0.5 around that treatment shift. If the plot were centered near +8, use -8 instead. Adding 8 to both groups would not recenter the plot because it would leave their difference unchanged.

More generally, c.mu gives the expected log2 scale change for each model coefficient and c.sd gives its SD. Use c.cov when the coefficient uncertainties are correlated. For each Monte Carlo draw, ALDEx3 samples a coefficient vector and applies it to the model matrix X; mathematically, b(m)∼N(c.mu,Sigma)b^{(m)} \sim N(c.mu, Sigma) and the sample scales are b(m)TXb^{(m)T} X.

Exactly one of c.sd or c.cov must be provided. The deprecated c.cor argument may be used in place of c.cov during the compatibility period.

Value

A numeric matrix of dimension N x nsample giving Monte Carlo draws of the log2 scale for each sample (rows) across nsample draws (columns).

Author(s)

Kyle McGovern

Examples

# Three control samples followed by three treatment samples.
condition <- factor(
  c("control", "control", "control", "treatment", "treatment", "treatment"),
  levels = c("control", "treatment")
)
X <- t(model.matrix(~ condition))
logComp <- array(0, c(2, 6, 10))
logScale <- coefficient.sm(
  # Shift treatment upward by 8, with SD 0.5 around that shift.
  X, logComp, c.mu = c(0, 8), c.sd = c(0, 0.5)
)

Gut Crohn's microbiome dataset (list)

Description

This dataset contains a matrix and a data frame: genus-level microbiome profiles and corresponding sample metadata from a Crohn's disease case–control cohort. The dataset is used in examples and vignettes throughout the package.

Usage

gut_crohns_data

Format

A named list of one matrix and a dataframe:

counts

A matrix with read counts with 195 rows and 95 columns)

metadata

A data frame with 95 rows and 7 columns containing subject-level covariates.

Details

The counts matrix has one row per sample and one column per genus. The metadata data frame has one row per sample with metadata, critically Health.status either CD or Control, and Average cell count per gram frozen feces.

Source

Vandeputte D, Falony G, Vieira-Silva S, Wang J, Sailer M, Theis S, Raes J (2017). "Quantitative microbiome profiling links gut community variation to microbial load". Nature, 551, 507–511. doi:10.1038/nature24460


Oral microbiome perturbation dataset (list)

Description

This dataset contains a matrix and a data frame: genus-level microbiome profiles and corresponding sample metadata from an oral microbiome perturbation study. 28 participants' oral microbiomes were measured before, 15 minutes after, and 2 hours after perturbation with either a water control, antiseptic mouthwash, alchohol-free mouthwash, or soda. The dataset is used in examples and vignettes throughout the package.

Usage

oral_mouthwash_data

Format

A named list of one matrix and a dataframe:

counts

A matrix with read counts with 116 rows and 81 columns)

metadata

A data frame with 81 rows and 38 columns containing sample-level covariates.

Details

The counts matrix has one row per sample and one column per genus. The metadata data frame has one row per sample with metadata, critically the participant ID, flow cytometry average (and replicate) cells, time_c (time points), and treat (the perturbations )

Source

Marotz C, Morton JT, Navarro P, Coker J, Belda-Ferre P, Knight R (2021). "Quantifying live microbial load in human saliva samples over time reveals stable composition and dynamic load". mSystems, 6(3), e01182-21. doi:10.1128/mSystems.01182-20


Per-sample scale model using external information

Description

Use this model when each sample has its own external scale measurement, such as a flow-cytometry cell count, qPCR concentration, or spike-in estimate. Put the log2 measurement for each sample in s.mu. Use s.sd to describe the measurement uncertainty for each sample.

Usage

sample.sm(
  X,
  logComp,
  s.mu = NULL,
  s.var = NULL,
  s.cor = NULL,
  s.sd = NULL,
  s.cov = NULL
)

Arguments

X

Model matrix passed automatically by aldex(). This function uses its number of columns to determine the number of samples.

logComp

Monte Carlo log-compositions passed automatically by aldex(). This function uses the third dimension to determine the number of draws.

s.mu

Expected log2 scale for each sample, in the same order as the columns of the count matrix. Must have length N.

s.var

Deprecated numeric vector of per-sample log2-scale variances. Use s.sd = sqrt(s.var) instead. Retained until ALDEx3 2.0.0 for backward compatibility.

s.cor

Deprecated N x N covariance matrix. Despite its name, this argument has always represented covariance rather than correlation. Use s.cov instead. Retained until ALDEx3 2.0.0.

s.sd

SD of the log2 scale for each sample. Must have length N. Use this when measurement errors are independent across samples.

s.cov

An N x N covariance matrix for the samples' log2 scales. Use this instead of s.sd when measurement errors are correlated.

Details

For example, if four samples have estimated total cell counts of 1e8, 2e8, 8e7, and 1.5e8, set s.mu = log2(c(1e8, 2e8, 8e7, 1.5e8)). If each measurement has an SD of 0.5 on the log2 scale, set s.sd = rep(0.5, 4).

Use s.sd when measurement errors are independent. Use s.cov instead when errors are correlated, for example because several samples share a calibration standard. The diagonal of s.cov contains variances, and its off-diagonal entries contain covariances. Thus independent SDs of 0.5 can also be written as s.cov = diag(0.5^2, 4).

Supply exactly one of s.sd or s.cov. With s.sd, each sample receives its own independent scale draw. Samples in the same group do not automatically share uncertainty as they do in coefficient-based models.

Value

A numeric matrix of dimension N x nsample giving Monte Carlo draws of the log2 scale for each sample (rows) across nsample draws (columns).

Author(s)

Kyle McGovern

Examples

# External total-cell estimates for four samples.
cell_count <- c(1e8, 2e8, 8e7, 1.5e8)
X <- matrix(1, 1, 4)
logComp <- array(0, c(2, 4, 10))
logScale <- sample.sm(
  X, logComp, s.mu = log2(cell_count), s.sd = rep(0.5, 4)
)

Summary Method for ALDEx3 Objects

Description

Summarize an ALDEx3 result object

Usage

## S3 method for class 'aldex'
summary(
  object,
  ignore.intercept = TRUE,
  component = c("all", "coefficients", "contrasts"),
  ...
)

Arguments

object

An object of class aldex

ignore.intercept

(default=TRUE), ignore intercept when creating summary table. Requested contrasts are never filtered by this argument.

component

"all" (the default) includes coefficients and any requested contrasts. Use "coefficients" or "contrasts" to select only that component.

...

Additional arguments (currently ignored).

Details

Provides a summary of coefficient and requested-contrast adjusted p-values, estimates, and standard errors from an ALDEx3 result object.

This method extracts adjusted p-values from object$p.val.adj, along with posterior estimates and standard errors averaged across Monte Carlo samples. The result is returned as a long-format data.frame suitable for downstream analysis or visualization. By default, requested contrasts are included alongside coefficients. This only combines stored summaries; it does not change adjustment families. By default each coefficient and contrast has a separate family. Use aldex.p.adjust first to group selected rows without refitting.

Value

A data.frame with columns parameter, entity, p.val.adj, estimate, and std.error. When component = "all" includes requested contrasts, an additional type column identifies "coefficient" or "contrast" rows. Without requested contrasts, the coefficient-only schema is preserved.

Author(s)

Justin Silverman


TSS-centered scale model

Description

Total-sum scaling (TSS) starts from the assumption that total scale does not change systematically between experimental groups. Use this model when that is a reasonable starting point but you want to express uncertainty about it. For example, if a treatment is expected to redistribute features without changing total biomass, TSS centers the treatment-versus-control scale difference at zero.

Usage

tss.sm(X, logComp, gamma = 0.5)

Arguments

X

Model matrix passed automatically by aldex(). Rows are model coefficients and columns are samples.

logComp

Monte Carlo log-compositions passed automatically by aldex(). This function uses the third dimension to determine the number of draws.

gamma

Non-negative scalar. Standard deviation of the Gaussian random shift applied to the scale-model coefficients (in log2 space). gamma = 0 implies no scale uncertainty (all draws are centered at zero effect); larger values allow greater departures from the TSS-centered assumption.

Details

Set gamma = 0 to enforce no scale difference. Setting gamma = 0.5 keeps the expected difference at zero but allows each scale-model coefficient to vary with SD 0.5 on the log2 scale. Larger values express less confidence that total scale is unchanged.

ALDEx3 applies this uncertainty to model coefficients: for each draw, b(m)∼N(0,γ2I)b^{(m)} \sim N(0, \gamma^2 I), and the sample scales are b(m)TXb^{(m)T} X. Samples with the same covariate values therefore share a random shift. This differs from sample.sm, which can draw independent uncertainty for every sample.

Value

A numeric matrix of dimension N x nsample giving Monte Carlo draws of the log2 scale for each sample (rows) across nsample draws (columns).

Author(s)

Justin Silverman

References

Nixon G, Gloor GB, Silverman JD (2025). "Incorporating scale uncertainty in microbiome and gene expression analysis as an extension of normalization". Genome Biology. doi:10.1186/s13059-025-03609-3

Examples

# Center the group-scale difference at zero, with moderate uncertainty.
Y <- matrix(seq_len(60), nrow = 10)
condition <- factor(c("control", "control", "control",
                      "treatment", "treatment", "treatment"))
fit <- aldex(Y, ~ condition, data.frame(condition), nsample = 20,
             scale = tss.sm, gamma = 0.5)