florianhartig / BayesianTools

General-Purpose MCMC and SMC Samplers and Tools for Bayesian Statistics
https://cran.r-project.org/web/packages/BayesianTools/index.html
115 stars 29 forks source link

Setup custom prior density #180

Open fkrauer opened 5 years ago

fkrauer commented 5 years ago

Hi Florian

I am using BT 0.1.6 and for a mechanistic model and I have so far used createUniformPrior to setup my priors, which worked perfectly.

I am now trying to write my own density and sampler function so that I can have different distributions for different parameters. As a test, I am trying to write the density and sampler function for uniform priors following the example given in the help file:

density = function(par){
  d1 = dunif(par[1], -2,6, log =TRUE)
  d2 = dnorm(par[2], mean= 2, sd = 3, log =TRUE)
  return(d1 + d2)
}

sampler = function(n=1){
  d1 = runif(n, -2,6)
  d2 = rnorm(n, mean= 2, sd = 3)
  return(cbind(d1,d2))
}

prior <- createPrior(density = density, sampler = sampler, 
                     lower = c(-3,-3), upper = c(3,3), best = NULL)

However, it is unclear to me why the boundaries for the uniform prior are different in density(), sampler() and createPrior(). Is this not the same thing? And why do I have to give the boundaries argument again in the createPrior() function when it is already given in the density() function?

Best, Fabienne

florianhartig commented 5 years ago

par is the vector of parameters handed over to the prior

fkrauer commented 5 years ago

I understand that par is the vector that contains the proposed values that are drawn with the sampler(), which are then passed to the density() function for evaluation of the point density (which is done in the posterior$density() function).

I am not sure though why there are different boundary values in the help file example: c(-2,6) for the uniform par[1] in the density() function vs. c(-3,3) in thecreatePrior() function?

florianhartig commented 5 years ago

I Fabienne,

I'm sorry, you're right - this is a problem in the code and documentation (see https://github.com/florianhartig/BayesianTools/issues/98), and I had thought that we had corrected this at least in the help, but apparently we didn't.

The bottomline is: lower / upper boundaries, if they exist, must fit between what is specified in density and sampler, and the createPrior function.

If they don't fit, the density will be cut by the createPrior (which would be fine), but there can be a problem in the MCMC samplers when the prior sampler is used and returns a prior value for which the prior density is -Inf.

We have to fix the documentation in the next release, and it's still a bit unclear to us how we can prevent the user to misspecify this, as we can't "look" into what is specified in the sampler.