How to call user defined functions arguments in the model?

I have tried this function in many ways. The first problem I got is that in stan we can not use real values as indexing. So I tried to fix that using integer arrays. But now I can not run the model because I do not know how to call these additional arguments in the model block. The following is my function.

// Create user define function

functions{

real tenismodel(matrix dat, vector theta, vector alpha, int ServerID, int ReceiverID){

vector[rows(dat)] prob;
real t;
real x;
int s;
int re;
real out;
real a;
real f;
real ws;
real rs;
real ms;
real wr;
real rr;
real mr;

for (i in 1:rows(dat)){

t <- dat[i, 1];
x <- dat[i, 2];
s <- ServerID[i];
re <- ReceiverID[i];

a <- theta[s, 1];
f <- theta[s, 2];
ws <- alpha[s, 1];
rs <- alpha[s, 2];
ms <- alpha[s, 3];
wr <- alpha[re, 1];
rr <- alpha[re, 2];
mr <- alpha[re, 3];

if(x == -1){
  
  prob[i] <- f; 
  
}else if(t == 1){
  
  prob[i] <- a^x * f^(1 - x);

}else if(fmod(t, 2) == 0){
  
  prob[i] <- ((1- a - f) * (rr)^(t/2.0 - 1.0) * (rs)^(t/2.0 - 1.0) * (mr)^x * (wr)^(1-x)); 

}else {
   prob[i] <- ((1- a - f) * (rr)^(t/2.0 - 0.5) * (rs)^(t/2.0 - 1.5) * (ms)^(1 - x) * (ws)^x);
}

}

out ← sum(log(prob));
return out;

}
}

// The input data is a vector ‘y’ of length ‘N’.
data {
int N; // number of observations (rally lengths)
int M; // number of players
matrix [N, 2] dat; // touches, indicator, servereID and receiverID
int ServerID [N];
int ReceiverID [N];
int <lower = 2> m;
row_vector [3] beta1;
row_vector [3] beta2;

}

parameters {

 simplex [m] theta_1 [M];
 simplex [m] theta_2 [M];

}

// The model to be estimated.
model {
// Define priors

theta_1 ~ dirichlet(beta1);

theta_2 ~ dirichlet(beta2);

dat ~ tenismodel(theta_1, theta_2, ServerID, ReceiverID);

}

I am getting an error that “Ill-typed arguments to ‘~’ statement. No distribution ‘tenismodel’ was found with the correct signature.”

How we can give additional arguments in a user defined function to get the posterior?.

If you want to use the ~ syntax, the function name needs to end with _lpmf or _lpdf: 22.3 User-defined Distributions | Stan User’s Guide

Alternatively, you could use the target += syntax to get at the same thing

1 Like

Thank you. I will try this.