torch_openreml.MixedModelREML

class torch_openreml.MixedModelREML(*args, R=None, method='auto', **kwargs)[source]

Bases: object

REML estimator for a structured linear mixed model.

The model is specified by zero or more random-effect terms and one residual term, supplied with the keyword R. A random-effect term is a (design, covariance) pair, where design is the incidence matrix \(\symbf{Z}_i(\boldsymbol{\theta})\), either a fixed tensor or a Matrix — possibly parameterised, in which case its free parameters are part of \(\boldsymbol{\theta}\) — and covariance is the Matrix for \(\symbf{G}_i\), or a fixed two-dimensional tensor for a parameter-free \(\symbf{G}_i\). The residual term is a single Matrix for \(\symbf{R}\), or a fixed two-dimensional tensor, which is wrapped in a KnownMatrix. When R is omitted it defaults to \(\sigma^2\symbf{I}\), with the dimension inferred from the random-effect design.

The constructor builds the composite marginal covariance

\[\symbf{V}(\boldsymbol{\theta}) = \symbf{R}(\boldsymbol{\theta}) + \symbf{Z}(\boldsymbol{\theta}) \symbf{G}(\boldsymbol{\theta}) \symbf{Z}(\boldsymbol{\theta})^\top,\]

with \(\symbf{Z}(\boldsymbol{\theta})\) the column-wise augmentation of the \(\symbf{Z}_i(\boldsymbol{\theta})\) and \(\symbf{G}(\boldsymbol{\theta})\) their block-diagonal combination. Score and average-information evaluation is then dispatched to a numerical method:

  • CForm for one or more random-effect blocks, with fixed or parameterised designs and dense, invertible \(\symbf{G}\) and \(\symbf{R}\);

  • Marginal for the general \(\symbf{V}\)-based case, including multiple random-effect blocks and approximate traces.

The method is selected by method, which is "auto" by default. With "auto" CForm is used when the model is eligible for it and Marginal otherwise; if an eligible CForm fails, a warning is emitted and Marginal is used instead. "cform" and "marginal" force a particular method. A configured CForm or Marginal instance may also be supplied, for example Marginal(trace_approx="auto"); the instance is stored on the model and reused across steps.

Free covariance parameters are ordered as [free_params_Z, free_params_G, free_params_R]. A block with no free parameters occupies a zero-length slice. The fitted model keeps the optimisation trace in history; use optimize() for fitting and blue(), blup(), blup_per_term(), build_params(), marginal_predict(), marginal_residual(), predict(), residual() and loglik() for post-fitting quantities.

Parameters:
  • *args – Random-effect (design, covariance) pairs.

  • R – Residual covariance \(\symbf{R}\), either a Matrix or a fixed two-dimensional tensor, which is wrapped in a KnownMatrix. Defaults to None, in which case \(\sigma^2\symbf{I}\) is used, i.e. a ScalarMatrix whose dimension is inferred from the random-effect design. R must be supplied explicitly when the model has no random-effect terms, because the dimension cannot then be inferred.

  • method – Numerical method used for score and average-information evaluation. "auto" (the default) uses CForm when the model is eligible for it and Marginal otherwise; if an eligible CForm fails, a warning is emitted and Marginal is used instead. "cform" and "marginal" force one method; a configured CForm or Marginal instance is stored on the model and reused across steps. Any other value behaves like "auto".

  • **kwargs – Named random-effect terms, each a (design, covariance) pair. Term names must be unique, and no term may be named R (or method).

Raises:
  • TypeError – If a positional argument is not a (design,     covariance) pair, a design is not a tensor or Matrix, or a covariance is not a Matrix or a fixed two-dimensional tensor.

  • ValueError – If R is omitted and the model has no random-effect terms, a term has the wrong length, a random-effect covariance tensor is not two-dimensional, a term name is duplicated, or the marginal covariance has no free parameters.

Example:

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

