File size: 13,173 Bytes
d2e6d2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env Rscript
# Post-processing for the reproduction of Bloeschl et al. (2020, Nature)
# Faithful to PART 2 + PART 3 of https://github.com/tuwhydro/500yrfloods analysis.R
# Outputs are saved as CSV files in the working directory.

suppressPackageStartupMessages({
  library(sp); library(sf); library(raster); library(rgeos); library(fields)
})
setwd(dirname(sub("--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))))

# ------------------------------------------------------------------ #
# Median of the 50 seeds
# ------------------------------------------------------------------ #
load('seeds/intrp_cubeSEED11.RData')
intrp_cube_50 <- intrp_cube
for (seed in 12:60) {
  load(paste('seeds/intrp_cubeSEED', seed, '.RData', sep = ''))
  intrp_cube_50 <- cbind(intrp_cube_50, intrp_cube[, 4])
}
names(intrp_cube_50)[-c(1:3)] <- paste('flInt', 11:60, sep = '')
save(intrp_cube_50, file = 'intrp_cube_50.RData', compress = 'xz')

i_i_cube <- cbind(intrp_cube_50[, 1:3], i_i = apply(intrp_cube_50[, -c(1:3)], 1, median))
write.csv(i_i_cube, 'i_i_cube_median.csv', row.names = FALSE)

# ------------------------------------------------------------------ #
# PART 2: FLOOD PERIOD SELECTION AND RANKING
# ------------------------------------------------------------------ #
thr_q = quantile(i_i_cube$i_i, prob = .95)
cat('threshold: 95% quantile of i_i =', thr_q, '\n')
thr_a = 10  # 1 pixel is 40.625km*48.4375km*4yr
minoverlap = 0.15
minfraction = 0.05
kmperyear = 50

yrs <- unique(i_i_cube$t)
x <- unique(i_i_cube$x)*kmperyear
y <- unique(i_i_cube$y)*kmperyear
matrice <- array(i_i_cube$i_i, dim = c(length(x), length(y), length(yrs)), dimnames = list(round(x, 1), round(y, 1), yrs))

# Algorithm to connect neighbouring voxels from Haslinger and Bloeschl (2017, doi:10.1002/2017WR020797)
if (exists('df01')) rm(df01)
for (ii in 1:length(yrs)) {
  dat1 <- list()
  dat1$x <- x
  dat1$y <- y
  dat1$z <- matrice[,,ii]
  r <- raster(dat1)
  r[r < thr_q] <- NA
  cl <- clump(r)
  n_cl <- data.frame(freq(cl))
  ind <- which(is.na(n_cl$value) == FALSE & n_cl$count >= thr_a, arr.ind = TRUE)
  if (length(ind) >= 1) {
    for (i in 1:length(ind)) {
      if (i == 1) {
        idc <- Which(cl == ind[i], cells = TRUE)
        d <- data.frame(id = rep(i, length(idc)),
                        yr = rep(yrs[ii], length(idc)),
                        x = coordinates(r)[, 1][idc],
                        y = coordinates(r)[, 2][idc],
                        igp = idc,
                        value = r[idc])
      } else {
        idc = Which(cl == ind[i], cells = TRUE)
        d1 <- data.frame(id = rep(i, length(idc)),
                         yr = rep(yrs[ii], length(idc)),
                         x = coordinates(r)[, 1][idc],
                         y = coordinates(r)[, 2][idc],
                         igp = idc,
                         value = r[idc])
        d <- rbind.data.frame(d, d1)
      }
    }
    if (!exists('df01')) {
      df01 <- d
    } else {
      d$id <- d$id + max(df01$id)
      df01 <- rbind.data.frame(df01, d)
    }
  }
}
events3 <- df01

# tracking flood areas for identifying coherent flood-rich periods in space-time
time <- yrs
for (t in 2:length(time)) {
  ind0 <- which(events3$yr == time[t-1])
  ind1 <- which(events3$yr == time[t])
  if (length(ind0) > 0 & length(ind1) > 0) {
    df0 <- events3[ind0, ]
    df1 <- events3[ind1, ]
    int <- intersect(df0$igp, df1$igp)
    ev0 <- unique(df0$id[df0$igp %in% int])
    ev1 <- unique(df1$id[df1$igp %in% int])
    if (length(ev0) > length(ev1)) {
      ev1 <- NULL
      for (i in 1:length(ev0)) {
        ev1[i] <- df1$id[df1$igp %in% intersect(df0$igp[df0$id == ev0[i]], df1$igp)][1]
      }
    } else {
      ev0 <- NULL
      for (i in 1:length(ev1)) {
        ev0[i] <- df0$id[df0$igp %in% intersect(df1$igp[df1$id == ev1[i]], df0$igp)][1]
      }
    }
    for (i in 1:length(ev1)) {
      size0 <- length(df0$id[df0$id == ev0[i]])
      size1 <- length(df1$id[df1$id == ev1[i]])
      if (size0 >= size1) fraction <- size1/size0 else fraction <- size0/size1
      if (size0 >= size1) {
        overlap <- length(intersect(df0$igp[df0$id == ev0[i]], df1$igp[df1$id == ev1[i]]))/size1
        mean_of_larger <- mean(df0$value[df0$igp %in% df1$igp])
      } else {
        overlap <- length(intersect(df0$igp[df0$id == ev0[i]], df1$igp[df1$id == ev1[i]]))/size0
        mean_of_larger <- mean(df1$value[df1$igp %in% df0$igp])
      }
      if (is.na(overlap) == FALSE) {
        if ((fraction >= minfraction & overlap >= minoverlap)) {
          events3$id[events3$id == ev1[i]] <- ev0[i]
        }
      }
    }
  }
}

# compiling event table
events <- events3
un <- unique(events$id)

for (i in 1:length(un)) {
  ind <- which(events$id == un[i])
  ev <- events[ind, ]
  event_a <- data.frame(id = ev$id[1])
  event_a$yr_st <- ev$yr[1]
  event_a$yr_en <- ev$yr[length(ind)]
  event_a$dur <- (event_a$yr_en - event_a$yr_st) + 1
  event_a$sumstrength <- round(sum(ev$value), 1)
  event_a$maxstrength <- round(max(ev$value), 3)
  event_a$meanstrength <- round(mean(ev$value), 3)
  event_a$maxarea <- length(unique(ev$igp))
  event_a$volume <- length(ev$value)
  if (i > 1) event_c <- rbind.data.frame(event_c, event_a) else event_c <- event_a
}
events <- event_c
events$scaledmeanstrength <- round((events$meanstrength - min(events$meanstrength))/(max(events$meanstrength) - min(events$meanstrength)), 3)
events$scaledvolume <- round((events$volume - min(events$volume))/(max(events$volume) - min(events$volume)), 3)
pixelsize <- diff(seq(-1450, 1150, length = 65))[1] * diff(seq(-1600, 1500, length = 65))[1]
voxelsize <- pixelsize * 4
events$maxarea_Mkm2 <- round(events$maxarea*pixelsize*1e-6, 3)
events$volume_Mkm2yr <- round(events$volume*voxelsize*1e-6, 2)

# Selection and ranking of the largest events
criterio <- events$scaledmeanstrength + events$scaledvolume
max10events <- events[order(criterio, decreasing = TRUE), ][1:10, ]
max10events$rank <- 1:10
max10events3 <- merge(events3, max10events, all.y = TRUE)
max10events$name <- NA
max10events[order(max10events$yr_st), 'name'] <- c('I','II','III','IV','Va','Vb','VI','VII','VIII','IX')
print(max10events[order(max10events$yr_st), ], row.names = FALSE)
write.csv(max10events[order(max10events$yr_st), ], 'max10events.csv', row.names = FALSE)
write.csv(events, 'all_events.csv', row.names = FALSE)
save(events3, file = 'events3.RData', compress = 'xz')
cat('number of events (>10 voxels):', nrow(events), '\n')

# ------------------------------------------------------------------ #
# PART 3.1: Temperature anomalies within and outside of flood-rich periods
# ------------------------------------------------------------------ #
CEtempanom500yEXT <- read.csv('Delta_T.csv')

eventsXregion <- data.frame(c = c(T,T,F,T,T,F,F,T,F,T), s = c(F,F,T,F,T,F,T,F,F,T), w = c(T,T,F,T,T,F,T,F,F,T), n = c(F,F,F,F,F,T,F,F,T,F))
rownames(eventsXregion) <- c('I','II','III','IV','Va','Vb','VI','VII','VIII','IX')
CEtempanom500y_periods <- data.frame(CEtempanom500yEXT, c = NA, s = NA, w = NA, n = NA)
for (reg in c('c','s','w','n')) {
  dummy <- max10events[order(max10events$id), ][eventsXregion[, reg], ]
  for (i in 1:nrow(dummy)) {
    if ((i == 1) & (dummy$yr_st[i] > 1500)) CEtempanom500y_periods[CEtempanom500y_periods$year < dummy$yr_st[i], reg] <- paste('STto', dummy$name[i], sep = '')
    CEtempanom500y_periods[(CEtempanom500y_periods$year >= dummy$yr_st[i]) & (CEtempanom500y_periods$year <= dummy$yr_en[i]), reg] <- dummy$name[i]
    if (i < nrow(dummy)) CEtempanom500y_periods[(CEtempanom500y_periods$year > dummy$yr_en[i]) & (CEtempanom500y_periods$year < dummy$yr_st[i+1]), reg] <- paste(dummy$name[i], 'to', dummy$name[i+1], sep = '')
    if (i == nrow(dummy)) CEtempanom500y_periods[CEtempanom500y_periods$year > dummy$yr_en[i], reg] <- paste(dummy$name[i], 'toEND', sep = '')
  }
}
write.csv(CEtempanom500y_periods, 'temperature_periods.csv', row.names = FALSE)

perioddefs <- list(
  c = list(flood = c('I','II','IV','Va','VII','IX'),
           interflood = c('ItoII','IItoIV','IVtoVa','VatoVII','VIItoIX','IXtoEND')),
  s = list(flood = c('III','Va','VI','IX'),
           interflood = c('STtoIII','IIItoVa','VatoVI','VItoIX','IXtoEND')),
  w = list(flood = c('I','II','IV','Va','VI','IX'),
           interflood = c('ItoII','IItoIV','IVtoVa','VatoVI','VItoIX','IXtoEND')),
  n = list(flood = c('Vb','VIII'),
           interflood = c('VbtoVIII','VIIItoEND'))
)

temp_summary <- data.frame()
for (reg in names(perioddefs)) {
  tt <- tapply(CEtempanom500y_periods$temp_anom, CEtempanom500y_periods[[reg]], mean)
  sdv <- tapply(CEtempanom500y_periods$temp_anom, CEtempanom500y_periods[[reg]], sd)
  nn <- tapply(CEtempanom500y_periods$temp_anom, CEtempanom500y_periods[[reg]], length)
  for (p in perioddefs[[reg]]$flood) {
    temp_summary <- rbind(temp_summary, data.frame(region = reg, kind = 'flood', period = p,
      meanT = round(tt[[p]], 3), sdT = round(sdv[[p]], 3), nyears = nn[[p]],
      lower90 = round(tt[[p]] - 1.645*sdv[[p]]/sqrt(nn[[p]]), 3),
      upper90 = round(tt[[p]] + 1.645*sdv[[p]]/sqrt(nn[[p]]), 3)))
  }
  for (p in perioddefs[[reg]]$interflood) {
    temp_summary <- rbind(temp_summary, data.frame(region = reg, kind = 'interflood', period = p,
      meanT = round(tt[[p]], 3), sdT = round(sdv[[p]], 3), nyears = nn[[p]],
      lower90 = round(tt[[p]] - 1.645*sdv[[p]]/sqrt(nn[[p]]), 3),
      upper90 = round(tt[[p]] + 1.645*sdv[[p]]/sqrt(nn[[p]]), 3)))
  }
}
print(temp_summary)
write.csv(temp_summary, 'temperature_summary.csv', row.names = FALSE)

# ------------------------------------------------------------------ #
# PART 3.2: Flood seasonality within and outside of flood periods
# ------------------------------------------------------------------ #
i_f <- read.csv('i_f.csv')
sites <- read.csv('sites.csv')
allevents00 <- i_f
allevents00$numIndex <- c(1, 2, 3, NA, NA, NA)[as.numeric(as.factor(allevents00$Index))]
allevents00 <- allevents00[!is.na(allevents00$numIndex), ]

dummy <- as.data.frame(sites); rownames(dummy) <- dummy$code
allevents00$regionEU <- dummy[as.character(allevents00$Code), 'regionEU']
allevents00$period <- NA
for (reg in c('c','s','w','n')) {
  dummy <- max10events[order(max10events$id), ][eventsXregion[, reg], ]
  for (i in 1:nrow(dummy)) {
    allevents00[(allevents00$regionEU == reg) & (allevents00$Year >= dummy$yr_st[i]) & (allevents00$Year <= dummy$yr_en[i]), 'period'] <- dummy$name[i]
  }
}
allevents00$Season[allevents00$Season == ''] <- 'undated'
allevents00$period[is.na(allevents00$period)] <- 'noFrich'

weights <- c(1, 2, 3)
seasonarray <- tapply(allevents00$numIndex,
                      list(allevents00$period, allevents00$Season, allevents00$regionEU, allevents00$numIndex),
                      length)[c('I','II','III','IV','Va','Vb','VI','VII','VIII','IX','noFrich'), c('spring','summer','autumn','winter'), c('c','s','w'), ]
seasonarray[is.na(seasonarray)] <- 0

seas00 <- data.frame(summerCeu = seasonarray[,'summer','c','1'] + seasonarray[,'summer','c','2'] + seasonarray[,'summer','c','3'],
                     autumnSeu = seasonarray[,'autumn','s','1'] + seasonarray[,'autumn','s','2'] + seasonarray[,'autumn','s','3'],
                     winterWeu = seasonarray[,'winter','w','1'] + seasonarray[,'winter','w','2'] + seasonarray[,'winter','w','3'])
seasWW <- data.frame(summerCeu = weights[1]*seasonarray[,'summer','c','1'] + weights[2]*seasonarray[,'summer','c','2'] + weights[3]*seasonarray[,'summer','c','3'],
                     autumnSeu = weights[1]*seasonarray[,'autumn','s','1'] + weights[2]*seasonarray[,'autumn','s','2'] + weights[3]*seasonarray[,'autumn','s','3'],
                     winterWeu = weights[1]*seasonarray[,'winter','w','1'] + weights[2]*seasonarray[,'winter','w','2'] + weights[3]*seasonarray[,'winter','w','3']) * apply(seasonarray, c(1,3), sum) /
          apply(weights[1]*seasonarray[,,,'1'] + weights[2]*seasonarray[,,,'2'] + weights[3]*seasonarray[,,,'3'], c(1,3), sum)
seasWW[is.nan(as.matrix(seasWW))] <- 0

seas00_3 <- rbind(seas00['noFrich', ], pastFrich = apply(seas00[1:9, ], 2, sum), seas00['IX', ])
seasWW_3 <- rbind(seasWW['noFrich', ], pastFrich = apply(seasWW[1:9, ], 2, sum), seasWW['IX', ])
n <- rbind(noFrich = apply(seasonarray, c(1,3), sum)['noFrich', ],
           pastFrich = apply(apply(seasonarray, c(1,3), sum)[1:9, ], 2, sum),
           IX = apply(seasonarray, c(1,3), sum)['IX', ])
p_hat <- seasWW_3/n
print(round(p_hat, 3))
std_p_hat <- sqrt(p_hat*(1 - p_hat)/n)
seas_out <- data.frame(group = rep(c('noFrich','pastFrich','IX'), 3),
                       region = rep(c('c','s','w'), each = 3),
                       season = c(rep('summer', 3), rep('autumn', 3), rep('winter', 3)),
                       p_hat = round(as.vector(as.matrix(p_hat)), 3),
                       lower90 = round(as.vector(as.matrix(p_hat - 1.645*std_p_hat)), 3),
                       upper90 = round(as.vector(as.matrix(p_hat + 1.645*std_p_hat)), 3),
                       n = as.vector(as.matrix(n)))
print(seas_out)
write.csv(seas_out, 'seasonality_summary.csv', row.names = FALSE)
saveRDS(allevents00, 'allevents00.rds')
cat('POSTPROCESS DONE\n')