lbelzile / TruncatedNormal

Simulation from truncated Gaussian and Student vectors, high dimensional CDF via exponential tilting
https://lbelzile.github.io/TruncatedNormal/
8 stars 4 forks source link

Crashing with bad sigma #8

Closed wiz21b closed 2 years ago

wiz21b commented 2 years ago

On R version 4.0.4 (2021-02-15) on linux, this code crashes (R exits):

library(TruncatedNormal)
sigma <- matrix( c(1, 0, 0, -1), nrow=2 )
mu <- c(1,1)
lb <- c(0,0)
ub <- c(Inf,Inf)
data <- rtmvnorm(1000, mu, sigma, lb, ub)

The error is :

> >  *** caught segfault ***
address 0x561ee1ef9800, cause 'memory not mapped'

Traceback:
 1: .cholpermGGE(Sigma = Sigma, l = l, u = u)
 2: cholperm(as.matrix(Sig), as.numeric(l), as.numeric(u))
 3: mvrandn(l = lb, u = ub, Sig = sigma, n = n, mu = mu)
 4: t(mvrandn(l = lb, u = ub, Sig = sigma, n = n, mu = mu))
 5: rtmvnorm(1000, mu, sigma, lb, ub)

The sigma matrix is ill defined I guess but the crash is unexpected. I use TruncatedNormal 2.2.2.

This may be related to that but I swear I have installed the package as usual :-)

lbelzile commented 2 years ago

Thanks for flagging this: I confirm I can reproduce the bug.

Checking that the input is valid is costly (because it requires running an eigendecomposition of sigma among other things), but I can add a logical switch (TRUE by default) to check the argument in rtmvnorm and rtmvt.

library(TruncatedNormal)
mu <- c(1,1)
lb <- c(0,0)
ub <- c(Inf,Inf)
# Diagonal entries are negative
data <- rtmvnorm(1000, mu, sigma = matrix(c(1, 0, 0, -1), nrow=2), lb, ub)
# Covariance matrix is not positive definite
sigma <- cbind(c(2,1),c(1,0.5))
data <- rtmvnorm(1000, mu, sigma,  lb, ub)
# Scale matrix is not symmetric
rtmvt(1000, mu, cbind(c(3,1),c(1.4,2)), df = 2, lb, ub)