 # PDF from copula

#1

I have two discrete distributions and I wish to introduce dependence between them using a copula.

I can write the copula myself, but the output is P(X<=x, Y<=y). I wish to back out P(X=x, Y=y) = P(X<=x, Y<=y)- P(X<=x-1, Y<=y) - P(X<=x, Y<=y-1) + P(X<=x-1, Y<=y-1).

Previously I have done these using labelled structs in an e.g. vector. I could use a spare matrix of size M(max(x), max(y)) but I think it is inefficient in memory.

Is there a better way in Stan?

#2

Maybe I am missing something, but why don’t you just write something as:

``````functions {
real my_copula_cumulative(int x, int y, real param) {
<copula code>
}
real my_copula(int x, int y, real param) {
return my_copula(x,y, param) - my_copula(x-1,y, param) - my_copula(x, y -1, param) + my_copula(x-1,y-1, param);
}
}

model {
target += log(my_copula(...));
}
``````

Or are you trying to reuse computation or something?

#3

I was trying to reuse the computation, so to speed up the program. As it happens it isn’t long running and so I can live with the inefficiency for the moment.

It would be nice if STAN could have some caching feature on the inputs, but I appreciate that’s a big job and there’s all sorts of pitfalls with floating point precision etc.

#4

Is the log() necessary for the target+= statement??? Or we can sample from the joint pmf without taking it???

Many thanks

#5

Stan expects the `target` to contain the log density. So unless you did the log-transform elsewhere I believe this is necessary.