skbio.stats.composition.dirmult_lme#

skbio.stats.composition.dirmult_lme(table, metadata, formula, grouping, pseudocount=0.5, draws=128, p_adjust='holm', seed=None, re_formula=None, vc_formula=None, model_kwargs={}, fit_method=None, fit_converge=False, fit_warnings=False, fit_kwargs={})[source]#

Fit a Dirichlet-multinomial linear mixed effects model.

Added in version 0.7.0.

The Dirichlet-multinomial distribution is a compound distribution that combines a Dirichlet distribution over the probabilities of a multinomial distribution. This distribution is used to model the distribution of species abundances in a community.

To fit the linear mixed effects model we first fit a Dirichlet-multinomial distribution for each sample, and then we compute the fold change and p-value for each feature. The fold change is computed as the slopes from the resulting model. Statistical tests are then performed on the posterior samples, drawn from each Dirichlet-multinomial distribution. The log-fold changes as well as their credible intervals, the p-values and the multiple comparison corrected p-values are reported.

Changed in version 0.7.4: Significantly improved computational efficiency under the default configuration by introducing an analytical kernel fitting all features at once. See Notes for details.

Parameters:
tabletable-like of shape (n_samples, n_features)

A matrix containing count or proportional abundance data of the samples. Counts are recommended over proportions for lower statistical uncertainty. See Notes of dirmult_ttest for details.

metadatapd.DataFrame or 2-D array-like

The metadata for the model. Rows correspond to samples and columns correspond to covariates in the model. Must be a pandas DataFrame or convertible to a pandas DataFrame.

formulastr or generic Formula object

The formula defining the model. Refer to Patsy’s documentation on how to specify a formula.

groupingstr, pd.Series or 1-D array-like

A vector or a metadata column name indicating the assignment of samples to groups. Samples are independent between groups during model fitting.

pseudocountfloat, optional

A non-zero value added to the input counts to ensure that all of the estimated abundances are strictly greater than zero. Default is 0.5.

drawsint, optional

Number of draws from the Dirichlet-multinomial posterior distribution. Default is 128.

p_adjuststr, optional

Method to correct p-values for multiple comparisons. Options are: Bonferroni (“bonf”/”bonferroni”), Holm-Bonferroni (“holm”/”holm-bonferroni”, default), Benjamini-Hochberg (“bh”/”benjamini-hochberg”), and Benjamini-Yekutieli (“by”/”benjamini-yekutieli”), or any method supported by statsmodels’ multipletests function. Case-insensitive. If None, no correction will be performed.

seedint, Generator or RandomState, optional

A user-provided random seed or random generator instance for drawing from the Dirichlet distribution. See details.

re_formulastr, optional

Random coefficient formula. See MixedLM.from_formula for details.

vc_formulastr, optional

Variance component formula. See MixedLM.from_formula for details.

model_kwargsdict, optional

Additional keyword arguments to pass to MixedLM.

fit_methodstr or list of str, optional

Optimization method for model fitting. Can be a single method name, or a list of method names to be tried sequentially. See statsmodels.optimization for available methods. If None (default), the default model is solved in closed form and no iterative optimizer is used. See Notes.

fit_convergebool, optional

If True, model fittings that were completed but did not converge will be excluded from the calculation of final statistics. Default is False. Setting this selects the iterative optimizer, which is what reports convergence.

fit_warningsbool, optional

Issue warnings if any during the model fitting process. Default is False. Warnings are usually issued when the optimization methods do not converge, which is common in the analysis. Default is False.

fit_kwargsdict, optional

Additional keyword arguments to pass to MixedLM.fit.

Returns:
pd.DataFrame

A table of features and covariates, their log-fold changes and other relevant statistics.

  • FeatureID: Feature identifier, i.e., dependent variable.

  • Covariate: Covariate name, i.e., independent variable.

  • Reps: Number of Dirichlet-multinomial posterior draws that supported the reported statistics, i.e., the number of successful model fittings on this feature. Max: draws (if none failed). Min: 0 (in which case all statistics are NaN).

  • Log2(FC): Expected log2-fold change of abundance from the reference category to the covariate category defined in the formula. The value is expressed in the center log ratio (see clr) transformed coordinates. The reported value is the average of all of the log2-fold changes computed from each of the posterior draws.

  • CI(2.5): 2.5% quantile of the log2-fold change. The reported value is the minimum of all of the 2.5% quantiles computed from each of the posterior draws.

  • CI(97.5): 97.5% quantile of the log2-fold change. The reported value is the maximum of all of the 97.5% quantiles computed from each of the posterior draws.

  • pvalue: p-value of the linear mixed effects model. The reported value is the average of all of the p-values computed from each of the posterior draws.

  • qvalue: Corrected p-value of the linear mixed effects model for multiple comparisons. The reported value is the result of a single correction applied to the average per-draw p-values across all posterior draws.

  • Signif: Whether the covariate category is significantly differentially abundant from the reference category. A feature-covariate pair marked as “True” suffice: 1) The q-value must be less than or equal to the significance level (0.05). 2) The confidence interval (CI(2.5)..CI(97.5)) must not overlap with zero.

