Skip to content
MATRIX-Research-LabPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

amma

amma is the Python implementation of AMMA, a method for mediation analysis of microbiome abundance and prevalence. For an exposure, the taxa of a microbiome count table as high-dimensional mediators, and a continuous, binary, ordinal or count outcome, AMMA tests whether the abundance part or the presence part of each taxon mediates the association between the exposure and the outcome, and reports (taxon, part) pairs that meet the Step-3 reporting rule. Natural direct and indirect effects are estimated as a secondary analysis.

The package implements the method of the R package AMMA and is tested for numerical agreement with it (see Agreement with the R package). It does not call R.

Installation

pip install amma            # requires numpy and scipy
pip install "amma[plot]"    # with matplotlib, for the convergence curves

Python 3.10 or later is required.

The method

For taxon j in sample i, the observed count is the product of a presence indicator R_ij and a latent abundance M_ij,

logit P(R_ij = 1) = D_i' delta_j,      log M_ij | R_ij = 1 ~ N(D_i' alpha_j + s_i, sigma_j^2),

where D_i holds an intercept, the exposure and the covariates, and s_i is a sample-specific offset shared by every taxon of sample i. The latent abundance is observed only above the detection threshold, so a zero count is either an absent taxon or a present taxon below detection.

  1. Step 1 (exposure side). The model is fitted taxon by taxon by penalized maximum likelihood. The offsets are estimated by alternating the taxon fits with a least-squares decomposition of the residuals of the detected counts into sample and taxon effects (two rounds), followed by a final fit at the estimated offsets. The exposure-side statistic of a pair is the signed normal score of the P value of a likelihood-ratio test of the exposure coefficient. In the abundance part, the statistic L of a taxon detected in m samples, with q columns in D, is referred to the F distribution, P = Pr{F(1, m - q) >= (m - q)(exp(L / m) - 1)}; in the presence part, the test is the likelihood-ratio test of a logistic regression of the detection indicator. Within each part the statistics are divided by an empirical null scale, and the tested family consists of the k pairs with the largest absolute statistics, where k is the number of pairs whose Benjamini-Hochberg adjusted marginal exposure-side P value is at most 0.5, bounded to the interval from 8 to 64. The exposure-side P value of a tested pair is conditional on its selection into the family. Step 1 does not use the outcome.
  2. Step 2 (outcome side). The two parts of every tested taxon are reconstructed from their conditional distribution given the observed counts: the abundance column is the log count where the taxon is detected and the conditional mean of the latent log abundance where it is not, and the presence column is one where the taxon is detected and the conditional probability of presence where it is not. A penalized outcome model is fitted to the reconstructed columns, the exposure and the covariates, with the penalty selected by tenfold cross-validation, and each tested coefficient is corrected by one Newton step along a node-wise decorrelated direction (the de-sparsified lasso). For a binary or an ordinal outcome, the outcome probabilities are integrated over the conditional distribution of the reconstructed columns by Monte Carlo draws; for a count outcome the mean is the exact conditional moment of the log-linear model.
  3. Step 3 (decision). The pairs whose exposure-side P value is at most alpha are retained, and the Benjamini-Hochberg procedure at level alpha is applied to the outcome-side P values of the retained pairs. A retained pair whose adjusted outcome-side P value is at most alpha is reported. The adjustment is outcome-side only; the rule does not generally control the false discovery rate over the full mediation null at alpha. Treat reported pairs as candidates for follow-up.

The default analysis

The default analysis requires the data, the outcome type and a seed.

import amma

result = amma.fit(
    counts,          # (n, d) counts, samples in rows, taxa in columns
    exposure,        # (n,)
    outcome,         # (n,)
    "continuous",    # or "binary", "ordinal", "count"
    covariates,      # (n, p), optional
    seed=1,
)
result                       # summary of the analysis
result.tested_pairs()        # one row per tested (taxon, part) pair
result.reported_pairs()      # the reported pairs
result.taxon_table()         # Step-1 results of every taxon
result.sample_offsets()      # the estimated offsets

The inputs are NumPy arrays or pandas objects. A count DataFrame gives the sample and taxon names; a covariate DataFrame may hold categorical, text or Boolean columns, which are represented by indicator columns of their levels other than the first. A binary outcome is coded 0 and 1, Boolean, or categorical with two levels; an ordinal outcome is a pandas Categorical (in the order of its categories) or a numeric vector whose sorted distinct values are the ordered categories, and its categories are coded 1, ..., K before the analysis; a count outcome holds nonnegative integers. Sample names must be unique.

The analysis seed controls the Step-2 cross-validation folds. Posterior integration for binary and ordinal outcomes uses 2,000 draws in chunks of 250, with a fixed seed of 1 plus the chunk number (starting at 1). The Python package uses the same fold and draw streams as the R package under its default random-number settings.

