Inverse Lognormal CDF

We use this function in our likelihood model, but it’s unavailable in the Stan function library. If someone needs this function in the meantime, this is a user-defined function for calculating it (where x is the vector of input values, m is the mu parameter, and s is the sigma parameter):

functions {

	//custom function for lognormal inverse CDF
	row_vector logncdfinv(row_vector x, real m, real s) {							

		int sz;												    //declaring size variable
		sz = size(x);											//calculating size variable
		row_vector[sz] y;										//declaring return variable
		y = exp( s .* sqrt(2) .* inv_erfc( -2 .* x + 2 ) + m ); //calculating result

		return y;											    //returning result


Note: can be fairly easily rewritten to accept real values instead of a row vector of values by declaring x as a real instead of a row vector in the input, getting rid of the two lines declaring and calculating sz, and declaring y as a real instead of a row vector.


Thanks @Corey.Plate. Maybe a candidate for @spinkney’s GitHub - spinkney/helpful_stan_functions?

1 Like

The inverse cdfs are slowly making their way into Stan. They’ll be called _qf for quantile functions. You can now also overload function signatures to have different types so you could specify one for a vector x, another with row vector x, real x, array real x, etc. Similarly you can make overloads for m and s.

I might rewrite that function as a one liner.

vector log_normal_qf(vector x, real m, real s) {																	
  return exp( s * sqrt(2) * inv_erfc( -2 * x + 2 ) + m );           

But I like having the explicit size declaration of int N = rows(x) to show what the expected output size is without inspecting the function.