Created
          August 15, 2017 20:55 
        
      - 
      
- 
        Save khakieconomics/2c78e26a41474c6c653f35958c0a8e61 to your computer and use it in GitHub Desktop. 
    Unconstrained quantile to truncated normal conversion
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | functions { | |
| // lower bound is a, upper bound is b, rv is x, mean is mu, sd is sigma | |
| vector xi(vector x, real mu, real sigma) { | |
| return((x - mu)./sigma); | |
| } | |
| real alpha(real a, real mu, real sigma) { | |
| real out; | |
| out = (a==negative_infinity())? negative_infinity(): (a - mu)/sigma; | |
| return(out); | |
| } | |
| real beta(real b, real mu, real sigma) { | |
| real out; | |
| out = (b==positive_infinity())? positive_infinity(): (b - mu)/sigma; | |
| return(out); | |
| } | |
| real Z(real a, real b, real mu, real sigma) { | |
| return(normal_cdf(beta(b, mu, sigma), 0.0, 1.0) - normal_cdf(alpha(a, mu, sigma), 0.0, 1.0)); | |
| } | |
| // converts a vector of inverse quantiles (a CDF) to the corresponding quantile of | |
| // a truncated normal distribution in [a, b] with location = location and scale = scale. | |
| // convenient for | |
| vector truncnorm_ng(vector p, // vector the cdf of some random variable | |
| real a, // lower bound, can be negative_infinity() and positive_infinity() | |
| real b, // upper bound, can be negative_infinity() and positive_infinity() | |
| real location, // location and scale are self explanatory | |
| real scale) { | |
| vector[rows(p)] out; | |
| real tmp_Z; | |
| real tmp_alpha; | |
| tmp_alpha = normal_cdf(alpha(a, location, scale), 0, 1); | |
| tmp_Z = normal_cdf(beta(b, location, scale), 0, 1) - tmp_alpha; | |
| for(i in 1:rows(p)) { | |
| out[i] = inv_Phi(tmp_alpha + p[i]*tmp_Z)*scale + location; | |
| } | |
| return(out); | |
| } | |
| } | |
| model { | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment