I am writing some code that transforms multi-variate distributions by operating mostly on the cholesky factor of the covariance matrix. Suppose I have
using Distributions
g1 = MvNormal([1,2], [2 1; 1 2])
The naive way to do it is
c1 = cholesky(cov(g1)).L
# work on matrix c1 in some way, for this example I'll just directly assign it to c2
c2 = c1
s2 = c2*c2'
g2 = MvNormal([1,2], s2)
But this means repeatedly calculating the Cholesky factor of a covariance matrix and then obtaining the corresponding covariance matrix, when for reasons of speed and numerical stability I would prefer to always use Cholesky factors, as I rarely need the covariance matrix. Note that even with this very simple example, some error can already be seen:
g2 = MvNormal([1,2], s2)
FullNormal(
dim: 2
μ: [1.0, 2.0]
Σ: [2.0000000000000004 1.0; 1.0 1.9999999999999996]
)
What is the correct Julia way to do this? I've seen, for example, this answer to a GitHub issue which suggests it's possible to specify only the Cholesky factor for MvNormal, but it assumes some familiarity with Julia which I don't have, and so it's not enough for me to figure out how to actually do it. Also it's quite old, and the surrounding discussion suggests the way this works has been changed in the meantime.
So, to summarize, if I have the cholesky factor of a covariance matrix, how can I efficiently define a MvNormal such that I can get that factor back efficiently, and also still have access to the methods defined for MvNormal?
Note: the transformation of c1
to c2
in my application is an implementation of the square root form of the unscented transform. I realise there are probably libraries that do this, but I would prefer to have my own implementation since I plan to tinker with it.
Using PDMats package I think you can get the functionality you need:
So now,
mvn
is supposadly the MvNormal withC
as the Cholesky factor. And any new Cholesky factor can be used to generate an MvNormal in this way, by constructing aPDMat
from a Cholesky factor object which can be constructed from a lower-triangular matrix.Hopefully, the overhead is less than generating the new MvNormal covariance matrix each time.
For example: