Random Effects with a Known Covariance¶
In some applications, the covariance structure among random-effect levels is known up to a scale factor. For example, a kinship, pedigree, phylogenetic, or spatial relationship matrix may be available before fitting the model. In this case, the random effects are modelled as
where \(\boldsymbol{A}\) is a fixed, known covariance structure and only the scale parameter \(\sigma^2\) is estimated. Thus, the random-effect covariance matrix is
In torch-openreml, this structure can be specified using
Product:
G = Product(
scale=ScalarMatrix(n_levels),
known=A,
)
Here, ScalarMatrix(n_levels) represents
\(\sigma^2 \boldsymbol{I}\). Product combines it with the
known matrix \(\boldsymbol{A}\) through ordinary matrix
multiplication to obtain \(\sigma^2 \boldsymbol{A}\).
This page provides a quick reference. For the special case of independent random intercepts, see Random-Intercept Models.
Define the known matrix¶
Consider six sites as the random-effect levels, with the known
correlation between sites \(i\) and \(j\) given by
\(A_{ij} = 0.3^{|i-j|}\). In practice, A could instead
represent a kinship, pedigree, phylogenetic, or spatial correlation
matrix.
import pandas as pd
import torch
from torch_openreml import MixedModelREML
from torch_openreml.covariance import DummyMatrix, Product, ScalarMatrix
torch.set_default_dtype(torch.float64)
torch.set_printoptions(precision=3, sci_mode=False)
pd.set_option("display.precision", 3)
n_sites = 6
site_index = torch.arange(n_sites)
A = 0.3 ** (site_index[:, None] - site_index[None, :]).abs()
A
tensor([[1.000, 0.300, 0.090, 0.027, 0.008, 0.002],
[0.300, 1.000, 0.300, 0.090, 0.027, 0.008],
[0.090, 0.300, 1.000, 0.300, 0.090, 0.027],
[0.027, 0.090, 0.300, 1.000, 0.300, 0.090],
[0.008, 0.027, 0.090, 0.300, 1.000, 0.300],
[0.002, 0.008, 0.027, 0.090, 0.300, 1.000]])
The known matrix A must be symmetric positive semidefinite, with
dimensions matching the number of columns in the random-effects design
matrix Z.
Simulate the data¶
Each site is observed on 20 days. Correlated site effects are drawn as \(\boldsymbol{u} = 10 \boldsymbol{L}\boldsymbol{z}\), where \(\boldsymbol{A} = \boldsymbol{L}\boldsymbol{L}^\top\) and \(\boldsymbol{z} \sim N(\boldsymbol{0}, \boldsymbol{I})\).
| site | day | y | |
|---|---|---|---|
| 0 | site_00 | 0 | 48.098 |
| 1 | site_00 | 1 | 52.730 |
| 2 | site_00 | 2 | 59.930 |
| 3 | site_00 | 3 | 64.175 |
| 4 | site_00 | 4 | 62.698 |
A per-column summary:
| count | unique | top | freq | mean | std | min | max | |
|---|---|---|---|---|---|---|---|---|
| site | 120 | 6 | site_00 | 20 | NaN | NaN | NaN | NaN |
| day | 120.0 | NaN | NaN | NaN | 9.5 | 5.79 | 0.0 | 19.0 |
| y | 120.0 | NaN | NaN | NaN | 82.246 | 20.292 | 42.265 | 125.53 |
Show simulation code
# A is defined in the setup cell above.
generator = torch.Generator().manual_seed(2026)
n_per_site = 20
n_obs = n_sites * n_per_site
site = torch.arange(n_sites).repeat_interleave(n_per_site)
day = torch.arange(n_per_site).repeat(n_sites)
L = torch.linalg.cholesky(A)
z = torch.randn(n_sites, generator=generator)
u = 10.0 * (L @ z)
e = 6.0 * torch.randn(n_obs, generator=generator)
y = 50.0 + 3.0 * day + u[site] + e
data = pd.DataFrame(
{
"site": [f"site_{s:02d}" for s in site.tolist()],
"day": day.numpy(),
"y": y.numpy(),
}
)
y = torch.tensor(data["y"].values)
X = torch.stack(
[
torch.ones(len(data)),
torch.tensor(data["day"].values, dtype=torch.float64),
],
dim=1,
)
X contains only the fixed effects: an intercept and day.
Fit the model¶
Use DummyMatrix to construct the random-intercept design matrix for
the sites. Specify the known covariance structure in G using
Product. The residual covariance is omitted, so it defaults to
\(\sigma_e^2 \boldsymbol{I}\).
Z = DummyMatrix(data["site"])
G = Product(scale=ScalarMatrix(data["site"]), known=A)
reml = MixedModelREML(site=(Z, G))
reml.optimize(y, X)
reml.build_params(out_format="dict")
{'G/scale/sigma^2': tensor([100.979]), 'R/sigma^2': tensor([32.426])}
Here, ScalarMatrix takes the site labels directly and creates a
diagonal scale matrix with one row and column per distinct site.
The fitted variance parameters are named G/scale/sigma^2 and
R/sigma^2. The former estimates the scale parameter
\(\sigma^2\) in \(\boldsymbol{G} = \sigma^2 \boldsymbol{A}\),
while the latter estimates the residual variance.
What the fitted covariance looks like¶
The fitted random-effect covariance matrix can be inspected directly
using tree():
reml.tree()["G"]
tensor([[100.979, 30.294, 9.088, 2.726, 0.818, 0.245],
[ 30.294, 100.979, 30.294, 9.088, 2.726, 0.818],
[ 9.088, 30.294, 100.979, 30.294, 9.088, 2.726],
[ 2.726, 9.088, 30.294, 100.979, 30.294, 9.088],
[ 0.818, 2.726, 9.088, 30.294, 100.979, 30.294],
[ 0.245, 0.818, 2.726, 9.088, 30.294, 100.979]])
The diagonal entries give the estimated site variances, while the off-diagonal entries represent the fitted covariances \(\hat{\sigma}^2 A_{ij}\).
After fitting¶
print("converged:", reml.is_converged())
print("loglik:", reml.loglik()[0])
print("fixed effects:", reml.blue())
print("fixed-effect SEs:", torch.sqrt(reml.var_blue()))
print("first five site BLUPs:")
print(reml.blup_per_term()["site"][:5])
converged: True
loglik: tensor(-280.699)
fixed effects: tensor([53.683, 2.932])
fixed-effect SEs: tensor([5.325, 0.090])
first five site BLUPs:
tensor([ -0.066, 16.020, 7.088, 2.454, -11.321])
blup_per_term() returns one BLUP per level of the site term, in the
same order as the columns of Z.