How do you specify a chi-square response distribution using custom_family()?

Hi! I’m attempting to fit a model in brms where the response variable fits a scaled chi-square distribution—without going to deep on the specific question, we’re looking at predictors of sample variance.

My first thought was to use family=skew_normal(), and while it’s an OK fit it’s not great, so instead, I’d like to use the custom_family() to call a chi-square distribution from Stan. It’s here where I’m running into trouble: while I can follow along with this useful vignette, it’s my understanding that since this distribution is already defined in Stan, I don’t need to provide any Stan functions; only define the family and make sure its name matches the prefix in Stan.

However, I think I’m missing something in my custom_family() syntax, as when I try to use family=chi_square, Stan fails to compile. I suspect I am missing something basic and apologize if I missed a similar question in the forum.

The code below is a reproducible example of my problem. Thanks in advance!


# simulate data from linear model
N <- 100
x <- rnorm(N)
beta <- 0.4
errors <- rchisq(100, df=1) # errors from chi-sq dist
errors <- errors - 1  # centers error distribution on 0
y <- 1 + x*beta + errors

# visualize response distribution
hist(y, breaks = 15)

# create dataframe
df <-, y)
colnames(df) <- c("predictor","response")

# run model with skew_normal distribution
mod1 <- brm(
  formula = bf(response ~ predictor),
  data = df, 
  family = skew_normal(), 
  iter = 10000

pp_check(mod1, nsamples=50) # peak off 

# define custom family
chi_square <- custom_family(
  "chi_square", dpars = c("mu", "nu"),
  type = "real"

# run model with chi_square distribution
mod2 <- brm(
  formula = bf(response ~ predictor),
  data = df, 
  family = chi_square,
  iter = 10000

# stops after "Compiling Stan program..."

(I’m using brms version 2.13.5 on Mac OS X 10.14.1; R version 4.0.2.)


I think you still need to add a stan function that calculates the likelihood.

stan_funs <- ...
stanvars <- ...

However, I am not entirely sure. Could you post the brms-generated Stan-code?