Factor Analysis of a Multi-Environment Trial

In a multi-environment trial (MET), the same genotypes are evaluated across several environments, resulting in correlated genotype-by-environment effects. An unstructured covariance matrix for \(m\) environments requires \(m(m+1)/2\) parameters (21 for \(m = 6\)). A factor-analytic (FA) structure reduces the number of parameters by representing the covariance through a small number of latent factors and environment-specific uniquenesses.

This vignette fits an FA(2) model to a simulated MET dataset, examining parameter recovery against the known generating values. It also demonstrates how the factor-analytic covariance is constructed from covariance classes and how its parameters are named. The analysis is then repeated on an unbalanced version of the trial, where each genotype is grown in only a subset of the environments.

The model

For genotype \(i = 1, \ldots, n\), environment \(j = 1, \ldots, m\) and replicate \(r = 1, \ldots, R\), write

\[y_{ijr} = \mu_j + g_{ij} + \varepsilon_{ijr}, \qquad \mathbf{g}_i = (g_{i1}, \ldots, g_{im})^\top \sim \mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma}), \qquad \varepsilon_{ijr} \sim \mathcal{N}(0, \sigma^2).\]

The genotype-by-environment effects follow a factor-analytic covariance structure with \(k\) latent factors,

\[\boldsymbol{\Sigma} = \boldsymbol{\Lambda}\boldsymbol{\Lambda}^\top + \boldsymbol{\Psi}, \qquad \boldsymbol{\Psi} = \operatorname{diag}(\psi_1, \ldots, \psi_m),\]

where \(\boldsymbol{\Lambda}\) is the \(m \times k\) factor-loading matrix and \(\psi_j\) is the uniqueness of environment \(j\). Stacking the observations gives the linear mixed model

\[\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \mathbf{Z}\mathbf{g} + \boldsymbol{\varepsilon}, \qquad \mathbf{g} \sim \mathcal{N}(\mathbf{0}, \mathbf{G}), \qquad \mathbf{G} = \mathbf{I}_n \otimes \boldsymbol{\Sigma}, \qquad \mathbf{R} = \sigma^2 \mathbf{I}_N,\]

where

  • \(\mathbf{X}\) has one column per environment, with \(\boldsymbol{\beta}\) containing the environment means \(\mu_j\),

  • \(\mathbf{Z}\) maps each observation to its genotype-by-environment cell,

  • \(\mathbf{g}\) contains the cell effects,

  • \(\mathbf{I}_n \otimes \boldsymbol{\Sigma}\) specifies that the \(m\)-vector of effects for each genotype has covariance \(\boldsymbol{\Sigma}\), and that genotypes are independent.

See Introduction to Mixed Model REML Estimation for the general formulation of the mixed model and the REML estimator.

Identification

The decomposition \(\boldsymbol{\Sigma} = \boldsymbol{\Lambda}\boldsymbol{\Lambda}^\top + \boldsymbol{\Psi}\) is not unique, since orthogonal rotations of \(\boldsymbol{\Lambda}\) leave \(\boldsymbol{\Sigma}\) unchanged. To identify the factor loadings, we impose a lower-triangular constraint, setting \({\Lambda}_{ij} = 0\) whenever \(j > i\).

This constraint fixes the rotational indeterminacy, but the sign of each factor remains arbitrary. Consequently, estimated loadings may differ in sign from their generating values. The trial below illustrates these differences.

The data

The trial is shipped with the package as the dataset torch_openreml.example_data.fa_met. It records the yield of 100 genotypes in six environments, with two replicates per genotype-by-environment cell:

import torch

torch.set_default_dtype(torch.float64)
torch.set_printoptions(precision=4, sci_mode=False)

from torch_openreml import MixedModelREML
from torch_openreml.covariance import (
    DiagonalMatrix,
    DummyMatrix,
    Gram,
    IdentityMatrix,
    KroneckerProduct,
    LowerTriangularMatrix,
    ScalarMatrix,
    Sum,
)
from torch_openreml.example_data import fa_met, fa_met_params

fa_met.head()
genotype environment rep yield genetic
0 001 01 1 4.779848 -0.231039
1 001 01 2 4.818141 -0.231039
2 001 02 1 4.614127 -0.638617
3 001 02 2 4.455589 -0.638617
4 001 03 1 5.057905 0.261934

The dataset contains 1,200 rows, covering 100 genotypes across 6 environments, with 2 replicates per genotype-environment combination. The columns are genotype, environment, rep (replicate 1 or 2), yield (observed yield), and genetic (latent genotype-by-environment effect).

The data were simulated from the FA(2) structure described above. The generating values are kept next to the trial in fa_met_params.json and exposed as torch_openreml.example_data.fa_met_params:

means = torch.tensor(fa_met_params["means"])
loadings = torch.tensor(fa_met_params["loadings"])
uniqueness = torch.tensor(fa_met_params["uniqueness"])
sigma2 = fa_met_params["sigma2"]

Sigma_g = loadings @ loadings.T + torch.diag(uniqueness)
print(f"{means=}")
print(f"{loadings=}")
print(f"{sigma2=}")
print(f"{Sigma_g=}")
means=tensor([5.0000, 5.2000, 4.8000, 5.1000, 5.3000, 4.9000])
loadings=tensor([[0.9000, 0.0000],
        [0.7000, 0.2000],
        [0.6000, 0.1000],
        [0.5000, 0.4000],
        [0.3000, 0.7000],
        [0.1000, 0.8000]])
sigma2=0.3
Sigma_g=tensor([[1.3100, 0.6300, 0.5400, 0.4500, 0.2700, 0.0900],
        [0.6300, 0.9300, 0.4400, 0.4300, 0.3500, 0.2300],
        [0.5400, 0.4400, 0.8700, 0.3400, 0.2500, 0.1400],
        [0.4500, 0.4300, 0.3400, 1.0100, 0.4300, 0.3700],
        [0.2700, 0.3500, 0.2500, 0.4300, 0.9800, 0.5900],
        [0.0900, 0.2300, 0.1400, 0.3700, 0.5900, 1.1500]])

Set up the design matrix \(\mathbf{X}\) and response vector \(\mathbf{y}\):

genotype = fa_met["genotype"]
environment = fa_met["environment"]

y = torch.tensor(fa_met["yield"].values)
X = DummyMatrix(environment)()

Specifying the covariance

The covariance of the genotype-by-environment cell effects is a sum of a rank-\(k\) term and a diagonal term. Gram with gram_type="xxt" turns the free loading matrix into \(\boldsymbol{\Lambda}\boldsymbol{\Lambda}^\top\), and LowerTriangularMatrix provides the free entries of \(\boldsymbol{\Lambda}\) with the upper triangle fixed at zero:

Z = DummyMatrix(genotype, environment)

k = 2

G = KroneckerProduct(
    genotype=IdentityMatrix(genotype),
    environment=Sum(
        factors=Gram(
            loadings=LowerTriangularMatrix(environment, k),
            gram_type="xxt",
        ),
        uniqueness=DiagonalMatrix(environment),
    ),
)

reml = MixedModelREML(g_by_e=(Z, G), R=ScalarMatrix(len(y)))
  • DummyMatrix builds the \(1200 \times 600\) incidence matrix with one column per genotype-by-environment cell.

  • LowerTriangularMatrix builds the \(6 \times 2\) lower triangular matrix with 11 free entries \(\lambda_{00}, \lambda_{10}, \lambda_{11}, \ldots, \lambda_{50}, \lambda_{51}\), and a structural zero in the upper triangle.

  • DiagonalMatrix supplies the six uniquenesses \(\psi_j\).

  • KroneckerProduct forms \(\mathbf{I}_{100} \otimes \boldsymbol{\Sigma}\). The genotype factor is an IdentityMatrix, so it has no free parameters. All of the free parameters live in the environment factor.

  • ScalarMatrix supplies \(\mathbf{R} = \sigma^2 \mathbf{I}\). It could be omitted, since it is the default residual covariance, but it is written out here for clarity.

Parameter names and ordering

The free parameters are ordered \([\boldsymbol{\theta}_Z, \boldsymbol{\theta}_G, \boldsymbol{\theta}_R]\). Here \(\boldsymbol{\theta}_Z\) is empty, so the first parameters belong to the random-effect covariance and the last one to the residual.

names = reml.V.free_param_names
names
['G/environment/factors/loadings/L_0_0',
 'G/environment/factors/loadings/L_1_0',
 'G/environment/factors/loadings/L_1_1',
 'G/environment/factors/loadings/L_2_0',
 'G/environment/factors/loadings/L_2_1',
 'G/environment/factors/loadings/L_3_0',
 'G/environment/factors/loadings/L_3_1',
 'G/environment/factors/loadings/L_4_0',
 'G/environment/factors/loadings/L_4_1',
 'G/environment/factors/loadings/L_5_0',
 'G/environment/factors/loadings/L_5_1',
 'G/environment/uniqueness/sigma^2_0',
 'G/environment/uniqueness/sigma^2_1',
 'G/environment/uniqueness/sigma^2_2',
 'G/environment/uniqueness/sigma^2_3',
 'G/environment/uniqueness/sigma^2_4',
 'G/environment/uniqueness/sigma^2_5',
 'R/sigma^2']

The names follow the paths of the covariance tree:

  • G/environment/factors/loadings/L_i_j is the loading of environment \(i\) on factor \(j\).

  • G/environment/uniqueness/sigma^2_j is the uniqueness \(\psi_j\).

  • R/sigma^2 is the residual variance.

The loadings are unconstrained. The uniquenesses and the residual variance are parameterised on the log-variance scale, \(\psi_j = \exp(2\theta)\) and \(\sigma^2 = \exp(2\theta)\), so a free value of zero corresponds to a variance of one. In total the model has \(11 + 6 + 1 = 18\) free parameters.

Fitting the model

The model is fitted with the default "auto" method, which selects the C-form for this covariance structure:

names, theta_hat = reml.optimize(y, X, verbose=1)
[  1] ∥∇∥:     507.6734, ∥Δ∥: 6.5757, η: 0.50, ∥Δᶜ∥: 3.2878, accepted: True , log 𝓛: -526.9347
[  2] ∥∇∥:     106.2137, ∥Δ∥: 4.1414, η: 0.50, ∥Δᶜ∥: 2.0707, accepted: True , log 𝓛: -484.2801
[  3] ∥∇∥:      89.9396, ∥Δ∥: 8.0011, η: 0.12, ∥Δᶜ∥: 1.0001, accepted: True , log 𝓛: -478.8517
[  4] ∥∇∥:      80.3064, ∥Δ∥: 6.3980, η: 0.25, ∥Δᶜ∥: 1.5995, accepted: True , log 𝓛: -472.0562
[  5] ∥∇∥:      65.9411, ∥Δ∥: 3.3889, η: 0.50, ∥Δᶜ∥: 1.6945, accepted: True , log 𝓛: -460.0205
[  6] ∥∇∥:      58.0163, ∥Δ∥: 1.4945, η: 1.00, ∥Δᶜ∥: 1.4945, accepted: True , log 𝓛: -449.7713
[  7] ∥∇∥:      59.2477, ∥Δ∥: 1.0082, η: 1.00, ∥Δᶜ∥: 1.0082, accepted: True , log 𝓛: -442.0145
[  8] ∥∇∥:      39.1265, ∥Δ∥: 0.4969, η: 1.00, ∥Δᶜ∥: 0.4969, accepted: True , log 𝓛: -434.7584
[  9] ∥∇∥:      14.5894, ∥Δ∥: 0.2143, η: 1.00, ∥Δᶜ∥: 0.2143, accepted: True , log 𝓛: -433.7947
[ 10] ∥∇∥:       4.0579, ∥Δ∥: 0.0649, η: 1.00, ∥Δᶜ∥: 0.0649, accepted: True , log 𝓛: -433.7195
[ 11] ∥∇∥:       1.2253, ∥Δ∥: 0.0314, η: 1.00, ∥Δᶜ∥: 0.0314, accepted: True , log 𝓛: -433.7115
[ 12] ∥∇∥:       0.4508, ∥Δ∥: 0.0098, η: 1.00, ∥Δᶜ∥: 0.0098, accepted: True , log 𝓛: -433.7106
[ 13] ∥∇∥:       0.1530, ∥Δ∥: 0.0038, η: 1.00, ∥Δᶜ∥: 0.0038, accepted: True , log 𝓛: -433.7105
[ 14] ∥∇∥:       0.0562, ∥Δ∥: 0.0013, η: 1.00, ∥Δᶜ∥: 0.0013, accepted: True , log 𝓛: -433.7105
[ 15] ∥∇∥:       0.0196, ∥Δ∥: 0.0005, η: 1.00, ∥Δᶜ∥: 0.0005, accepted: True , log 𝓛: -433.7105
[ 16] ∥∇∥:       0.0071, ∥Δ∥: 0.0002, η: 1.00, ∥Δᶜ∥: 0.0002, accepted: True , log 𝓛: -433.7105
[ 17] ∥∇∥:       0.0025, ∥Δ∥: 0.0001, η: 1.00, ∥Δᶜ∥: 0.0001, accepted: True , log 𝓛: -433.7105

[∇: score, Δ: 𝐉⁻¹∇, η: step length, Δᶜ: clip(𝛉 + ηΔ, lb, ub) - 𝛉, 𝓛: restricted likelihood]

✓ Converged at iteration 17, total time: 1.44s

The columns of the iteration log are the norm of the score vector \(\lVert\nabla\rVert\), the length of the average-information step \(\lVert\Delta\rVert\), the step length \(\eta\) after any backtracking, the length of the clipped step actually taken \(\lVert\Delta^{c}\rVert\), whether the step was accepted, and the restricted log-likelihood. The fit converges in 17 iterations, in about a second and a half.

The fitted covariance-parameter vector is on the transformed scale: the first 11 entries are loadings, the next six are half-log uniquenesses, and the last is the half-log residual variance.

theta_hat
tensor([ 1.0415,  0.7377, -0.4160,  0.4099, -0.4198,  0.4374, -0.4983,  0.2225,
        -0.8084,  0.1063, -0.7854, -0.6087, -0.7816, -0.4924, -0.2082, -0.3351,
        -0.2155, -0.6066])

For interpretation, build_params() applies the transforms and returns the parameters on the model scale. It can return them as a name-keyed dictionary, which is convenient for picking out individual components:

params = reml.build_params(out_format="dict")
params
{'G/environment/factors/loadings/L_0_0': tensor([1.0415]),
 'G/environment/factors/loadings/L_1_0': tensor([0.7377]),
 'G/environment/factors/loadings/L_1_1': tensor([-0.4160]),
 'G/environment/factors/loadings/L_2_0': tensor([0.4099]),
 'G/environment/factors/loadings/L_2_1': tensor([-0.4198]),
 'G/environment/factors/loadings/L_3_0': tensor([0.4374]),
 'G/environment/factors/loadings/L_3_1': tensor([-0.4983]),
 'G/environment/factors/loadings/L_4_0': tensor([0.2225]),
 'G/environment/factors/loadings/L_4_1': tensor([-0.8084]),
 'G/environment/factors/loadings/L_5_0': tensor([0.1063]),
 'G/environment/factors/loadings/L_5_1': tensor([-0.7854]),
 'G/environment/uniqueness/sigma^2_0': tensor([0.2960]),
 'G/environment/uniqueness/sigma^2_1': tensor([0.2095]),
 'G/environment/uniqueness/sigma^2_2': tensor([0.3735]),
 'G/environment/uniqueness/sigma^2_3': tensor([0.6594]),
 'G/environment/uniqueness/sigma^2_4': tensor([0.5116]),
 'G/environment/uniqueness/sigma^2_5': tensor([0.6499]),
 'R/sigma^2': tensor([0.2972])}

