Skip to content

Instantly share code, notes, and snippets.

@khakieconomics
Created August 15, 2017 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khakieconomics/2c78e26a41474c6c653f35958c0a8e61 to your computer and use it in GitHub Desktop.
Save khakieconomics/2c78e26a41474c6c653f35958c0a8e61 to your computer and use it in GitHub Desktop.
Unconstrained quantile to truncated normal conversion
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