Hi INLA group,
Can I use “rgeneric” to code “slm” model?
Considering the following spatial lag model, taking the form
y=\rhoy+x\beta+e and e is a tiny noise term.
E(y)=(I-rhoW)^-1 x\beta
and
Var(y) = \sigma^2[(I-\rhoW)^T(I-\rhoW)] ^-1, so the precision is written
Prec(y)=\tau[(I-\rhoW)^T(I-\rhoW)]
I checked the "generic" vignette and found it can be used for a model with a mean structure.
However, I can not figure out how to code this term (I-rhoW)^-1 x\beta in generic, furthermore, theta contains four hyperparameters, how to code them?
And what about the Graph part in the code?
I copy my code below, but it does not run well.
Could you give me some hints to improve it?
Thanks in advance
Charles
'inla.rgeneric.SLM.model' <- function(
cmd = c("graph", "Q", "mu", "initial", "log.norm.const",
"log.prior", "quit"),
theta = NULL) {
prec.high = exp(15)
#Internal function
interpret.theta <- function() {
return(
list(prec = exp(theta[1L]),
rho = 1 / (1 + exp(-theta[2L]))),
a = theta[3L],
b = theta[4L]
)
}
graph = function() {
G = Diagonal(n = length(x), x=1)
return(G)
}
Q <- function() {
require(Matrix)
param <- interpret.theta()
return(param$prec * (Diagonal(nrow(W), x = 1) - param$rho * W) %*% t(Diagonal(nrow(W), x = 1) - param$rho * W))
}
mu <- function()
{
par = interpret.theta()
return( solve(Diagonal(nrow(W), x = 1) - param$rho * W) * (par$a + par$b * x))
}
log.norm.const <- function() {
return(numeric(0))
}
log.prior <- function() {
param = interpret.theta()
val =
(dgamma(param$prec, 1, .1, log = T) + log(param$prec) +
log(1) + log(param$rho) + log(1 - param$rho) +
dnorm(par$a, mean=0, sd=1, log=TRUE) +
dnorm(par$b, mean=0, sd=1, log=TRUE))
return(val)
}
initial <- function() {
return(rep(0, 2))
}
quit <- function() {
return(invisible())
}
if (is.null(theta))
theta <- initial()
res <- do.call(match.arg(cmd), args = list())
return(res)
}