The residual variance R/sigma^2 is estimated at \(\hat{\sigma}^2 \approx 0.30\), almost exactly the generating value of 0.3.

The covariance tree is often the most direct way to get at the matrices themselves. The fitted \(\boldsymbol{\Sigma}\) is at "G/environment", the loadings at "G/environment/factors/loadings", and the uniqueness matrix at "G/environment/uniqueness":

tree = reml.tree()

Sigma_hat = tree["G/environment"]
Lambda_hat = tree["G/environment/factors/loadings"]
Psi_hat = tree["G/environment/uniqueness"]
Psi_hat
tensor([[0.2960, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.2095, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.3735, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.6594, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.0000, 0.5116, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.6499]])

The estimated uniquenesses are in the right range but do not exactly match the generating values \((0.5, 0.4, 0.5, 0.6, 0.4, 0.5)\). This reflects sampling variability in estimating the genetic covariance structure from 100 genotypes, with the uniquenesses estimated jointly with the factor loadings. Such deviations are expected even when the model is correctly specified and successfully fitted.

The fitted loadings are a representative of the rotation orbit, and the sign of each column is arbitrary. Before comparing with the generating matrix, it is therefore natural to flip each column so that its leading entry is positive. The flip does not change \(\boldsymbol{\Sigma}\):

sign = torch.sign(torch.diagonal(Lambda_hat))
Lambda_aligned = Lambda_hat * sign

Lambda_aligned
tensor([[1.0415, -0.0000],
        [0.7377, 0.4160],
        [0.4099, 0.4198],
        [0.4374, 0.4983],
        [0.2225, 0.8084],
        [0.1063, 0.7854]])
loadings
tensor([[0.9000, 0.0000],
        [0.7000, 0.2000],
        [0.6000, 0.1000],
        [0.5000, 0.4000],
        [0.3000, 0.7000],
        [0.1000, 0.8000]])

The first factor captures the same broad pattern as the generator, with loadings that decline from early to late environments. The second factor is similarly dominated by the later environments, although its smaller loadings differ from the generating values. This reflects the trade-off between factor loadings and uniquenesses in the likelihood, making individual parameter estimates less stable than the covariance structure they jointly determine. Therefore, the appropriate quantity to compare with the generating values is \(\boldsymbol{\Sigma}\), rather than the individual loadings.

(Sigma_hat - Sigma_g).abs().max()
tensor(0.2346)
torch.corrcoef(torch.stack([Sigma_hat.flatten(), Sigma_g.flatten()]))[0, 1]
tensor(0.9490)

The fitted covariance has a correlation of approximately 0.95 with the generating covariance, with a maximum element-wise absolute error of approximately 0.23.

Recovery of the genotype-by-environment effects

The random-effect predictions can be obtained from blup_per_term(), which returns predictions keyed by term name. Here, there is a single term, “genotype”. Comparing these predictions with the generating effects in the genetic column assesses the fit at the individual genotype-by-environment level:

genetic = torch.tensor(fa_met.drop_duplicates(["genotype", "environment"])["genetic"].values)

blup = reml.blup_per_term()["g_by_e"]

torch.corrcoef(torch.stack([genetic, blup]))[0, 1]
tensor(0.9361)
(blup - genetic).pow(2).mean().sqrt()
tensor(0.3777)

The correlation is high, but the root mean squared error remains nonzero because the BLUPs are shrunk towards zero relative to the generating effects and are affected by estimation error in the covariance parameters.

Recovery of the fixed effects

The fixed effects are the environment means. Their estimates and standard errors are:

beta_hat = reml.blue()
se_beta = torch.sqrt(reml.var_blue())

beta_hat, se_beta
(tensor([5.2067, 5.4320, 4.7818, 5.1043, 5.3627, 4.9291]),
 tensor([0.1237, 0.1037, 0.0931, 0.1117, 0.1168, 0.1194]))

Compared with the generating means \((5.0, 5.2, 4.8, 5.1, 5.3, 4.9)\), all estimates are within approximately 2 standard errors.

Choosing the number of factors

In practice, \(k\) is unknown. A simple approach is to fit the model with \(k = 1, 2, 3\) and compare the restricted log-likelihoods. Since the fixed-effects structure is identical across fits, the AIC is \(-2\ell_R + 2p\), where \(p\) is the number of covariance parameters.

def fit_fa(k):
    G = KroneckerProduct(
        genotype=IdentityMatrix(genotype),
        environment=Sum(
            factors=Gram(
                LowerTriangularMatrix(environment, k),
                gram_type="xxt",
            ),
            uniqueness=DiagonalMatrix(environment),
        ),
    )
    model = MixedModelREML(g_by_e=(Z, G), R=ScalarMatrix(len(y)))
    names_k, _ = model.optimize(y, X, armijo_trials=5, fallback_eta=0.1)
    loglik_k = model.loglik()[0].item()
    p_k = len(names_k)
    return p_k, loglik_k, -2 * loglik_k + 2 * p_k

for k_k in (1, 2, 3):
    p_k, loglik_k, aic_k = fit_fa(k_k)
    print(f"k = {k_k}: p = {p_k}, loglik = {loglik_k:.3f}, AIC = {aic_k:.3f}")
k = 1: p = 13, loglik = -448.071, AIC = 922.143
k = 2: p = 18, loglik = -433.710, AIC = 903.421
k = 3: p = 22, loglik = -432.292, AIC = 908.584

AIC prefers two factors here, which is consistent with the generating model.

An unbalanced design

The trial above is balanced by construction, with every genotype appearing in every environment and two replicates per cell. Real multi-environment trials rarely have such a complete structure. Genotypes enter and leave testing at different sites, resulting in a ragged pattern of observed cells and different numbers of genotypes across environments. In this second part, cells are removed from the simulated trial while retaining both replicates in every remaining cell. Each genotype is grown in three of the six environments, selected at random using a fixed seed to ensure reproducibility.

Removing cells changes only the data. The model, parameterisation and number of free parameters remain the same as in the first part. The difference lies in how much information the data provide about those parameters.

The unbalanced trial

env_levels = sorted(fa_met["environment"].unique())
gen_levels = sorted(fa_met["genotype"].unique())

generator = torch.Generator().manual_seed(20261120)
missing = {}
for genotype in gen_levels:
    picks = torch.randperm(len(env_levels), generator=generator)[:3]
    missing[genotype] = {env_levels[i] for i in picks.tolist()}

keep = [
    environment not in missing[genotype]
    for genotype, environment in zip(fa_met["genotype"], fa_met["environment"])
]
unbalanced = fa_met[keep].reset_index(drop=True)

unbalanced.head()
genotype environment rep yield genetic
0 001 02 1 4.614127 -0.638617
1 001 02 2 4.455589 -0.638617
2 001 04 1 5.997604 0.150623
3 001 04 2 4.610560 0.150623
4 001 05 1 4.631243 -0.792489

Each genotype retains three randomly selected environments, with both replicates in each. missing records the environments omitted for each genotype.

The resulting subset contains 600 observations across 300 genotype–environment cells, with between 42 and 55 genotypes per environment, down from 100:

unbalanced.drop_duplicates(["genotype", "environment"]).groupby("environment").size()
environment
01    51
02    55
03    42
04    51
05    48
06    53
dtype: int64

The fixed and random effects are declared exactly as before:

y_u = torch.tensor(unbalanced["yield"].values)
X_u = DummyMatrix(unbalanced["environment"], levels=[env_levels])()
Z_u = DummyMatrix(unbalanced["genotype"], unbalanced["environment"])

