---
title: 'INLAspacetime: spatial model example'
author: "Elias Teixeira Krainski"
date: "February 2022, last update: `r format(Sys.Date(), '%B %d, %Y')`"
output: pdf_document
bibliography: INLAspacetime.bib
vignette: >
  %\VignetteIndexEntry{INLAspacetime: spatial model example}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
set.seed(1)
library(INLAspacetime)
knitr::opts_chunk$set(echo = TRUE)
```

## Abstract 

Build a SPDE model precision matrix, simulate data from and visualize. 

## Introduction 

Define a continuous domain Whittle-Matérn model 
considering the discretization method 
as proposed in @lindgren2011explicit. 

## Define the precison matrix 

Domain:
```{r domain}
domain <- cbind(x=c(0,10,10,0,0), y=c(0,0,5,5,0))
```

Build a mesh:
```{r mesh}
mesh <- mesh2d(domain=domain, max.edge=0.7, offset=2)
```

Build the Finite Element Method (FEM) matrices:
```{r fem}
fem <- mesh2fem(mesh, order=2)
```

Build the precision matrix for a given range and 
marginal variance, see @lindgren2015bayesian, 
for fixed $\nu=1$ or $\alpha=2$:
```{r precmat}
range <- 2.0 ## the empirically derived one
sigma2u <- 1.0 ### marginal variance
tau2 <- range^2/(4*pi*8*sigma2u) ### local variance
Qmesh <- tau2 * spde2precision(kappa=sqrt(8*pi)/range, fem, alpha=2)
```

## Sample from the model 

At the mesh nodes:
```{r samplemesh}
u0 <- drop(solve(Qmesh, rnorm(mesh$n)))
summary(u0)
```

Locations:
```{r locs}
nlocs <- 70
locs <- cbind(x=runif(nlocs, min(domain[,1]), max(domain[,1])),  
              y=runif(nlocs, min(domain[,2]), max(domain[,2])))
```

Projector matrix:
```{r projl}
Alocs <- mesh2projector(mesh, locs)
```

Project the samples to the locations:
```{r projx}
x <- drop(Alocs$proj$A %*% u0)
summary(x)
```

## Visualize 

Visualize the mesh and the location points with size 
proportional to the projected field at the locations.

```{r plotlocs}
par(mfrow=c(1,1), mar=c(0,0,1,0), mgp=c(1,0.5,0), las=1)
plot(mesh$SP)
points(locs, col=2, pch=19, cex=0.5+(x-min(x))/diff(range(x))) 
```

## References

