Debug code to get log likelihood from truncated Weibull distribution

Below is my stan code for fitting a truncated Weibull. I would like to output the log-likelihood for use in calculating information criteria. I thought that to do this for a truncated distribution, I need to specify the truncation “longhand” in the generated quantities block, but my model will not compile as written. Please help me debug this code!

Stan code

data {
	int<lower=0> N;
	vector<lower=0>[N] x;
	real<lower=0> UL; // Upper truncation limit
	real<lower=0> LL; // Lower truncation limit
}

parameters {
	// Weibull density
	real<lower=0> m;
	real<lower=0> n;
}

model {
	// Priors: Weibull density
	m ~ lognormal(1, 1);
	n ~ lognormal(1, 1);
	
	// Likelihood: Weibull density
	for (i in 1:N) x[i] ~ weibull(m, n) T[LL,UL];

}

generated quantities {
	// Log likelihood
	vector[N] log_lik;
	
	for (i in 1:N) {
		log_lik[i] = weibull_lpdf(x[i] | m, n);
		if (x[i] < LL || x[i] > UL) {
		  log_lik[i] += negative_infinity();
		} else { 
		  log_lik[i] += log_diff_exp(weibull_lcdf(UL | m, n), weibull_lcdf(LL | m, n));
		}
	}
	
}

Parser error log

SYNTAX ERROR, MESSAGE(S) FROM PARSER:

  error in 'model3004df43e7a_testweib' at line 31, column 22
  -------------------------------------------------
    29: 		log_lik[i] = weibull_lpdf(x[i] | m, n);
    30: 		if (x[i] < LL || x[i] > UL) {
    31: 		  log_lik[i] += negative_infinity();
                             ^
    32: 		} else { 
  -------------------------------------------------

PARSER EXPECTED: <expression>
Error in stanc(file = file, model_code = model_code, model_name = model_name,  : 
  failed to parse Stan model 'testweib' due to the above error.

Replying to my own question . . .

I’ve removed the if statement from the generated quantities block because I am sure I do not have any x values outside the upper and lower limits. The code now compiles, but I am still curious whether this will give correct results, and also how to fix the if statement in the original post for future reference.

New generated quantities block

generated quantities {
	// Log likelihood
	vector[N] log_lik;
	real k;
	
	k = log_diff_exp(weibull_lcdf(UL | m, n), weibull_lcdf(LL | m, n));
	for (i in 1:N) log_lik[i] = weibull_lpdf(x[i] | m, n) + k;
	
}

Your model as posted above compiles in RStan 2.17.3 for me.

Are you using a late enough version of Stan ot have the += operator for anyting other than target?

Thanks for the help. It compiled once I updated from 2.16.2 to 2.17.3. I wasn’t aware that the += operator wasn’t available for other variables in the version of Stan I was running.