For R Users

torch-openreml can be used in R through the reticulate package. We recommend installing torch-openreml inside a dedicated conda environment.

Installation

1. Install Conda

You can skip this step if conda is already installed on your system.

if (is.null(reticulate:::find_conda()[[1]])) {
    reticulate::install_miniconda()
}

2. Create a Conda Environment

if (reticulate::condaenv_exists("torch-openreml")) {
    reticulate::conda_remove("torch-openreml")
}

reticulate::conda_create("torch-openreml",
                         python_version = "3.12.12")

3. Install torch-openreml

reticulate::conda_install("torch-openreml",
                          pip = TRUE,
                          packages = c("git+https://github.com/anu-aagi/torch-openreml.git"))

Usage

The following example mirrors the Getting Started example. In R, it is often more convenient to construct design matrices directly using model.matrix(). As in Python, a matrix dimension may be given as the grouping factor itself, whose distinct values define the dimension.

library(reticulate)
use_condaenv("torch-openreml")

openreml <- import("torch_openreml", convert = FALSE)
torch <- import("torch", convert = FALSE)

ScalarMatrix <- openreml$covariance$ScalarMatrix
IdentityMatrix <- openreml$covariance$IdentityMatrix
KroneckerProduct <- openreml$covariance$KroneckerProduct
MixedModelREML <- openreml$MixedModelREML

data <- agridat::john.alpha
n <- nrow(data)

y <- torch$tensor(data$yield, dtype = torch$float32)
X <- model.matrix(~ rep, data = data) |>
    torch$tensor(dtype = torch$float32)

Z_gen <- model.matrix(~ 0 + gen, data = data) |>
    torch$tensor(dtype = torch$float32)
Z_rep_block <- model.matrix(~ 0 + block:rep, data = data) |>
    torch$tensor(dtype = torch$float32)

reml <- MixedModelREML(
    genotype = list(Z_gen, ScalarMatrix(data$gen)),
    replicate_block = list(
        Z_rep_block,
        KroneckerProduct(
            G_rep = IdentityMatrix(data$rep),
            G_block = ScalarMatrix(data$block)
        )
    ),
    R = ScalarMatrix(n)
)
print(reml)

Printing the model shows the marginal covariance it assembles from those terms. The optimize method is then called with y, X, and an initial value for the covariance parameters (zeros in this example), and the estimated parameters are mapped back to variance components using build_params():

result <- reml$optimize(y, X, torch$zeros(3L), verbose = 1L)
print(py_to_r(reml$build_params()$numpy()))

The fixed effects follow from generalized least squares, the best linear unbiased estimate (BLUE):

print(py_to_r(reml$blue(y, X)$numpy()))

The random effects are predicted with the best linear unbiased predictor (BLUP), one value per random-effect level. In this example the predictions correspond to the 24 genotypes followed by the 18 replicate-by-block combinations:

print(py_to_r(reml$blup(y, X)$numpy()))

blup_per_term splits the same predictions by random-effect term, returning a dict keyed by the term names supplied to the constructor. The random intercepts for gen are then:

gen_blup <- reml$blup_per_term(y, X)[["genotype"]]
print(setNames(py_to_r(gen_blup$numpy()), levels(data$gen)))
MarginalCovariance(
  operands={
    'Z': torch.Size([72, 42]),
    'G': BlockDiagonal(
      operands={
        'genotype': ScalarMatrix(shape=(24, 24), param_specs={'sigma^2': {'fixed': False, 'default': tensor([0.]), 'trans': TransformExpPow2()}}),
        'replicate_block': KroneckerProduct(
          operands={
            'G_rep': IdentityMatrix(shape=(3, 3)),
            'G_block': ScalarMatrix(shape=(6, 6), param_specs={'sigma^2': {'fixed': False, 'default': tensor([0.]), 'trans': TransformExpPow2()}})
          }
        )
      }
    ),
    'R': ScalarMatrix(shape=(72, 72), param_specs={'sigma^2': {'fixed': False, 'default': tensor([0.]), 'trans': TransformExpPow2()}})
  }
)
[  1] ∥∇∥:      41.8198, ∥Δ∥: 8.9438, η: 0.25, ∥Δᶜ∥: 2.2359, accepted: True , log 𝓛:  13.4244
[  2] ∥∇∥:      19.0068, ∥Δ∥: 0.4705, η: 1.00, ∥Δᶜ∥: 0.4705, accepted: True , log 𝓛:  16.6687
[  3] ∥∇∥:       3.6187, ∥Δ∥: 0.0932, η: 1.00, ∥Δᶜ∥: 0.0932, accepted: True , log 𝓛:  16.7988
[  4] ∥∇∥:       0.1519, ∥Δ∥: 0.0042, η: 1.00, ∥Δᶜ∥: 0.0042, accepted: True , log 𝓛:  16.8141
[  5] ∥∇∥:       0.0020, ∥Δ∥: 0.0001, η: 0.00, ∥Δᶜ∥: 0.0000, accepted: False, log 𝓛:  16.8081
[  6] ∥∇∥:       0.0019, ∥Δ∥: 0.0001, η: 1.00, ∥Δᶜ∥: 0.0001, accepted: True , log 𝓛:  16.8137
[  7] ∥∇∥:       0.0001, ∥Δ∥: 0.0000, η: 1.00, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛:  16.8157
[  8] ∥∇∥:       0.0001, ∥Δ∥: 0.0000, η: 0.02, ∥Δᶜ∥: 0.0000, accepted: True , log 𝓛:  16.8157

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

✓ Converged at iteration 8, total time: 0.03s

[1] 0.14290200 0.07021844 0.08161712
[1]  4.5182447  0.2978498 -0.4140421
 [1]  0.501184165  0.004964266 -0.784560025  0.006126862  0.474950671
 [6]  0.044642225 -0.308945537  0.062230300 -0.809928179 -0.089371264
[11] -0.196432576  0.225759938  0.231666133  0.243400127  0.424700201
[16]  0.200965792  0.078079604 -0.110178962  0.289576948 -0.338967472
[21]  0.256133080  0.024090428 -0.176996052 -0.253055513  0.123139009
[26] -0.141222149 -0.150390953 -0.106752411  0.073707275  0.201536730
[31] -0.532639027 -0.301232427  0.243238658  0.134878069  0.275336236
[36]  0.180418551  0.050570097 -0.047783975  0.151078418  0.053760573
[41] -0.008047673 -0.199577644
         G01          G02          G03          G04          G05          G06 
 0.501184165  0.004964266 -0.784560025  0.006126862  0.474950671  0.044642225 
         G07          G08          G09          G10          G11          G12 
-0.308945537  0.062230300 -0.809928179 -0.089371264 -0.196432576  0.225759938 
         G13          G14          G15          G16          G17          G18 
 0.231666133  0.243400127  0.424700201  0.200965792  0.078079604 -0.110178962 
         G19          G20          G21          G22          G23          G24 
 0.289576948 -0.338967472  0.256133080  0.024090428 -0.176996052 -0.253055513