-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtau_effect.Rmd
667 lines (520 loc) · 18.5 KB
/
tau_effect.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
---
title: "The rol of $\\tau$"
date: "Created: 05-07-2024. Last modified: `r format(Sys.time(), '%d-%m-%Y.')`"
output:
html_document:
mathjax: "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"
highlight: pygments
theme: flatly
code_folding: show # class.source = "fold-hide" to hide code and add a button to show it
# df_print: paged
toc: true
toc_float:
collapsed: true
smooth_scroll: true
number_sections: false
fig_caption: true
code_download: true
always_allow_html: true
bibliography:
- references.bib
- grateful-refs.bib
header-includes:
- \newcommand{\ar}{\mathbb{R}}
- \newcommand{\llav}[1]{\left\{#1\right\}}
- \newcommand{\pare}[1]{\left(#1\right)}
- \newcommand{\Ncal}{\mathcal{N}}
- \newcommand{\Vcal}{\mathcal{V}}
- \newcommand{\Ecal}{\mathcal{E}}
- \newcommand{\Wcal}{\mathcal{W}}
---
```{r xaringanExtra-clipboard, echo = FALSE}
htmltools::tagList(
xaringanExtra::use_clipboard(
button_text = "<i class=\"fa-solid fa-clipboard\" style=\"color: #00008B\"></i>",
success_text = "<i class=\"fa fa-check\" style=\"color: #90BE6D\"></i>",
error_text = "<i class=\"fa fa-times-circle\" style=\"color: #F94144\"></i>"
),
rmarkdown::html_dependency_font_awesome()
)
```
```{css, echo = FALSE}
body .main-container {
max-width: 100% !important;
width: 100% !important;
}
body {
max-width: 100% !important;
}
body, td {
font-size: 16px;
}
code.r{
font-size: 14px;
}
pre {
font-size: 14px
}
.custom-box {
background-color: #f5f7fa; /* Light grey-blue background */
border-color: #e1e8ed; /* Light border color */
color: #2c3e50; /* Dark text color */
padding: 15px; /* Padding inside the box */
border-radius: 5px; /* Rounded corners */
margin-bottom: 20px; /* Spacing below the box */
}
.caption {
margin: auto;
text-align: center;
margin-bottom: 20px; /* Spacing below the box */
}
```
Below we set some global options for all code chunks in this document.
```{r}
# Set seed for reproducibility
set.seed(593)
# Set global options for all code chunks
knitr::opts_chunk$set(
# Disable messages printed by R code chunks
message = FALSE,
# Disable warnings printed by R code chunks
warning = FALSE,
# Show R code within code chunks in output
echo = TRUE,
# Include both R code and its results in output
include = TRUE,
# Evaluate R code chunks
eval = TRUE,
# Enable caching of R code chunks for faster rendering
cache = FALSE,
# Align figures in the center of the output
fig.align = "center",
# Enable retina display for high-resolution figures
retina = 2,
# Show errors in the output instead of stopping rendering
error = TRUE,
# Do not collapse code and output into a single block
collapse = FALSE
)
# Start the figure counter
fig_count <- 0
# Define the captioner function
captioner <- function(caption) {
fig_count <<- fig_count + 1
paste0("Figure ", fig_count, ": ", caption)
}
# Define the function to truncate a number to two decimal places
truncate_to_two <- function(x) {
floor(x * 100) / 100
}
```
```{r}
gets_f_in_dist_mesh <- function(graph, f_values){
VtE <- graph$mesh$VtE
E <- graph$E
nE <- graph$nE
nV <- graph$nV
E_ext <- data.frame(edge_number = 1:nE, vertex_start = E[,1], vertex_end = E[,2])
original_vertex <- VtE[1:nV,]
f <- f_values[1:nV]
no_vertices <- cbind(VtE[(nV+1):length(f_values),], f_values[(nV+1):length(f_values)])
same_vertex_list <- list()
for (i in 1:nE) {
same_vertex_list[[i]] <- E_ext %>%
filter(vertex_start == i | vertex_end == i) %>%
mutate(lor = case_when(vertex_start == i ~ 0,vertex_end == i ~ 1)) %>%
dplyr::select(edge_number, lor) %>%
as.matrix()
}
for (i in seq_len(nrow(original_vertex))) {
current_row <- original_vertex[i, ]
# Find which matrix in same_vertex_list contains this row
for (j in seq_along(same_vertex_list)) {
if (any(apply(same_vertex_list[[j]], 1, function(x) all(x == current_row)))) {
# Add a new column with the corresponding value from f
same_vertex_list[[j]] <- cbind(same_vertex_list[[j]], f[i])
break
}
}
}
result_matrix <- do.call(rbind, same_vertex_list)
return(rbind(no_vertices, result_matrix))
}
```
Below we load the necessary libraries and define the auxiliary functions.
```{r}
library(rSPDE)
library(MetricGraph)
library(dplyr)
library(plotly)
library(scales)
library(patchwork)
library(tidyr)
library(here)
library(rmarkdown)
# Cite all loaded packages
library(grateful)
```
Let's build a small graph to illustrate the effect of $\tau$ on the graph.
```{r}
edge1 <- rbind(c(0,0),c(1,0))
edge2 <- rbind(c(0,0),c(0,1))
edge3 <- rbind(c(0,1),c(-1,1))
theta <- seq(from = pi,to = 3*pi/2,length.out = 50)
edge4 <- cbind(sin(theta),1+ cos(theta))
edges <- list(edge1, edge2, edge3, edge4)
```
```{r}
h = 0.01
graph <- metric_graph$new(edges = edges)
aux_graph <- graph$clone()
graph$build_mesh(h=h, continuous = TRUE)
edge_number <- graph$mesh$VtE
XY_graph <- graph$mesh$V
aux_graph$build_mesh(h=h, continuous = FALSE)
aux_edge_number <- aux_graph$mesh$VtE
aux_XY_graph <- aux_graph$mesh$V
```
```{r}
f <- edge_number[,1]/4 # discontinuous covariate
g <- 0.5*(XY_graph[, 1]^2 - XY_graph[, 2]^2) + 0.5 # continuous covariate
aux_f <- aux_edge_number[,1]/4# discontinuous covariate
aux_g <- 0.5*(aux_XY_graph[, 1]^2 - aux_XY_graph[, 2]^2) + 0.5 # continuous covariate
```
# Plot the functions. They play the role of covariates.
:::: {style="display: grid; grid-template-columns: 400px 400px; grid-column-gap: 1px;"}
::: {}
```{r, out.width = "100%", fig.cap = captioner("Discontinuous covariate.")}
aux_graph$plot_function(aux_f, vertex_size = 0, type = "plotly", line_color = "blue", line_width = 3, continuous = FALSE, interpolate_plot = FALSE) %>%
config(mathjax = 'cdn') %>%
layout(title = "Non-continuous covariate")
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Continuous covariate.")}
graph$plot_function(g, vertex_size = 0, type = "plotly", line_color = "red", line_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = "Continuous covariate")
```
:::
::::
```{r}
a = 1.8
normal_sample <- rnorm(length(g))
```
# Both covariates are continuous
```{r}
# Define the matrices B.tau and B.kappa
B.tau = cbind(0, 1, 0, g, 0)
B.kappa = cbind(0, 0, 1, 0, g)
# Log-regression coefficients
theta <- c(0, 0, 1, 1)
# Choose alpha
nu = 2.5
alpha = nu + 1/2
# Compute the operator
op <- rSPDE::spde.matern.operators(graph = graph,
B.tau = B.tau,
B.kappa = B.kappa,
parameterization = "spde",
theta = theta,
alpha = alpha)
# Simulate the non-stationary field
Sigma <- precision(op)
R <- chol(Sigma)
u = solve(R, normal_sample)
model_for_tau <- exp(B.tau[,-1]%*%theta)
model_for_kappa <- exp(B.kappa[,-1]%*%theta)
```
:::: {style="display: grid; grid-template-columns: 400px 400px 400px; grid-column-gap: 1px;"}
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\tau$.")}
graph$plot_function(model_for_tau, vertex_size = 0, type = "plotly", line_color = "blue", line_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\tau(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\kappa$.")}
graph$plot_function(model_for_kappa, vertex_size = 0, type = "plotly", line_color = "red", line_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\kappa(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Simulated field.")}
graph$plot_function(X = u, vertex_size = 0, type = "plotly", line_color = "darkgreen", line_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("u(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::::
# Both covariates are discontinuos
```{r}
tau <- 1
# Define the matrices B.tau and B.kappa
B.tau <- cbind(0, 1, 0, log(tau)*rep(1, length(f)), 0)
realB.tau <- cbind(0, 1, 0, f, 0)
B.kappa = cbind(0, 0, 1, 0, f)
# Log-regression coefficients
theta <- c(0, 0, 1, 1)
# Compute the operator
op1 <- rSPDE::spde.matern.operators(graph = graph,
B.tau = B.tau,
B.kappa = B.kappa,
parameterization = "spde",
theta = theta,
alpha = alpha)
realmodel_for_tau <- exp(realB.tau[,-1]%*%theta)
normal_sample1 <- normal_sample #rnorm(length(g))
Sigma1 <- precision(op1)
R1 <- chol(Sigma1)
u1cont <- solve(R1, normal_sample1)
u1 <-u1cont*tau/realmodel_for_tau
op2 <- rSPDE::spde.matern.operators(graph = graph,
B.tau = realB.tau,
B.kappa = B.kappa,
parameterization = "spde",
theta = theta,
alpha = alpha)
Sigma2 <- precision(op2)
R2 <- chol(Sigma2)
u2 = solve(R2, normal_sample1)
# To plot the models for tau and kappa
aux_B.tau = cbind(0, 1, 0, aux_f, 0)
aux_B.kappa = cbind(0, 0, 1, 0, aux_f)
model_for_tau <- exp(aux_B.tau[,-1]%*%theta)
model_for_kappa <- exp(aux_B.kappa[,-1]%*%theta)
```
```{r}
gg <- gets_f_in_dist_mesh(graph, u1cont)
aux_df <- data.frame(.edge_number = gg[,1], .distance_on_edge = gg[,2], f = gg[,3])
another_df <- cbind(tau/model_for_tau, aux_graph$mesh$VtE)
colnames(another_df) <- c("tau_rel", ".edge_number", ".distance_on_edge")
another_df <- as.data.frame(another_df)
# Step 1: Sort aux_df by the four columns
aux_df_sorted <- aux_df %>%
arrange(.edge_number, .distance_on_edge)
another_df_sorted <- another_df %>%
arrange(.edge_number, .distance_on_edge)
# Merge
merged_df <- cbind(aux_df_sorted, another_df_sorted)[c(1:4)] %>% mutate(final_f = f*tau_rel) %>% dplyr::select(-tau_rel, -f) %>% rename(edge_number = .edge_number, distance_on_edge = .distance_on_edge, f = final_f)
prod <- aux_graph$process_data(data = merged_df, normalized = TRUE)
```
:::: {style="display: grid; grid-template-columns: 400px 400px 400px; grid-column-gap: 1px;"}
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\tau$.")}
aux_graph$plot_function(model_for_tau, vertex_size = 0, type = "plotly", line_color = "blue", line_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\tau(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\kappa$.")}
aux_graph$plot_function(model_for_kappa, vertex_size = 0, type = "plotly", line_color = "red", line_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\kappa(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Simulated field.")}
aux_graph$plot_function(data = "f", newdata= prod, vertex_size = 0, type = "plotly", line_color = "darkgreen", line_width = 3, continuous = FALSE) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("u(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::::
# The covariate for $\tau$ is discontinuous and the covariate for $\kappa$ is continuous
```{r}
# Define the matrices B.tau and B.kappa
B.tau <- cbind(0, 1, 0, log(tau)*rep(1, length(f)), 0)
realB.tau <- cbind(0, 1, 0, f, 0)
B.kappa = cbind(0, 0, 1, 0, g)
# Log-regression coefficients
theta <- c(0, 0, 1, 1)
# Compute the operator
op1 <- rSPDE::spde.matern.operators(graph = graph,
B.tau = B.tau,
B.kappa = B.kappa,
parameterization = "spde",
theta = theta,
alpha = alpha)
realmodel_for_tau <- exp(realB.tau[,-1]%*%theta)
normal_sample2 <- normal_sample#rnorm(length(g))
Sigma1 <- precision(op1)
R1 <- chol(Sigma1)
u1cont <- solve(R1, normal_sample2)
u1 <-u1cont*tau/realmodel_for_tau
op2 <- rSPDE::spde.matern.operators(graph = graph,
B.tau = realB.tau,
B.kappa = B.kappa,
parameterization = "spde",
theta = theta,
alpha = alpha)
Sigma2 <- precision(op2)
R2 <- chol(Sigma2)
u2 = solve(R2, normal_sample2)
# To plot the models for tau and kappa
aux_B.tau = cbind(0, 1, 0, aux_f, 0)
model_for_tau <- exp(aux_B.tau[,-1]%*%theta)
model_for_kappa <- exp(B.kappa[,-1]%*%theta)
```
```{r}
gg <- gets_f_in_dist_mesh(graph, u1cont)
aux_df <- data.frame(.edge_number = gg[,1], .distance_on_edge = gg[,2], f = gg[,3])
another_df <- cbind(tau/model_for_tau, aux_graph$mesh$VtE)
colnames(another_df) <- c("tau_rel", ".edge_number", ".distance_on_edge")
another_df <- as.data.frame(another_df)
# Step 1: Sort aux_df by the four columns
aux_df_sorted <- aux_df %>%
arrange(.edge_number, .distance_on_edge)
another_df_sorted <- another_df %>%
arrange(.edge_number, .distance_on_edge)
# Merge
merged_df <- cbind(aux_df_sorted, another_df_sorted)[c(1:4)] %>% mutate(final_f = f*tau_rel) %>% dplyr::select(-tau_rel, -f) %>% rename(edge_number = .edge_number, distance_on_edge = .distance_on_edge, f = final_f)
prod <- aux_graph$process_data(data = merged_df, normalized = TRUE)
```
:::: {style="display: grid; grid-template-columns: 400px 400px 400px; grid-column-gap: 1px;"}
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\tau$.")}
aux_graph$plot_function(model_for_tau, vertex_size = 1, type = "plotly", line_color = "blue", line_width = 3, edge_color = "black", edge_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\tau(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\kappa$.")}
graph$plot_function(model_for_kappa, vertex_size = 1, type = "plotly", line_color = "red", line_width = 3, edge_color = "black", edge_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\kappa(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Simulated field.")}
aux_graph$plot_function(data = "f", newdata= prod, vertex_size = 1, type = "plotly", line_color = "darkgreen", line_width = 3, continuous = FALSE, interpolate_plot = FALSE, edge_color = "black", edge_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("u(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::::
# The covariate for $\tau$ is continuous and the covariate for $\kappa$ is discontinuous
```{r}
# Define the matrices B.tau and B.kappa
B.tau = cbind(0, 1, 0, g, 0) #rep(1, length(f))
B.kappa = cbind(0, 0, 1, 0, f)
# Log-regression coefficients
theta <- c(0, 0, 1, 1)
# Compute the operator
op <- rSPDE::spde.matern.operators(graph = graph,
B.tau = B.tau,
B.kappa = B.kappa,
parameterization = "spde",
theta = theta,
alpha = alpha)
# Simulate the non-stationary field
Sigma <- precision(op)
R <- chol(Sigma)
u = solve(R, normal_sample)
aux_B.kappa = cbind(0, 0, 1, 0, aux_f)
model_for_tau <- exp(B.tau[,-1]%*%theta)
model_for_kappa <- exp(aux_B.kappa[,-1]%*%theta)
```
:::: {style="display: grid; grid-template-columns: 400px 400px 400px; grid-column-gap: 1px;"}
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\tau$.")}
graph$plot_function(model_for_tau, vertex_size = 1, type = "plotly", line_color = "blue", line_width = 3, edge_color = "black", edge_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\tau(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Model for $\\kappa$.")}
aux_graph$plot_function(model_for_kappa, vertex_size = 1, type = "plotly", line_color = "red", line_width = 3, edge_color = "black", edge_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("\\kappa(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::: {}
```{r, out.width = "100%", fig.cap = captioner("Simulated field.")}
graph$plot_function(X = u, vertex_size = 1, type = "plotly", line_color = "darkgreen", line_width = 3, edge_color = "black", edge_width = 3) %>%
config(mathjax = 'cdn') %>%
layout(title = TeX("u(s)"),
font = list(family = "Palatino"),
showlegend = FALSE,
scene = list(
aspectratio = list(x = 1/2, y = 1, z = 1),
camera = list(
eye = list(x = -1*a, y = 0.5*a, z = 0.7*a))))
```
:::
::::
# References
```{r}
cite_packages(output = "paragraph", out.dir = ".")
```