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

How to specify triangular priors? #211

Closed florianhartig closed 3 years ago

florianhartig commented 3 years ago

Question from a user

I am trying to model two parameters in BayesianTools: DLcstart and DLcend. Both may range from zero to 24, but DLcend must be greater than DLcstart. How do I tell BayesianTools this information?

florianhartig commented 3 years ago

Something like this should work - please check carefully that this does exactly what you want to do!

library(BayesianTools)

density = function(pars){
  ifelse(any(pars< 0) | any(pars > 24) | diff(pars) > 0, -Inf, 1) 
  # could replace 1 by 1/area to get normalized pdf, but usually this doesn't matter
}

sampler = function(n=1){
  d1 = runif(n, 0,24)
  d2 = runif(n, 0, 24)

  for(i in 1:n){
    if (d1[i] - d2[i] > 0) {
      d1[i] = 24 - d1[i]
      d2[i] = 24 - d2[i]
    }    
  }
  return(cbind(d1,d2))
}

x = sampler(100)
plot(x[,1], x[,2])

prior <- createPrior(density = density, sampler = sampler)