n, p = 100, 3
y = torch.randn(n)
x = torch.randn(n, p)
group = [f"g{i % 20}" for i in range(n)]
z = DummyMatrix(group)
reml = MixedModelREML((z, ScalarMatrix(20)), R=ScalarMatrix(n))
free_param_names, free_params_hat = reml.optimize(y, x, torch.tensor([0.0, 0.0]), verbose=1)
[  1] ∥∇∥:      14.3431, ∥Δ∥: 3.3371, η: 1.00, ∥Δᶜ∥: 3.3371, accepted: True , log 𝓛: -54.7283
[  2] ∥∇∥:       1.8396, ∥Δ∥: 6.1245, η: 1.00, ∥Δᶜ∥: 6.1245, accepted: True , log 𝓛: -54.7202
[  3] ∥∇∥:       1.2686, ∥Δ∥: 0.0066, η: 1.00, ∥Δᶜ∥: 0.0066, accepted: True , log 𝓛: -54.7161
[  4] ∥∇∥:       0.0084, ∥Δ∥: 0.0000, η: 0.12, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛: -54.7160

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

✓ Converged at iteration 4, total time: 0.02s

Methods

ai_step([y, x, free_params, require_loglik])

Evaluate one AI step with the selected method.

blue([y, x, free_params])

Best linear unbiased estimator of the fixed effects.

blup([y, x, free_params])

Best linear unbiased predictions of the random effects.

blup_per_term([y, x, free_params])

BLUPs split by random-effect term.

build_params([free_params, include_fixed, ...])

Build covariance parameters from free parameters.

c_inverse_blocks([x, free_params])

Blocks of the inverse of the mixed-model coefficient matrix.

cov_blue([x, free_params])

Covariance matrix of the fixed-effect BLUE.

cov_blup([x, free_params])

Covariance matrix of the BLUPs.

cov_blup_per_term([x, free_params])

BLUP covariance matrices split by random-effect term.

get_free_params([select])

Return a covariance-parameter iterate from the history.

is_converged()

Whether the log-likelihood and parameter update have settled.

loglik([y, x, free_params])

Evaluate the restricted log-likelihood with the selected method.

marginal_predict([y, x, free_params])

Marginal fitted values at free_params.

marginal_residual([y, x, free_params])

Marginal residuals at free_params.

optimize(y, x[, init_values, max_iter, lb, ...])

Run the AI-REML optimisation loop with Armijo backtracking.

predict([y, x, free_params])

Conditional fitted values including random effects.

predict_new(x[, z, free_params])

Predictions at new rows from already-built design matrices.

residual([y, x, free_params])

Conditional residuals after removing fixed and random effects.

tree([free_params])

Evaluate the covariance structure and return its path-keyed tree.

update(free_params, delta, eta[, lb, ub])

Apply a damped AI step and clip to bounds.

var_blue([x, free_params])

Variances of the fixed-effect BLUE.

var_blup([x, free_params])

Variances of the BLUPs.

var_blup_per_term([x, free_params])

BLUP variances split by random-effect term.

Attributes

G

Composite random-effect covariance \(\symbf{G}\).

G_terms

Named (name, covariance) random-effect terms.

R

Residual covariance \(\symbf{R}\).

V

Marginal covariance \(\symbf{V}(\boldsymbol{\theta})=\symbf{R}(\boldsymbol{\theta})+\symbf{Z}(\boldsymbol{\theta})\symbf{G}(\boldsymbol{\theta})\symbf{Z}(\boldsymbol{\theta})^\top\).

Z

Composite incidence matrix \(\symbf{Z}(\boldsymbol{\theta})\); it may carry its own free parameters.

Z_terms

Named (name, design) random-effect terms.

property V

Marginal covariance \(\symbf{V}(\boldsymbol{\theta})=\symbf{R}(\boldsymbol{\theta})+\symbf{Z}(\boldsymbol{\theta})\symbf{G}(\boldsymbol{\theta})\symbf{Z}(\boldsymbol{\theta})^\top\).

property R

Residual covariance \(\symbf{R}\).

property G

Composite random-effect covariance \(\symbf{G}\).

property Z

Composite incidence matrix \(\symbf{Z}(\boldsymbol{\theta})\); it may carry its own free parameters.

property G_terms

Named (name, covariance) random-effect terms.

property Z_terms

Named (name, design) random-effect terms.

ai_step(y=None, x=None, free_params=None, require_loglik=True)[source]

Evaluate one AI step with the selected method.

The score and AI matrix are computed by CForm or Marginal. With method="auto" CForm is used when the model is eligible for it and Marginal otherwise; if an eligible CForm fails, a warning is emitted and Marginal is used instead.

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor, optional) – Flat covariance-parameter tensor, ordered as [free_params_Z, free_params_G, free_params_R]. Default: the last fitted iterate.

  • require_loglik (bool, optional) – Whether to evaluate the restricted log-likelihood. Default: True.

Returns:

(score, ai, loglik, method). score has shape (k,), ai has shape (k, k), and loglik is a scalar tensor, or torch.nan when require_loglik is False. method is the numerical method that produced the step, either "cform" or "marginal".

Return type:

tuple

blue(y=None, x=None, free_params=None)[source]

Best linear unbiased estimator of the fixed effects.

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Estimated fixed effects of shape (p,).

Return type:

torch.Tensor

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.blue(y, x, torch.zeros(2))
tensor([0.0381, 0.0891])
cov_blue(x=None, free_params=None)[source]

Covariance matrix of the fixed-effect BLUE.

The BLUE is \(\hat{\boldsymbol{\beta}} = (\symbf{X}^{\top}\symbf{V}^{-1}\symbf{X})^{-1} \symbf{X}^{\top}\symbf{V}^{-1}\symbf{y}\), so its covariance is

\[\operatorname{Var}(\hat{\boldsymbol{\beta}}) = \left(\symbf{X}^{\top}\symbf{V}^{-1}\symbf{X}\right)^{-1},\]

the C11 block of the inverse C-form matrix. The covariance does not depend on the response \(\symbf{y}\), only on the design and the covariance parameters.

Parameters:
  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

BLUE covariance matrix of shape (p, p).

Return type:

torch.Tensor

Example

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

torch.manual_seed(0)
n = 30
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.cov_blue(x, torch.zeros(2))
tensor([[ 0.0792, -0.0180],
        [-0.0180,  0.0439]])
var_blue(x=None, free_params=None)[source]

Variances of the fixed-effect BLUE.

This is the diagonal of cov_blue(),

\[\operatorname{Var}(\hat{\beta}_j) = \left[\left(\symbf{X}^{\top}\symbf{V}^{-1}\symbf{X}\right)^{-1} \right]_{jj},\]

the sampling variance of each fixed-effect estimate.

Parameters:
  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

BLUE variances of shape (p,).

Return type:

torch.Tensor

Example

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

torch.manual_seed(0)
n = 30
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.var_blue(x, torch.zeros(2))
tensor([0.0792, 0.0439])
c_inverse_blocks(x=None, free_params=None)[source]

Blocks of the inverse of the mixed-model coefficient matrix.

With the coefficient matrix

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

the method returns the blocks of \(\symbf{C}^{-1}\). Block \(\symbf{C}_{11} = (\symbf{X}^\top\symbf{V}^{-1}\symbf{X})^{-1}\) is the covariance of the fixed-effect estimates and \(\symbf{C}_{22}\) is the prediction-error covariance of the random-effect predictions.

Parameters:
  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

(c11, c12, c21, c22), the blocks of \(\symbf{C}^{-1}\), with shapes (p, p), (p, q), (q, p) and (q, q).

Return type:

tuple

Raises:

RuntimeError – If the model has no random-effect term or no free parameters.

Example

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

torch.manual_seed(0)
n = 30
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
c11, c12, c21, c22 = reml.c_inverse_blocks(x, torch.zeros(2))
print(c11.shape, c12.shape, c21.shape, c22.shape)
torch.Size([2, 2]) torch.Size([2, 5]) torch.Size([5, 2]) torch.Size([5, 5])
marginal_predict(y=None, x=None, free_params=None)[source]