Notes

The default model has one random intercept per group, for which the REML fit has a closed form. In that case all features of a replicate are fitted at once by maximizing the one-dimensional profile likelihood over the ratio of the group variance to the residual variance, instead of running one numeric optimization per feature through MixedLM.fit. The estimates, standard errors, p-values and confidence intervals are those of MixedLM, computed from the same REML profile likelihood and the same observed information matrix.

Supplying re_formula, vc_formula, model_kwargs, fit_method, fit_kwargs or fit_converge selects a model, an optimizer, or a convergence filter that has no closed form, and falls back to fitting each feature separately with MixedLM.

Changed in version 0.7.4: The default random intercept model is fitted for all features at once. Results may differ slightly from earlier versions on replicates where the iterative optimizer of MixedLM stopped short of the optimum. Any other configuration falls back to running one numeric optimization per feature per draw using MixedLM, which can take much longer to finish.

Examples

>>> import pandas as pd
>>> from skbio.stats.composition import dirmult_lme

In a longitudinal fiber supplement study, each subject provides a stool sample at three weekly visits during the intervention. Use the synthetic count table below to ask which taxa differ between treatment arms while accounting for week and the repeated samples from each subject.

>>> subjects = ["p1", "p2", "p3", "p4"]
>>> weeks = [1, 2, 3]
>>> ids = [f"{s}_w{i}" for s in subjects for i in weeks]
>>> table = pd.DataFrame(
...     [[260,  830, 910], [530, 775, 695], [ 650, 710, 640],
...      [370,  810, 820], [290, 900, 810], [1080, 525, 395],
...      [175, 1030, 795], [550, 780, 670], [ 425, 895, 680],
...      [420,  770, 810], [830, 645, 525], [ 755, 735, 510]],
...     index=ids, columns=["taxon1", "taxon2", "taxon3"],
... )
>>> metadata = pd.DataFrame({
...     "subject": [p for p in subjects for _ in weeks],
...     "week": weeks * len(subjects),
...     "arm": ["control"] * 6 + ["fiber"] * 6
... }, index=ids)

Execute the function with the formula week + arm, which estimates a common weekly trend for both arms and a difference between arms at the same week. Grouping by subject gives each person a random intercept so their repeated samples share a subject-specific baseline. Use 32 posterior draws to make this example quick.

>>> result = dirmult_lme(
...     table, metadata, formula="week + arm", grouping="subject",
...     draws=32, seed=0,
... )
>>> print(result.to_string(index=False, float_format="{:.3g}".format))
FeatureID    Covariate  Reps  Log2(FC)  CI(2.5)  CI(97.5)   pvalue   qvalue  Signif
   taxon1 arm[T.fiber]    32  -0.00595   -0.926     0.906    0.951    0.951   False
   taxon1         week    32      0.57    0.164     0.978  0.00103  0.00207    True
   taxon2 arm[T.fiber]    32    0.0904   -0.454     0.607    0.668    0.668   False
   taxon2         week    32    -0.202   -0.434    0.0191   0.0303   0.0607   False
   taxon3 arm[T.fiber]    32   -0.0844   -0.568     0.404    0.675    0.675   False
   taxon3         week    32    -0.368   -0.583    -0.146 5.78e-05 0.000116    True

The arm[T.fiber] rows compare fiber with control at the same week. None of them is statistically significant, and all three confidence intervals (CIs) span zero. This suggests limited evidence of a difference between arms in any taxon.

The week rows show the time trend shared by both arms. For taxon 1, a positive Log2(FC) of 0.57 means that its abundance relative to the geometric mean of the three taxa in each sample is \(2^{0.57} \approx 1.5\) times as large one week later. Its CI sits above zero, suggesting high confidence of the estimated increase. A q-value (adjusted p-value) of 0.002 indicates statistical significance of this result. It should be noted that this q-value accounts for the two tests (week and arm) run within each taxon, but not for testing three taxa.