nuee is a comprehensive Python implementation of the popular R package vegan
for community ecology analysis. It provides tools for ordination, diversity analysis,
dissimilarity measures, and statistical testing commonly used in ecological research.
nuee is inspired by the R package vegan developed by Jari Oksanen and the vegan
development team. It aims to provide similar functionality in a Pythonic interface
while leveraging the scientific Python ecosystem (NumPy, SciPy, pandas, matplotlib).
Non-metric Multidimensional Scaling with automatic transformation.
This function provides a high-level interface for NMDS ordination, following
the conventions of the R vegan package’s metaMDS function. It automatically
handles data transformation and uses multiple random starts to find the best
ordination solution.
Parameters:
X (np.ndarray or pd.DataFrame) – Community data matrix with samples in rows and species in columns.
Values should be non-negative abundances or counts.
k (int, default=2) – Number of dimensions for the ordination. Common choices are 2 or 3.
distance (str, default="bray") – Distance metric to use for calculating dissimilarities.
See nuee.vegdist() for available options.
trymax (int, default=20) – Maximum number of random starts to find the best solution.
Higher values increase computation time but may find better solutions.
maxit (int, default=1000) – Maximum number of iterations for each random start.
trace (bool, default=False) – If True, print progress information including stress values.
autotransform (bool, default=True) – If True, automatically apply square root transformation to abundance data
(values > 1) to reduce the influence of dominant species.
wascores (bool, default=True) – If True, calculate weighted average species scores based on site scores
and species abundances.
expand (bool, default=True) – If True, expand the result to include additional information.
random_state (int, optional) – Seed used for reproducible random starts. If None, each run is
initialised independently.
**kwargs (dict) – Additional parameters passed to the NMDS class.
NMDS is a rank-based ordination method that attempts to preserve the rank
order of dissimilarities between samples. Unlike metric methods like PCA,
NMDS makes no assumptions about the linearity of relationships.
Stress values provide a measure of fit:
- < 0.05: excellent
- 0.05 - 0.10: good
- 0.10 - 0.20: acceptable
- > 0.20: poor (consider increasing k or using a different method)
The function uses multiple random starts (trymax) because NMDS can get stuck
in local optima. The solution with the lowest stress is returned.
RDA is a constrained ordination method that finds linear combinations
of explanatory variables that best explain the variation in the response matrix.
Supplying Z fits a partial RDA: the effect of the conditioning
variables is removed from both the response and the explanatory matrix
before the constrained decomposition, and the inertia it accounts for is
reported separately as partial_chi.
Parameters:
X – Response matrix (samples x species)
Y – Explanatory matrix (samples x variables)
Z – Conditioning matrix for partial RDA (optional)
formula – Formula string (e.g., “~ var1 + var2”)
data – DataFrame containing variables for formula
scale – Whether to scale species to unit variance
center – Whether to centre species column-wise
**kwargs – Additional parameters
Returns:
ConstrainedOrdinationResult with RDA results. Inertia is expressed as
variance, and every component shares that scale, so
partial_chi+sum(constrained_eig)+sum(unconstrained_eig) equals
tot_chi (partial_chi being None for a non-partial fit). See
inertia_partition()
for the decomposition as a table.
Examples
# Simple RDA
result = rda(species_data, environmental_data)
# RDA with formula
result = rda(species_data, formula=”~ pH + temperature”, data=env_data)
# Partial RDA, conditioning on covariates
result = rda(species_data, environmental_data, Z=conditioning_data)
result.inertia_partition()
Canonical Correspondence Analysis (or CA when X is None).
Parameters:
Y – Species data matrix (sites x species).
X – Environmental data matrix (sites x variables) or DataFrame for
formula evaluation. When None and no formula is given, an
unconstrained Correspondence Analysis (CA) is performed.
formula – R-style formula string referencing columns in X.
X (array-like) – Data matrix (samples x variables).
y (array-like) – Group labels for each sample.
n_components (int, optional) – Number of discriminant axes to keep.
Defaults to min(n_classes - 1, n_features).
solver ({"svd", "eigen"}) – Solver for sklearn LDA. Default "svd". sklearn’s "lsqr" is
rejected: it provides neither a transform nor discriminant scalings,
so it cannot produce an ordination.
Returns:
points holds the discriminant scores and species the loadings,
rescaled onto the score extent so biplot arrows stay visible whatever
the units of X (the unscaled coefficients remain on
result.raw_loadings). proportion_explained gives each retained
axis’ share of the between-group variance across all axes, so it
sums to less than 1 when n_components truncates the set.
Stepwise model selection for constrained ordination.
Terms are added and/or dropped one at a time using permutation tests, in
the manner of vegan’s ordistep. A candidate is tested as a constraint
conditioned on the terms already retained, so each test is marginal.
Parameters:
ordination – A fitted constrained ordination (e.g. from nuee.rda()), used as
the source of the response matrix.
env – Candidate explanatory variables, one per column.
direction – "forward" only adds terms, "backward" starts from the full set
and only drops them, "both" alternates.
permutations – Permutations per test.
p_enter – A term is added when its p-value is at or below this.
p_remove – A retained term is dropped when its p-value rises above this.
max_steps – Safety bound on the number of add/drop rounds.
random_state – Seed, for reproducible selection.
Returns:
selected_variables (in the order chosen), p_values for those
terms, the direction used, and the steps taken.
This function provides a unified interface for calculating various diversity
indices commonly used in ecology. It can calculate diversity for individual
samples or for pooled groups.
Parameters:
x (np.ndarray or pd.DataFrame) – Community data matrix with samples in rows and species in columns.
Values should be non-negative abundances or counts. Can also be a
1D array for a single sample.
index ({'shannon', 'simpson', 'invsimpson', 'fisher'}, default='shannon') – Diversity index to calculate:
- ‘shannon’: Shannon entropy H’ = -sum(p_i * log(p_i))
- ‘simpson’: Gini-Simpson index 1 - sum(p_i^2)
- ‘invsimpson’: Inverse Simpson 1 / sum(p_i^2)
- ‘fisher’: Fisher’s alpha
groups (np.ndarray or pd.Series, optional) – Grouping factor for calculating pooled diversities. If provided,
samples are pooled within each group before calculating diversity.
base (float, default=e) – Base of logarithm for Shannon index. Common choices:
- e (natural log): nats
- 2: bits
- 10: dits
Returns:
Diversity values for each sample (or group if groups is provided).
If input is a DataFrame, returns a pd.Series with sample/group names.
Shannon diversity (H’) measures both richness and evenness:
- Higher values indicate more diverse communities
- Ranges from 0 (single species) to log(S) where S is species richness
- Most common diversity index in ecology
Simpson’s index measures dominance:
- We report the Gini-Simpson form (1 - sum(p_i^2)), matching vegan::diversity
- Larger values indicate greater diversity
- The inverse Simpson (1 / sum(p_i^2)) is available via index='invsimpson'
Fisher’s alpha assumes a log-series distribution:
- Useful for abundance data
- Less sensitive to sample size than richness
- Can be slow for large datasets
method – Accumulation method. "random" averages the accumulation
over random site orderings; "exact" returns the analytic
expected richness for each subset size, which is deterministic.
permutations – Number of permutations for the random method
random_state – Seed for the random method, for reproducible curves
Returns:
Dictionary with accumulation results
Raises:
ValueError – if method is not one of the supported accumulators.
Accumulate extrapolated richness estimators over pooled sites.
For every subset size from minsize to the number of sites, sites are
pooled in a random order and the specpool estimators are computed;
the curves are then averaged over permutations orderings. This mirrors
vegan’s poolaccum.
Parameters:
x – Community data matrix
permutations – Number of random site orderings to average over
minsize – Smallest number of pooled sites to report (vegan uses 3)
random_state – Seed, for reproducible curves
Returns:
Dictionary with the number of pooled sites (sites), the mean
observed richness (richness), and the mean chao, jack1,
jack2 and boot estimates, plus a means DataFrame holding
them together.
Raises:
ValueError – if minsize exceeds the number of sites.
This function calculates various dissimilarity indices commonly used
in community ecology. It is designed to be compatible with the R vegan
package’s vegdist function.
Parameters:
x (np.ndarray or pd.DataFrame) – Community data matrix with samples in rows and species in columns.
Permutation test for constrained ordination (RDA/CCA).
Partial ordinations are supported: the conditioning matrix is held fixed
across permutations, and the degrees of freedom it consumes are removed
from the residual, so the residual Df is
n_samples-1-rank(constraints)-rank(conditioning).
Parameters:
ordination_result – Constrained ordination result (e.g., from nuee.rda()).
permutations – Number of permutations used to build the null distribution.
random_state – Optional random seed or Generator for reproducible results.
Returns:
Dictionary containing the ANOVA-style table and permutation details.
For unconstrained ordination (PCA, CA, LDA), species loadings are drawn
as arrows from the origin. For constrained ordination (RDA / CCA),
species are shown as points and environmental variables as arrows.
Draws one box per group of the distances to the group centroid, the same
view as vegan’s boxplot.betadisper, with the group means marked and
the permutation test reported in the title.
Compute the inner product matrix in the Aitchison simplex.
The Aitchison inner product is
(1/D)*sum_{i<j}log(x_i/x_j)log(y_i/y_j), and the identity
sum_{i<j}log(x_i/x_j)log(y_i/y_j)=D*clr(x).clr(y) makes that
exactly the ordinary dot product of the clr coordinates. Dividing by D
on top of the clr product would deflate every entry by that factor.
denominator_idx indexes the restored composition, which has one more
component than mat. Negative indices are resolved against that wider
result: np.insert counts a negative position from the end of the
input, so passing -1 straight through would place the denominator
second-to-last instead of last, and the transform would not round-trip.
Multiplicative zero replacement for compositional data.
Replaces zeros with a small value proportional to the detection limit
(or column minimum of non-zero values) and adjusts non-zero entries so
that each row sum is preserved exactly.
Parameters:
X (array-like or DataFrame, shape (n, D)) – Compositional data matrix. Zeros mark below-detection-limit values.
detection_limits (array-like of shape (D,), optional) – Per-component detection limits. When None, the column-wise minimum
of strictly positive values is used as a proxy.
delta (float, optional) – Fraction of the detection limit used as the replacement value.
Default is 0.65 (Martín-Fernández et al. 2003).
Returns:
Data with zeros replaced. Row sums match the input exactly.
Impute missing values in compositional data using the lrEM algorithm.
Uses the ALR (additive log-ratio) EM algorithm of Palarea-Albaladejo &
Martín-Fernández (2008), matching the approach in R’s zCompositions
package. Observed values are preserved exactly in the output.
Ideally one column should be fully observed (no NaN values) to serve
as the ALR denominator. When no column is complete, the column with the
fewest missing values is chosen and its gaps are pre-filled using
row-proportional estimation from column-mean ratios before running EM.
Parameters:
X (array-like or DataFrame, shape (n, D)) – Compositional data matrix. NaN marks missing components.
Observed (non-NaN) values must be strictly positive.
method ({"lrEM", "lrDA"}, default "lrEM") – "lrEM" returns the conditional expectation (deterministic).
"lrDA" adds noise from the conditional covariance for multiple
imputation / data augmentation.
max_iter (int, default 100) – Maximum number of EM iterations.
tol (float, default 1e-4) – Convergence tolerance on the relative change of the log-likelihood.
random_state (int, optional) – Seed for the random number generator (only used when method=”lrDA”).
Returns:
Completed data. Observed values are unchanged; imputed values are
scaled consistently with the original observed components.