IDF.R 8.04 KB
Newer Older
1
# This file contains the functions:  
2
# -IDF.agg for preparing the data
3
4
5
6
7
# -IDF.plot for plotting of IDF curves at a chosen station


#### IDF.agg ####

8
#' Aggregation and annual maxima for chosen durations
9
10
11
12
13
#' @description Aggregates several time series for chosen durations and finds annual maxima 
#' (either for the whole year or chosen months). Returns data.frame that can be used for
#' the function \code{\link{gev.d.fit}}.
#'
#' @param data list of data.frames containing time series for every station. 
Laura Mack's avatar
typos    
Laura Mack committed
14
#' The data.frame must have the columns 'date' and 'RR' unless other names 
15
16
17
18
#' are specified in the parameter `names`. The column 'date' must contain strings with 
#' standard date format.
#' @param ds numeric vector of aggregation durations. 
#' (Must be multiples of time resolution at all stations.)
19
20
#' @param na.accept numeric in [0,1) giving maximum percentage of missing values 
#' for which block max. should still be calculated.
21
22
23
24
25
26
27
#' @param which.stations optional, subset of stations. Either numeric vector or character vector 
#' containing names of elements in data. If not given, all elements in `data` will be used.
#' @param which.mon optional, subset of months of which to calculate the annual maxima from. 
#' @param names optional, character vector of length 2, containing the names of the columns to be used. 
#' @param cl optional, number of cores to be used from \code{\link[pbapply]{pblapply}} for parallelization.
#'
#' @details If data contains stations with different time resolutions that need to be aggregated at
Laura Mack's avatar
typos    
Laura Mack committed
28
29
#' different durations, IDF.agg needs to be run separately for the different groups of stations. 
#' Afterwards the results can be joint together using `rbind`.
30
#'
Jana Ulrich's avatar
Jana Ulrich committed
31
#' @return data.frame containing the annual intensity maxima [mm/h] in `$xdat`, the corresponding duration in `$ds` 
32
33
34
35
36
#' and the station id or name in `$station`.
#' 
#' @seealso \code{\link{pgev.d}}
#' 
#' @export
Jana Ulrich's avatar
Jana Ulrich committed
37
#' @importFrom pbapply pbsapply 
38
#' @importFrom RcppRoll roll_sum
Laura Mack's avatar
Laura Mack committed
39
#' @importFrom fastmatch ctapply
40
#'
Christoph Ritschel's avatar
Christoph Ritschel committed
41
#' @examples
42
43
44
45
46
47
48
49
50
51
#' dates <- as.Date("2019-01-01")+0:729
#' x <- rgamma(n = 730, shape = 0.4, rate = 0.5)
#' df <- data.frame(date=dates,RR=x)
#' IDF.agg(list(df),ds=c(24,48))
#' 
#'##        xdat ds station
#'## 1 0.3025660 24       1
#'## 2 0.4112304 24       1
#'## 3 0.1650978 48       1
#'## 4 0.2356849 48       1
52
    IDF.agg <- function(data,ds,na.accept = 0,
53
                        which.stations = NULL,which.mon = list(0:11),names = c('date','RR'),cl = NULL){
54
55
56
57
58
59
60
61
62
63
64
65
66
67
      
      if(!inherits(data, "list"))stop("Argument 'data' must be a list, instead it is a: ", class(data))
      
      # function 2: aggregate station data over durations and find annual maxima:                                
      agg.station <- function(station){
        data.s <- data[[station]]
        if(!is.data.frame(data.s)){stop("Elements of 'data' must be data.frames. But element "
                                        ,station," contains: ", class(data.s))}
        if(sum(is.element(names[1:2],names(data.s)))!=2){stop('Dataframe of station ', station 
                                                              ,' does not contain $', names[1]
                                                              ,' or $', names[2], '.')}
        dtime<-as.numeric((data.s[,names[1]][2]-data.s[,names[1]][1]),units="hours")
        
        if(any(ds %% dtime > 10e-16)){
68
          stop('At least one of the given aggregation durations is not multiple of the time resolution = '
69
70
71
72
               ,dtime,' of station ',station,'.')}
        
        # function 1: aggregate over single durations and find annual maxima:
        agg.ts <- function(ds){
73
          runsum = RcppRoll::roll_sum(data.s[,names[2]],ds/dtime,fill=NA,align='right')
74
75
          #runmean <- rollapplyr(as.zoo(data.s[,names[2]]),ds/dtime,FUN=sum,fill =NA,align='right')
          runsum <- runsum/ds #intensity per hour
76
77
          max.subset <- lapply(1:length(which.mon),function(m.i){
            subset <- is.element(as.POSIXlt(data.s[,names[1]])$mon,which.mon[[m.i]])
Laura Mack's avatar
Laura Mack committed
78
            max <- ctapply(runsum[subset],(as.POSIXlt(data.s[,names[1]])$year+1900)[subset],
79
80
81
82
83
84
85
86
                          function(vec){
                            n.na <- sum(is.na(vec))
                            max <- ifelse(n.na <= na.accept*length(vec),max(vec,na.rm = TRUE),NA)
                            return(max)})
            df <- data.frame(xdat=max,ds=ds,year=as.numeric(names(max)),mon=deparse(which.mon[[m.i]]),
                             stringsAsFactors = FALSE)
            return(df)})
          df <- do.call(rbind,max.subset)  
87
          return(df) # maxima for single durations
88
89
        }
        # call function 1 in lapply to aggregate over all durations at single station
90
        data.agg <- pbapply::pblapply(ds,agg.ts,cl=cl)  
91
        df <- do.call(rbind,data.agg)
92
93
94
95
96
97
98
99
        return(df) # maxima for all durations at one station
      }
      # which stations should be used?
      if(is.null(which.stations))which.stations <- 1:length(data)
      # call function 2 in lapply to aggregate over all durations at all stations
      station.list <- lapply(which.stations,agg.station)
      
      return(do.call('rbind',station.list))
Christoph Ritschel's avatar
Christoph Ritschel committed
100
    }
