Introduction to Mixed Model REML Estimation

The MixedModelREML class implements restricted maximum likelihood (REML) estimation for linear mixed models, using the average information (AI) algorithm. The AI algorithm combines the stability of the expected information matrix with the curvature information of the observed information matrix, leading to efficient and robust estimation of covariance parameters.

This vignette introduces the mixed model formulation, explains how to specify random-effect and residual terms, demonstrates optimisation workflows, and covers post-estimation utilities such as BLUEs, BLUPs, marginal predictions, residuals, and convergence diagnostics.

The model

The MixedModelREML class assumes the linear mixed model

\[\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \sum_{i=1}^{b}\mathbf{Z}_i(\boldsymbol{\theta})\mathbf{u}_i + \boldsymbol{\epsilon}, \qquad \mathbf{u}_i \sim \mathcal{N}(\mathbf{0}, \mathbf{G}_i(\boldsymbol{\theta})), \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{R}(\boldsymbol{\theta})),\]

where

  • \(\mathbf{y}\) is the response vector of length \(n\),

  • \(\mathbf{X}\) is the fixed-effects design matrix,

  • \(\boldsymbol{\beta}\) is the vector of fixed effects,

  • \(b\) is the number of random-effect terms,

  • \(\mathbf{Z}_i(\boldsymbol{\theta})\) is the incidence matrix of the \(i\)-th random-effect term, which may be fixed or parameterised,

  • \(\mathbf{u}_i\) is the vector of random effects of the \(i\)-th term,

  • \(\mathbf{G}_i(\boldsymbol{\theta})\) is the covariance matrix of \(\mathbf{u}_i\),

  • \(\boldsymbol{\epsilon}\) is the vector of residual errors, and

  • \(\mathbf{R}(\boldsymbol{\theta})\) is the residual covariance matrix.

The random effects and the residual errors are independent, so the response has the marginal distribution

\[\mathbf{y} \sim \mathcal{N}(\mathbf{X}\boldsymbol{\beta}, \mathbf{V}(\boldsymbol{\theta})),\]

where the marginal covariance matrix is

\[\mathbf{V}(\boldsymbol{\theta}) = \mathbf{R}(\boldsymbol{\theta}) + \sum_{i=1}^{b} \mathbf{Z}_i(\boldsymbol{\theta}) \mathbf{G}_i(\boldsymbol{\theta}) \mathbf{Z}_i(\boldsymbol{\theta})^\top,\]

with \(\boldsymbol{\theta}\) the variance-component vector collecting the parameters of the random-effect covariances, the residual covariance, and any parameterised incidence matrices.

The REML estimator maximises the restricted log-likelihood

\[\ell_R(\boldsymbol{\theta}) = -\frac{1}{2} \Bigl( \log |\mathbf{V}| + \log |\mathbf{X}^\top \mathbf{V}^{-1} \mathbf{X}| + \mathbf{y}^\top \mathbf{P} \mathbf{y} \Bigr),\]

where

\[\mathbf{P} = \mathbf{V}^{-1} - \mathbf{V}^{-1}\mathbf{X} \left( \mathbf{X}^\top \mathbf{V}^{-1}\mathbf{X} \right)^{-1} \mathbf{X}^\top \mathbf{V}^{-1}\]

is the residual projection matrix.

The C-form evaluates the same log-likelihood without forming \(\mathbf{V}\). Write \(\mathbf{Z}\) for the combined incidence matrix of all \(b\) terms and \(\mathbf{G}\) for the block-diagonal covariance of their random effects, and let

\[\mathbf{W} = [\mathbf{X}, \mathbf{Z}], \qquad \mathbf{C} = \mathbf{W}^\top \mathbf{R}^{-1} \mathbf{W} + \operatorname{blockdiag}(\mathbf{0}, \mathbf{G}^{-1}), \qquad \mathbf{U} = \mathbf{R}^{-1}\mathbf{W}.\]

