-
Notifications
You must be signed in to change notification settings - Fork 0
/
bivariate.Rmd
524 lines (429 loc) · 14.9 KB
/
bivariate.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
---
title: "Bivariate type-G models in Ngme2"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Bivariate type-G models in Ngme2}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
## Introduction
For many applications, we need to deal with multivariate data. In this vignette, we will introduce the bivariate model which supports modeling two (non-Gaussian) fields and their correlation jointly. The main reference is Bolin and Wallin (2020) [Multivariate Type G Matérn Stochastic Partial Differential Equation Random Fields](https://doi.org/10.1111/rssb.12351).
The `f` function specification is similar to ordinary model (See e.g. [Ngme2 AR(1) model](AR1-model.html)), but with two more fields to help identify the variables.
Extra arguments for the `f` are:
1. `group`: a vector of labels to indicate the group of different observations. For example, `group = c("field1", "field1", "field2", "field2", "field2)`.
If `group` is provided in `ngme()` function, no need to provide in `f()` function again.
2. `sub_models`: characters of length 2 with names equal to one of the labels in `group`, specifying the sub-models for the two fields. e.g. `sub_models=c(field1="rw1", field2="ar1")`.
We will see more examples in the following.
## Model structure
The bivariate model can model two fields $\mathbf{X}(s) = (X_1(s), X_2(s))$ jointly.
To model their correlation, we use dependence matrix $D(\theta, \rho)$ to correlate them (See Bolin and Wallin, 2020, section 2.2).
Remember that, for the univariate model, it can be written as:
$$ \mathcal{L} \mathbf{X}(s) = \mathcal{M},$$ where $\mathcal{L}$ is some operator, $\mathcal{M}$ represents the noise (Gaussian or non-Gaussian).
The bivariate model is similar, but with one more term to correlate the two fields:
$$ \mathbf{D(\theta, \rho)} diag(\mathcal{L_1}, \mathcal{L_2}) \mathbf{X}(s) = \mathcal{M},$$ where $\mathbf{D}$ is the dependence matrix. The noise can be classified into 4 types by their complexity, we will discuss them later.
The dependence matrix is defined as
$$
D(\theta, \rho) = \begin{pmatrix}
\cos(\theta) + \rho \sin(\theta) & -\sin(\theta) \sqrt{1+\rho^2} \\
\sin(\theta) - \rho \cos(\theta) & \cos(\theta) \sqrt{1+\rho^2}
\end{pmatrix},
$$
where $\theta \in [-\pi/4, \pi/4]$ and $\rho \in \mathbb{R}$. The $\theta$ controls the angle (rotation) of the bivariate model, and $\rho$ represents the cross-correlation between the two fields.
## One simple example
It's eaiser to understand with one exmaple. Say we have a time series model over 5 year from 2001 to 2005, with 2 fields *temperature* and *precipitation*. You want to model the two fields jointly. The data look like the following:
```{r toy-data, message=FALSE}
library(fmesher)
library(ngme2)
temp <- c(32, 33, 35.5, 36); year_temp <- c(2001, 2002, 2003, 2004)
precip <- c(0.1, 0.2, 0.5, 1, 0.2); year_pre <- c(2001, 2002, 2003, 2004, 2005)
# bind 2 fields in one vector, and make labels for them
y <- c(temp, precip); year <- c(year_temp, year_pre)
labels <- c(rep("temp", 4), rep("precip", 5)) # group is label for 2 fields
x1 <- 1:9
data <- data.frame(y, year, x1, labels)
data
```
Next we need to specify the model using `f()` function. Notice the way to specify 2 sub-models, and also 2 types of noises for each sub-model.
Notice that if we choose the Gaussian noise, we need to specify the model type as "bv_normal" so that the rotation is fixed to 0 (no rotation). If we choose the non-Gaussian noise, we can use "bv" model type.
```{r toy-model}
# 1st way: simply put model types, using both c() and list() are ok
# Choose model="bv_normal" if use Gaussian noise,
bv1 <- f(
year, model = "bv_normal",
theta = pi / 8, rho = 0.5,
sub_models = list(precip="ar1", temp="rw1"),
group = labels, # can be inherited from ngme() function
noise = list(
precip=noise_normal(),
temp=noise_normal()
)
)
bv1
# 2nd way: allow more argument for sub_models
bv_normal <- f(
year, model = "bv",
sub_models = list(
precip=list(model="ar1", rho=0.5), # specify correlation parameter for ar1 model
temp=list(model="rw1")
),
group = labels,
noise = list(
precip=noise_nig(),
temp=noise_nig()
)
)
bv_normal
```
## Four increasing construction of noise
In bivariate models, we can have more detailed control over the noise of the model. The noise can be classified into 4 category (See Bolin and Wallin, 2020, section 3.1 for details):
- Type-G1: single mixing variable V, share V over 2 fileds.
- Type-G2: single V, different V for each field.
- Type-G3: general V, share V.
- Type-G4: general V, different V.
We can specify the type of noise by the following:
```{r type-G}
t1 <- f(
year, model = "bv",
sub_models = list(precip="ar1", temp="rw1"),
group = labels,
noise = list(
precip=noise_nig(single_V=TRUE),
temp=noise_nig(single_V=TRUE),
share_V = TRUE
)
)
t1
t2 <- f(
year, model = "bv",
sub_models = list(precip="ar1", temp="rw1"),
group = labels,
noise = list(
precip=noise_nig(single_V=TRUE),
temp=noise_nig(single_V=TRUE)
)
)
t2
t3 <- f(
year, model = "bv",
sub_models = list(precip="ar1", temp="rw1"),
group = labels,
noise = list(
precip=noise_nig(),
temp=noise_nig(),
share_V = TRUE
)
)
t3
t4 <- f(
year, model = "bv",
sub_models = list(precip="ar1", temp="rw1"),
group = labels,
noise = list(
precip=noise_nig(),
temp=noise_nig()
)
)
t4
```
## Interaction with other fields (e.g. fixed effects)
When it involves more than one field, things get complicated. When we have fixed effects but only for 1 field, we can use the special syntax `fe(<formula>, which_group=<group_name>)`. The argument `which_group` will tell which field we have fixed effects on. It works similar for modeling using `f()` function.
Here is one example, we have different fixed effects on different fields (Intercept for both fields, and *x1* for only *precip* field).
```{r fixed-effect, cache=TRUE}
m1 <- ngme(
y ~ 0 + fe(~1, which_group = "temp") +
fe(~1+x1, which_group = "precip") +
f(year, model="rw1", which_group = "temp") +
f(year,
model = "bv",
sub_models = list(precip="ar1", temp="rw1"),
noise = list(
precip = noise_nig(),
temp = noise_nig()
)
),
data = data,
group = data$labels,
control_opt = control_opt(estimation = FALSE)
)
# examine the design matrix
m1$replicates[[1]]$X
```
## The correlated measurement noise
Now since we are taking measures of 2 different fields, there is some situation that we might want to assume the measurement of 2 fields have some correlation.
It can be written as $Y = X \beta + A W + \epsilon$, here $W$ is the bivariate model, and $\epsilon | V_{\epsilon} \sim N(0, \Sigma)$, $\Sigma_{i j} \neq 0$ if $Y_i$ and $Y_j$ are 2 different fields but measured at same location.
Now we need to modify the `family` argument in `ngme` function, we need to set `corr_measurement` and give the `index_corr` to indicate which observations are correlated.
We will see how to estimate it in the next example.
## Put it all together (Simulation + Estimation example)
In this example, we will first use `simulate` function to simulate the hidden bivariate process. Notice that we need to provide the labels for the 2 fields. Then we will generate the measurement noise $\epsilon$ with some correlation. Finally, we will use the `ngme` function to estimate the model.
### Ex1. Fixed effects + Bivariate model (AR1, Normal) + Correlated measurement noise
```{r}
n_obs <- 2000
n_each <- n_obs / 2
group <- rep(c("W1", "W2"), n_each)
reorder_loc = sample(1:n_each)
reorder_loc = 1:n_each
sim_fields <- simulate(
f(rep(reorder_loc, each=2),
model="bv_normal",
rho=3,
c1=1, c2=1,
sub_models = list(
W1 = list(model="ar1", rho=0.6),
W2 = list(model="ar1", rho=-0.4)
),
group=group,
noise=list(
W1 = noise_normal(sigma = 1),
W2 = noise_normal(sigma = 1)
)
)
)[[1]]
# Check the correlation of the simulated fields
# acf(sim_fields[group=="W1"])
# acf(sim_fields[group=="W2"])
# Here we assume fields W1 and W2 have positive correlated measurement error
# if they are measured at same index.
# Meaning Y(i) and Y(j) have correlated measurement noise
# if they represent underlying W1(index=k) and W2(index=k)
# Generate covariance matrix for measurement noise
sd_1 = 0.6; sd_2 = 0.9; rho_e = 0.9
Cov_same_idx <- matrix(c(sd_1^2, rho_e*sd_1*sd_2, rho_e*sd_1*sd_2, sd_2^2), nrow=2)
print("The covariance matrix for 2 correlated fields: ")
print(Cov_same_idx)
tmp <- replicate(n_each, Cov_same_idx, simplify = FALSE)
Cov_measurement <- Matrix::bdiag(tmp)
# e ~ N(0, Cov_measurement)
L <- t(chol(Cov_measurement))
e <- L %*% rnorm(n_obs)
# fixed effects
x1 <- rexp(n_obs)
x2 <- rnorm(n_obs)
feff <- c(-3, 1.5)
Y <- sim_fields + x1 * feff[1] + x2 * feff[2] + as.numeric(e)
B_sigma = matrix(0, nrow=n_obs, ncol=2)
B_sigma[group=="W1", 1] = 1
B_sigma[group=="W2", 2] = 1
bvar_cor <- ngme(
Y ~ 0 + x1 + x2 +
f(rep(reorder_loc, each=2),
model="bv_normal",
name = "bv",
sub_models = list(W1 = "ar1", W2 = "ar1"),
noise=list(
W1 = noise_normal(),
W2 = noise_normal()
)
),
group = group,
family = noise_normal(
corr_measurement = TRUE,
index_corr = rep(1:n_each, each=2),
rho = 0.5,
B_sigma = B_sigma,
theta_sigma = c(0, 0)
),
data = data.frame(Y, x1, x2),
control_opt = control_opt(
n_parallel_chain = 4,
optimizer = adam(stepsize = 0.01),
iterations = 5000,
iters_per_check = 1,
rao_blackwellization = TRUE,
seed = 7
)
)
bvar_cor
# Compare the estimated value with the simulated value
traceplot(bvar_cor, "bv", hline=c(3,1,1,0.6,-0.4))
traceplot(bvar_cor, hline=c(log(sd_1), log(sd_2), rho_e, -3, 1.5))
```
### Ex2. Fixed effects + Bivariate model (AR1, NIG) + Correlated measurement noise
```{r corr-measurement, cache=TRUE}
set.seed(125)
n_obs <- 1000
n_each <- n_obs / 2
group <- c(rep("W1", n_each), rep("W2", n_each))
theta = pi/8; rho = 2; rho_1 = 0.6; rho_2 = 0.4
mu_1 = -2; sigma_1 = 1; nu_1 = 1
mu_2 = 2; sigma_2 = 2; nu_2 = 0.5
reorder_loc = sample(1:n_each)
sim_fields <- simulate(
f(c(reorder_loc, reorder_loc),
model="bv",
theta = theta,
rho = rho,
sub_models = list(
W1 = list(model="ar1", rho=rho_1),
W2 = list(model="ar1", rho=rho_2)
),
group=group,
noise=list(
W1 = noise_nig(mu=mu_1, sigma=sigma_1, nu=nu_1),
W2 = noise_nig(mu=mu_2, sigma=sigma_2, nu=nu_2)
)
)
)[[1]]
# Same as previous
Cov_same_idx <- matrix(c(1, 0.7, 0.7, 1), nrow=2)
Cov_measurement <- Cov_same_idx %x% diag(n_obs / 2)
# e ~ N(0, Cov_measurement)
L <- t(chol(Cov_measurement))
e <- L %*% rnorm(n_obs)
# fixed effects
x1 <- rexp(n_obs)
x2 <- rnorm(n_obs)
feff <- c(-3, 1.5)
Y <- sim_fields + x1 * feff[1] + x2 * feff[2] + as.numeric(e)
out <- ngme(
Y ~ 0 + x1 + x2 +
f(c(reorder_loc, reorder_loc),
model="bv",
name = "bv",
sub_models = list(W1 = "ar1", W2 = "ar1"),
noise=list(
W1 = noise_nig(),
W2 = noise_nig()
)
),
group = group,
family = noise_normal(
corr_measurement = TRUE,
index_corr = c(1:n_each, 1:n_each)
),
data = data.frame(Y, x1, x2),
control_opt = control_opt(
optimizer = adam(),
iterations = 5000,
# verbose = TRUE,
n_parallel_chain = 4,
seed = 113
)
)
out
# comparing with simulated value
traceplot(
out, "bv",
hline=c(theta, rho, rho_1, rho_2,
mu_1, mu_2, sigma_1, sigma_2, nu_1, nu_2)
)
```
### Ex3. Fixed effects + Bivariate model (Matérn, Normal) + Correlated measurement noise
Next, we consider a spatial bivariate Matérn model with correlated noise.
The `model="bv_matern_normal"` can be used specifically only for bivariate model with Gaussian driven noise, so that the parameterization matches with the paper.
```{r spatial}
pl01 <- cbind(c(0, 1, 1, 0, 0) * 10, c(0, 0, 1, 1, 0) * 5)
mesh <- fmesher::fm_mesh_2d(
loc.domain = pl01,
cutoff = 0.2,
max.edge = c(0.5, 10)
)
mesh$n
n_obs <- 1000
# generate random locations (same for two fields)
long <- runif(n_obs/2, 0, 10); lat <- runif(n_obs/2, 0, 5)
long <- c(long, long); lat <- c(lat, lat)
group <- c(rep("W1", n_obs/2), rep("W2", n_obs/2))
# plot the mesh
plot(mesh); points(long, lat)
# parameters of the bivariate model
theta = 0; rho = 1;
theta_K_1 = log(2); theta_K_2 = log(5);
mu_1 = -2; sigma_1 = 0.5; nu_1 = 1
mu_2 = 2; sigma_2 = 0.3; nu_2 = 0.5
true_model <- f(
~ long + lat,
theta = theta,
rho = rho,
mesh = mesh,
sd1=sigma_1, sd2=sigma_2,
model = "bv_matern_normal",
sub_models = list(
W1 = list(model = "matern", theta_K = theta_K_1),
W2 = list(model = "matern", theta_K = theta_K_2)
),
group = group,
noise = list(
W1 = noise_normal(),
W2 = noise_normal()
)
)
W <- simulate(true_model)[[1]]
sd_1 = 0.6; sd_2 = 0.9; rho_e = 0.9
Cov_same_idx <- matrix(c(sd_1^2, rho_e*sd_1*sd_2, rho_e*sd_1*sd_2, sd_2^2), nrow=2)
Cov_measurement <- Cov_same_idx %x% diag(n_obs / 2)
# e ~ N(0, Cov_measurement)
L <- t(chol(Cov_measurement))
e <- L %*% rnorm(n_obs)
# fixed effects
x1 <- rexp(n_obs)
x2 <- rnorm(n_obs)
feff <- c(-3, 1.5)
Y <- sim_fields + x1 * feff[1] + x2 * feff[2] + as.numeric(e)
B_sigma = matrix(0, nrow=n_obs, ncol=2)
B_sigma[group=="W1", 1] = 1
B_sigma[group=="W2", 2] = 1
out_cor <- ngme(
Y ~ 0 + f(
~ long + lat,
mesh = mesh,
model = "bv_normal",
name = "bv",
sub_models = list(
W1 = list(model = "matern"),
W2 = list(model = "matern")
),
# debug=T,
noise = list(
W1 = noise_normal(),
W2 = noise_normal()
)
),
group = group,
family = noise_normal(
corr_measurement = TRUE,
index_corr = c(1:(n_obs/2), 1:(n_obs/2)),
B_sigma = B_sigma,
theta_sigma = c(0, 0)
),
data = data.frame(Y, long, lat),
control_opt = control_opt(
iterations = 5000,
n_parallel_chain = 4,
rao_blackwellization = TRUE,
# verbose = TRUE,
print_check_info = FALSE,
seed = 50
),
debug = FALSE
)
out_cor
# comparing with simulated value
traceplot(
out_cor, "bv",
hline=c(rho, sigma_1, sigma_2, exp(theta_K_1), exp(theta_K_2))
)
traceplot(
out_cor,
hline=c(log(sd_1), log(sd_2), rho_e)
)
```
## Helper tool to build correlation index between two fields
Sometimes it's tedious to provide to `index_corr` argument to indicate which observations are correlated,
we can use the helper function `compute_index_corr_from_map` to reduce the work.
It can helps to compute the distance (both 1d or 2d distance) given the location we want to use.
If some of them are close enough, then we will correlate them.
```{r compute_index_corr_from_map}
# provide the x,y coordinate (2d locations)
x_coord <- c(1.11, 2.5, 1.12, 2, 1.3, 1.31)
y_coord <- c(1.11, 3.3, 1.11, 2, 1.3, 1.3)
coords <- data.frame(x_coord, y_coord)
# here we can see 2 pairs (1 and 3, 5 and 6) of observations are close enough
compute_index_corr_from_map(coords, eps = 0.1)
```
<!-- ## Cross-validation for the bivariate model -->