Fitting Latent Factor Mixed Models (Least squares algorithm)
Description
Latent Factor Mixed Models (LFMMs) are factor regression models in which the response variable is a genotypic matrix, and the explanatory variables are environmental measures of ecological interest or trait values. The lfmm2 function estimates latent factors based on an exact least-squares approach. The resulting object can be used by the function lfmm2.test to identify genetic polymorphisms exhibiting association with ecological gradients or phenotypes, while correcting for unobserved confounders. An MCMC estimation algorithm is implemented in the function lfmm, but this version should be prefered.
Usage
lfmm2 (input, env, K, lambda = 1e-5, effect.sizes = FALSE, formula = NULL)
lfmm2 (input, env, K, lambda = 1e-5, effect.sizes = FALSE, formula = NULL)
Arguments
input |
A genotypic matrix or a character string containing a path to the input file. The genotypic matrix must be in the lfmm{lfmm_format} format without missing values (9 or NA). See impute for completion based on nonnegative matrix factorization and consider R packages for reading large matrices.
|
env |
A numeric matrix, a data frame containing only ordinary numeric columns, or a character string containing a path to the environmental file. The environment matrix must be in the env format without missing values. Response variables must be encoded as numeric.
|
K |
An integer corresponding to the number of latent factors. The number of latent factors could be estimated from the elbow point in the PCA screeplot for the genotype matrix.
|
lambda |
A positive numeric value for a ridge regularization parameter. The default value is set to 1e-5.
|
effect.sizes |
A logical value indicating whether per-locus GEA coefficients are retained in @B. The default FALSE keeps the historical NA placeholder and saves storage. Coefficients are still estimated internally to retain their small second-moment matrix Cb in both modes.
|
formula |
An optional one-sided formula, allowed only with a numeric data frame in env. The default NULL uses every column in its original order. Supported terms are numeric variables, I(x^k) for positive literal integer powers, log(x) and sqrt(x), joined by +. Interactions, factors, arbitrary calls and . are not supported. Non-numeric data-frame columns cause an error even if not selected.
|
Details
New fits carry optional version-1 attributes without changing the five S4
slots or the version-1 env.spec schema. The descriptive
fit.info list contains version, genotype and
environment records (label, mode,
dimensions), fitted.dimensions, predictors,
formula, and predictor.sd. Labels capture argument
expressions without re-evaluation, or file paths for file input. Long
expression labels are truncated. No input matrices, environments or calls
are retained. Environmental dimensions describe the original table;
fitted dimensions, ordered names and sample standard deviations describe
the actual transformed predictor columns before internal centering.
Standard deviations are descriptive and do not change fitting.
The separate gea.metric attribute is a list with version = 1L
and Cb, a finite symmetric d-by-d numeric matrix in fitted predictor
order, with predictor dimnames when available. For L fitted loci and the
L-by-d coefficient matrix B, Cb=BTB/L. This is an uncentered
second moment, not a covariance matrix. With retained coefficients it uses
crossprod(B)/L; otherwise equivalent crossproducts are accumulated
in locus blocks without retaining the full B. No eigendecomposition is stored
in the fit. The estimator, ridge penalty and association tests are unchanged.
show and print display concise provenance, dimensions,
latent-factor location and coefficient-retention information, without
printing matrices, accessing input files or computing eigenvalues.
Unavailable historical provenance is explicitly identified.
summary computes the symmetric eigendecomposition of Cb and returns
all eigenvalues in decreasing order, eigenvectors, spectral proportions,
cumulative proportions, and the smallest number of leading axes reaching
99 percent. Small negative roundoff eigenvalues are clipped to zero using
a scale-aware tolerance (100 times machine epsilon times d, on a unit-scale
metric). Materially asymmetric, indefinite, nonfinite or malformed metrics
are reported as unavailable. A zero trace gives undefined proportions and
an undefined 99-percent axis count. Historical objects without Cb use valid
retained B; the 1-by-1 NA placeholder is never treated as coefficients.
Without either, the spectrum is unavailable. Missing or malformed descriptive
metadata does not prevent concise display.
Standardizing environmental predictors to unit standard deviation (sd = 1)
is recommended before fitting LFMM2 for meaningful comparisons of spectral
contributions. For formula fits this refers to the transformed predictor
columns used in the fit. Standardization should precede fitting, not merely
spectral decomposition. No automatic standardization is performed.
Spectral contributions depend on predictor scaling and coordinates:
99 percent of the Cb spectrum does not mean 99 percent of total genotype
variance. Dominant axes are linear combinations of predictors; retaining r
axes is not equivalent to removing d-r original environmental variables.
Reparameterization and refitting under ridge regularization are not
necessarily equivalent.
Formula transformations are applied before the existing column centering.
No intercept column is added to the environmental matrix. This does not
remove the intercept from the association regressions in lfmm2.test.
The prepared matrix is not standardized. Explicit ~ 0 + x and
~ x - 1 are equivalent to ~ x for environmental preparation.
Formula predictors must be finite and nonconstant. Rank is diagnosed on a
separate centered, unit-norm representation, with QR tolerance equal to
machine epsilon times the larger environmental dimension. An anchor is
subtracted before diagnostic centering to retain small variation around a
large absolute level. No diagnostic transformation changes the matrix
returned for fitting or association. Dependencies at floating-point
precision are rejected, and no predictor is silently dropped.
Arguments in transformations must be unnamed. Each term produces one
column, in formula order.
For objects fitted with a formula, association testing also checks that
the environmental coefficients are estimable conditional on the intercept
and latent factors. Checks of fitted models use their own QR tolerances,
which need not equal the preparatory rank tolerance. The global test also
checks absorption by the retained nuisance design at machine precision on
a centered, normalized diagnostic copy, before checking the fitted
residual regression. Unestimable predictors cause an
explicit error rather than substitution of a latent-factor statistic.
The formula is normalized and stored without its original R environment
in a small internal env.spec attribute. The five statistical S4 slots
are unchanged. No environmental matrix or numerical fingerprint is stored.
The fitted formula is reconstructed automatically by lfmm2.test;
that function has no formula argument. With a formula, the same predictors,
values and individual order must be supplied when testing. Dimensions and
predictor structure are checked, but numerical identity and individual
identity cannot be verified. They remain the user's responsibility.
Old objects and objects fitted without a formula retain the historical
association path. No restriction on the identity of tested loci is added.
Value
lfmm2 returns an object of class lfmm2Class that contains $K$ estimated latent factors @U and their loadings @V.
show and print return the fit invisibly.
summary returns a compact S3 list of class summary.lfmm2,
with model information and gea.spectrum. For an available spectrum,
the latter contains available, source, eigenvalues,
vectors, proportion, cumulative, axes99,
variables, tolerance, and relative.tolerance.
An unavailable spectrum contains available = FALSE and reason.
The summary print method returns its argument invisibly and may omit trailing
axes when there are more than twelve predictors; the full spectrum remains
available programmatically. Eigenvector signs and bases within repeated
eigenvalues are indeterminate.
The following method can be applied to an object of class lfmm2Class:
\link{lfmm2.test} |
P-values adjusted for the $K$ latent factors computed by lfmm2.
|
Author(s)
Olivier Francois
References
Caye K, Jumentier B, Lepeule J, Francois O. (2019). LFMM 2: fast and accurate inference of gene-environment associations in genome-wide studies. Molecular biology and evolution, 36(4), 852-860.
Gain C, Francois O. (2021). LEA 3: Factor models in population genetics and ecological genomics with R. Molecular Ecology Resources. doi: 10.1111/1755-0998.13366
See Also
lfmm.data
impute
lfmm2.test
pca
lfmm
tutorial
Examples
### Example of analysis using lfmm2 ###
# Simulation with 10 target loci, with effect sizes ranging between -10 an 10
# n = 100 individuals and L = 1000 loci
X <- as.matrix(rnorm(100)) # causal environmental variable
B <- rep(0, 1000)
target <- sample(1:1000, 10) # target loci
B[target] <- runif(10, -10, +10) # effect sizes
# Creating hidden factors and loadings
U <- t(tcrossprod(as.matrix(c(-1,0.5,1.5)), X))+ matrix(rnorm(300), ncol = 3)
V <- matrix(rnorm(3000), ncol = 3)
# Simulating a binarized matrix containing haploid genotypes
# Simulation performed with the generative LFMM
Y <- tcrossprod(as.matrix(X), B) + tcrossprod(U, V) + matrix(rnorm(100000, sd = .5), nrow = 100)
Y <- matrix(as.numeric(Y > 0), ncol = 1000)
######################################
# Fitting an LFMM with K = 3 factors #
######################################
mod2 <- lfmm2(input = Y, env = X, K = 3)
# Computing P-values and plotting their minus log10 values
# Target loci are highlighted
pv <- lfmm2.test(object = mod2, input = Y, env = X, linear = TRUE)
plot(-log10(pv$pvalues), col = "grey", cex = .4, pch = 19)
points(target, -log10(pv$pvalues[target]), col = "red")
#rm(list = ls())
X <- as.matrix(rnorm(100))
B <- rep(0, 1000)
target <- sample(1:1000, 10)
B[target] <- runif(10, -10, +10)
U <- t(tcrossprod(as.matrix(c(-1,0.5,1.5)), X))+ matrix(rnorm(300), ncol = 3)
V <- matrix(rnorm(3000), ncol = 3)
Y <- tcrossprod(as.matrix(X), B) + tcrossprod(U, V) + matrix(rnorm(100000, sd = .5), nrow = 100)
Y <- matrix(as.numeric(Y > 0), ncol = 1000)
mod2 <- lfmm2(input = Y, env = X, K = 3)
pv <- lfmm2.test(object = mod2, input = Y, env = X, linear = TRUE)
plot(-log10(pv$pvalues), col = "grey", cex = .4, pch = 19)
points(target, -log10(pv$pvalues[target]), col = "red")