-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiproxy-mbr.Rmd
1427 lines (1204 loc) · 45.2 KB
/
multiproxy-mbr.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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Multi-Proxy, Multi-Season Streamflow Reconstruction with Mass Balance Adjustment"
output:
html_document:
theme: journal
toc: yes
toc_float: yes
highlight: tango
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(fig.retina = 2)
```
# Introduction
This code repository reproduces the results of the manuscript "Multi-Proxy, Multi-Season Streamflow Reconstruction with Mass Balance Adjustment" by Hung Nguyen, Stefano Galelli, Chenxi Xu, and Brendan Buckley. The manuscript is currently available as a preprint with [DOI: 10.1002/essoar.10504791.1](https://www.essoar.org/doi/10.1002/essoar.10504791.1).
The repository contains all data used in and results produced by the paper. Data are stored in the folder `data/`. R scripts that are used as subroutines are in the folder `R/`. Pre-computed results are stored in the folder `results/`.
The package `mbr`, in which the mass-balance-adjusted regression is implemented, is currently available on GitHub. Before we start, please install it with
```{r, eval=FALSE}
install.packages('remotes')
remotes::install_github('ntthung/mbr')
```
Next, we load the necessary packages and utility functions.
```{r, message=FALSE, warning=FALSE}
source('R/init.R')
source('R/correlation_functions.R')
source('R/input_selection_functions.R')
```
We also use some special fonts for the plots, so we need to load them as well.
```{r, echo=FALSE, eval=FALSE}
if (!require(extrafont)) install.packages('extrafont')
extrafont::loadfonts(quiet = TRUE) # For MAC
extrafont::loadfonts(device = 'win', quiet = TRUE) # For Windows
```
```{r, include=FALSE}
if (!require(extrafont)) install.packages('extrafont')
extrafont::loadfonts() # For MAC
extrafont::loadfonts(device = 'win') # For Windows
```
We are now ready to proceed with the workflow.
# Data and Preprocessing
## Tree ring proxies
```{r}
# Read the metadata
crnMeta <- fread('data/crnMeta.csv', key = 'site') # Ring width chronologies
oxiMeta <- fread('data/oxiMeta.csv', key = 'site') # Oxygen isotope
# Labelling for plots
oxiLab <- function(s) oxiMeta[s, display]
crnLab <- function(s) crnMeta[s, display]
meta <- rbind(oxiMeta[, .(site, display)], crnMeta[, .(site, display)])
setkey(meta, site)
siteLab <- function(s) meta[s, display]
# Markdown code to make the species displayed in italic
crnMeta[, species := paste0('*', species, '*')]
oxiMeta[, species := paste0('*', species, '*')]
# Some other labelling functions
seasonClass <- fread('data/season_class.csv', key = 'season')
ssnLabBrief <- function(x) seasonClass[x, type]
lambdaLab <- function(x) sapply(x, function(v) paste0('\u03bb = ', v))
dark2 <- RColorBrewer::brewer.pal(3, 'Dark2')[c(2, 1, 3)]
metricLab <- function(x) replace(x, x == 'R2', 'R\u00b2')
to_char_1dp <- function(x) sprintf("%.1f", x)
```
### Map
**Figure 1** was made in QGIS, but we can produce a similar map here with R.
```{r map, fig.width=7, fig.height=6}
# Map
ggplot() +
# Country borders
geom_polygon(
aes(long, lat, group = group),
map_data('world', c('Vietnam', 'Laos', 'Cambodia', 'Thailand', 'Myanmar')),
fill = 'gray98', colour = 'black') +
# Ring width sites
geom_point(
aes(long, lat, colour = species, shape = 'Ring width'),
size = 2,
crnMeta) +
# Oxygen isotope sites
geom_point(
aes(long, lat -0.25, colour = species, shape = 'δ<sup>18</sup>O'),
size = 2,
oxiMeta) +
# Map theming
scale_x_continuous(name = NULL, labels = pasteLong) +
scale_y_continuous(name = NULL, labels = pasteLat) +
scale_colour_brewer(name = 'Species', palette = 'Set1') +
scale_shape_discrete(name = 'Proxy') +
coord_quickmap() +
theme(
legend.key.height = unit(0.75, 'cm'),
legend.text = element_markdown()) +
panel_border('black', 0.2)
```
### Time series
Now we read the proxy data and infill them with the package `missMDA`.
```{r impute}
# Read data
oxi <- fread('data/oxi.csv', key = 'site')
crn <- fread('data/crn.csv', key = 'site')
# Count number of years in each chronology
crnCount <- crn[year %in% 1748:2005, .(first = year[1], final = year[.N], .N), by = site
][order(N, decreasing = TRUE)
][, ID := .GRP, by = site]
oxiCount <- oxi[year %in% 1748:2005, .(first = year[1], final = year[.N], .N), by = site
][order(N, decreasing = TRUE)
][, ID := .GRP, by = site]
# Imputation
crnWideFull <- crn[year %in% 1748:2005, dcast(.SD, year ~ site, value.var = 'rwi')]
crnMatFull <- as.matrix(crnWideFull[, -'year'])
crnImpModel <- imputePCA(crnMatFull, ncp = 19)
crnMatFilled <- crnImpModel$completeObs
crnWideFilled <- as.data.table(crnMatFilled)
attributes(crnImpModel$fittedX) <- attributes(crnImpModel$completeObs)
crnPcaImputed <-
as.data.table(crnImpModel$fittedX)[, year := crnWideFull$year] %>%
melt(id.var = 'year', variable.name = 'site', value.name = 'X')
oxiWideFull <- oxi[year %in% 1748:2005, dcast(.SD, year ~ site, value.var = 'do18')]
oxiMatFull <- as.matrix(oxiWideFull[, -'year'])
oxiImpModel <- imputePCA(oxiMatFull, ncp = 3)
oxiMatFilled <- oxiImpModel$completeObs
oxiWideFilled <- as.data.table(oxiMatFilled)
attributes(oxiImpModel$fittedX) <- attributes(oxiImpModel$completeObs)
oxiPcaImputed <-
as.data.table(oxiImpModel$fittedX)[, year := oxiWideFull$year] %>%
melt(id.var = 'year', variable.name = 'site', value.name = 'X')
```
**Figure S5**
```{r, fig.width=8, fig.height=7}
crnSpan <- ggplot(crnCount) +
geom_rect(
aes(xmin = first, xmax = final, ymin = ID - 1, ymax = ID + 0.1),
fill = 'steelblue') +
geom_text(
aes(1950, ID - 0.5, label = crnLab(site)),
colour = 'wheat',
fontface = 'bold',
size = 3.5) +
scale_x_continuous(expand = c(0, 0), breaks = seq(1750, 2005, 10), labels = skip_label(5)) +
scale_y_continuous(expand = c(0, 0)) +
labs(x = NULL, y = 'Number of chronologies', subtitle = 'Ring width') +
theme(
plot.subtitle = element_text(face = 'bold'),
panel.background = element_rect('gray95'),
panel.grid = element_blank())
oxiSpan <- ggplot(oxiCount) +
geom_rect(
aes(xmin = first, xmax = final, ymin = ID - 1, ymax = ID + 0.1), fill = 'steelblue') +
geom_text(
aes(1950, ID - 0.5, label = oxiLab(site)),
colour = 'wheat',
fontface = 'bold',
size = 3.5) +
scale_x_continuous(expand = c(0, 0), breaks = seq(1750, 2005, 10), labels = skip_label(5)) +
scale_y_continuous(expand = c(0, 0)) +
labs(x = NULL, y = 'Number of chronologies', subtitle = 'δ<sup>18</sup>O') +
theme(
plot.subtitle = element_markdown(face = 'bold'),
panel.background = element_rect('gray95'),
panel.grid = element_blank())
crnSpan + oxiSpan +
plot_layout(heights = c(5, 1.2)) +
plot_annotation(title = 'Temporal coverage')
```
**Figure S6**
```{r, fig.width=8, fig.height=8}
crnImpPlot <- ggplot() +
geom_line(aes(year, rwi, colour = 'RWI', linetype = 'RWI'), crn[year >= 1748]) +
geom_line(aes(year, X, colour = 'Imputed', linetype = 'Imputed'), crnPcaImputed) +
scale_colour_manual(
name = NULL,
breaks = c('RWI', 'Imputed'),
values = c('steelblue', 'darkorange')) +
scale_linetype_manual(
name = NULL,
breaks = c('RWI', 'Imputed'),
values = c(1, 2)) +
facet_wrap(
vars(site),
labeller = as_labeller(crnLab),
ncol = 4,
scales = 'free_y') +
labs(x = NULL, y = 'RWI')
oxiImpPlot <- ggplot() +
geom_line(
aes(year, do18, colour = 'δ<sup>18</sup>O', linetype = 'δ<sup>18</sup>O'),
oxi[year >= 1748]) +
geom_line(
aes(year, X, colour = 'Imputed', linetype = 'Imputed'),
oxiPcaImputed) +
scale_colour_manual(
name = NULL,
breaks = c('δ<sup>18</sup>O', 'Imputed'),
values = c('steelblue', 'darkorange')) +
scale_linetype_manual(
name = NULL,
breaks = c('δ<sup>18</sup>O', 'Imputed'),
values = c(1, 2)) +
facet_wrap(
vars(site),
labeller = as_labeller(oxiLab),
ncol = 4,
scales = 'free_y') +
labs(x = NULL, y = 'δ<sup>18</sup>O') +
theme(
axis.title.y = element_markdown(),
legend.text = element_markdown())
pl <- crnImpPlot + oxiImpPlot &
theme(
strip.background = element_blank(),
strip.text = element_text(face = 'plain'),
legend.position = 'top',
legend.key.width = unit(2, 'cm'),
panel.border = element_rect(NA, 'black', 0.2))
pl +
plot_layout(ncol = 1, heights = c(5, 1)) +
plot_annotation(title = 'Comparing imputed values with proxies')
```
## Streamflow
### Exploring monthly streamflow
**Figure S1**
```{r, fig.width=8, fig.height=6}
p1m <- fread('data/P1-monthly.csv')
p1m[, Qa := sum(Qm), by = year]
ggplot(p1m[year %in% 1922:2016]) +
geom_point(aes(Qa, Qm / Qa * 100), colour = 'steelblue') +
facet_wrap(
vars(month),
labeller = as_labeller(monthLab),
ncol = 4,
scales = 'free') +
labs(x = 'Annual flow [Mm\u00b3]', y = 'Monthly flow fraction [%]') +
panel_border('black', 0.2)
```
**Figure 1c**
```{r, fig.width=8, fig.height=4}
ggplot(p1m) +
geom_boxplot(aes(factor(month, labels = month.abb), Qm)) +
labs(x = NULL, y = 'Q [Mm\u00b3]')
```
### Season delineation
Read daily data.
```{r daily-data}
p1d <- fread('data/P1-daily-raw.csv')
# Calculate day of the year
p1d[, doy := {
date <- paste(year, month, day, sep = '-') %>% as.Date(format = c('%Y-%B-%d'))
yday(date)
}]
# Ignore leap days
p1d <- p1d[!(year %% 4 == 0 & doy == 60)]
p1d[year %% 4 == 0 & doy > 59, doy := doy - 1]
# Convert flow rate to volumetric (m3/s to million m3 each day)
p1d[, Qv := cumsum(Q * 0.0864), by = year]
p1dfy <- p1d[year %in% 1922:2016] # Full years
setkey(p1dfy, year, doy)
```
Two-phase linear regression, following Cook and Buckley (2009).
```{r change-point}
# Changepoint functions
ssq_left_right <- function(x, t.range, d) {
idx1 <- which(t.range <= d)
idx2 <- which(t.range > d)
t1 <- matrix(c(rep(1, length(idx1)), t.range[idx1]), ncol = 2)
t2 <- matrix(c(rep(1, length(idx2)), t.range[idx2]), ncol = 2)
left <- .lm.fit(t1, x[idx1])$residuals
right <- .lm.fit(t2, x[idx2])$residuals
sum(left^2) + sum(right^2)
}
# doy.range: vector of days of the year, must be contiguous
scan_2lr <- function(DT, doy.range, scan.range, var.name) {
dt <- DT[doy %in% doy.range]
x <- dt[, get(var.name)]
ssq <- sapply(scan.range, ssq_left_right, x = x, t.range = doy.range)
data.table(doy = scan.range, ssq = ssq)
}
summary_2lr <- function(ssq) ssq[which.min(ssq)][, date := doy_to_ddMMM(doy)][]
plot_2lr <- function(ssq, nudge_y = 2) {
changeDate <- summary_2lr(ssq)
ggplot(ssq, aes(doy, ssq)) +
geom_line(colour = 'steelblue') +
geom_point(data = changeDate, colour = 'steelblue') +
geom_text(aes(label = date), changeDate, nudge_y = nudge_y) +
labs(x = 'Day of year', y = 'RSS') +
theme_classic()
}
dryRange <- seq( 1, 280)
dryScan <- seq( 51, 270)
wetRange <- seq(220, 365)
wetScan <- seq(230, 355)
d2wAnn <- p1dfy[, summary_2lr(scan_2lr(.SD, dryRange, dryScan, 'Qv')), by = year]
w2dAnn <- p1dfy[, summary_2lr(scan_2lr(.SD, wetRange, wetScan, 'Qv')), by = year]
annualWetSeason <- merge(d2wAnn[, .(year, doy, date)], w2dAnn[, .(year, doy, date)],
by = 'year',
suffixes = c('sta', 'fin'))
```
**Figure S2**
```{r, fig.width=8, fig.height=7}
Qtails <- p1dfy[, last(.SD), by = year
][order(Qv), rbind(head(.SD, 3), last(.SD, 3))]
yearOrder <- Qtails$year
cumuPlot <- ggplot(p1dfy) +
geom_line(aes(doy, Qv, group = year), na.rm = TRUE, colour = 'gray', size = 0.2) +
geom_line(
aes(doy, Qv, group = year, colour = factor(year, levels = yearOrder)),
p1d[year %in% Qtails$year],
size = 0.4, show.legend = FALSE) +
geom_text(
aes(366, Qv, label = year),
Qtails,
vjust = c(0.5, 0.5, 0.5, 0.9, 0.5, 0.5),
hjust = 0,
size = 2.5) +
stat_summary(aes(doy, Qv), fun = mean, geom = 'line', na.rm = TRUE, size = 0.6) +
scale_x_continuous(breaks = c(1, 100, 200, 300), labels = doy_month_label) +
scale_colour_brewer(palette = 'RdBu') +
labs(x = 'Day of the year', y = 'Q [million m\u00b3]')
p1 <- ggplot(annualWetSeason) +
geom_linerange(aes(year, ymin = doysta, ymax = doyfin), colour = 'gray', size = 0.2) +
geom_line(aes(year, doysta), size = 0.2, colour = 'darkorange') +
geom_line(aes(year, doyfin), size = 0.2, colour = 'steelblue') +
geom_point(aes(year, doysta), size = 0.7, colour = 'darkorange') +
geom_point(aes(year, doyfin), size = 0.7, colour = 'steelblue') +
scale_colour_manual(name = NULL, values = c('darkgreen', 'steelblue')) +
scale_x_continuous(breaks = seq(1920, 2015, 5),
labels = function(x) ifelse(x %% 10 == 0, x, '')) +
scale_y_continuous(breaks = c(110, seq(100, 300, 50)), labels = doy_month_label) +
labs(x = 'Year', y = 'Day of the year') +
theme(legend.position = 'none')
p2 <- ggplot(annualWetSeason) +
geom_density(
aes(y = doysta),
size = 0.3,
colour = 'darkorange',
fill = 'darkorange',
alpha = 0.25) +
geom_density(
aes(y = doyfin),
size = 0.3,
colour = 'steelblue',
fill = 'steelblue',
alpha = 0.25) +
geom_hline(aes(yintercept = mean(doysta)), size = 0.2, colour = 'darkorange') +
geom_hline(aes(yintercept = mean(doyfin)), size = 0.2, colour = 'steelblue') +
scale_x_continuous(breaks = scales::pretty_breaks(2)) +
scale_y_continuous(breaks = c(110, seq(100, 300, 50))) +
labs(x = 'Density', y = NULL) +
theme(
plot.tag.position = c(-0.2, 1),
plot.margin = margin(l = 20),
axis.text.y = element_blank())
delinPlot <- p1 + p2 +
plot_layout(widths = c(4, 1))
wrap_plots(cumuPlot) + wrap_plots(delinPlot) +
plot_layout(ncol = 1, heights = c(1.5, 1)) +
plot_annotation(tag_levels = 'a', tag_suffix = ')')
```
### Daily streamflow naturalization
We use robust empirical quantile mapping, following Gudmundsson *et al*. (2012). The procedure is implemented in the package `qmap` (Gudmundsson, 2016). See also Robeson *et al.* (2020).
```{r naturalization}
# Merge VIC-Res simulated streamflow to daily streamflow
p1MergeDaily <- merge(
p1d[year %in% 1922:2005, .(year, month = match(month, month.abb), day, Qobs = Q)],
fread('data/P1-VIC-Res.csv'),
on = c('year', 'month', 'day'))
p1MergeDaily[, period := fifelse(year > 1985, 'Since 1985', 'Before 1985')]
#N aturalize with quantile mapping.
p1MergeDaily[, Qnat := {
fit <- fitQmap(.SD[period == 'Before 1985', Qobs],
.SD[period == 'Before 1985', Qvic],
'RQUANT',
nlls = 30, wet.day = 0.01, nboot = 100)
doQmap(.SD[, Qvic], fit)
}, by = month]
# Calculate monthly means
p1Mon <- p1MergeDaily[, lapply(.SD, mean), by = .(year, month, period), .SDcols = -'day']
p1MonLong <- melt(
p1Mon[period == 'Before 1985', -'period'], # Use data before 1985 only
id.var = c('year', 'month'),
variable.name = 'type',
value.name = 'Q',
variable.factor = FALSE)
# Calculate volumetric flow
p1DayLong <- melt(
p1MergeDaily[, -'period'],
id.var = c('year', 'month', 'day'),
variable.name = 'type',
value.name = 'Q',
variable.factor = FALSE)
p1DayLong[, Q := Q * 3600 * 24 / 1e6]
p1MonVol <- p1DayLong[, .(Q = sum(Q)), by = .(year, month, type)]
# Aggregate to seasonal flows
# First, define the seasons
names(seasons) <- seasons <- c('NJ', 'JO', 'WY')
seasonClass <- fread('data/season_class.csv', key = 'season')
ssnLabBrief <- function(x) seasonClass[x, type]
# Get seasonal total
natSeas <- rbindlist(list(
NJ = p1MonVol[, get_seasons(.SD, 'Q', 'Qa', c(11:12, 1:6), months.fwd = 11:12), by = type],
JO = p1MonVol[, get_seasons(.SD, 'Q', 'Qa', 7:10), by = type],
WY = p1MonVol[, get_seasons(.SD, 'Q', 'Qa', 1:12, months.fwd = 11:12), by = type]),
idcol = 'season')
natSeas[, type := fcase(type == 'Qvic', 'Uncorrected',
type == 'Qobs', 'Observed',
type == 'Qnat', 'Bias-corrected')]
natSeas[, season := factor(season, seasons)]
```
**Figure S3**
```{r naturalization-plot, fig.width=7, fig.height=7}
Qx <- seq(min(p1MonLong$Q), max(p1MonLong$Q), length.out = 1000)
cdf <- p1MonLong[, .(Q = Qx, FQ = ecdf(Q)(Qx)), by = type]
cdf[, type := fcase(type == 'Qvic', 'Uncorrected',
type == 'Qobs', 'Observed',
type == 'Qnat', 'Bias-corrected')]
monCDFcomm <- ggplot(cdf, aes(Q, FQ, colour = type, linetype = type)) +
geom_line() +
scale_colour_manual(name = NULL, values = c('darkorange', 'black', 'gray')) +
scale_linetype_manual(name = NULL, values = c(1, 2, 1)) +
labs(x = 'Q [m\u00b3/s]', y = 'F(Q)') +
labs(subtitle = 'b) CDF of monthly data')
DT <- melt(p1MergeDaily[period == 'Before 1985', -'period'],
id.var = c('year', 'month', 'day'),
variable.name = 'type',
value.name = 'Q',
variable.factor = FALSE)
Qx <- seq(min(DT$Q), max(DT$Q), length.out = 1000)
cdf <- DT[, .(Q = Qx, FQ = ecdf(Q)(Qx)), by = type]
cdf[, type := fcase(type == 'Qvic', 'Uncorrected',
type == 'Qobs', 'Observed',
type == 'Qnat', 'Bias-corrected')]
dayCDF <- ggplot(cdf, aes(Q, FQ, colour = type, linetype = type)) +
geom_line() +
scale_colour_manual(name = NULL, values = c('darkorange', 'black', 'grey')) +
scale_linetype_manual(name = NULL, values = c(1, 2, 1)) +
labs(x = 'Q [m\u00b3/s]', y = 'F(Q)') +
labs(subtitle = 'a) CDF of daily data')
tsPlot <- ggplot(natSeas) +
geom_rect(aes(xmin = 1976, xmax = 1985, ymin = -Inf, ymax = Inf), fill = 'gray97') +
geom_line(aes(year, Qa, colour = type, linetype = type)) +
facet_wrap(vars(season), scales = 'free_y', ncol = 1, labeller = as_labeller(ssnLabBrief)) +
scale_linetype_manual(name = NULL, values = c(1, 2, 1)) +
scale_colour_manual(name = NULL, values = c('darkorange', 'black', 'grey')) +
scale_x_continuous(
expand = c(0, 0),
breaks = seq(1975, 2005, 5)) +
labs(
subtitle = 'c) Time series',
x = NULL,
y = 'Volumetric flow [million m\u00b3]')
layout <- '
DDDD
AABB
AABB
AABB
AABB
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
'
monCDFcomm <- monCDFcomm +
theme(axis.text.y = element_blank(),
axis.title.y = element_blank(),
axis.line.y = element_blank(),
axis.ticks.y = element_blank())
pl <- dayCDF + monCDFcomm + tsPlot + guide_area() &
theme(
strip.background = element_blank(),
plot.subtitle = element_text(face = 'bold'),
legend.key.width = unit(1.5, 'cm'),
legend.position = 'top')
pl + plot_layout(design = layout, guides = 'collect')
```
### Combine flow
```{r}
# Seasonal observed flow from 1922 to 1985
p1s <- rbindlist(list(
NJ = get_seasons(p1m, 'Qm', 'Qa', c(11:12, 1:6), months.fwd = 11:12),
JO = get_seasons(p1m, 'Qm', 'Qa', 7:10),
WY = get_seasons(p1m, 'Qm', 'Qa', 1:12, months.fwd = 11:12) # New water year, Nov - Oct
), idcol = 'season')[year %in% 1922:1984]
p1s[, season := factor(season, levels = seasons)]
setkey(p1s, season)
# Naturalized seasonal flow from 1986 to 2005
p1merge <- rbind(
p1s,
natSeas[type == 'Bias-corrected' & year >= 1985, -'type'])
p1merge[, season := factor(season, seasons)]
setkey(p1merge, season)
# Target: 1922:2003
p1tar <- p1merge[year %in% 1922:2003]
## Hinkley D and transformation type
p1HD <- p1merge[, .(D = round(hinkley(Qa), 2),
Dlog = round(hinkley(log(Qa)), 2)),
keyby = season
][, trans := fifelse(abs(D) > abs(Dlog), 'log', 'none')]
```
**Table S1.** Flow transformation type.
```{r}
p1HD[]
```
**Figure S4**
```{r, fig.width=6.5, fig.height=3}
instDens <- p1tar[, {
bw <- if (.BY$season == 'NJ') 0.7 else 0.5
d1 <- density(standardize(Qa), bw = bw, cut = 1)
d2 <- density(standardize(log(Qa)), bw = bw, cut = 1)
c(list(x0 = d1$x, y0 = d1$y, xlog = d2$x, ylog = d2$y))
}, by = season]
ggplot(instDens) +
geom_line(aes(x0, y0, colour = 'No transformation')) +
geom_line(aes(xlog, ylog, colour = 'Log transformation')) +
scale_colour_manual(
name = NULL,
values = pal) +
facet_wrap(
vars(season),
labeller = as_labeller(ssnLabBrief),
scales = 'free') +
labs(x = 'z-score', y = 'Density') +
theme(
strip.background = element_rect('gray95', NA),
legend.key.width = unit(2, 'cm'),
legend.position = 'top')
```
So all targets need to be log-transformed.
# Correlation analyses
## Streamflow-proxy correlations
Bootstrapped correlations.
```{r correlation-calc}
# Core years: 1750:2003, and shift back or forth
crnLags <- -2:2 # All lags for ring width
oxiLags <- 0:2 # Positive lags only for d18O
# Input matrices
Xrw <- do.call(cbind, lapply(crnLags, function(l) {
x <- crnMatFilled[3:256 - l, ]
colnames(x) <- paste0(colnames(x), l)
x
}))
Xdo <- do.call(cbind, lapply(oxiLags, function(l) {
x <- oxiMatFilled[3:256 - l, ]
colnames(x) <- paste0(colnames(x), l)
x
}))
Xrwdo <- cbind(Xrw, Xdo)
# Streamflow target: 1922 to 2003
QMat <- log(as.matrix(dcast(p1tar, year ~ season, value.var = 'Qa')[, -'year']))
cor_lag <- function(X, Y, l, Xyears, Yyears, alpha) {
ind <- which(Xyears %in% Yyears) - l
cor_boot(cbind(X[ind, ], Y),
1:ncol(X),
1:ncol(Y) + ncol(X),
c('site', 'season'),
alpha = alpha)
}
set.seed(42)
rhoCrn <- lapplyrbind(crnLags, function(l) {
DT <- cor_lag(crnMatFilled, QMat, l, 1748:2005, 1922:2003, 0.05)
DT[, lag := l]
DT[, alpha := 0.05][]
})
rhoOxi <- lapplyrbind(oxiLags, function(l) {
DT <- cor_lag(oxiMatFilled, QMat, l, 1748:2005, 1922:2003, 0.05)
DT[, lag := l]
DT[, alpha := 0.05][]
})
dt <- CJ(s = factor(seasons, seasons), l = crnLags)
dt[, sl := paste0(s, '(', l, ')')]
rhoCrn[, season_lag := paste0(season, '(', lag, ')')]
rhoCrn[, season_lag := factor(season_lag, levels = dt$sl)]
rhoCrn[, season := factor(season, levels = seasons)]
rhoCrn[, lag := factor(lag, levels = crnLags)]
rhoOxi[, season_lag := paste0(season, '(', lag, ')')]
rhoOxi[, season_lag := factor(season_lag, levels = dt$sl)]
rhoOxi[, season := factor(season, levels = seasons)]
rhoOxi[, lag := factor(lag, levels =crnLags)]
```
**Figure 2**
```{r cor-plot, fig.width=8, fig.height=8}
ssnLabLag <- function(x) {
char <- sapply(x, substr, start = 1, stop = 2)
yr <- sapply(x, function(xx) {
c1 <- substr(xx, 4, 4)
if (c1 == '-') c1 <- substr(xx, 4, 5)
c1
})
fcase(
char == 'NJ', paste0('<span style="color:', dark2[1], '">', yr, '</span>'),
char == 'JO', paste0('<span style="color:', dark2[2], '">', yr, '</span>'),
char == 'WY', paste0('<span style="color:', dark2[3], '">', yr, '</span>')
)
}
p1 <- ggplot(rhoCrn) +
geom_hline(yintercept = 0, colour = 'gray') +
geom_vline(
xintercept = c(length(crnLags) + 0.5, length(crnLags) * 2 + 0.5),
colour = 'gray') +
geom_linerange(aes(season_lag, ymin = low, ymax = high, alpha = signif, colour = season)) +
geom_point(aes(season_lag, median, alpha = signif, colour = season)) +
scale_colour_manual(name = 'Season', values = dark2, labels = ssnLabBrief) +
facet_wrap(vars(site), labeller = as_labeller(crnLab), ncol = 4) +
scale_alpha_manual(name = 'Significance', values = c(0.25, 1)) +
scale_x_discrete(labels = ssnLabLag) +
scale_y_continuous(breaks = c(-0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6)) +
labs(
x = 'Lag [years]', y = 'Correlation [-]',
subtitle = 'a) Correlations between ring width and instrumental + naturalized streamflow') +
theme(axis.text.x = ggtext::element_markdown(family = 'Arial Narrow', size = 8),
axis.ticks.y = element_blank(),
axis.line = element_line(size = 0.1),
axis.ticks.x = element_line(size = 0.1),
legend.key.width = unit(0.1, 'cm'),
legend.text = element_text(margin = margin(r = 0.3, unit = 'cm')),
legend.title = element_text(margin = margin(r = 0.3, unit = 'cm')),
legend.position = 'top',
legend.box.spacing = unit(-0.3, 'cm'),
panel.grid.major.y = element_line('gray95', 0.1),
panel.border = element_rect(NA, 'black', 0.1),
strip.text = element_text(face = 'plain'),
strip.background = element_blank(),
plot.subtitle = element_text(face = 'bold'))
p2 <- ggplot(rhoOxi) +
geom_hline(yintercept = 0, colour = 'gray') +
geom_vline(
xintercept = c(length(oxiLags) + 0.5, length(oxiLags) * 2 + 0.5),
colour = 'gray') +
geom_linerange(aes(season_lag, ymin = low, ymax = high, alpha = signif, colour = season)) +
geom_point(aes(season_lag, median, alpha = signif, colour = season)) +
facet_wrap(vars(site), labeller = as_labeller(oxiLab), nrow = 1) +
scale_colour_manual(name = 'Season', values = dark2, labels = ssnLabBrief) +
scale_alpha_manual(name = 'Significance', values = c(0.25, 1)) +
scale_x_discrete(labels = ssnLabLag) +
scale_y_continuous(breaks = c(-0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6)) +
labs(
x = 'Lag [years]', y = 'Correlation [-]',
subtitle = 'b) Correlations between \u03b4\u00b9\u2078O and instrumental + naturalized streamflow') +
theme(axis.text.x = ggtext::element_markdown(family = 'Arial Narrow', size = 8),
axis.ticks.y = element_blank(),
axis.ticks.x = element_line(size = 0.1),
axis.line = element_line(size = 0.1),
panel.grid.major.y = element_line('gray95', 0.1),
panel.border = element_rect(NA, 'black', 0.1),
legend.position = 'none',
strip.text = element_text(face = 'plain'),
strip.background = element_blank(),
plot.subtitle = element_text(face = 'bold'))
p1 / p2 + plot_layout(heights = c(6.25, 1))
```
## Proxy-climate correlations
We calculate the correlations between tree rings and CRU TS-4.04 precipitation data (Harris *et al.*, 2020). Here we provide a subset of the CRU data set that contains only the grid points in Southeast Asia.
```{r}
pre <- readRDS('data/CRU-precip.RDS')
preMS <- pre[month %in% 7:10, .(pre = sum(pre)), by = .(lon, lat, year)]
preMAM <- pre[month %in% 3:5, .(pre = sum(pre)), by = .(lon, lat, year)]
preMS.sd <- preMS[, .(sd = sd(pre)), by = .(lon, lat)][sd < 0.1]
setkey(preMS, lon, lat)
setkey(preMS.sd, lon, lat)
preMS <- preMS[!preMS.sd]
corMS <- grid_cor(crn, preMS, 'rwi', 'pre', crnMeta)
corMAM <- grid_cor(crn, preMAM, 'rwi', 'pre', crnMeta)
corOxiMS <- grid_cor(oxi, preMS, 'do18', 'pre', oxiMeta)
corOxiMAM <- grid_cor(oxi, preMAM, 'do18', 'pre', oxiMeta)
```
### Tree rings
**Figure S7**
```{r, fig.width=8, fig.height=7}
plot_cor(corMS)
```
**Figure S8**
```{r, fig.width=8, fig.height=7}
plot_cor(corMAM, cor.limits = abs_range(corMS$rho$r))
```
### Oxygen isotope
**Figure S9**
```{r, fig.width=8, fig.height=4}
p1 <- plot_cor(corOxiMS)
p2 <- plot_cor(corOxiMAM, cor.limits = abs_range(corOxiMS$rho$r))
p1 + p2 +
plot_layout(ncol = 1, guides = 'collect')
```
# Reconstruction
## Site selection
Number of potential inputs for each season
```{r}
allInputs <- rbind(rhoCrn[{signif}, .(site, lag, absRho = abs(rho0), rho = rho0, season)],
rhoOxi[{signif}, .(site, lag, absRho = abs(rho0), rho = rho0, season)])
allInputs[, .N, by = season]
```
To speed up the search process, we only use at most 20 inputs for each season. So we take the 20 inputs with highest correlation magnitudes. This means for the wet season, we keep all 19 inputs.
```{r}
poolDT <- allInputs[, head(.SD[order(absRho, decreasing = TRUE)], 20), by = season]
poolDT[, site2 := paste0(site, lag)]
setkey(poolDT, season)
poolDT
```
```{r}
poolDT[, .N, by = season]
```
Now we export the necessary data for the site selection script, which should be run on a computing cluster.
```{r selection-prep, eval=FALSE}
saveRDS(poolDT, 'results/poolDT.RDS')
saveRDS(Xrwdo, 'results/Xrwdo.RDS')
saveRDS(p1tar, 'results/p1tar.RDS')
```
The site selection script is provided in the file `site-selection-GA.R`. The National Supercomputing Center in Singapore, where I ran the computations, used the PBS job management program. I provided a PBS script in this repo. If your cluster uses SLURM then you will need to replace the PBS script with your SLURM script.
## GA outputs
Read GA outputs and get the solution for each λ value:
```{r best, rows.print=16}
# Read all GA ouptuts
fl <- list.files('results/', pattern = 'pop', full.names = TRUE)
gaOut <- lapply(fl, function(fn) {
out <- readRDS(fn)
lambda <- as.integer(substr(fn, 29, 30)) / 10
seed <- as.integer(substr(fn, 33, 35))
data.table(
lambda = lambda,
seed = seed,
fval = -out@fitnessValue,
ga = c(out))
}) %>%
rbindlist()
# Find the best seed for each lambda value
best <- gaOut[, .SD[which.min(fval)], by = lambda]
best[, 1:3]
```
Check GA convergence
```{r, fig.width=8, fig.height=8}
par(mfrow = c(4, 4))
best[, {
plot(ga[[1]], main = paste0('\u03bb = ', lambda))
}, by = lambda] %>%
invisible()
```
**Figure S10**
```{r, fig.width=7, fig.height=4}
par(mfrow = c(1, 2))
plot(
best[lambda == 0, ga[[1]]],
main = expression(lambda == 0),
col = c('steelblue', NA, adjustcolor('steelblue', alpha.f = 0.1)))
plot(
best[lambda == 1.2, ga[[1]]],
main = expression(lambda == 1.2),
col = c('steelblue', NA, adjustcolor('steelblue', alpha.f = 0.1)))
```
## Run final reconstructions and cross-validations from the selected inputs
```{r reconst}
# Function to run reconstructions and cross-validation
reconstruct <- function(sol, lambda, pool, Xused, target, cvFolds) {
pool <- pool[c(sol@solution) == 1]
# Run cross validation to get R2, RE, and CE
pcaOut <- lapply(seasons, function(s) {
Qa <- target[s]
X <- Xused[, pool[season == s, site2]]
pcaModel <- prcomp(X, scale. = TRUE)
PC <- pcaModel$x
sv <- input_selection(PC[173:254, ], Qa$Qa, 'leaps backward', nvmax = 8)
list(loadings = pcaModel$rotation[, sv, drop = FALSE],
PC = PC[, sv, drop = FALSE])
})
pc3s <- lapply(pcaOut, '[[', 'PC')
beta <- mb_par(target, pc3s, 1750, lambda = lambda, log.trans = 1:3)
loadingList <- lapply(pcaOut, '[[', 'loadings')
nPCs <- sapply(loadingList, ncol)
interceptIdx <- c(1, nPCs[1] + 2, nPCs[1] + nPCs[2] + 3)
beta2 <- beta[-interceptIdx]
loadingMat <- as.matrix(Matrix:::.bdiag(loadingList))
weight <- loadingMat %*% beta2
rec <- mb_reconstruction(target, pc3s, 1750, lambda = lambda, log.trans = 1:3)
cv <- cv_mb(target, pc3s, cvFolds, 1750,
lambda = lambda,
log.trans = 1:3,
return.type = 'all')
cv[, season := factor(season, seasons)]
list(rec = list(rec),
cv = list(cv[, -c('nRMSE', 'KGE')]),
loadings = list(loadingList),
beta = list(beta),
weight = list(weight))
}
# Run the function for each lambda
set.seed(24)
cvFolds <- make_Z(1922:2003, nRuns = 50, frac = 0.25, contiguous = TRUE)
best[, c('rec', 'cv', 'loadings', 'beta', 'weight') :=
reconstruct(ga[[1]], lambda, poolDT, Xrwdo, p1tar, cvFolds), by = lambda]
# Extract reconstructions
rec <- rbindlist(best$rec)
rec[, season := factor(season, seasons)]
# Extract CV scores
cv <- best[, cv[[1]], by = lambda]
cvLong <- melt(cv,
id.vars = c('lambda', 'rep', 'season'),
measure.vars = c('R2', 'RE', 'CE'),
variable.name = 'metric')
```
Check if we get the correct f-value.
```{r, rows.print=16}
merge(cv[, .(fnew = mean(fval)), by = lambda], best[, .(lambda, fval)], by = 'lambda')
```
All is good.
Check PCA loadings (**Tables S2 to S7**)
```{r}
best[lambda == 0, loadings][[1]] %>%
lapply(round, digits = 4)
```
````{r}
best[lambda == 1.2, loadings][[1]] %>%
lapply(round, digits = 4)
```
# Results
## Skill scores as a function of λ
### Mean skill scores and Wilcoxon test
```{r}
cvMean <- cv[, lapply(.SD, mean), .SDcols = c('R2', 'RE', 'CE'), keyby = .(lambda, season)]
cvMeanLong <- cvMean %>% melt(id.var = c('lambda', 'season'), variable.name = 'metric')
cv0 <- cvLong[lambda == 0]
cvp <- cvLong[,
.(p.value = {
s <- .BY$season
m <- .BY$metric
wilcox.test(value, cv0[season == s & metric == m, value])$p.value
}),
by = .(lambda, season, metric)]
cvMeanMerged <- merge(cvMeanLong, cvp, by = c('lambda', 'season', 'metric')) %>%
merge(cvMeanLong[lambda == 0, .(season, metric, v0 = value)], by = c('season', 'metric'))
```
**Figure 3**
```{r, fig.width=6, fig.height=5}