Guest User

Untitled

a guest
Aug 22nd, 2016
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.66 KB | None | 0 0
  1. mainF <- function(v) {#This gets run once for every river cell
  2.   #Set discharges lower than 0 to NA
  3.   v[v<=minQ] <- NA
  4.  
  5.   df <- na.omit(data.table(discharge=v, year=tyears))
  6.   rm(v)
  7.  
  8.   alloc.col(df, length(durations)+2) #allocate sufficient columns
  9.   #assign rolling means in a loop
  10.   for (i in durations) {
  11.     set(df,
  12.         j = paste0("D", i),
  13.         value = roll_mean(df[["discharge"]], i, na.rm=TRUE, fill=NA))
  14.   }
  15.   df <- na.omit(df)
  16.  
  17.   dfsumm <- df[, lapply(.SD, max, na.rm = TRUE), by = year]
  18.   #Now clean away infinites from dfsumm
  19.   invisible(lapply(names(dfsumm),function(.name) set(dfsumm, which(is.infinite(dfsumm[[.name]])), j = .name,value =NA)))
  20.   d <- dfsumm[["D1"]]
  21.   gscale <- sd(d, na.rm=TRUE) * sqrt(6) / pi          #Alpha
  22.   glocation <- mean(d, na.rm=TRUE) - emgamma * gscale #Mu
  23.   fit <- fitdist(d, #default options: MLE estimation
  24.                'gumbel',
  25.                start = list(location = glocation, scale = gscale)
  26.                )
  27.   fitmu <- fit$estimate[1]
  28.   fitalpha <- fit$estimate[2]
  29.   eps<-NULL
  30.   for (i in seq_along(durations)) {
  31.     eps[i] <- mean(dfsumm[[paste0("D", durations[i])]], na.rm=TRUE) / mean(d, na.rm=TRUE)
  32.   }
  33.  
  34.   #Fit for epsilon values (least squares method)
  35.   fit <- nlsLM(epsilon ~ I((1 + fitbeta * D)^(-fitgamma)), #Function from NERC(1975)
  36.             data = data.frame(epsilon=eps, D=durations),
  37.             start = list(fitbeta = startbeta, fitgamma=startgamma),
  38.             lower=c(lowerbeta, lowergamma),
  39.             upper=c(upperbeta, uppergamma))
  40.   #Get the coefficients of the fit
  41.   fitbeta  <- coef(fit)[1]
  42.   fitgamma <- coef(fit)[2]
  43.  
  44.   return(c(eps, fitmu, fitalpha, fitbeta, fitgamma))
  45. }
Advertisement
Add Comment
Please, Sign In to add comment