Skip to content

Extension needed for StaticArrays #2021

@astrozot

Description

@astrozot

I believe we should consider writing an extension for StaticArrays, so that multivariate distributions with "static" parameters works as expected. For example, as noted in #992, rand(MvNormal(μ::SVector, Σ)) should return an SVector. Similarly, when building a MvNormal with just the covariance as a static matrix, the mean should be set to a vanishing static vector.

I think the work should be not too complicated, but the gain is obvious as we would avoid allocations when using these distributions with small static vectors. For example, these few lines could solve the two issues I just mentioned:

Distributions.MvNormal::SMatrix{N, N, T}) where {N,T<:Real} = 
    Distributions.MvNormal(zero(SVector{N,T}), Σ)

Distributions.rand(rng::Random.AbstractRNG, d::Distributions.MvNormal{T,P,<:SVector{N}}) where {T, P, N} = 
    Distributions.unwhiten(d.Σ, randn(rng, SVector{N, T})) .+ d.μ

Moreover, I propose that when generating multiple random vectors from static-array multivariate distributions, the result is not a matrix, but a vector of static vectors:

Distributions.rand(rng::Random.AbstractRNG, d::Distributions.MvNormal{T,P,<:SVector{N}}, n::Int) where {T,P,N} =
    [Distributions.unwhiten(d.Σ, randn(rng, SVector{N,T})) .+ d.μ for _ in 1:n]

I believe this is much more natural; also, conversion to a matrix (and vice-versa) is trivial (see this section in the documentation of StaticArrays).

If there is agreement on this I would be happy helping to implement the extension.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions