#!/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')