Marginal fitted values at free_params.

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Marginal fitted values of shape (n,).

Return type:

torch.Tensor

marginal_residual(y=None, x=None, free_params=None)[source]

Marginal residuals at free_params.

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Marginal residuals of shape (n,).

Return type:

torch.Tensor

blup(y=None, x=None, free_params=None)[source]

Best linear unbiased predictions of the random effects.

\[\hat{\symbf{b}} = \symbf{G}\symbf{Z}^{\top}\symbf{V}^{-1} (\symbf{y} - \symbf{X}\hat{\boldsymbol{\beta}}).\]
Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Random-effect predictions of shape (q,).

Return type:

torch.Tensor

Raises:

ValueError – If the model has no random-effect terms, so there is no random-effect vector to predict.

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.blup(y, x, torch.zeros(2))
tensor([ 0.1196, -0.3840, -0.4495, -0.0960,  0.2879])
cov_blup(x=None, free_params=None)[source]

Covariance matrix of the BLUPs.

The BLUP is \(\hat{\symbf{b}} = \symbf{G}\symbf{Z}^{\top}\symbf{P}\symbf{y}\), so its covariance is

\[\operatorname{Var}(\hat{\symbf{b}}) = \symbf{G}\symbf{Z}^{\top}\symbf{P}\symbf{Z}\symbf{G},\]

with \(\symbf{P} = \symbf{V}^{-1} - \symbf{V}^{-1}\symbf{X}(\symbf{X}^{\top}\symbf{V}^{-1}\symbf{X})^{-1}\symbf{X}^{\top}\symbf{V}^{-1}\). This is equal to \(\symbf{G} - \symbf{C}_{22}\), but it only requires \(\symbf{V}\) to be invertible, not \(\symbf{G}\). The covariance does not depend on the response \(\symbf{y}\), only on the design and the covariance parameters.

Parameters:
  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

BLUP covariance matrix of shape (q, q).

Return type:

torch.Tensor

Raises:

ValueError – If the model has no random-effect terms, so there is no random-effect vector to predict.

Example

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

torch.manual_seed(0)
n = 30
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.cov_blup(x, torch.zeros(2))
tensor([[ 8.4931e-01,  1.3791e-02, -5.7334e-03,  4.4898e-04, -2.8237e-03],
        [ 1.3791e-02,  8.3263e-01,  8.2773e-03,  1.4521e-03,  3.8330e-03],
        [-5.7334e-03,  8.2773e-03,  8.3916e-01,  1.7353e-02, -1.0705e-02],
        [ 4.4898e-04,  1.4521e-03,  1.7353e-02,  8.3609e-01,  1.0829e-02],
        [-2.8237e-03,  3.8330e-03, -1.0705e-02,  1.0829e-02,  8.5071e-01]])
var_blup(x=None, free_params=None)[source]

Variances of the BLUPs.

This is the diagonal of cov_blup(), the sampling variance of each random-effect prediction. The variance does not depend on the response \(\symbf{y}\), only on the design and the covariance parameters.

Parameters:
  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

BLUP variances of shape (q,).

Return type:

torch.Tensor

Raises:

ValueError – If the model has no random-effect terms, so there is no random-effect vector to predict.

Example

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

torch.manual_seed(0)
n = 30
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.var_blup(x, torch.zeros(2))
tensor([0.8493, 0.8326, 0.8392, 0.8361, 0.8507])
blup_per_term(y=None, x=None, free_params=None)[source]

BLUPs split by random-effect term.

The combined BLUP is computed once, then sliced into the random-effect term order used by the constructor. This shares one factorization and one residual solve across all terms.

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Mapping from random-effect term name to its BLUP vector of shape (q_i,).

Return type:

dict

Raises:

ValueError – If the model has no random-effect terms, or if no fitted parameters are available.

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z1 = DummyMatrix([f"a{i % 5}" for i in range(n)])
z2 = DummyMatrix([f"b{i % 3}" for i in range(n)])
reml = MixedModelREML(
    (z1, ScalarMatrix(5)),
    (z2, ScalarMatrix(3)),
    R=ScalarMatrix(n),
)
reml.blup_per_term(y, x, torch.zeros(3))
{'random_term_0': tensor([ 0.1661, -0.3896, -0.3975,  0.0200,  0.3679]),
 'random_term_1': tensor([-0.3866,  0.0284,  0.1251])}
cov_blup_per_term(x=None, free_params=None)[source]

BLUP covariance matrices split by random-effect term.

The combined BLUP covariance is computed once, then sliced into the random-effect term order used by the constructor. Each entry is the covariance of that term’s BLUPs,

\[\operatorname{Var}(\hat{\symbf{b}}_i) = \symbf{G}_i\symbf{Z}_i^\top\symbf{P}\symbf{Z}_i\symbf{G}_i,\]

the corresponding diagonal block of cov_blup(). The fit is shared across terms, so only one factorization is performed. Cross-covariances between terms can be sliced from the full cov_blup() matrix.

Parameters:
  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Mapping from random-effect term name to its covariance matrix of shape (q_i, q_i).

Return type:

dict

Raises:

ValueError – If the model has no random-effect terms, or if no fitted parameters are available.

Example

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

torch.manual_seed(0)
n = 30
x = torch.randn(n, 2)
z1 = DummyMatrix([f"a{i % 5}" for i in range(n)])
z2 = DummyMatrix([f"b{i % 3}" for i in range(n)])
reml = MixedModelREML(
    (z1, ScalarMatrix(5)),
    (z2, ScalarMatrix(3)),
    R=ScalarMatrix(n),
)
reml.cov_blup_per_term(x, torch.zeros(3))
{'random_term_0': tensor([[ 0.7484, -0.0862, -0.1056, -0.1014, -0.1030],
         [-0.0862,  0.7292, -0.0914, -0.1006, -0.0966],
         [-0.1056, -0.0914,  0.7402, -0.0836, -0.1100],
         [-0.1014, -0.1006, -0.0836,  0.7330, -0.0905],
         [-0.1030, -0.0966, -0.1100, -0.0905,  0.7510]]),
 'random_term_1': tensor([[ 0.8015, -0.1081, -0.1054],
         [-0.1081,  0.7999, -0.1041],
         [-0.1054, -0.1041,  0.7978]])}
var_blup_per_term(x=None, free_params=None)[source]

BLUP variances split by random-effect term.

This is the diagonal of cov_blup_per_term(),

\[\operatorname{Var}(\hat{b}_{ij}) = \left(\symbf{G}_i\symbf{Z}_i^\top\symbf{P} \symbf{Z}_i\symbf{G}_i\right)_{jj},\]

the sampling variance of each random-effect prediction, grouped by the term that produced it. The combined covariance is computed once and shared across terms.

Parameters:
  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Mapping from random-effect term name to its variance vector of shape (q_i,).

Return type:

dict

Raises:

ValueError – If the model has no random-effect terms, or if no fitted parameters are available.

Example

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

torch.manual_seed(0)
n = 30
x = torch.randn(n, 2)
z1 = DummyMatrix([f"a{i % 5}" for i in range(n)])
z2 = DummyMatrix([f"b{i % 3}" for i in range(n)])
reml = MixedModelREML(
    (z1, ScalarMatrix(5)),
    (z2, ScalarMatrix(3)),
    R=ScalarMatrix(n),
)
reml.var_blup_per_term(x, torch.zeros(3))
{'random_term_0': tensor([0.7484, 0.7292, 0.7402, 0.7330, 0.7510]),
 'random_term_1': tensor([0.8015, 0.7999, 0.7978])}
predict(y=None, x=None, free_params=None)[source]

Conditional fitted values including random effects.

For a model with no random-effect terms this reduces to marginal_predict().

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Conditional fitted values of shape (n,).

Return type:

torch.Tensor

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.predict(y, x, torch.zeros(2))
tensor([ 0.1989, -0.3319, -0.3935, -0.1397,  0.3796,  0.1688, -0.0223, -0.6178,
        -0.1293,  0.3481,  0.2768, -0.2117, -0.3145, -0.2071,  0.2251,  0.1782,
        -0.4332, -0.3919, -0.1279,  0.2843,  0.2001, -0.1883, -0.4001, -0.2419,
         0.1424, -0.1056, -0.3796, -0.4356, -0.2179,  0.2228])
predict_new(x, z=None, free_params=None)[source]

Predictions at new rows from already-built design matrices.

This method only consumes materialised tensors: it does not encode factors or construct the incidence matrix of new data. Build x and each z block in the training column order, then pass them here. A single new observation is just a one-row batch. For a DummyMatrix block, DummyMatrix.transform does that encoding onto the training columns. The random-effect contribution uses the BLUPs computed from the stored training data by blup().

Parameters:
  • x (torch.Tensor) – Fixed-effect design matrix of shape (n_new, p) with at least one row. It must have the same columns as the training design, in the same order.

  • z (torch.Tensor, list, dict or None, optional) – Incidence matrix of new data. Either a full tensor of shape (n_new, q), a list with one (n_new, q_i) block per random-effect term, or a dict keyed by term name. Terms omitted from a dict contribute zero, so the caller chooses the active terms by what it supplies. None gives the population prediction, ignoring the random effects. Default: None.

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used.

Returns:

Predictions of shape (n_new,).

Return type:

torch.Tensor

Raises:
  • ValueError – If x is empty, the shapes disagree, a term name is unknown, or the model has no random-effect terms but z is given.

  • TypeError – If x or z has an unsupported type.

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.optimize(y, x, torch.zeros(2))

x_new = torch.zeros(2, 2)
z_new = torch.zeros(2, 5)
z_new[0, 0] = 1.0
reml.predict_new(x_new, z_new)
tensor([6.3345e-05, 0.0000e+00])
residual(y=None, x=None, free_params=None)[source]

Conditional residuals after removing fixed and random effects.

For a model with no random-effect terms this reduces to marginal_residual().

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters in model order, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

Conditional residuals of shape (n,).

Return type:

torch.Tensor

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.predict(y, x, torch.zeros(2))
reml.residual(y, x, torch.zeros(2))
tensor([-1.3247, -0.8204,  0.1429, -0.2942,  0.4691,  0.5232, -0.2937, -1.4974,
         0.4516, -1.6114,  0.0732,  0.5199,  0.4344,  1.4447, -0.3685, -0.2898,
        -0.1804,  0.4235, -0.3648, -0.0359,  0.2396,  0.3007, -0.4410, -2.0741,
        -0.2447,  0.8981,  0.0899,  0.4881,  0.7408,  2.0794])
get_free_params(select='last')[source]

Return a covariance-parameter iterate from the history.

Parameters:

select (str, optional) – "last" for the final iterate or "best" for the iterate with the highest recorded log-likelihood. Default: "last".

Returns:

(free_param_names, free_params), where free_param_names is the list of namespaced covariance parameter names and free_params is the selected covariance-parameter tensor.

Return type:

tuple

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
reml.optimize(y, x, torch.zeros(2), max_iter=20)
names, values = reml.get_free_params("best")
names, values
(['G/sigma^2', 'R/sigma^2'], tensor([-4.8637, -0.0509]))
build_params(free_params=None, include_fixed=True, trans=True, out_format='tensor')[source]

Build covariance parameters from free parameters.

This exposes the covariance model’s build_params on the fitted model, using the selected model parameters when free_params is omitted.

Parameters:
  • free_params (torch.Tensor, dict or str, optional) – Free parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used.

  • include_fixed (bool, optional) – Whether to include fixed parameters in the output. Default: True.

  • trans (bool, optional) – Whether to apply parameter transforms. Default: True.

  • out_format (str, optional) – "tensor" for a flat tensor or "dict" for a name-keyed mapping. Default: "tensor".

Returns:

The requested covariance parameters.

Return type:

torch.Tensor or dict

Raises:

ValueError – If no fitted parameters are available, or if out_format is invalid.

Example

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

torch.manual_seed(0)
n = 30
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 5}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(5)), R=ScalarMatrix(n))
raw = reml.build_params(torch.zeros(2), trans=False)
model_scale = reml.build_params(torch.zeros(2), trans=True)
raw, model_scale
(tensor([0., 0.]), tensor([1., 1.]))
tree(free_params=None)[source]

Evaluate the covariance structure and return its path-keyed tree.

Parameters:

free_params (torch.Tensor, dict or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used.

Returns:

Path-keyed covariance tree.

Return type:

dict

Raises:

ValueError – If no fitted parameters are available.

Example

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

torch.manual_seed(0)
n = 8
y = torch.randn(n)
x = torch.randn(n, 2)
z = DummyMatrix([f"g{i % 3}" for i in range(n)])
reml = MixedModelREML((z, ScalarMatrix(3)), R=ScalarMatrix(n))
reml.optimize(y, x, torch.zeros(2), max_iter=20)
reml.tree()
{'/': tensor([[1.5933, 0.0000, 0.0000, 0.7964, 0.0000, 0.0000, 0.7964, 0.0000],
         [0.0000, 1.5933, 0.0000, 0.0000, 0.7964, 0.0000, 0.0000, 0.7964],
         [0.0000, 0.0000, 1.5933, 0.0000, 0.0000, 0.7964, 0.0000, 0.0000],
         [0.7964, 0.0000, 0.0000, 1.5933, 0.0000, 0.0000, 0.7964, 0.0000],
         [0.0000, 0.7964, 0.0000, 0.0000, 1.5933, 0.0000, 0.0000, 0.7964],
         [0.0000, 0.0000, 0.7964, 0.0000, 0.0000, 1.5933, 0.0000, 0.0000],
         [0.7964, 0.0000, 0.0000, 0.7964, 0.0000, 0.0000, 1.5933, 0.0000],
         [0.0000, 0.7964, 0.0000, 0.0000, 0.7964, 0.0000, 0.0000, 1.5933]]),
 'Z': tensor([[1., 0., 0.],
         [0., 1., 0.],
         [0., 0., 1.],
         [1., 0., 0.],
         [0., 1., 0.],
         [0., 0., 1.],
         [1., 0., 0.],
         [0., 1., 0.]]),
 'G': tensor([[0.7964, 0.0000, 0.0000],
         [0.0000, 0.7964, 0.0000],
         [0.0000, 0.0000, 0.7964]]),
 'R': tensor([[0.7969, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.7969, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.7969, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.7969, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.7969, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.7969, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.7969, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.7969]])}
is_converged()[source]

Whether the log-likelihood and parameter update have settled.

A step is accepted only when both enabled checks pass: the change in log-likelihood is below tol_loglik and the largest absolute parameter update is below tol_update.

Raises:

ValueError – If no fit has been run yet, i.e. history is None. Call optimize() before checking convergence.

update(free_params, delta, eta, lb=-inf, ub=inf)[source]

Apply a damped AI step and clip to bounds.

Parameters:
  • free_params (torch.Tensor) – Current parameters.

  • delta (torch.Tensor) – AI direction.

  • eta (float) – Step-length multiplier.

  • lb (float, optional) – Lower bound. Default: -torch.inf.

  • ub (float, optional) – Upper bound. Default: torch.inf.

Returns:

(updated, step), where updated = clip(free_params + eta * delta) and step = updated - free_params.

Return type:

tuple

loglik(y=None, x=None, free_params=None)[source]

Evaluate the restricted log-likelihood with the selected method.

With method="auto" CForm is used when the model is eligible for it and Marginal otherwise. A CForm failure falls back to Marginal silently, because the value is often evaluated at a trial point.

Parameters:
  • y (torch.Tensor, optional) – Response vector of shape (n,). Default: the response stored by optimize().

  • x (torch.Tensor, optional) – Fixed-effect design matrix of shape (n, p). Default: the design stored by optimize().

  • free_params (torch.Tensor or str, optional) – Covariance parameters, or "last" / "best" to select a fitted iterate. If omitted, the last fitted parameters are used. A ValueError is raised when no fit exists.

Returns:

(loglik, method). loglik is a scalar tensor with the restricted log-likelihood, and method is the numerical method that evaluated it, either "cform" or "marginal".

Return type:

tuple

Raises:

RuntimeError – If method="cform" and CForm cannot handle the model.

optimize(y, x, init_values=None, max_iter=200, lb=-inf, ub=inf, verbose=0, check_update=True, check_loglik=True, tol_update=0.0001, tol_loglik=0.0001, armijo_trials=30, armijo_c=0.0001, eta_shrink=0.5, eta_max=1.0, eta_min=1e-10, fallback_eta=0.001, armijo_slack=1e-07)[source]

Run the AI-REML optimisation loop with Armijo backtracking.

The AI direction is always delta = AI^{-1} score. A backtracking line search starts from eta_max and multiplies it by eta_shrink after each rejected candidate. eta_max is also the value restored after every accepted or fallback step, so it acts as the maximum step length. If the line search cannot find a finite candidate that sufficiently increases the log-likelihood, one small gradient-ascent step is taken instead.

A candidate is accepted when

\[\ell_{\mathrm{new}} \geq \ell + c \, \eta \, \symbf{s}^\top\boldsymbol{\delta} - \epsilon \max(1, |\ell|),\]

where c = armijo_c and epsilon = armijo_slack. The last term is a small numerical slack; set armijo_slack=0 for strict Armijo.

Any score history kept by the selected Marginal instance for trace_approx="auto" is reset before the first iteration.

Parameters:
  • y (torch.Tensor) – Response vector of shape (n,).

  • x (torch.Tensor) – Fixed-effect design matrix of shape (n, p).

  • init_values (torch.Tensor, optional) – Initial covariance parameters. When omitted, the model’s default parameters are used.

  • max_iter (int, optional) – Maximum number of AI iterations. Default: 200.

  • lb (float, optional) – Lower bound for parameters. Default: -torch.inf.

  • ub (float, optional) – Upper bound for parameters. Default: torch.inf.

  • verbose (int, optional) – If positive, print one line per iteration. Default: 0.

  • check_update (bool, optional) – Whether the maximum absolute parameter update participates in convergence. Default: True.

  • check_loglik (bool, optional) – Whether the log-likelihood change participates in convergence. Default: True.

  • tol_update (float, optional) – Convergence tolerance for the maximum absolute parameter update. Default: 1e-4.

  • tol_loglik (float, optional) – Convergence tolerance for the log-likelihood change. Default: 1e-4.

  • armijo_trials (int, optional) – Maximum number of backtracking candidates. Default: 30.

  • armijo_c (float, optional) – Armijo sufficient-increase constant. Default: 1e-4.

  • eta_shrink (float, optional) – Multiplier applied after each rejected candidate. Default: 0.5.

  • eta_max (float, optional) – Initial and restored step length. Default: 1.0.

  • eta_min (float, optional) – Smallest step length tried. Default: 1e-10.

  • fallback_eta (float, optional) – Step length for the normalized gradient fallback. Default: 1e-3.

  • armijo_slack (float, optional) – Relative numerical slack in the Armijo test. Default: 1e-7.

Returns:

(free_param_names, free_params), where free_param_names is the list of namespaced covariance parameter names and free_params is the final covariance-parameter tensor in that order.

Return type:

tuple

Notes

The optimisation trace is stored in history with keys "free_params", "loglik", "score", "ai", "delta", "update", "eta", "accepted" and "method". "accepted" is True only for a line-search-accepted Newton step; gradient fallback steps are recorded with False. "method" records, for each iteration, the method that produced the AI step, either "cform" or "marginal". The response y and design x are stored on the instance and are reused by the post-estimation methods (blue(), blup(), predict(), residual(), loglik(), and the covariance methods) when called without them.