Evaluating a MvNormal density with a sparse covariance matrix

Suppose that Q is a sparse covariance matrix, and I want to evaluate \mathbf{y} \sim N(\boldsymbol{0},Q). Can I leverage the sparsity of Q? Right now, I have Q as a SparseMatrixCSC{Float64, Int64}. Roughly 97% of the matrix is 0.

When I use pdf(MvNormal(zeros(n), Q), y), I get the following error: MethodError: no method matching PDMats.PDMat(::SparseMatrixCSC{Float64, Int64}, ::SuiteSparse.CHOLMOD.Factor{Float64}). It seems that MvNormal() does not accept a sparse matrix as the covariance matrix because of some incompatibility in the PDMats package. For the time begin, I am using pdf(MvNormal(zeros(n), Hermitian(Array(Cov_y_star))), y). However, this seems incredibly inefficient.

Do you know of a way that I can leverage the sparsity of Q to improve the computational speed in evaluating a multivariate normal distribution?

You need to explicitly wrap Q as a PDSparseMat. I’m not sure why there isn’t an outer constructor for MvNormal that converts to PDSparseMat automatically, but regardless, the following should work:

using Distributions, PDMats, SparseArrays
Q = spdiagm(ones(10))
d = MvNormal(PDSparseMat(Q))
logpdf(d, randn(10))
2 Likes