rmvn <- function(n, mu=0, V = matrix(1)){
p <- length(mu)
if(any(is.na(match(dim(V),p))))
stop("Dimension problem!")
D <- chol(V)
t(matrix(rnorm(n*p), ncol=p)%*%D + rep(mu,rep(n,p)))
}
##Make some data
set.seed(1)
n <- 100
coords <- cbind(runif(n,0,1), runif(n,0,1))
x <- cbind(1, rnorm(n))
B <- as.matrix(c(1,5))
sigma.sq <- 5
tau.sq <- 1
phi <- 3/0.5
D <- as.matrix(dist(coords))
R <- exp(-phi*D)
w <- rmvn(1, rep(0,n), sigma.sq*R)
y <- rnorm(n, x%*%B + w, sqrt(tau.sq))
##Fit a Response and Latent NNGP model
n.samples <- 500
starting <- list("phi"=phi, "sigma.sq"=5, "tau.sq"=1)
tuning <- list("phi"=0.5, "sigma.sq"=0.5, "tau.sq"=0.5)
priors <- list("phi.Unif"=c(3/1, 3/0.01), "sigma.sq.IG"=c(2, 5), "tau.sq.IG"=c(2, 1))
cov.model <- "exponential"
m.s <- spNNGP(y~x-1, coords=coords, starting=starting, method="latent", n.neighbors=10,
tuning=tuning, priors=priors, cov.model=cov.model,
n.samples=n.samples, n.omp.threads=1)
summary(m.s)
plot(apply(m.s$p.w.samples, 1, median), w)
m.r <- spNNGP(y~x-1, coords=coords, starting=starting, method="response", n.neighbors=10,
tuning=tuning, priors=priors, cov.model=cov.model,
n.samples=n.samples, n.omp.threads=1)
summary(m.r)
##Fit with some user defined neighbor ordering
##ord <- order(coords[,2]) ##y-axis
ord <- order(coords[,1]+coords[,2]) ##x+y-axis
##ord <- sample(1:n, n) ##random
m.r.xy <- spNNGP(y~x-1, coords=coords, starting=starting, method="response", n.neighbors=10,
tuning=tuning, priors=priors, cov.model=cov.model,
ord=ord, return.neighbor.info=TRUE,
n.samples=n.samples, n.omp.threads=1)
summary(m.r.xy)
if (FALSE) {
##Visualize the neighbor sets and ordering constraint
n.indx <- m.r.xy$neighbor.info$n.indx
ord <- m.r.xy$neighbor.info$ord
##This is how the data are ordered internally for model fitting
coords.ord <- coords[ord,]
for(i in 1:n){
plot(coords.ord, cex=1, xlab="Easting", ylab="Northing")
points(coords.ord[i,,drop=FALSE], col="blue", pch=19, cex=1)
points(coords.ord[n.indx[[i]],,drop=FALSE], col="red", pch=19, cex=1)
readline(prompt = "Pause. Press to continue...")
}
}
Run the code above in your browser using DataLab