The covariance is built from the same classes as in the first part:

G_u = KroneckerProduct(
    genotype=IdentityMatrix(gen_levels),
    environment=Sum(
        factors=Gram(LowerTriangularMatrix(env_levels, 2), gram_type="xxt"),
        uniqueness=DiagonalMatrix(env_levels),
    ),
)

model_u = MixedModelREML(genotype=(Z_u, G_u), R=ScalarMatrix(len(y_u)))

Fitting the unbalanced trial

names_u, theta_u = model_u.optimize(y_u, X_u, verbose=1)
[  1] ∥∇∥:     232.4998, ∥Δ∥: 7.1491, η: 0.50, ∥Δᶜ∥: 3.5746, accepted: True , log 𝓛: -300.7863
[  2] ∥∇∥:      41.6616, ∥Δ∥: 6.3930, η: 0.25, ∥Δᶜ∥: 1.5982, accepted: True , log 𝓛: -288.0995
[  3] ∥∇∥:      42.2211, ∥Δ∥: 2.8327, η: 1.00, ∥Δᶜ∥: 2.8327, accepted: True , log 𝓛: -280.0281
[  4] ∥∇∥:      24.9921, ∥Δ∥: 15.8148, η: 0.12, ∥Δᶜ∥: 1.9768, accepted: True , log 𝓛: -279.2710
[  5] ∥∇∥:      22.9592, ∥Δ∥: 4.9669, η: 0.25, ∥Δᶜ∥: 1.2417, accepted: True , log 𝓛: -274.6874
[  6] ∥∇∥:      20.5298, ∥Δ∥: 19.6949, η: 1.00, ∥Δᶜ∥: 19.6949, accepted: True , log 𝓛: -269.6175
[  7] ∥∇∥:      12.7599, ∥Δ∥: 0.4775, η: 1.00, ∥Δᶜ∥: 0.4775, accepted: True , log 𝓛: -267.5594
[  8] ∥∇∥:       6.1950, ∥Δ∥: 0.1315, η: 1.00, ∥Δᶜ∥: 0.1315, accepted: True , log 𝓛: -267.2806
[  9] ∥∇∥:       0.4922, ∥Δ∥: 0.0171, η: 1.00, ∥Δᶜ∥: 0.0171, accepted: True , log 𝓛: -267.2773
[ 10] ∥∇∥:       0.0444, ∥Δ∥: 0.0067, η: 1.00, ∥Δᶜ∥: 0.0067, accepted: True , log 𝓛: -267.2773
[ 11] ∥∇∥:       0.0096, ∥Δ∥: 0.0005, η: 1.00, ∥Δᶜ∥: 0.0005, accepted: True , log 𝓛: -267.2773
[ 12] ∥∇∥:       0.0015, ∥Δ∥: 0.0004, η: 1.00, ∥Δᶜ∥: 0.0004, accepted: True , log 𝓛: -267.2773
[ 13] ∥∇∥:       0.0004, ∥Δ∥: 0.0000, η: 1.00, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛: -267.2773

[∇: score, Δ: 𝐉⁻¹∇, η: step length, Δᶜ: clip(𝛉 + ηΔ, lb, ub) - 𝛉, 𝓛: restricted likelihood]

✓ Converged at iteration 13, total time: 0.80s

The residual variance, against a generating value of 0.3, is

model_u.build_params(out_format="dict")["R/sigma^2"]
tensor([0.3389])

Recovery of the covariance

tree_u = model_u.tree()
Sigma_u = tree_u["G/environment"]
Psi_u = tree_u["G/environment/uniqueness"]
Psi_u
tensor([[0.2305, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.4881, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.1667, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.6493, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.8802]])

The uniquenesses are noisier. The fifth is estimated to be zero, or rather, so close to zero that it prints as zero. Since uniquenesses are exponentiated, no finite parameter estimate can reach the boundary. However, the optimizer pushes the unconstrained parameter far into the negative region, causing \(e^{2\theta}\) to underflow. This reflects a flat direction in the likelihood: the two factors can explain almost all of environment 5’s variance.

torch.corrcoef(torch.stack([Sigma_u.flatten(), Sigma_g.flatten()]))[0, 1]
tensor(0.9045)
(Sigma_u - Sigma_g).abs().max()
tensor(0.3837)

The correlation with the generating covariance drops slightly, and the largest entry-wise error grows.

Recovery of the genotype-by-environment effects

The practical reason for fitting the covariance is to predict the cells that were not observed. The BLUPs of the 600 cell effects are

blup_u = model_u.blup_per_term()["genotype"]
seen = (Z_u() != 0).any(dim=0)

seen marks the 300 cells that have observations.

def corr(x, y):
    return torch.corrcoef(torch.stack([x, y]))[0, 1]

def rmse(x, y):
    return (x - y).pow(2).mean().sqrt()

Against the generating effects, the cells with observations are predicted as

corr(genetic[seen], blup_u[seen])
tensor(0.9366)
rmse(genetic[seen], blup_u[seen])
tensor(0.3722)

and the cells without observations as

corr(genetic[~seen], blup_u[~seen])
tensor(0.5017)
rmse(genetic[~seen], blup_u[~seen])
tensor(0.8858)
blup_u[~seen].std(), genetic[~seen].std()
(tensor(0.5971), tensor(1.0037))

The observed cells are predicted as well as before. The unobserved cells are not simply left at zero. Their BLUPs are given by

\[\text{BLUP} = \mathbf{G}\mathbf{Z}^\top\mathbf{V}^{-1}\mathbf{r},\]

and the rows of \(\mathbf{G}\) corresponding to unobserved cells are correlated with those of the same genotype’s observed cells. Through \(\boldsymbol{\Sigma}\), the model therefore borrows information from the environments where the genotype was grown. The resulting predictions have a correlation of 0.50 with the generating effects and an RMSE of 0.89.

Two factors limit their accuracy. First, the covariance is estimated, so the prediction weights are estimated rather than known. Second, the observed effects are themselves shrunk, providing a shrunken basis for predicting the missing cells. The standard deviation of the unobserved BLUPs is 0.60, compared with 1.00 for the generating values. This shrinkage pulls predictions towards the mean, under-predicting good genotypes and over-predicting poor ones.

Choosing the number of factors

The comparison of the previous section has to be repeated on the reduced data:

def fit_fa_u(k):
    G = KroneckerProduct(
        genotype=IdentityMatrix(gen_levels),
        environment=Sum(
            factors=Gram(
                LowerTriangularMatrix(env_levels, k),
                gram_type="xxt",
            ),
            uniqueness=DiagonalMatrix(env_levels),
        ),
    )
    model = MixedModelREML(genotype=(Z_u, G), R=ScalarMatrix(len(y_u)))
    names_k, _ = model.optimize(y_u, X_u, armijo_trials=5, fallback_eta=0.1)
    loglik_k = model.loglik()[0].item()
    p_k = len(names_k)
    return p_k, loglik_k, -2 * loglik_k + 2 * p_k

for k_k in (1, 2, 3):
    p_k, loglik_k, aic_k = fit_fa_u(k_k)
    print(f"k = {k_k}: p = {p_k}, loglik = {loglik_k:.3f}, AIC = {aic_k:.3f}")
k = 1: p = 13, loglik = -270.979, AIC = 567.959
k = 2: p = 18, loglik = -267.277, AIC = 570.555
k = 3: p = 22, loglik = -267.017, AIC = 578.035

AIC now favours one factor, 568.0 compared with 570.6 for two factors, reversing the result from the balanced analysis. Although the covariance is still recovered, there is little evidence for the second factor. The \(k=2\) fit also had to push one uniqueness to zero to accommodate it.

A difference of 2.6 provides only weak evidence, and this is a simulated trial whose true number of factors is two. The conclusion is not that the model has one factor, but that 300 observed cells provide too little information to distinguish between the two.