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.
Non-metric Multidimensional Scaling for community ecology.
This implementation follows the approach used in vegan’s metaMDS function,
including multiple random starts and stress evaluation. NMDS is a rank-based
ordination method that attempts to represent ecological distances in a
reduced dimensional space.
Parameters:
n_components (int, default=2) – Number of dimensions for the embedding (ordination axes).
max_iter (int, default=1000) – Maximum number of iterations for the optimization algorithm.
n_init (int, default=20) – Number of random initializations. The solution with minimum stress
is returned.
eps (float, default=1e-12) – Convergence tolerance for the stress value.
random_state (int, optional) – Random seed for reproducibility. If None, the random state is not fixed.
dissimilarity (str, default="bray") – Distance metric to use. See nuee.vegdist() for available options.
n_jobs (int, optional) – Number of parallel jobs for computation. If None, uses a single core.
High-level interface with automatic transformations
MDS
Scikit-learn’s MDS implementation
Notes
NMDS is particularly useful when:
- Relationships between samples are non-linear
- You want to use a specific distance metric
- You have presence/absence or abundance data
The stress value indicates goodness-of-fit:
- Values < 0.05 indicate excellent fit
- Values 0.05-0.10 indicate good fit
- Values > 0.20 indicate poor fit
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()
This implementation follows the classical algorithm:
Centre/scale the response matrix as requested, then divide by
sqrt(n - 1) so that the total sum of squares is a variance. This is
the inertia scale vegan reports, and every eigenvalue inherits it.
Centre the constraining variables.
Solve the weighted least-squares regression analytically.
Perform SVD on fitted (constrained) and residual (unconstrained) matrices.
Store the full decomposition so downstream tools can reconstruct
scaled scores mirroring vegan’s behaviour.
For a partial RDA the conditioning step happens between 1 and 3, and the
already-prepared residual must not be rescaled a second time; see
_partial_rda() and the prepared argument of _simple_rda().
Y – Constraining variables (samples x predictors) or DataFrame used with a formula.
Z – Conditioning matrix for partial RDA. When supplied, its effect is
removed from both X and Y, and the inertia it accounts for is
reported as partial_chi rather than folded into the
constrained or unconstrained components.
Returns:
All inertia components share the scale of tot_chi; see
ConstrainedOrdinationResult.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.
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.
For PCA the species loadings are shown as arrows from the origin.
For constrained ordination (RDA / CCA), environmental variables
are shown as arrows while species are shown as points.