Results

tested_pairs() returns, for every tested pair, the taxon and its part, the exposure-side P values (exposure_p_marginal, and exposure_p, conditional on the selection into the tested family), the outcome-side estimate, standard error and statistic of the de-sparsified coefficient (per standard deviation of the reconstructed column), the outcome-side P value outcome_p, whether the coefficient converged, whether the pair is retained, the adjusted outcome-side P value outcome_q among the retained pairs, and whether the pair is reported. Tables are mappings from column names to NumPy arrays; table.to_pandas() returns a pandas.DataFrame when pandas is installed.

Two properties of taxa detected in one exposure group only affect the interpretation of the results.

  • When the design restricted to the samples in which a taxon is detected does not have full column rank, or when m <= q (for example, for a taxon detected in one exposure group only), the abundance exposure coefficient of the taxon is not estimable. The abundance part of the taxon then has no statistic and is not tested (column abundance_estimable of taxon_table()); its presence part is analyzed as that of any other taxon.
  • The abundance coefficients of such a taxon are determined mainly by the penalty of the Step-1 likelihood and only weakly by the data. When its presence part is tested, these coefficients are used in the reconstruction of its columns in Step 2, so its outcome-side results are numerically less stable than those of other taxa.

Options

Supplied offsets and the latent-presence statistic

The estimated offsets of the default analysis assume that the sampling fraction does not depend on the exposure. For data in which it may, offsets estimated by a method that accounts for this dependence are supplied with offsets (one value per sample; they are centered), and Step 1 is then one fit at the supplied offsets. With prevalence_statistic="latent", the statistic of the presence part is the signed square root of the likelihood-ratio statistic for the exposure coefficient delta_j of the latent presence in the two-part model, whose censoring model includes the offsets, so that a change of detection that the offsets explain is not attributed to the presence of the taxon. Within the presence part these statistics are centered and scaled by a two-group normal mixture fitted to them. The two arguments are intended to be used together:

result = amma.fit(counts, exposure, outcome, "continuous", covariates, seed=1,
                  offsets=offsets, prevalence_statistic="latent")
result.taxon_table()   # prevalence_estimate and prevalence_p of the latent presence

Adjustment set by post-double selection

With adjustment="pds" (continuous outcome only), the Step-2 outcome model also includes the other part of every tested taxon whose other part is not tested, and the candidate columns chosen by post-double selection, so that each tested coefficient is adjusted for these columns. The candidates are the parts of the other taxa; they are selected by lasso regressions of the outcome and of each tested column on the candidates, after the intercept, the exposure and the covariates are removed by least squares, and at most 32 candidates are kept. The penalty of these regressions is the plug-in penalty 2 c sqrt(n) sigma Phi^{-1}(1 - gamma / (2p)) with c = 1.1, gamma = 0.1 / log(n) and an iterated residual standard deviation sigma (pds_penalty="formula", the default), or the penalty that minimizes the cross-validated error (pds_penalty="cv_min"). The tested family, the exposure side and Step 3 are unchanged. The column identification of tested_pairs() gives the status of each tested coefficient; a tested coefficient that is not identified (a constant column, or a column that duplicates another column or is a linear combination of the other columns) has outcome-side P value one.

result = amma.fit(counts, exposure, outcome, "continuous", covariates, seed=1,
                  adjustment="pds")

Iteration of Step 1 to convergence

With step1_rounds="convergence", the rounds of the alternating estimator of the offsets continue until the largest absolute change of an offset between two rounds is below step1_tol (0.001), with at most step1_max_rounds (50) rounds; a warning is given when the tolerance is not reached. convergence_record() returns the record of the rounds, and amma.plot_convergence(result) draws the convergence curves: the change of the offsets in each round, with the tolerance, and the penalized negative log-likelihood of the taxon fits by round.

result = amma.fit(counts, exposure, outcome, "continuous", covariates, seed=1,
                  step1_rounds="convergence")
result.convergence_record()
amma.plot_convergence(result)     # requires matplotlib

Box-Cox scale of the abundance part

boxcox_lambda (one finite number, at least 0, the same for every taxon and supplied by the analyst) replaces the log scale of the abundance part by the Box-Cox scale h(x) = (x^lambda - 1) / lambda; the default, 0, is the log transformation. With lambda > 0 the offsets s_i are estimated on the log scale as before (or supplied), the sampling fraction is removed on the count scale, and the corrected counts are transformed: a detected count contributes h(O_ij exp(-s_i)), computed as expm1(lambda (log O_ij - s_i)) / lambda, and the detection limit of sample i is h(exp(-s_i)), computed as expm1(-lambda s_i) / lambda. The taxon models are refitted on that scale at the fixed offsets; the Step-1 likelihood includes the Jacobian of the transformation, so that its value is the density of the observed counts. Every later step (the reconstruction, the outcome models of the four outcome types, the adjustment set and the effect estimates, including the hurdle exposure model and the influence values) uses the same formulas on the transformed scale. The detection regression of the presence part does not use the transformation.