Rust Henning's avatar
Rust Henning committed
101

102
103
104
105
#### IDF.plot ####

#' Plotting of IDF curves at a chosen station
#'
106
#' @param durations vector of durations for which to calculate the quantiles. 
107
108
#' @param fitparams vector containing parameters mut, sigma0, xi, theta, eta
#' (modified location, scale, shape, duration offset, duration exponent) for chosen station
109
110
#' as obtained from \code{\link{gev.d.fit}}
#' (or \code{\link{gev.d.params}} for model with covariates).
111
112
#' @param probs vector of exeedance probabilities for which to plot IDF curves (p = 1-1/ReturnPeriod)
#' @param cols vector of colors for IDF curves. Should have same length as \code{probs}
113
114
#' @param add logical indicating if plot should be added to existing plot, default is FALSE
#' @param legend logical indicating if legend should be plotted (TRUE, the default)
115
116
#' @param ... additional parameters passed on to the \code{plot} function
#'
117
#' @export
118
119
120
121
#' @importFrom grDevices rgb
#' @importFrom graphics axis box lines plot points 
#' @examples
#' data('example',package = 'IDF')
122
#' # fit d-gev
123
124
#' fit <- gev.d.fit(example$dat,example$d,ydat = as.matrix(example[,c("cov1","cov2")])
#'                  ,mul = c(1,2),sigl = 1)
125
#' # get parameters for cov1 = 1, cov2 = 1
126
#' par <- gev.d.params(fit = fit, ydat = matrix(1,1,2))
127
128
129
130
131
132
133
#' # plot quantiles
#' IDF.plot(durations = seq(0.5,35,0.2),fitparams = par)
#' # add data points
#' points(example[example$cov1==1,]$d,example[example$cov1==1,]$dat)
IDF.plot <- function(durations,fitparams,probs=c(0.5,0.9,0.99),
                     cols=4:2,add=FALSE,
                     legend=TRUE,...){
134
  
135
  # if cols is to short, make longer    
136
137
138
  if(length(cols)!=length(probs))cols <- rep_len(cols,length.out=length(probs))
  
  ## calculate IDF values for given probability and durations
139
140
  qs <- lapply(durations,qgev.d,p=probs,mut=fitparams[1],sigma0=fitparams[2],xi=fitparams[3],
         theta=fitparams[4],eta=fitparams[5])
141
  idf.array <- matrix(unlist(qs),length(probs),length(durations)) # array[probs,durs]
142
143
  if(!add){ #new plot
    ## initialize plot window
144
145
146
147
    # check if limits were passed
    if(is.element('ylim',names(list(...)))){
      ylim <- list(...)[['ylim']]
    }else{ylim <- range(idf.array,na.rm=TRUE)}
Laura Mack's avatar
Laura Mack committed
148
    if(is.element('xlim',names(list(...)))){
149
150
      xlim <- list(...)[['xlim']]
    }else{xlim <- range(durations,na.rm=TRUE)}
Laura Mack's avatar
Laura Mack committed
151
152
153
    if(is.element('main',names(list(...)))){
      main <- list(...)[['main']]
    }else{main <- ''}
154
    
155
    # empty plot
Laura Mack's avatar
Laura Mack committed
156
    plot(NA,xlim=xlim,ylim=ylim,xlab="Duration [h]",ylab="Intensity [mm/h]",log="xy",main=main)
157
158
  }
  
159
  ## plot IDF curves
160
161
162
163
  for(i in 1:length(probs)){
    lines(durations,idf.array[i,],col=cols[i],...)
  }
  
164
  if(legend){## plot legend
165
166
167
168
169
170
171
172
173
174
175
    # check if lwd, lty were passed
    if(is.element('lwd',names(list(...)))){
      lwd <- list(...)[['lwd']]
    }else{lwd <- 1}
    if(is.element('lty',names(list(...)))){
      lty <- list(...)[['lty']]
    }else{lty <- 1}
    
    legend(x="topright",title = 'p-quantile',legend=probs,
           col=cols,lty=lty,lwd=lwd)
  }
176
}