The projection matrix is then

\[\mathbf{P} = \mathbf{R}^{-1} - \mathbf{U}\mathbf{C}^{-1}\mathbf{U}^\top,\]

and the restricted log-likelihood becomes

\[\ell_R(\boldsymbol{\theta}) = -\frac{1}{2} \Bigl( \log |\mathbf{C}| + \log |\mathbf{R}| + \log |\mathbf{G}| + \mathbf{y}^\top \mathbf{P} \mathbf{y} \Bigr),\]

which involves only \(\mathbf{C}\), \(\mathbf{R}\) and \(\mathbf{G}\). This is the form used by CForm.

Important

Internally, MixedModelREML repeatedly evaluates

  • the score vector,

  • and the average information matrix,

until convergence criteria are satisfied. The default CForm method derives these from the random-effect and residual covariances \(\mathbf{Z}_i\), \(\mathbf{G}_i\) and \(\mathbf{R}\) and their derivatives, forming the projection \(\mathbf{P}\) from that block structure without ever assembling the \(n \times n\) marginal covariance \(\mathbf{V}\). The alternative Marginal method instead evaluates \(\mathbf{V}\) and its derivatives \(\partial \mathbf{V} / \partial \theta_k\) directly.

Constructing the REML object

The MixedModelREML constructor accepts random-effect terms as (design, covariance) pairs, where design is the incidence matrix \(\mathbf{Z}_i\) and covariance represents \(\mathbf{G}_i\). Terms can be supplied positionally or by keyword. Positional terms are named random_term_0, random_term_1, and so on, in the order supplied, and precede keyword terms. Keyword names must be unique and cannot be R or method. Each term name defines a namespace for its parameters and serves as the key in post-estimation methods that report results by term, such as blup_per_term().

Both design and covariance can be specified as either a tensor or a Matrix. Tensors are treated as fixed matrices, while Matrix objects may contain free parameters that are estimated jointly with the other model parameters.

The residual covariance R accepts either a Matrix or a two-dimensional tensor. If omitted, it defaults to \(\sigma^2 \mathbf{I}\), with its dimension inferred from the random-effect design. It must be supplied explicitly when the model has no random-effect terms.

from torch_openreml import MixedModelREML

reml = MixedModelREML((Z, G), R=R)

Via SimpleMatrix (function-based)

For quick prototyping, SimpleMatrix provides a convenient way to define a matrix through a user-supplied function. All parameters are free and unconstrained, so transformations can be applied within the function to enforce parameter constraints.

import torch
from torch_openreml import MixedModelREML
from torch_openreml.covariance import SimpleMatrix

n = 50

def my_r(theta):
    sigma2 = theta[0].exp()
    rho = torch.sigmoid(theta[1])

    I = torch.eye(n)
    J = torch.ones(n, n)

    return sigma2 * (I + rho * J)

R = SimpleMatrix(num_free_params=2, call=my_r)
reml = MixedModelREML(R=R)

In this example:

  • theta[0] controls the variance scale through an exponential transformation.

  • theta[1] controls the correlation parameter through a sigmoid transformation.

The resulting residual covariance matrix is

\[\mathbf{R} = \sigma^2 (\mathbf{I} + \rho \mathbf{J}),\]

where \(\mathbf{J}\) is the all-ones matrix.

The supplied function is automatically differentiated by PyTorch, so no derivative code is required.

SimpleMatrix can also be used to define design matrices \(\mathbf{Z}_i\) and random-effect covariance matrices \(\mathbf{G}_i\). For example, the following defines a diagonal random-effect covariance matrix with an estimated variance parameter:

def my_g(theta):
    sigma2 = theta[0].exp()
    return sigma2 * torch.eye(3)

G = SimpleMatrix(num_free_params=1, call=my_g)

Z = torch.eye(3)
reml = MixedModelREML((Z, G))

The gradient can also be supplied manually through the manual_grad argument. This is useful when analytical derivatives are available and can be computed more efficiently than automatic differentiation, particularly for computationally expensive matrix constructions. For the diagonal covariance matrix above, the analytical gradient is:

def my_g_grad(theta):
    sigma2 = theta[0].exp()
    return (sigma2 * torch.eye(3)).unsqueeze(0)

G = SimpleMatrix(num_free_params=1, call=my_g, manual_grad=my_g_grad)

reml = MixedModelREML((Z, G))

The gradient function returns a tensor of shape (num_free_params, *matrix_shape), where each slice along the first dimension contains the derivative of the matrix with respect to the corresponding parameter. Here, the shape is (1, 3, 3).

Via a covariance Matrix builder

When a covariance structure matches one of the built-in structures, it is generally clearer to construct it using the covariance builders rather than defining it manually.

The covariance builder API provides reusable components, including:

These components can be combined using composition operators, including:

For example:

from torch_openreml.covariance import IdentityMatrix, KroneckerProduct
from torch_openreml.example_data import john_alpha

gen, rep, block = john_alpha["gen"], john_alpha["rep"], john_alpha["block"]

reml = MixedModelREML(
    gen=(DummyMatrix(gen), ScalarMatrix(gen)),
    block=(
        DummyMatrix(rep, block),
        KroneckerProduct(IdentityMatrix(rep), ScalarMatrix(block)),
    )
)

The covariance builders handle the underlying implementation, including:

  • Parameter bookkeeping and transformations.

  • Construction of the design matrices \(\mathbf{Z}_i\), random-effect covariance matrices \(\mathbf{G}_i\), and residual covariance matrix \(\mathbf{R}\).

  • Computation of component derivatives.

Note

Internally, MixedModelREML calls __call__() to construct each matrix component and grad() to compute its Jacobian. The gradient implementation first attempts to use a closed-form manual_grad() implementation and falls back to automatic differentiation when one is not available.

Parameter names and ordering

The free parameters in \(\boldsymbol{\theta}\) are named according to their associated term and matrix. Since these are the same parameters used to construct the marginal covariance matrix, their names can be inspected before fitting:

n, n_env = 50, 5
environment = [f"env{i % n_env}" for i in range(n)]
genotype = ["a", "b"] * 25

reml = MixedModelREML(
    env=(DummyMatrix(environment), CompoundSymmetricMatrix(environment)),
    gen=(DummyMatrix(genotype), ScalarMatrix(genotype))
)
reml.V.free_param_names

which returns:

['G/env/sigma^2', 'G/env/rho', 'G/gen/sigma^2', 'R/sigma^2']

The parameters are ordered as \([\boldsymbol{\theta}_{Z}, \boldsymbol{\theta}_{G}, \boldsymbol{\theta}_{R}]\).

Choosing the numerical method

The method argument controls how the score vector and average information matrix are computed. By default, "auto" uses the C-form when applicable and falls back to the \(\mathbf{V}\)-based marginal method otherwise. The "cform" and "marginal" options force the corresponding method:

reml = MixedModelREML(
    genotype=(DummyMatrix(genotype), ScalarMatrix(genotype)),
    method="marginal",
)

You can also pass a configured method instance to customise its options, such as the trace approximation used by the marginal method:

from torch_openreml.methods import Marginal

reml = MixedModelREML(
    genotype=(DummyMatrix(genotype), ScalarMatrix(genotype)),
    method=Marginal(trace_approx="auto"),
)

Running the optimiser

Once the REML object is constructed, optimisation is performed with optimize():

import torch

from torch_openreml import MixedModelREML
from torch_openreml.covariance import DummyMatrix, ScalarMatrix

n, p = 10, 2

group = ["a", "b"] * 5
effect = torch.tensor([1.0, -1.0]).repeat(n // 2)

X = torch.randn(n, p)
y = X @ torch.tensor([0.5, -0.5]) + effect + 0.5 * torch.randn(n)

reml = MixedModelREML(
    genotype=(DummyMatrix(group), ScalarMatrix(group)),
)

names, free_params = reml.optimize(y, X, verbose=1)
names, free_params
[  1] ∥∇∥:       3.2245, ∥Δ∥: 0.5514, η: 1.00, ∥Δᶜ∥: 0.5514, accepted: True , log 𝓛:  -5.5253
[  2] ∥∇∥:       2.3492, ∥Δ∥: 0.1410, η: 1.00, ∥Δᶜ∥: 0.1410, accepted: True , log 𝓛:  -5.3458
[  3] ∥∇∥:       0.2984, ∥Δ∥: 0.0241, η: 1.00, ∥Δᶜ∥: 0.0241, accepted: True , log 𝓛:  -5.3422
[  4] ∥∇∥:       0.0070, ∥Δ∥: 0.0006, η: 1.00, ∥Δᶜ∥: 0.0006, accepted: True , log 𝓛:  -5.3422
[  5] ∥∇∥:       0.0000, ∥Δ∥: 0.0000, η: 0.50, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛:  -5.3422

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

✓ Converged at iteration 5, total time: 0.01s

(['G/sigma^2', 'R/sigma^2'], tensor([-0.1667, -0.3574]))

Inputs

y

Response vector of shape (n,).

X

Fixed-effects design matrix of shape (n, p).

init_values

Initial values for the covariance parameters, ordered according to reml.V.free_param_names. If omitted, the model’s default initial values are used. Providing explicit starting values can improve convergence, particularly for complex covariance structures.

Returned values

names

Names of the covariance parameters.

free_params

Final covariance-parameter estimates, in the same order as names.

The update step

At iteration \(t\), the optimiser evaluates the score vector \(\mathbf{s}\) and the average-information matrix \(\mathbf{AI}\) at the current parameter estimate \(\boldsymbol{\theta}^{(t)}\):

\[s_k = \frac{1}{2} \left( \mathbf{y}^{\top} \mathbf{P} \frac{\partial \mathbf{V}}{\partial \theta_k} \mathbf{P} \mathbf{y} - \operatorname{tr}\!\left( \mathbf{P} \frac{\partial \mathbf{V}}{\partial \theta_k} \right) \right),\]
\[\mathrm{AI}_{kj} = \frac{1}{2}\, \mathbf{y}^{\top} \mathbf{P} \frac{\partial \mathbf{V}}{\partial \theta_k} \mathbf{P} \frac{\partial \mathbf{V}}{\partial \theta_j} \mathbf{P} \mathbf{y},\]

where

\[\mathbf{P} = \mathbf{V}^{-1} - \mathbf{V}^{-1}\mathbf{X} (\mathbf{X}^{\top}\mathbf{V}^{-1}\mathbf{X})^{-1} \mathbf{X}^{\top}\mathbf{V}^{-1}.\]

The CForm method computes these quantities without explicitly forming \(\mathbf{V}\).

The AI direction is obtained by solving \(\mathbf{AI}\,\boldsymbol{\delta} = \mathbf{s}\) in the least-squares sense. Given a step length \(\eta\), the candidate parameter update is

\[\boldsymbol{\theta}^{c} = \mathrm{clip}\!\left( \boldsymbol{\theta}^{(t)} + \eta \, \boldsymbol{\delta}, \mathrm{lb}, \mathrm{ub} \right).\]

The candidate is accepted if it satisfies the Armijo sufficient-increase condition:

\[\ell_R\!\left(\boldsymbol{\theta}^{c}\right) \geq \ell_R\!\left(\boldsymbol{\theta}^{(t)}\right) + c \, \eta \, \mathbf{s}^{\top} \boldsymbol{\delta} - \epsilon \, \max\!\left( 1, \left|\ell_R\!\left(\boldsymbol{\theta}^{(t)}\right)\right| \right),\]

where \(c\) and \(\epsilon\) correspond to armijo_c and armijo_slack, respectively.

If the condition is not satisfied, the step length is reduced according to

\[\eta \leftarrow \texttt{eta\_shrink} \times \eta,\]

and the candidate is evaluated again. This backtracking continues for at most armijo_trials attempts and stops if \(\eta\) falls below eta_min.

If no candidate is accepted, the optimiser takes a single normalised gradient step as a fallback:

\[\boldsymbol{\theta}^{(t+1)} = \mathrm{clip}\!\left( \boldsymbol{\theta}^{(t)} + \texttt{fallback\_eta}\, \frac{\mathbf{s}}{\max(\|\mathbf{s}\|, 1)}, \mathrm{lb}, \mathrm{ub} \right).\]

This fallback step is recorded as not accepted. After each iteration, the step length is reset to eta_max.

Optimisation controls

max_iter (default 200)

Maximum number of AI iterations.

verbose (default 0)

If positive, print one line per iteration showing the score norm \(\|\nabla\|\), the AI step norm \(\|\Delta\|\), the step length \(\eta\), the clipped step norm \(\|\Delta^{c}\|\), whether the step was accepted, and the restricted log-likelihood. A legend, the convergence status and the total optimisation time are printed at the end.

lb and ub (default -torch.inf and torch.inf)

Lower and upper bounds applied to the free parameters. Each can be a scalar float or a tensor broadcastable to the free-parameter vector, allowing per-parameter bounds. If either is specified as a tensor, both must be tensors. Bounds apply to the untransformed parameter values, before any covariance parameter transformations. For example, lb=0 on a variance parameter constrains its underlying parameter to be non-negative, rather than constraining the variance itself to be non-negative. Each candidate update is clipped to [lb, ub] before evaluating the log-likelihood.

eta_max (default 1.0)

Initial and maximum step length. Every iteration starts from eta_max and backtracks from there.

eta_shrink (default 0.5)

Multiplier applied to the step length after each rejected candidate.

eta_min (default 1e-10)

Backtracking stops once the step length falls below eta_min.

armijo_trials (default 30)

Maximum number of backtracking candidates tried per iteration.

armijo_c (default 1e-4) and armijo_slack (default 1e-7)

Constants \(c\) and \(\epsilon\) in the acceptance test defined in the update step. The last term is numerical slack; set armijo_slack=0 for a strict Armijo test.

fallback_eta (default 1e-3)

Step length of the normalised gradient step taken when no candidate is accepted.

Convergence criteria

Two checks are available.

Parameter update

The largest absolute component of the clipped step must satisfy

\[\max_i |\Delta_i^{c}| < \texttt{tol\_update}.\]
Log-likelihood change

The restricted log-likelihood change must satisfy

\[\left| \ell_R^{(t)} - \ell_R^{(t-1)} \right| < \texttt{tol\_loglik}.\]

The defaults are tol_update = 1e-4 and tol_loglik = 1e-4. Both enabled checks must pass simultaneously, and at least two iterations are required before convergence can be declared. Either check can be disabled with check_update=False or check_loglik=False. is_converged() reports whether the last recorded iteration met the criteria.

Optimisation history

Every iteration of optimize() is appended to reml.history, a dict of lists that is reset when a new optimisation starts; it is None until optimize has run. Each list holds one entry per iteration, where k is the number of free parameters:

free_params

Covariance parameters after the step, shape (k,).

loglik

Restricted log-likelihood at the new parameters, a scalar tensor.

score

Score vector used to compute the step, shape (k,).

ai

Average information matrix, shape (k, k).

delta

AI direction, the least-squares solution of \(\mathbf{AI}\,\boldsymbol{\delta} = \mathbf{s}\), shape (k,).

update

Clipped step actually taken, shape (k,).

eta

Step length used, which is below eta_max when backtracking shortened it.

accepted

True for an accepted Newton step and False for a gradient fallback step.

method

"cform" or "marginal" for that iteration.

history = reml.history
history["loglik"]
[tensor(-5.5253),
 tensor(-5.3458),
 tensor(-5.3422),
 tensor(-5.3422),
 tensor(-5.3422)]

Stacking a list gives the trajectory, for example the log-likelihood:

torch.stack(history["loglik"])
tensor([-5.5253, -5.3458, -5.3422, -5.3422, -5.3422])

or the covariance parameters:

torch.stack(history["free_params"])
tensor([[-0.1784, -0.5217],
        [-0.1623, -0.3817],
        [-0.1665, -0.3579],
        [-0.1667, -0.3574],
        [-0.1667, -0.3574]])

Post-estimation methods

After optimisation, the fitted REML object provides several utilities for extracting estimates and predictions.

Retrieving parameter estimates

get_free_params(select=”last”)

Return (names, free_params). select="best" selects the iterate with the largest recorded log-likelihood, which is useful when optimisation overshoots or oscillates near convergence.

names, theta_hat = reml.get_free_params("last")
names, theta_hat
(['G/sigma^2', 'R/sigma^2'], tensor([-0.1667, -0.3574]))
build_params(free_params=None, include_fixed=True, trans=True, out_format=”tensor”)

Build the covariance parameters from the free parameters. By default, trans=True applies each parameter’s transformation, returning values on the model scale. trans=False returns the untransformed values. Set out_format="dict" to return a name-keyed mapping, or include_fixed=False to exclude fixed parameters.

params = reml.build_params("last", out_format="dict")
params
{'G/sigma^2': tensor([0.7165]), 'R/sigma^2': tensor([0.4893])}
tree(free_params=None)

Evaluate the covariance structure and return the matrix at each node, keyed by its path in the operand tree. The root path "/" contains the marginal covariance \(\mathbf{V}\). Other paths identify the model components: "Z" contains the combined random-effect design, with individual terms under "Z/<term>"; "G" contains the block-diagonal random-effect covariance, with individual terms under "G/<term>"; and "R" contains the residual covariance.

Nested builders contribute additional paths using their operand names. For example, a term constructed with KroneckerProduct adds paths such as "G/block/op_0" and "G/block/op_1". Each entry contains the evaluated matrix at that level, allowing the dimensions of individual components and how they combine to be inspected. If the model has no random-effect terms, the tree contains only {"/": V}.

tree = reml.tree("last")
tree
{'/': tensor([[1.2059, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165,
          0.0000],
         [0.0000, 1.2059, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000,
          0.7165],
         [0.7165, 0.0000, 1.2059, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165,
          0.0000],
         [0.0000, 0.7165, 0.0000, 1.2059, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000,
          0.7165],
         [0.7165, 0.0000, 0.7165, 0.0000, 1.2059, 0.0000, 0.7165, 0.0000, 0.7165,
          0.0000],
         [0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 1.2059, 0.0000, 0.7165, 0.0000,
          0.7165],
         [0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 1.2059, 0.0000, 0.7165,
          0.0000],
         [0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 1.2059, 0.0000,
          0.7165],
         [0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 1.2059,
          0.0000],
         [0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000, 0.7165, 0.0000,
          1.2059]]),
 'Z': tensor([[1., 0.],
         [0., 1.],
         [1., 0.],
         [0., 1.],
         [1., 0.],
         [0., 1.],
         [1., 0.],
         [0., 1.],
         [1., 0.],
         [0., 1.]]),
 'G': tensor([[0.7165, 0.0000],
         [0.0000, 0.7165]]),
 'R': tensor([[0.4893, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000],
         [0.0000, 0.4893, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000],
         [0.0000, 0.0000, 0.4893, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000],
         [0.0000, 0.0000, 0.0000, 0.4893, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.4893, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.4893, 0.0000, 0.0000, 0.0000,
          0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.4893, 0.0000, 0.0000,
          0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.4893, 0.0000,
          0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.4893,
          0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.4893]])}

Fixed effects

The BLUE of the fixed effects is

\[\widehat{\boldsymbol{\beta}} = \left(\mathbf{X}^\top \mathbf{V}^{-1} \mathbf{X}\right)^{-1} \mathbf{X}^\top \mathbf{V}^{-1} \mathbf{y}.\]
blue(y=None, x=None, free_params=None)

Fixed-effect estimates of shape (p,).

beta_hat = reml.blue(y, X, theta_hat)
beta_hat
tensor([ 0.1491, -0.1059])
cov_blue(x=None, free_params=None)

Covariance matrix of the BLUE, shape (p, p).

cov_beta = reml.cov_blue(X, theta_hat)
cov_beta
tensor([[ 0.0803, -0.0063],
        [-0.0063,  0.0468]])
var_blue(x=None, free_params=None)

Sampling variances, the diagonal of cov_blue.

se_beta = torch.sqrt(reml.var_blue(X, theta_hat))
se_beta
tensor([0.2834, 0.2164])

Random effects

The BLUP of the random effects is

\[\widehat{\mathbf{b}} = \mathbf{G}\mathbf{Z}^\top\mathbf{V}^{-1} \left(\mathbf{y} - \mathbf{X}\widehat{\boldsymbol{\beta}}\right),\]

with covariance \(\operatorname{Var}(\widehat{\mathbf{b}}) = \mathbf{G}\mathbf{Z}^\top\mathbf{P}\mathbf{Z}\mathbf{G}\).

blup(y=None, x=None, free_params=None)

Random-effect predictions of shape (q,).

b_hat = reml.blup()
b_hat
tensor([ 0.9518, -0.5837])
cov_blup(x=None, free_params=None)

Covariance matrix of the BLUPs, shape (q, q).

b_cov = reml.cov_blup()
b_cov
tensor([[ 0.6188, -0.0020],
        [-0.0020,  0.6278]])
var_blup(x=None, free_params=None)

BLUP sampling variances, the diagonal of cov_blup.

b_var = reml.var_blup()
b_var
tensor([0.6188, 0.6278])
blup_per_term(y=None, x=None, free_params=None)

BLUPs split by random-effect term, as a dict keyed by term name.

b_by_term = reml.blup_per_term()
b_by_term
{'genotype': tensor([ 0.9518, -0.5837])}
cov_blup_per_term(x=None, free_params=None)

Diagonal blocks of cov_blup, one per term, as a dict.

b_cov_by_term = reml.cov_blup_per_term()
b_cov_by_term
{'genotype': tensor([[ 0.6188, -0.0020],
         [-0.0020,  0.6278]])}
var_blup_per_term(x=None, free_params=None)

Term-wise sampling variances, as a dict.

b_var_by_term = reml.var_blup_per_term()
b_var_by_term
{'genotype': tensor([0.6188, 0.6278])}

Predictions

marginal_predict(y=None, x=None, free_params=None)

Marginal fitted values \(\mathbf{X}\widehat{\boldsymbol{\beta}}\).

y_marginal = reml.marginal_predict()
y_marginal
tensor([ 0.2085,  0.2068, -0.0635, -0.0856, -0.3319, -0.1261, -0.1581, -0.0698,
        -0.0692,  0.0351])
predict(y=None, x=None, free_params=None)

Conditional fitted values \(\mathbf{X}\widehat{\boldsymbol{\beta}} + \mathbf{Z}\widehat{\mathbf{b}}\). For a model with no random-effect terms this reduces to marginal_predict.

y_conditional = reml.predict()
y_conditional
tensor([ 1.1603, -0.3769,  0.8882, -0.6693,  0.6199, -0.7098,  0.7937, -0.6535,
         0.8825, -0.5485])
predict_new(x, z=None, free_params=None)

Predict responses for new observations using pre-built design matrices. The z argument accepts a full (n_new, q) tensor, a list of design blocks (one per random-effect term), or a dictionary keyed by term name. Terms omitted from a dictionary contribute zero. If z=None, predictions use only the fixed effects, giving the population-level predictions.

The random-effect predictions use BLUPs computed from the stored training data, so optimize must have been called. Construct the design matrices using the same column order as the training data. DummyMatrix.transform encodes new factor levels against the training columns. A single new observation should be supplied as a one-row batch.

y_new = reml.predict_new(
    X[:2],
    {"genotype": torch.tensor([[1.0, 0.0], [0.0, 1.0]])},
)
y_new
tensor([ 1.1603, -0.3769])
z_new = DummyMatrix(group).transform(["a", "b"])

y_new = reml.predict_new(
    X[:2],
    z_new,
)
y_new
tensor([ 1.1603, -0.3769])

Residuals

marginal_residual(y=None, x=None, free_params=None)

Marginal residuals \(\mathbf{y} - \mathbf{X}\widehat{\boldsymbol{\beta}}\).

e_marginal = reml.marginal_residual(y, X, theta_hat)
e_marginal
tensor([ 0.7184, -0.3836,  0.3567, -1.6394,  0.8334, -0.6956,  1.7113, -0.4290,
         1.7891, -0.1692])
residual(y=None, x=None, free_params=None)

Conditional residuals \(\mathbf{y} - \mathbf{X}\widehat{\boldsymbol{\beta}} - \mathbf{Z}\widehat{\mathbf{b}}\). For a model with no random-effect terms this reduces to marginal_residual.

e_conditional = reml.residual(y, X, theta_hat)
e_conditional
tensor([-0.2334,  0.2000, -0.5950, -1.0558, -0.1184, -0.1120,  0.7595,  0.1547,
         0.8373,  0.4145])

Covariance blocks

c_inverse_blocks(x=None, free_params=None)

Blocks (c11, c12, c21, c22) of the inverse coefficient matrix

\[\begin{split}\mathbf{C} = \begin{pmatrix} \mathbf{X}^\top\mathbf{R}^{-1}\mathbf{X} & \mathbf{X}^\top\mathbf{R}^{-1}\mathbf{Z} \\ \mathbf{Z}^\top\mathbf{R}^{-1}\mathbf{X} & \mathbf{Z}^\top\mathbf{R}^{-1}\mathbf{Z} + \mathbf{G}^{-1} \end{pmatrix},\end{split}\]

with shapes (p, p), (p, q), (q, p) and (q, q). \(\mathbf{C}_{11}\) equals cov_blue and \(\mathbf{C}_{22}\) is the prediction-error covariance of the random effects. The model must have random-effect terms.

c11, c12, c21, c22 = reml.c_inverse_blocks(X, theta_hat)
c11, c12, c21, c22
(tensor([[ 0.0803, -0.0063],
         [-0.0063,  0.0468]]),
 tensor([[ 0.0201, -0.0069],
         [-0.0191, -0.0092]]),
 tensor([[ 0.0201, -0.0191],
         [-0.0069, -0.0092]]),
 tensor([[0.0978, 0.0020],
         [0.0020, 0.0888]]))

Log-likelihood and convergence

loglik(y=None, x=None, free_params=None)

Evaluate the log-likelihood and return (loglik, method), where method indicates the evaluation method: "cform" or "marginal". With method="auto", the evaluation silently falls back to the marginal method when the C-form is not applicable.

loglik_value, loglik_method = reml.loglik(y, X, theta_hat)
loglik_value, loglik_method
(tensor(-5.3422), 'cform')
is_converged()

Whether the last recorded iteration met the enabled convergence checks.

reml.is_converged()
True