The option is a heuristic sensitivity analysis: the theory of the method is stated for the log scale, and the option has not been evaluated by simulation. The abundance coefficients and the abundance part of the mediator are on the transformed scale, while the tests, the reported pairs and the effects on the scale of the outcome mean remain comparable across values of lambda. The option can be combined with the other options and with amma.effects.

result = amma.fit(counts, exposure, outcome, "continuous", covariates, seed=1,
                  boxcox_lambda=0.5)

Effect estimates

amma.effects(result) estimates, for the exposure contrast z1 versus z0 (contrast=(1, 0)), the indirect effect through each taxon of the tested family (NIE) with its abundance and presence components (NIE_a, NIE_p, which sum to NIE), the direct effect (NDE), the total indirect effect through the tested family (TIE), and the indirect effect through the reported taxa (OIE_selected), on the scale of the outcome mean: the mean of a continuous outcome, P(Y = 1) for a binary outcome, E(Y) for a count outcome, and P(Y <= k) for each category k except the last of an ordinal outcome.

eff = amma.effects(result)                       # contrast=(1, 0), level=0.95
eff.effects                                      # estimate, se, lower, upper per effect

These differences are interpretable as natural direct and indirect effects under the assumptions of no unmeasured confounding of the exposure-outcome, exposure-mediator and mediator-outcome relations given the covariates, cross-world independence, positivity, and independence of the mediators of different taxa given the exposure and the covariates. The exposure side of each taxon is its Step-1 two-part model. The outcome model uses the de-sparsified coefficient for the reported taxa and for the taxon whose own effect is evaluated, the penalized coefficient of the Step-2 outcome model for the other taxa of the tested family, and the exposure coefficient of the unpenalized refit of the outcome model on the exposure, the covariates and the selected mediator columns. For a continuous outcome the effects are computed in closed form; otherwise by Monte Carlo integration with draws draws (200) per sample and taxon generated from seed (1). Standard errors are computed by the delta method from the influence functions of the Step-1 and Step-2 estimates, and the intervals are Wald intervals at level (0.95).

For a taxon with at most one detection in an exposure group whose fitted two-part model makes a present taxon undetectable in that group, the exposure model is a hurdle model in which the exposure acts through presence alone (exposure_model = "hurdle"). For a taxon whose abundance exposure coefficient is not estimable, the effect estimates are numerically less stable than those of other taxa, for the reason given above. Effect estimates are available for an analysis without an adjustment set.

Agreement with the R package

The test suite compares every stage of the procedure with values computed with the R package AMMA (version 0.99.0; R 4.5.3, glmnet 4.1-10, ordinalNet 2.14, MASS 7.3-65, Matrix 1.7-4), stored in tests/fixtures with 17 significant digits; the versions are recorded in tests/fixtures/reference.json. The data sets are simulated: 80 samples and 40 taxa, 60 samples and 24 taxa, and a data set in which two taxa are detected in one exposure group only, each with the four outcome types. The numerical algorithms of R that the procedure uses (the BFGS algorithm of optim, the QR decomposition of LINPACK, glm.fit, the coordinate descent of glmnet, the penalized proportional-odds model of ordinalNet, MASS::polr, and the random number generators) are transcribed, so that the stages agree to rounding error when they start from the same inputs. Within this range, the remaining differences are bounded by the stopping rule of the optimizer of the Step-1 taxon fits (relative change of the objective below 1.5e-8):

Comparison Tolerance
Steps 2 and 3, adjustment set and effect estimates from the Step-1 quantities of R (log scale, and Box-Cox scale at lambda = 0.5) estimates 1e-9 absolute; P values 1e-9 relative; standard errors of effects 1e-8 relative
Step 1 coefficients 1e-6 absolute plus 1e-3 standard errors; offsets 1e-6
Complete procedure computed in Python estimates 1e-5 absolute; P values and standard errors 1e-4 relative
Tested families, retained pairs, reported pairs, selected adjustment columns identical

For a taxon without an estimable abundance exposure coefficient, the Step-1 fit stops on a flat region of the likelihood, at a point that depends on rounding error, so the outcome-side results of an analysis that tests the prevalence part of such a taxon agree to about 1e-3 relative.

Development

python -m venv .venv
.venv/bin/python -m pip install -e ".[dev]"
python -m pytest

The test of the stopping rule of Step 1 at the default tolerance runs when the environment variable AMMA_RUN_SLOW is set to 1. With the environment variable AMMA_AGREEMENT_REPORT set to a file name, the test suite writes the largest observed difference from the R values of every compared quantity to that file.

License

See LICENSE.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages