invert_mat_batched

Invert a batch of symmetric positive-definite matrices

Description

Batched counterpart of invert_mat: inverts a (batch, n, n) stack of symmetric positive-definite matrices in a single Cholesky factorisation call rather than looping invert_mat() over each slice. SpaNorm’s own model never needs this (its per-gene fit shares a single coefficient across all genes, so it only ever inverts one matrix at a time); it is exposed for downstream packages (e.g. spiDE) that need a genuinely per-gene/per-feature covariance – a different n x n matrix for every slice of the batch, varying with a per-gene working weight – where looping invert_mat()’s R-level tryCatch/Cholesky call once per gene is the dominant cost.

Usage

invert_mat_batched(mat)

Arguments

mat a (batch, n, n) torch tensor, or a base R array of the same shape (dim(mat) == c(batch, n, n)).

Details

Unlike invert_mat()’s per-matrix tryCatch, a failure here (e.g. one non-SPD slice) falls back to a general solve for the whole batch, not just the failing slice – correctness is unaffected (the fallback solves every slice correctly regardless of conditioning), it is simply not the exact same numerical routine applied per-slice in that (rare) case.

Value

the batch of matrix inverses, in the same representation as mat.

Examples

library("SpaNorm")

m <- array(0, c(4, 3, 3))
for (i in 1:4) m[i, , ] <- crossprod(matrix(rnorm(9), 3, 3)) + diag(3)
invert_mat_batched(m)
, , 1

          [,1]       [,2]        [,3]
[1,] 0.5201964 0.01049228  0.15742941
[2,] 0.4514860 0.19222278 -0.19947046
[3,] 0.4081982 0.10561012 -0.15529614
[4,] 0.4132632 0.24351185 -0.06857583

, , 2

           [,1]      [,2]        [,3]
[1,] 0.01049228 0.2391953 -0.05882009
[2,] 0.19222278 0.2270381 -0.17125128
[3,] 0.10561012 0.2221758 -0.14930068
[4,] 0.24351185 0.4763677 -0.03038899

, , 3

            [,1]        [,2]      [,3]
[1,]  0.15742941 -0.05882009 0.5367104
[2,] -0.19947046 -0.17125128 0.6676834
[3,] -0.15529614 -0.14930068 0.8286051
[4,] -0.06857583 -0.03038899 0.3372644