diff --git a/.Rbuildignore b/.Rbuildignore index 91114bf..58867b7 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,2 +1,3 @@ ^.*\.Rproj$ ^\.Rproj\.user$ +ignore diff --git a/.gitignore b/.gitignore index b5e4d04..0b3be01 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,5 @@ commonR init.R downscaleR.Rproj .Rprofile -*.Rbuildignore +.Rbuildignore .~lock.fwimean_CFSv2_seasonal_operative_6_8.csv# diff --git a/DESCRIPTION b/DESCRIPTION index fdac9ae..f2df281 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -3,22 +3,23 @@ Depends: R(>= 3.1.0) Imports: abind, - downscaleR, + transformeR, + parallel, +Suggests: + visualizeR, + loadeR, loadeR.ECOMS, + downscaleR, easyVerification -Suggests: - visualizeR Type: Package Title: Fire weather index calculation -Version: 0.0-0 -Date: 2016-06-13 +Version: 1.0-0 +Date: 2016-10-04 Authors@R: as.person(c( "Santander Meteorology Group [aut]", "Joaquin Bedia [ctb, cre]", - "Maialen Iturbide [ctb]", - "Rodrigo Manzanas [ctb]", - "Max Tuni [ctb]")) -BugReports: https://github.com/SantanderMetGroup/downscaleR/issues + "Maialen Iturbide [ctb]")) +BugReports: https://github.com/SantanderMetGroup/fireDanger/issues URL: https://github.com/SantanderMetGroup/fireDanger Description: Tools for computing the Fire Weather Index, the package is conceived for dealing with forecast (multi-member) data. diff --git a/NAMESPACE b/NAMESPACE index de8b6fe..3237c58 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,22 +1,17 @@ -# Generated by roxygen2 (4.1.1): do not edit by hand +# Generated by roxygen2: do not edit by hand -export(fwi) +export(fwi1D) export(fwiGrid) -export(fwiSkill) -export(fwiWorld) -export(indexOperative) -export(plotFwiSkill) -export(wfwiOP) -import(downscaleR) -import(loadeR.ECOMS) importFrom(abind,abind) -importFrom(downscaleR,aggregateGrid) -importFrom(downscaleR,climatology) -importFrom(downscaleR,getGrid) -importFrom(downscaleR,getYearsAsINDEX) -importFrom(downscaleR,interpGrid) -importFrom(downscaleR,makeMultiGrid) -importFrom(downscaleR,subsetGrid) -importFrom(easyVerification,veriApply) -importFrom(parallel,detectCores) -importFrom(parallel,makeCluster) +importFrom(abind,asub) +importFrom(parallel,parLapply) +importFrom(parallel,splitIndices) +importFrom(stats,complete.cases) +importFrom(transformeR,array3Dto2Dmat) +importFrom(transformeR,getDim) +importFrom(transformeR,getShape) +importFrom(transformeR,getYearsAsINDEX) +importFrom(transformeR,mat2Dto3Darray) +importFrom(transformeR,parallelCheck) +importFrom(transformeR,redim) +importFrom(transformeR,subsetGrid) diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..4b95ab5 --- /dev/null +++ b/NEWS @@ -0,0 +1,11 @@ +New in fireDanger +================= + +* Depends from transformeR, eliminated dependencies from downscaleR and loadeR.ECOMS +* Calculation of all FWI System components from grids +* FWI spin.up argument introduced to consider user-selected spin-up periods +* New version to preserve missing values of the input series (i.e. temporal i/o consistency) +* Deleted the implicit removal of first month in `fwiGrid` (`subsetGrid` can be optionally applied after FWI calculation) +* Bug fix in latitudinal chunking +* Other minor bug fixes and enhancements +* Documentation updates \ No newline at end of file diff --git a/R/fwi.R b/R/fwi.R deleted file mode 100644 index 21ea6bb..0000000 --- a/R/fwi.R +++ /dev/null @@ -1,110 +0,0 @@ -#' @title Fire Weather Index applied to multigrids -#' -#' @description Implementation of the Canadian Fire Weather Index System for multigrids -#' -#' @param multigrid containing Tm (temperature records in deg. Celsius); H (relative humidity records in \%); -#' r (last 24-h accumulated precipitation in mm); W (wind velocity records in Km/h). -#' @param mask Optional. Binary (0 an 1) Grid. -#' @param latLim Same as \code{lonLim} argument, but for latitude. -#' @param lonLim Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees, -#' @param lat Optional. Latitude of the records (in decimal degrees). Default to 46, -#' applying the default parameters of the original FWI System, developed in Canada. See details. -#' @param return.all Logical. Should all components of the FWI system be returned?. -#' Default to FALSE, indicating that only FWI is returned. -#' @param init.pars A numeric vector of length 3 with the initialization values for the -#' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' @param parallel Logical. Should parallel execution be used? -#' @param max.ncores Integer. Upper bound for user-defined number of cores. -#' @param ncores Integer number of cores used in parallel computation. Self-selected number of -#' cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value. -#' -#' @return A vector of the same length as the input vectors (minus possible missing observations), -#' containing the requested components of the FWI system (either all or just FWI). See details. -#' -#' @section Daylength adjustment factors: -#' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), -#' although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -#' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -#' Lawson and Armitage (2008). -#' -#' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -#' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -#' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -#' -#' @author J. Bedia & M. Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -#' @export -#' @importFrom abind abind -#' @import downscaleR - - -fwi <- function(multigrid, mask = NULL, lonLim = NULL, latLim = NULL, lat = 46, return.all = FALSE, init.pars = c(85, 6, 15), - parallel = FALSE, - max.ncores = 16, - ncores = NULL){ - months <- as.integer(substr(multigrid$Dates[[1]]$start, start = 6, stop = 7)) - parallel.pars <- parallelCheck(parallel, max.ncores, ncores) - if (parallel.pars$hasparallel) { - apply_fun <- function(...) { - parallel::parLapply(cl = parallel.pars$cl, ...) - } - on.exit(parallel::stopCluster(parallel.pars$cl)) - } else { - apply_fun <- lapply - } -# if (!is.null(lonLim)){ -# multigrid <- subsetGrid(multigrid, lonLim = lonLim) -# } -# if (!is.null(latLim)){ -# multigrid <- subsetGrid(multigrid, lonLim = latLim) -# } - cords <- getCoordinates(multigrid) - if(!is.null(mask)){ - mask1 <- downscaleR:::redim(mask, member = F, runtime = F, drop = F) - } - Tm1 <- subsetGrid(multigrid, var = "tas") - Tm1 <- downscaleR:::redim(Tm1, drop = F) - H1 <- subsetGrid(multigrid, var = "hurs") - H1 <- downscaleR:::redim(H1, drop = F) - r1 <- subsetGrid(multigrid, var = "tp") - r1 <- downscaleR:::redim(r1, drop = F) - W1 <- subsetGrid(multigrid, var = "wss") - W1 <- downscaleR:::redim(W1, drop = F) - fwigrid <- W1 - n.mem <- downscaleR:::getShape(W1, "member") - message("[", Sys.time(), "] Calculating FWI...") - a <- apply_fun(1:n.mem, function(x) { - Tm2 <- array3Dto2Dmat(subsetGrid(Tm1, members = x)$Data) - H2 <- array3Dto2Dmat(subsetGrid(H1, members = x)$Data) - r2 <- array3Dto2Dmat(subsetGrid(r1, members = x)$Data) - W2 <- array3Dto2Dmat(subsetGrid(W1, members = x)$Data) - if(!is.null(mask)){ - mskmsk <- array3Dto2Dmat(mask1$Data)[1,] - ind <- which(mskmsk > 0) - }else{ - ind <- which(!is.na(Tm2)) - } - b <- array(dim = dim(Tm2)) - if(length(ind)!=0){ - for(i in 1:length(ind)){ - z <- tryCatch({fwi1D(months, Tm = Tm2[,ind[i]], H = H2[,ind[i]], r = r2[,ind[i]], W = W2[,ind[i]], lat = lat, return.all = return.all, init.pars = init.pars)}, - error = function(err){rep(NA, nrow(b))}) - if(length(z) < length(b[,1])) z <- rep(NA, length(b[,1])) - b[,ind[i]] <- z - } - } - c <- mat2Dto3Darray(mat2D = b, x = cords$x, y = cords$y) - return(c) - }) - fwidat <- do.call("abind", list(a, along = 0)) - message("[", Sys.time(), "] Done.") - dimNames <- attr(fwigrid$Data, "dimensions") - fwigrid$Data <- unname(fwidat) - attr(fwigrid$Data, "dimensions") <- dimNames - fwigrid$Variable <- list() - fwigrid$Variable$varName <- "fwi" - return(fwigrid) -} - diff --git a/R/fwi1D.R b/R/fwi1D.R index 8148a14..2d23dc2 100644 --- a/R/fwi1D.R +++ b/R/fwi1D.R @@ -8,15 +8,19 @@ #' @param r Vector of last 24-h accumulated precipitation (mm) #' @param W Vector of wind velocity records (Km/h) #' @param lat Optional. Latitude of the records (in decimal degrees). Default to 46, -#' applying the default parameters of the original FWI System, developed in Canada. See details. -#' @param return.all Logical. Should all components of the FWI system be returned?. -#' Default to FALSE, indicating that only FWI is returned. +#' applying the default parameters of the original FWI System, developed in Canada. See Daylength Adjustment details. +#' @param what Character vector, indicating the components of the FWI system to be returned. +#' Accepted values include any possible subset of the set \{\code{"FFMC"},\code{"DMC"},\code{"DC"} +#' ,\code{"BUI"},\code{"ISI"},\code{"FWI"},\code{"DSR"}\}. Default to \code{"FWI"}. #' @param init.pars A numeric vector of length 3 with the initialization values for the #' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' -#' -#' @return A vector of the same length as the input vectors (minus possible missing observations), -#' containing the requested components of the FWI system (either all or just FWI). See details. +#' @param spin.up Non-negative integer indicating the number of days considered for FWI spin-up. +#' Default to 0 (i.e. no spin-up is considered). See the dedicated Section below for further details. +#' +#' @importFrom stats complete.cases +#' +#' @return A matrix with the time (days) arranged in rows and the components selected in \code{what} +#' in columns. The attribute \code{colnames} gives the component ordering. #' #' @section Daylength adjustment factors: #' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), @@ -24,21 +28,40 @@ #' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in #' Lawson and Armitage (2008). #' -#' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). +#' @section FWI spin-up: +#' FWI is initialized with some values for FFMC, DMC and DC components. This means that the first values of the series are not reliable, +#' until the index is iterated over several time steps and stabilizes (typically a few days suffice). +#' Thus, the first index values can be optionally set to \code{NA}. The number of days at the beginning of the series to be set to \code{NA} +#' is controlled via the \code{spin.up} argument. #' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. +#' @references +#' \itemize{ +#' \item Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). #' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +#' \item van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. #' +#' \item van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +#' } #' @author J. Bedia, partially based on the original FORTRAN code by van Wagner and Pickett (1985) #' +#' @export +#' - -fwi1D <- function (months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars = c(85, 6, 15)) { - mes <- months - ret <- return.all +fwi1D <- function(months, Tm, H, r, W, + lat = 46, + what = "FWI", + init.pars = c(85, 6, 15) , + spin.up = 0) { + if (any(c(length(Tm), length(H), length(r), length(W)) != length(months))) { + stop("Input vector lengths differ") + } + what <- match.arg(arg = what, + choices = c("FFMC", "DMC", "DC", "ISI", "BUI", "FWI", "DSR"), + several.ok = TRUE) + out <- matrix(nrow = length(months), ncol = length(what), dimnames = list(NULL, what)) rm.ind <- which(!complete.cases(Tm, H, r, W)) + non.na.ind <- setdiff(1:length(months), rm.ind) + mes <- months ## (I feel lazy for renaming...) if (length(rm.ind) > 0) { warning("Missing values were removed from the time series before computation") mes <- mes[-rm.ind] @@ -120,7 +143,7 @@ fwi1D <- function (months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars if (m < 0) { m <- 0 } - f0[i+1] <- 59.5 * (250 - m) / (147.2 + m) + f0[i + 1] <- 59.5 * (250 - m) / (147.2 + m) if (Tm[i] < -1.1) { Tm[i] <- -1.1 } @@ -140,9 +163,9 @@ fwi1D <- function (months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars if (pr < 0) { pr <- 0 } - p0[i+1] <- pr + 100 * K + p0[i + 1] <- pr + 100 * K } else { - p0[i+1] <- p0[i] + 100 * K + p0[i + 1] <- p0[i] + 100 * K } if (Tm[i] < -2.8) { Tm[i] <- -2.8 @@ -159,17 +182,17 @@ fwi1D <- function (months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars if (dr < 0) { dr <- 0 } - d0[i+1] <- dr + 0.5 * v + d0[i + 1] <- dr + 0.5 * v } else { - d0[i+1] <- d0[i] + 0.5 * v + d0[i + 1] <- d0[i] + 0.5 * v } fW <- exp(0.05039 * W[i]) fF <- 91.9 * exp(-0.1386 * m) * (1 + ((m ^ 5.31) / (4.93 * 1e+07))) ISI[i] <- 0.208 * fW * fF - if (p0[i+1] <= 0.4 * d0[i+1]) { - BUI[i] <- (0.8 * p0[i+1] * d0[i+1]) / (p0[i+1] + 0.4 * d0[i+1]) - } else if (p0[i+1] > 0.4 * d0[i+1]) { - BUI[i] <- p0[i+1] - (1 - (0.8 * d0[i+1]) / (p0[i+1] + 0.4 * d0[i+1])) * (0.92 + (0.0114 * p0[i+1]) ^ 1.7) + if (p0[i + 1] <= 0.4 * d0[i + 1]) { + BUI[i] <- (0.8 * p0[i + 1] * d0[i + 1]) / (p0[i + 1] + 0.4 * d0[i + 1]) + } else if (p0[i + 1] > 0.4 * d0[i + 1]) { + BUI[i] <- p0[i + 1] - (1 - (0.8 * d0[i + 1]) / (p0[i + 1] + 0.4 * d0[i + 1])) * (0.92 + (0.0114 * p0[i + 1]) ^ 1.7) } if (!is.finite(BUI[i]) | BUI[i] < 0) { BUI[i] <- 0 @@ -186,12 +209,20 @@ fwi1D <- function (months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars FWI[i] <- B } } - if (!return.all) { - return(FWI) + FFMC <- f0[-1] + DMC <- p0[-1] + DC <- d0[-1] + if ("DSR" %in% what) DSR <- 0.0272 * FWI ^ 1.77 + aux <- vapply(X = colnames(out), + FUN = function(x) cbind(get(x)), + FUN.VALUE = numeric(length(mes))) + if (length(non.na.ind) > 0) { + out[non.na.ind,] <- aux } else { - DSR <- 0.0272 * FWI ^ 1.77 - fds <- cbind.data.frame(FFMC = f0[-1], DMC = p0[-1], DC = d0[-1], ISI = ISI, BUI = BUI, FWI = FWI, DSR = DSR) - return(fds) + out <- aux } + aux <- NULL + if (spin.up > 0) out[1:spin.up,] <- NA + return(out) } # End diff --git a/R/fwi1D.R~ b/R/fwi1D.R~ deleted file mode 100644 index 8148a14..0000000 --- a/R/fwi1D.R~ +++ /dev/null @@ -1,197 +0,0 @@ -#' @title Fire Weather Index applied to 1D data -#' -#' @description Implementation of the Canadian Fire Weather Index System to 1D data -#' -#' @param months Vector of integers corresponding to the months in the data -#' @param Tm Vector of temperature records (deg. Celsius) -#' @param H Vector of relative humidity records (\%) -#' @param r Vector of last 24-h accumulated precipitation (mm) -#' @param W Vector of wind velocity records (Km/h) -#' @param lat Optional. Latitude of the records (in decimal degrees). Default to 46, -#' applying the default parameters of the original FWI System, developed in Canada. See details. -#' @param return.all Logical. Should all components of the FWI system be returned?. -#' Default to FALSE, indicating that only FWI is returned. -#' @param init.pars A numeric vector of length 3 with the initialization values for the -#' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' -#' -#' @return A vector of the same length as the input vectors (minus possible missing observations), -#' containing the requested components of the FWI system (either all or just FWI). See details. -#' -#' @section Daylength adjustment factors: -#' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), -#' although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -#' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -#' Lawson and Armitage (2008). -#' -#' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -#' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -#' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -#' -#' @author J. Bedia, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -#' - - -fwi1D <- function (months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars = c(85, 6, 15)) { - mes <- months - ret <- return.all - rm.ind <- which(!complete.cases(Tm, H, r, W)) - if (length(rm.ind) > 0) { - warning("Missing values were removed from the time series before computation") - mes <- mes[-rm.ind] - Tm <- Tm[-rm.ind] - H <- H[-rm.ind] - r <- r[-rm.ind] - W <- W[-rm.ind] - } - # Table A3.1 - Lawson and Armitage, p69 - ref.lats <- c(-90, -30, -10, 10, 30, 90) # L&A p71 - loc <- as.character(findInterval(lat, ref.lats)) - aux <- switch(loc, - "1" = list(c(11.5, 10.5, 9.2, 7.9, 6.8, 6.2, 6.5, 7.4, 8.7, 10.0, 11.2, 11.8), - c(6.4, 5.0, 2.4, 0.4, -1.6, -1.6, -1.6, -1.6, -1.6, 0.9, 3.8, 5.8)), - "2" = list(c(10.1, 9.6, 9.1, 8.5, 8.1, 7.8, 7.9, 8.3, 8.9, 9.4, 9.9, 10.2), - c(6.4, 5.0, 2.4, 0.4, -1.6, -1.6, -1.6, -1.6, -1.6, 0.9, 3.8, 5.8)), - "3" = list(rep(9, 12), rep(1.4, 12)), - "4" = list(c(7.9, 8.4, 8.9, 9.5, 9.9, 10.2, 10.1, 9.7, 9.1, 8.6, 8.1, 7.8), - c(-1.6, -1.6, -1.6, 0.9, 3.8, 5.8, 6.4, 5.0, 2.4, 0.4, -1.6, -1.6)), - "5" = list(c(6.5, 7.5, 9.0, 12.8, 13.9, 13.9, 12.4, 10.9, 9.4, 8.0, 7.0, 6.0), - c(-1.6, -1.6, -1.6, 0.9, 3.8, 5.8, 6.4, 5.0, 2.4, 0.4, -1.6, -1.6)) - ) - Le <- aux[[1]] - dlf <- aux[[2]] - aux <- NULL - if (any(H > 100)) { - warning("One or more values of humidity above 100% were corrected") - H[which(H > 100)] <- 100 - } - if (any(H < 0)) { - warning("Some negative values of humidity were corrected") - H[which(H < 0)] <- 0 - } - if (any(r < 0)) { - warning("Some negative values of precipitation were corrected") - r[which(r < 0)] <- 0 - } - if (any(W < 0)) { - warning("Some negative values of wind were corrected") - W[which(W < 0)] <- 0 - } - f0 <- c(init.pars[1], rep(NA,length(mes))) - p0 <- c(init.pars[2], rep(NA,length(mes))) - d0 <- c(init.pars[3], rep(NA,length(mes))) - ISI <- rep(NA, length(mes)) - BUI <- rep(NA, length(mes)) - FWI <- rep(NA, length(mes)) - for (i in 1:length(mes)) { - m0 <- (147.2 * (101 - f0[i]))/(59.5 + f0[i]) - if (r[i] > 0.5) { - rA <- r[i] - 0.5 - if (m0 <= 150) { - mr <- m0 + 42.5 * rA * exp(-100 / (251 - m0)) * (1 - exp(-6.93 / rA)) - } else { - mr <- m0 + 42.5 * rA * exp(-100 / (251 - m0)) * (1 - exp(-6.93 / rA)) + (0.0015 * (m0 - 150) ^ 2 * (rA ^ (0.5))) - } - if (mr > 250) { - mr <- 250 - } - m0 <- mr - } - Ed <- 0.942 * H[i] ^ 0.679 + 11 * exp((H[i] - 100) / 10) + 0.18 * (21.1 - Tm[i]) * (1 - (1 / exp(0.115 * H[i]))) - Ew <- 0.618 * H[i] ^ 0.753 + 10 * exp((H[i] - 100) / 10) + 0.18 * (21.1 - Tm[i]) * (1 - (1 / exp(0.115 * H[i]))) - if (m0 > Ed) { - k0 <- 0.424 * (1 - ((H[i] / 100) ^ 1.7)) + 0.0694 * (W[i] ^ 0.5) * (1 - ((H[i] / 100) ^ 8)) - kd <- k0 * 0.581 * exp(0.0365 * Tm[i]) - m <- Ed + (m0 - Ed) * (10 ^ (-kd)) - } - if (m0 < Ed) { - if (m0 < Ew) { - k1 <- 0.424 * (1 - ((100 - H[i]) / 100) ^ 1.7) + 0.0694 * (W[i] ^ 0.5) * (1 - ((100 - H[i]) / 100) ^ 8) - kw <- k1 * (0.581 * (exp(0.0365 * Tm[i]))) - m <- Ew - ((Ew - m0) * 10 ^ (-kw)) - } - } - if (Ed >= m0 & m0 >= Ew) { - m <- m0 - } - if (m < 0) { - m <- 0 - } - f0[i+1] <- 59.5 * (250 - m) / (147.2 + m) - if (Tm[i] < -1.1) { - Tm[i] <- -1.1 - } - K <- 1.894 * (Tm[i] + 1.1) * (100 - H[i]) * Le[mes[i]] * 1e-06 - if (r[i] > 1.5) { - re <- (0.92 * r[i]) - 1.27 - M0 <- 20 + exp(5.6348 - (p0[i] / 43.43)) - if (p0[i] <= 33) { - b <- 100 / (0.5 + (0.3 * p0[i])) - } else if (p0[i] > 65) { - b <- (6.2 * log(p0[i])) - 17.2 - } else if (p0[i] > 33 & p0[i] <= 65) { - b <- 14 - 1.3 * log(p0[i]) - } - Mr <- M0 + ((1000 * re)/(48.77 + b * re)) - pr <- 244.72 - 43.43 * log(Mr - 20) - if (pr < 0) { - pr <- 0 - } - p0[i+1] <- pr + 100 * K - } else { - p0[i+1] <- p0[i] + 100 * K - } - if (Tm[i] < -2.8) { - Tm[i] <- -2.8 - } - v <- 0.36 * (Tm[i] + 2.8) + dlf[mes[i]] - if (v < 0) { - v <- 0 - } - if (r[i] > 2.8) { - rd <- 0.83 * r[i] - 1.27 - q0 <- 800 * exp(-d0[i] / 400) - qr <- q0 + 3.937 * rd - dr <- 400 * log(800 / qr) - if (dr < 0) { - dr <- 0 - } - d0[i+1] <- dr + 0.5 * v - } else { - d0[i+1] <- d0[i] + 0.5 * v - } - fW <- exp(0.05039 * W[i]) - fF <- 91.9 * exp(-0.1386 * m) * (1 + ((m ^ 5.31) / (4.93 * 1e+07))) - ISI[i] <- 0.208 * fW * fF - if (p0[i+1] <= 0.4 * d0[i+1]) { - BUI[i] <- (0.8 * p0[i+1] * d0[i+1]) / (p0[i+1] + 0.4 * d0[i+1]) - } else if (p0[i+1] > 0.4 * d0[i+1]) { - BUI[i] <- p0[i+1] - (1 - (0.8 * d0[i+1]) / (p0[i+1] + 0.4 * d0[i+1])) * (0.92 + (0.0114 * p0[i+1]) ^ 1.7) - } - if (!is.finite(BUI[i]) | BUI[i] < 0) { - BUI[i] <- 0 - } else if (BUI[i] > 80) { - fD <- 1000/(25 + 108.64 * exp(-0.023 * BUI[i])) - } else { - fD <- (0.626 * BUI[i] ^ 0.809) + 2 - } - B <- 0.1 * ISI[i] * fD - if (B > 1) { - Slog <- 2.72 * (0.434 * log(B)) ^ 0.647 - FWI[i] <- exp(Slog) - } else { - FWI[i] <- B - } - } - if (!return.all) { - return(FWI) - } else { - DSR <- 0.0272 * FWI ^ 1.77 - fds <- cbind.data.frame(FFMC = f0[-1], DMC = p0[-1], DC = d0[-1], ISI = ISI, BUI = BUI, FWI = FWI, DSR = DSR) - return(fds) - } -} -# End diff --git a/R/fwiGrid.R b/R/fwiGrid.R index e0b2754..d504501 100644 --- a/R/fwiGrid.R +++ b/R/fwiGrid.R @@ -1,114 +1,252 @@ -#' @title Fire Weather Index (FWI) +#' @title Fire Weather Index applied to multigrids #' -#' @description Implementation of the Canadian Fire Weather Index System +#' @description Implementation of the Canadian Fire Weather Index System for multigrids #' -#' @param multigrid A multigrid of the variables needed to compute the FWI. -#' @param mask Optional. Grid of the land mask to be applied to the data. -#' @param return.all Logical. Should all components of the FWI system be returned?. -#' Default to FALSE, indicating that only FWI is returned. -#' @param init.pars A numeric vector of length 3 with the initialization values for the -#' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' @param parallel Logical. Should parallel execution be used? -#' @param max.ncores Integer. Upper bound for user-defined number of cores. -#' @param ncores Integer number of cores used in parallel computation. Self-selected number of -#' cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value. +#' @param multigrid containing Tm (temperature records in deg. Celsius); H (relative humidity records in \%); +#' r (last 24-h accumulated precipitation in mm); W (wind velocity records in Km/h). See details. +#' @param mask Optional. Binary grid (0 and 1, 0 for sea areas) with \code{dimensions} attribute \code{c("lat", "lon")}. +#' @param what Character string. What component of the FWI system is computed?. Default to \code{"FWI"}. +#' See \code{\link{fwi1D}} for details and possible values. +#' @param nlat.chunks For an efficient memory usage, the computation of FWI can be split into +#' latitudinal bands (chunks) sepparately. The number of chunks is controlled here. +#' Default to \code{NULL} (i.e., no chunking applied). +#' @param restart.annual Logical. Should the calculation be restarted at the beginning of every year? +#' If the grid encompasses just one season (e.g. JJA...), this is the recommended option. Default to \code{TRUE}. +#' @param ... Further arguments passed to \code{\link{fwi1D}}. +#' @template templateParallelParams #' -#' @return A grid, containing the requested components of the FWI system (either all or just FWI). See details. +#' @return A grid corresponding to the variable defined in argument \code{what}. #' -#' @section Daylength adjustment factors: -#' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), -#' although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -#' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -#' Lawson and Armitage (2008). +#' @details +#' +#' \strong{Variable names} +#' +#' The variables composing the input multigrid are expected to have standard names, as defined by the dictionary +#' (their names are stored in the \code{multigrid$Variable$varName} component). +#' These are: \code{"tas"} for temperature, \code{"tp"} for precipitation, \code{"wss"} for windspeed. In the case of relative humidity, +#' either \code{"hurs"} or \code{"hursmin"} are accepted, the latter in case of FWI calculations according to the \dQuote{proxy} version +#' described in Bedia \emph{et al} 2014. +#' +#' \strong{Landmask definition} +#' +#' The use of a landsmask is highly recommended when using RCM/GCM data becasue (i) there is no point in calculating +#' FWI over sea areas and (ii) for computational efficiency, as sea gridboxes will be skipped before calculations. +#' +#' The landmask must be a grid spatially consistent with the input multigrid. You can use +#' \code{\link[transformeR]{interpGrid}} in combination with the \code{getGrid} method to ensure this condition is fulfilled. . Its \code{data} component can be either a 2D or 3D array with the \code{dimensions} +#' attribute \code{c("lat","lon")} or \code{c("time","lat","lon")} respectively. In the latter case, the length of the time +#' dimension should be 1. Note that values of 0 correspond to sea areas (thus discarded for FWI calculation), being land areas any other +#' values different from 0 (tipically 1 or 100, corresponding to the land/sea area fraction). +#' +#' \strong{Latitudinal chunking} +#' +#' Splitting the calculation in latitudinal chunks is highly advisable, and absolutely necessary when +#' considering large spatial domains, otherwise running out of memory during the computation. The number +#' of latitudinal chunks need to be estimated on a case-by-case basis, but in general there are no restrictions in the +#' number of chunks that can be used, as long as it does not exceed the number of actual latitudes +#' in the model grid. +#' +#' @template templateParallel #' #' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). +#' \itemize{ +#' \item Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). +#' +#' \item van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. #' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. +#' \item van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +#' } #' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +#' @author J. Bedia \& M. Iturbide #' -#' @author J. Bedia \& M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) #' @export -#' @importFrom abind abind -#' @importFrom downscaleR subsetGrid -#' @importFrom downscaleR getYearsAsINDEX - - +#' +#' @importFrom abind abind asub +#' @importFrom parallel parLapply splitIndices +#' @importFrom transformeR redim getDim getShape parallelCheck getYearsAsINDEX subsetGrid array3Dto2Dmat mat2Dto3Darray fwiGrid <- function(multigrid, - mask = NULL, - return.all = FALSE, - init.pars = c(85, 6, 15), - parallel = FALSE, - max.ncores = 16, - ncores = NULL){ - x <- c(-90, -80, -70, -60, -50, -40, -30, -20, -10, 1, 10, 20, 30, 40, 50, 60, 70, 80, 90) - - latLim <- range(multigrid$xyCoords$y) - lonLim <- range(multigrid$xyCoords$x) - latind <- findInterval(latLim, x)[1] : findInterval(latLim, x)[2] - if(x[latind[length(latind)]] < latLim[2]) latind[3] <- latind[2]+1 - x <- x[latind] - lats <- seq(min(x)+5, max(x)-5, 10) - if(x[length(x)] > latLim[2]) x[length(x)] <- latLim[2] - if(x[1] < latLim[1]) x[1] <- latLim[1] + mask = NULL, + what = "FWI", + nlat.chunks = NULL, + restart.annual = TRUE, + parallel = FALSE, + ncores = NULL, + max.ncores = 16, + ...) { + what <- match.arg(what, + choices = c("FFMC", "DMC", "DC", "ISI", "BUI", "FWI", "DSR"), + several.ok = FALSE) + fwi1D.opt.args <- list(...) - dataset <- attr(multigrid, "dataset") - years <- unique(getYearsAsINDEX(multigrid)) - latdim <- which(downscaleR:::getDim(multigrid) == "lat") - a <- list() - message("[", Sys.time(), "] Calculating FWI..") - for(i in 1:(length(x)-1)){ - latLimchunk <- c(x[i], x[i+1]) - lat <- lats[i] - multigrid_chunk <- subsetGrid(multigrid, latLim = latLimchunk) - if(is.null(mask) & dataset == "WFDEI"){ - msk <- subsetGrid(multigrid_chunk, var = "tas") - msk$Data <- msk$Data[1,,] - msk$Data[which(!is.na(msk$Data))] <- 100 - msk$Data[which(is.na(msk$Data))] <- 0 - attr(msk$Data, "dimensions") <- c("lat", "lon") - }else if(!is.null(mask)){ - msk <- subsetGrid(mask, latLim = latLimchunk, lonLim = lonLim, outside = T) - }else{ - message("The use of a land mask is recommended") + months <- as.integer(substr(multigrid$Dates[[1]]$start, start = 6, stop = 7)) + fwi1D.opt.args <- c(fwi1D.opt.args, list("what" = what)) + if ("lat" %in% names(fwi1D.opt.args)) { + message("NOTE: argument 'lat' will be overriden by the actual latitude of gridboxes\n(See help of fwi1D for details).") + fwi1D.opt.args[-grep("lat", names(names(fwi1D.opt.args)))] + } + varnames <- multigrid$Variable$varName + ycoords <- multigrid$xyCoords$y + xcoords <- multigrid$xyCoords$x + co <- expand.grid(ycoords, xcoords)[2:1] + dimNames.mg <- getDim(multigrid) + n.mem <- tryCatch(getShape(multigrid, "member"), + error = function(er) 1L) + ## if (n.mem == 1L) multigrid <- redim(multigrid) + yrsindex <- getYearsAsINDEX(multigrid) + nyears <- length(unique(yrsindex)) + if (!is.null(mask)) { + dimNames.mask <- getDim(mask) + } + if (is.null(nlat.chunks)) { + nlat.chunks <- 1L + } + if (nlat.chunks <= 0) { + nlat.chunks <- 1L + message("Invalid 'nlat.chunks' argument value. It was ignored") + } + idx.chunk.list <- parallel::splitIndices(length(ycoords), nlat.chunks) + if (any(vapply(idx.chunk.list, FUN = "length", FUN.VALUE = numeric(1)) < 2L)) { + stop("Too many latitudinal chunks. Reduce the value of 'nlat.chunks' to a maximum of ", length(ycoords) %/% 2) + } + message("[", Sys.time(), "] Calculating ", what) + aux.list <- lapply(1:nlat.chunks, function(k) { + ## Lat chunking + ind.lat <- idx.chunk.list[[k]] + dims <- grep("lat", dimNames.mg) + multigrid_chunk <- multigrid + mask_chunk <- mask + if (nlat.chunks > 1) { + aux <- asub(multigrid$Data, idx = ind.lat, dims = dims) + attr(aux, "dimensions") <- dimNames.mg + multigrid_chunk$Data <- aux + multigrid_chunk$xyCoords$y <- multigrid$xyCoords$y[ind.lat] + ## Mask chunking + if (!is.null(mask)) { + aux <- asub(mask$Data, idx = ind.lat, dims = grep("lat", dimNames.mask)) + attr(aux, "dimensions") <- dimNames.mask + mask_chunk$Data <- aux + mask_chunk$xyCoords$y <- mask_chunk$xyCoords$y[ind.lat] + } + aux <- NULL + } + ## Multigrid subsetting + Tm1 <- subsetGrid(multigrid_chunk, var = grep("tas", varnames, value = TRUE)) + Tm1 <- redim(Tm1, drop = FALSE) + H1 <- subsetGrid(multigrid_chunk, var = grep("hurs", varnames, value = TRUE)) + H1 <- redim(H1, drop = FALSE) + r1 <- subsetGrid(multigrid_chunk, var = "tp") + r1 <- redim(r1, drop = FALSE) + W1 <- subsetGrid(multigrid_chunk, var = "wss") + W1 <- redim(W1, drop = FALSE) + multigrid_chunk <- NULL + ## Parallel checks + parallel.pars <- parallelCheck(parallel, max.ncores, ncores) + if (n.mem < 2 && isTRUE(parallel.pars$hasparallel)) { + parallel.pars$hasparallel <- FALSE + message("NOTE: parallel computing only applies to multimember grids. The option was ignored") + } + if (parallel.pars$hasparallel) { + apply_fun <- function(...) { + parallel::parLapply(cl = parallel.pars$cl, ...) + } + on.exit(parallel::stopCluster(parallel.pars$cl)) + } else { + apply_fun <- lapply } - if(i != (length(x)-1)){ - xx <- dim(multigrid_chunk$Data)[latdim]-1 - }else{ - xx <- dim(multigrid_chunk$Data)[latdim] + ## Landmask + if (!is.null(mask)) { + if (!("^time" %in% dimNames.mask)) { + aux <- unname(abind(mask_chunk$Data, along = 0L)) + attr(aux, "dimensions") <- c("time", dimNames.mask) + } else { + aux <- mask_chunk$Data + } + msk <- array3Dto2Dmat(aux)[1,] + ind <- which(msk > 0) + msk <- NULL + } else { + aux <- suppressWarnings(subsetGrid(Tm1, members = 1))$Data + aux <- array3Dto2Dmat(aux) + ind <- which(apply(aux, MARGIN = 2, FUN = function(y) !all(is.na(y)))) } - o <- lapply(1:length(years), function(x){ - multigrid.y <- subsetGrid(multigrid_chunk, years = years[x]) - suppressMessages( - fwi(multigrid = multigrid.y, mask = msk, lat = lat, return.all = return.all, - parallel = parallel, init.pars = init.pars, - max.ncores = max.ncores, ncores = ncores)$Data[,,1:xx,,drop=FALSE] - ) + aux <- NULL + ## FWI calculation + message("[", Sys.time(), "] Processing chunk ", k, " out of ", nlat.chunks, "...") + a <- apply_fun(1:n.mem, function(x) { + Tm2 <- array3Dto2Dmat(subsetGrid(Tm1, members = x)$Data) + H2 <- array3Dto2Dmat(subsetGrid(H1, members = x)$Data) + r2 <- array3Dto2Dmat(subsetGrid(r1, members = x)$Data) + W2 <- array3Dto2Dmat(subsetGrid(W1, members = x)$Data) + b <- array(dim = dim(Tm2)) + if (length(ind) > 0) { + for (i in 1:length(ind)) { + if (isTRUE(restart.annual)) { + ## Iterate over years + annual.list <- lapply(1:nyears, function(j) { + idx <- which(yrsindex == unique(yrsindex)[j]) + arg.list2 <- list("months" = months[idx], + "Tm" = Tm2[idx,ind[i]], + "H" = H2[idx,ind[i]], + "r" = r2[idx,ind[i]], + "W" = W2[idx,ind[i]], + "lat" = co[ind[i],2]) + arg.list <- c(fwi1D.opt.args, arg.list2) + z <- tryCatch({suppressWarnings(drop(do.call("fwi1D", + args = arg.list)))}, + error = function(err) {rep(NA, length(idx))}) + ## if (length(z) < length(idx)) z <- rep(NA, length(idx)) + return(z) + }) + b[,ind[i]] <- do.call("c", annual.list) + } else { + arg.list2 <- list("months" = months, + "Tm" = Tm2[,ind[i]], + "H" = H2[,ind[i]], + "r" = r2[,ind[i]], + "W" = W2[,ind[i]], + "lat" = co[ind[i],2]) + arg.list <- c(fwi1D.opt.args, arg.list2) + z <- tryCatch({suppressWarnings(drop(do.call("fwi1D", + args = arg.list)))}, + error = function(err) {rep(NA, length(months))}) + ## if (length(z) < nrow(b)) z <- rep(NA, nrow(b)) + b[,ind[i]] <- z + } + } + out <- mat2Dto3Darray(mat2D = b, + x = Tm1$xyCoords$x, + y = Tm1$xyCoords$y) + return(out) + } }) - o.full <- unname(do.call("abind", list(o, along = 2))) - months <- as.integer(substr(multigrid$Dates[[1]]$start, start = 6, stop = 7)) - multigrid.y <- NULL - month.ind <- which(months == months[1]) - a[[i]] <- o.full[,-month.ind,,] - } + Tm1 <- r1 <- H1 <- W1 <- NULL + unname(do.call("abind", list(a, along = 0))) + }) message("[", Sys.time(), "] Done.") - temp <- subsetGrid(multigrid, var = "tas") - dimNames <- attr(temp$Data, "dimensions") - latdim.f <- which(downscaleR:::getDim(temp) == "lat") - out <- unname(do.call("abind", list(a, along = latdim.f))) - temp$Data <- out - attr(temp$Data, "dimensions") <- dimNames - temp$Variable$varName <- "fwi" - attr(temp$Variable, "use_dictionary") <- FALSE - attr(temp$Variable, "description") <- "Fire Weather Index" - attr(temp$Variable, "units") <- "none" - attr(temp$Variable, "longname") <- "Fire Weather Index" - # if(length(years) > 1){ - # yname <- paste(years[1], "_", years[length(years)], sep = "") - # }else{ - # yname <- years - # } - return(temp) -} \ No newline at end of file + ## Final grid and metadata + fwigrid <- redim(subsetGrid(multigrid, var = varnames[1]), drop = FALSE) + multigrid <- NULL + dimNames <- getDim(fwigrid) + fwigrid$Data <- unname(do.call("abind", c(aux.list, along = grep("lat", dimNames)))) + aux.list <- NULL + attr(fwigrid$Data, "dimensions") <- dimNames + fwigrid$Variable <- list() + fwigrid$Variable$varName <- what + fwigrid$Variable$level <- NA + desc <- switch(what, + "FFMC" = "Fine Fuel Moisture Code", + "DMC" = "Duff Moisture Code", + "DC" = "Drought Code", + "ISI" = "Initial Spread Index", + "BUI" = "Builtup Index", + "FWI" = "Fire Weather Index", + "DSR" = "Daily Severity Rating") + attr(fwigrid$Variable, "use_dictionary") <- FALSE + attr(fwigrid$Variable, "description") <- desc + attr(fwigrid$Variable, "units") <- "adimensional" + attr(fwigrid$Variable, "longname") <- paste(desc, "component of the Canadian Fire Weather Index System") + attr(fwigrid, "calculation") <- "Calculated with the fireDanger package (https://github.com/SantanderMetGroup/fireDanger)" + return(fwigrid) +} + diff --git a/R/fwiSkill.R b/R/fwiSkill.R deleted file mode 100644 index 8c02fea..0000000 --- a/R/fwiSkill.R +++ /dev/null @@ -1,73 +0,0 @@ -#' @title Skill calculation -#' -#' @description Skill calculation with function veriApply -#' -#' @param obs Grid of the observation data -#' @param fcst Grid of the seasonal forecast data -#' @param verifun Name of function to compute verification metric (score, skill score). -#' Type help(veriApply) for details. -#' @param prob Probability threshold for category forecasts (Type help(veriApply) for details). -#' @param threshold Aabsolute threshold for category forecasts (Type help(veriApply) for details). -#' @param parallel Logical. Should parallel execution be used? -#' @param na.rm Logical. Should incomplete forecasts be used? -#' -#' @return A grid of the skill scores. -#' -#' @author M.Iturbide -#' @export -#' @importFrom easyVerification veriApply - - -fwiSkill <- function(obs, - fcst, - verifun = c(""), - prob, - threshold = NULL, - parallel = FALSE, - na.rm = TRUE){ - obs <- interpGrid(obs, getGrid(fcst)) - ensdim <- which(downscaleR:::getDim(fcst) == "member") - tdim <- which(downscaleR:::getDim(fcst) == "time") - - score <- veriApply(verifun = verifun, - fcst = fcst$Data, - obs = obs$Data, - prob = prob, - ensdim = ensdim, - tdim = tdim, - parallel = parallel, - na.rm = na.rm) - score.grid <- easyVeri2grid(easyVeri.mat = score[[1]], - obs.grid = obs, - verifun = verifun) - if(verifun == "EnsRocss"){ - data <- array(dim = c(length(prob)+1, length(obs$xyCoords$y), length(obs$xyCoords$x))) - for(i in 1:(length(prob)+1)){ - data[i,,] <- score[[i]] - } - score.grid$Data <- data - } - attr(score.grid$Data, "dimensions") <- c("cat", "lat", "lon") - return(score.grid) -} - -#End - -#' @title Plot grid returned by functionfFwiSkill -#' -#' @description Plot grid returned by functionfFwiSkill through function plotClimatology from package downscaleR -#' -#' @param grid The grid object returned by function fwiSkill -#' -#' @author M.Iturbide -#' @export - -plotFwiSkill <- function(grid){ - catdim <- which(downscaleR:::getDim(grid) == "cat") - lc <- dim(grid$Data)[catdim] - attr(grid$Data, "dimensions") <- c("member", "lat", "lon") - grid.r <- downscaleR:::redim(grid) - plotClimatology(climatology(grid.r), backdrop.theme = "coastline", par.strip.text = list(labels =paste("cat", 1:lc))) -} - - diff --git a/R/fwiWorld.R b/R/fwiWorld.R deleted file mode 100644 index 628a439..0000000 --- a/R/fwiWorld.R +++ /dev/null @@ -1,159 +0,0 @@ -#' @title World Fire Weather Index -#' -#' @description Implementation of the Canadian Fire Weather Index System -#' -#' @param dataset A character string indicating the database to be accessed (partial matching is enabled). -#' Currently accepted values are "WFDEI, "CFSv2_seasonal" and "S4_seasonal_15members". -#' @param dictionary A logical flag indicating if a dictionary is used for variable homogenization. Default (strongly recommended) -#' is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -#' variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization. -#' @param members A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -#' (see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -#' members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -#' a forecast or the requested variable is static (e.g. orography) it will be ignored. -#' @param season An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -#' one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -#' the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -#' See details on the definition of temporal slices. -#' @param years Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -#' it will be ignored. See details on the definition of temporal slices. -#' @param lonLim Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees, of the bounding box selected. -#' For single-point queries, a numeric value with the longitude coordinate. If \code{NULL} (default), the whole longitudinal range -#' is selected (Note that this may lead to a large output object size). -#' @param latLim Same as \code{lonLim}, but for the selection of the latitudinal range. -#' @param leadMonth Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -#' season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -#' forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -#' case if its value is different from NULL. See details on initialization times. -#' @param mask Grid of the land mask to be applied to the data. -#' @param return.all Logical. Should all components of the FWI system be returned?. -#' Default to FALSE, indicating that only FWI is returned. -#' @param init.pars A numeric vector of length 3 with the initialization values for the -#' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' @param parallel Logical. Should parallel execution be used? -#' @param max.ncores Integer. Upper bound for user-defined number of cores. -#' @param ncores Integer number of cores used in parallel computation. Self-selected number of -#' cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value. -#' -#' @return A grid, containing the requested components of the FWI system (either all or just FWI). See details. -#' -#' @section Daylength adjustment factors: -#' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), -#' although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -#' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -#' Lawson and Armitage (2008). -#' -#' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -#' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -#' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -#' -#' @author J. Bedia \& M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -#' @export -#' @importFrom abind abind -#' @importFrom downscaleR makeMultiGrid -#' @importFrom downscaleR subsetGrid -#' @import loadeR.ECOMS - - - -fwiWorld <- function(dataset = "WFDEI", - dictionary = TRUE, - years = NULL, - season = NULL, - lonLim = NULL, - latLim = NULL, - members = NULL, - leadMonth = 0, - mask = NULL, - return.all = FALSE, - init.pars = c(85, 6, 15), - parallel = FALSE, - max.ncores = 16, - ncores = NULL){ - x <- c(-90, -80, -70, -60, -50, -40, -30, -20, -10, 1, 10, 20, 30, 40, 50, 60, 70, 80, 90) - - if (is.null(latLim)) latLim <-c(-90, 90) - if (is.null(lonLim)) lonLim <- c(-180, 180) - latind <- findInterval(latLim, x)[1] : findInterval(latLim, x)[2] - if(x[latind[length(latind)]] < latLim[2]) latind[3] <- latind[2]+1 - x <- x[latind] - lats <- seq(min(x)+5, max(x)-5, 10) - if(x[length(x)] > latLim[2]) x[length(x)] <- latLim[2] - if(x[1] < latLim[1]) x[1] <- latLim[1] - - message("[", Sys.time(), "] Pre-processing...") - suppressMessages( - temp <- loadECOMS(dataset, latLim = latLim, lonLim = lonLim, var = "tas", dictionary = dictionary, - leadMonth = leadMonth, - season = season[-1], years = years, members = members, time = "DD", - aggr.d = "mean") - ) - latdim <- which(downscaleR:::getDim(temp) == "lat") - dimNames <- attr(temp$Data, "dimensions") - a <- list() - for(i in 1:(length(x)-1)){ - latLimchunk <- c(x[i], x[i+1]) - lat <- lats[i] - message("------------processing latitude chunk ", i, " out of ", length(x)-1, "-------------") - Tm <- loadECOMS(dataset, latLim = latLimchunk, lonLim = lonLim, var = "tas", dictionary = dictionary, - season = season, years = years, members = members, leadMonth = leadMonth, time = "DD", - aggr.d = "mean") - H <- loadECOMS(dataset, latLim = latLimchunk, lonLim = lonLim, var = "hurs", dictionary = dictionary, - season = season, years = years, members = members, leadMonth = leadMonth, time = "DD", - aggr.d = "min") - r <- loadECOMS(dataset, latLim = latLimchunk, lonLim = lonLim, var = "tp", dictionary = dictionary, - season = season, years = years, members = members, time = "DD", - aggr.d = "sum") - W <- loadECOMS(dataset, latLim = latLimchunk, lonLim = lonLim, var = "wss", dictionary = dictionary, - season = season, years = years, members = members, time = "DD", - aggr.d = "mean") - W$Data <- W$Data*3.6 - attr(W$Data, "dimensions") <- attr(r$Data, "dimensions") - multigrid <- makeMultiGrid(Tm, H, r, W) - if(is.null(mask) & dataset == "WFDEI"){ - msk <- W - msk$Data <- msk$Data[1,,] - msk$Data[which(!is.na(msk$Data))] <- 100 - msk$Data[which(is.na(msk$Data))] <- 0 - attr(msk$Data, "dimensions") <- c("lat", "lon") - }else if(!is.null(mask)){ - msk <- subsetGrid(mask, latLim = latLimchunk, lonLim = lonLim, outside = T) - }else{ - message("The use of a land mask is recommended") - } - if(i != (length(x)-1)){ - xx <- dim(Tm$Data)[latdim]-1 - }else{ - xx <- dim(Tm$Data)[latdim] - } - Tm <- H <- r <- W <- NULL - o <- lapply(1:length(years), function(x){ - multigrid.y <- subsetGrid(multigrid, years = years[x]) - fwi(multigrid = multigrid.y, mask = msk, lat = lat, return.all = return.all, - parallel = parallel, init.pars = init.pars, - max.ncores = max.ncores, ncores = ncores)$Data[,,1:xx,,drop=FALSE] - }) - o.full <- unname(do.call("abind", list(o, along = 2))) - months <- as.integer(substr(multigrid$Dates[[1]]$start, start = 6, stop = 7)) - multigrid.y <- NULL - month.ind <- which(months == months[1]) - a[[i]] <- o.full[,-month.ind,,] - } - out <- unname(do.call("abind", list(a, along = latdim))) - temp$Data <- out - attr(temp$Data, "dimensions") <- dimNames - temp$Variable$varName <- "fwi" - attr(temp$Variable, "use_dictionary") <- FALSE - attr(temp$Variable, "description") <- "Fire Weather Index" - attr(temp$Variable, "units") <- "none" - attr(temp$Variable, "longname") <- "Fire Weather Index" -# if(length(years) > 1){ -# yname <- paste(years[1], "_", years[length(years)], sep = "") -# }else{ -# yname <- years -# } -return(temp) -} \ No newline at end of file diff --git a/R/indexOperative.R b/R/indexOperative.R deleted file mode 100644 index e4256df..0000000 --- a/R/indexOperative.R +++ /dev/null @@ -1,354 +0,0 @@ -#' @title Index calculation for CFS operative seasonal forecast and csv file generation -#' -#' @description Implementation of the Canadian Fire Weather Index System -#' -#' @param dataset A character string indicating the database to be accessed (partial matching is enabled). -#' Currently accepted values are "CFSv2_seasonal". -#' @param index Index to be computed, e.g. "fwi". -#' @param destdir Output directory. -#' @param climdir Directory where observational climatologies are stored. -#' @param url ncml directory. -#' @param mask Directory (including file name) of the land-mask grid (*.rda). -#' @param fwi.mask Logical. If TRUE (default), a mask is applied to exclude -#' land areas which will most likely not burn, like deserts etc. -#' @param dictionary Path to the dictionary for variable homogenization. -#' is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -#' variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization. -#' @param members A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -#' (see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -#' members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -#' a forecast or the requested variable is static (e.g. orography) it will be ignored. -#' @param aggr.mem Member aggregation function. A list indicating the name of the -#' aggregation function in first place, and other optional arguments to be passed to the aggregation function. -#' @param season An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -#' one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -#' the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -#' See details on the definition of temporal slices. -#' @param years Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -#' it will be ignored. See details on the definition of temporal slices. -#' @param leadMonth Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -#' season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -#' forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -#' case if its value is different from NULL. See details on initialization times. -#' @param lonLim Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees, of the bounding box selected. -#' For single-point queries, a numeric value with the longitude coordinate. If \code{NULL} (default), the whole longitudinal range -#' is selected (Note that this may lead to a large output object size). -#' @param latLim Same as \code{lonLim}, but for the selection of the latitudinal range. -#' @param operative Path of the R object that contains the fwi of the operative dataset. Default is NULL, so the load and fwi is computed. -#' @param init.pars A numeric vector of length 3 with the initialization values for the -#' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' @param parallel Logical. Should parallel execution be used? -#' @param max.ncores Integer. Upper bound for user-defined number of cores. -#' @param ncores Integer number of cores used in parallel computation. Self-selected number of -#' cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value. -#' -#' @return A vector of the same length as the input vectors (minus possible missing observations), -#' containing the requested components of the FWI system (either all or just FWI). See details. -#' -#' @section Daylength adjustment factors: -#' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), -#' although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -#' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -#' Lawson and Armitage (2008). -#' -#' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -#' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -#' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -#' -#' @author J. Bedia \& M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -#' @export -#' @importFrom abind abind -#' @importFrom downscaleR makeMultiGrid -#' @importFrom downscaleR getGrid -#' @importFrom downscaleR aggregateGrid -#' @importFrom downscaleR subsetGrid -#' @importFrom downscaleR climatology -#' @importFrom downscaleR interpGrid -#' @import loadeR.ECOMS - -indexOperative <- function(dataset = "CFSv2_seasonal_operative", - index = "fwi", - climdir = getwd(), - destdir = getwd(), - url, - mask = NULL, - fwi.mask = TRUE, - dictionary = TRUE, - members = 1:24, - aggr.mem = list(FUN = NULL), - season = NULL, - lonLim = NULL, - latLim = NULL, - years = NULL, - leadMonth = 0, - operative = NULL, - init.pars = c(85, 6, 15), - parallel = FALSE, - max.ncores = 16, - ncores = NULL){ - if(is.null(operative)){ - operative <- wfwiOP(dataset =dataset, - index = index, - url=url, - mask = mask, - dictionary = dictionary, - members = members, - aggr.mem = aggr.mem, - season = season, - lonLim = lonLim, - latLim = latLim, - years = years, - leadMonth = leadMonth, - return.all = FALSE, - init.pars = init.pars, - parallel = parallel, - max.ncores = max.ncores, - ncores = ncores) -# save(operative, file = paste(destdir, "/", dataset,"_", years, "_", season[2], "_", season[length(season)], "_operative.rda")) - save(operative, file = paste(destdir, "/", "operative_",season[2], "_", season[length(season)], ".rda", sep = "")) - }else{ - operative <- get(load(operative)) - } - lati <- operative$xyCoords$y - loni <- operative$xyCoords$x - operative <- subsetGrid(operative, lonLim = range(loni), latLim = range(lati), outside = T) - coords <- expand.grid(operative$xyCoords$x, operative$xyCoords$y) - lat <- coords[,2] - lon <- coords[,1] - - cellID <- paste(as.integer(lon*100), "-", as.integer(lat*100), sep = "") - indexes <- c("indexmean", "index90", "index30") - for(i in 1:3){ - index.type <- indexes[i] - if(index.type == "indexmean"){ - aggr.clim <- list(FUN = mean, na.rm = T) - }else if(index.type == "index90"){ - aggr.clim <- list(FUN = quantile, probs = .9, na.rm = T) - }else if(index.type == "index30"){ - aggr.clim <- list(FUN = function(x) sum(x > 30)/length(x)) - } - dirskill <- paste(climdir, "/", index, gsub("index",replacement = "", x = index.type),"_SKILL_", season[2], "_", season[length(season)], ".rda", sep = "") - dirClim <- paste(climdir, "/", index, gsub("index",replacement = "", x = index.type),"_WFDEI_", season[2], "_", season[length(season)], ".rda", sep = "") - if(fwi.mask == TRUE){ - dirMask <- paste(climdir, "/fwi_mask.rda", sep = "") - fwmsk <- get(load(dirMask)) - fwmsk_sub <- subsetGrid(fwmsk, lonLim = range(lon), latLim = range(lat), outside = T) - fwi_Mask <- as.vector(t(fwmsk_sub$Data)) - } - sk <- get(load(dirskill)) - sk_sub <- subsetGrid(sk, lonLim = range(lon), latLim = range(lat), outside = T) - ### - obs <- get(load(dirClim, verbose = T)) - obs_sub <- subsetGrid(obs, lonLim = range(lon), latLim = range(lat), outside = T, season = season[-1])#season = season[-1] - obs_clim <- downscaleR:::redim(climatology(obs_sub, clim.fun = list(FUN=mean, na.rm = T)), drop = T) - oper_clim <- downscaleR:::redim(climatology(operative, clim.fun = aggr.clim), drop = T) - fwiClimatology <- as.vector(t(obs_clim$Data)) - fwiClimatology[which(is.na(fwiClimatology))] <- NA - fwiPrediction <- as.vector(t(oper_clim$Data)) - ind <- which(is.na(fwiPrediction)) - skill.cat1 <- as.vector(t(sk_sub$Data[1,,])) - skill.cat2 <- as.vector(t(sk_sub$Data[2,,])) - skill.cat3 <- as.vector(t(sk_sub$Data[3,,])) - print("hello") - if(fwi.mask == TRUE){ - output <- cbind(cellID, lon, lat, fwiPrediction, fwiClimatology, skill.cat1, skill.cat2, skill.cat3, fwi_Mask)[-ind,] - }else{ - output <- cbind(cellID, lon, lat, fwiPrediction, fwiClimatology, skill.cat1, skill.cat2, skill.cat3)[-ind,] - } - write.table(output, file = paste(destdir, "/", index, gsub("index",replacement = "", x = index.type), "_", dataset,"_", years, "_", season[2], "_", season[length(season)], "_lm", leadMonth, ".csv", sep=""), sep = " ", na = "", row.names = F, quote = F) - } -} - - -#' @title Index calculation for CFS operative seasonal forecast -#' -#' @description Implementation of the Canadian Fire Weather Index System -#' -#' @param dataset A character string indicating the database to be accessed (partial matching is enabled). -#' Currently accepted values are "CFSv2_seasonal". -#' @param index Index to be computed, e.g. "fwi". -#' @param url ncml directory. -#' @param mask Directory (including file name) of the land-mask grid (*.rda). -#' @param dictionary A logical flag indicating if a dictionary is used for variable homogenization. Default (strongly recommended) -#' is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -#' variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization. -#' @param members A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -#' (see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -#' members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -#' a forecast or the requested variable is static (e.g. orography) it will be ignored. -#' @param aggr.mem Member aggregation function. A list indicating the name of the -#' aggregation function in first place, and other optional arguments to be passed to the aggregation function. -#' @param season An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -#' one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -#' the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -#' See details on the definition of temporal slices. -#' @param years Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -#' it will be ignored. See details on the definition of temporal slices. -#' @param lonLim Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees, of the bounding box selected. -#' For single-point queries, a numeric value with the longitude coordinate. If \code{NULL} (default), the whole longitudinal range -#' is selected (Note that this may lead to a large output object size). -#' @param latLim Same as \code{lonLim}, but for the selection of the latitudinal range. -#' @param leadMonth Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -#' season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -#' forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -#' case if its value is different from NULL. See details on initialization times. -#' @param return.all Logical. Should all components of the FWI system be returned?. -#' @param init.pars A numeric vector of length 3 with the initialization values for the -#' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' @param parallel Logical. Should parallel execution be used? -#' @param max.ncores Integer. Upper bound for user-defined number of cores. -#' @param ncores Integer number of cores used in parallel computation. Self-selected number of -#' cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value. -#' -#' @return A vector of the same length as the input vectors (minus possible missing observations), -#' containing the requested components of the FWI system (either all or just FWI). See details. -#' -#' @section Daylength adjustment factors: -#' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), -#' although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -#' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -#' Lawson and Armitage (2008). -#' @export -#' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -#' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -#' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -#' - -wfwiOP <- function(dataset = "CFSv2_seasonal_operative", - index = "fwi", - url, - mask = NULL, - dictionary = TRUE, - members = 1:24, - aggr.mem = list(FUN = NULL), - season = NULL, - years = NULL, - lonLim = NULL, - latLim = NULL, - leadMonth = 0, - return.all = FALSE, - init.pars = c(85, 6, 15), - parallel = FALSE, - max.ncores = 16, - ncores = NULL){ - x <- c(-90, -80, -70, -60, -50, -40, -30, -20, -10, 1, 10, 20, 30, 40, 50, 60, 70, 80, 90) - - if (is.null(latLim)) latLim <-c(-90, 90) - if (is.null(lonLim)) lonLim <- c(-180, 180) - latind <- findInterval(latLim, x)[1] : findInterval(latLim, x)[2] - if(x[latind[length(latind)]] < latLim[2]) latind[3] <- latind[2]+1 - x <- x[latind] - lats <- seq(min(x)+5, max(x)-5, 10) - if(x[length(x)] > latLim[2]) x[length(x)] <- latLim[2] - if(x[1] < latLim[1]) x[1] <- latLim[1] - - a <- list() - coords.x <- list() - coords.y <- list() - for(i in 1:(length(x)-1)){ - latLimchunk <- c(x[i], x[i+1]) - lat <- lats[i] - msk <- subsetGrid(mask, latLim = latLimchunk, lonLim = lonLim, outside = T) - #SEASONAL - message("latitude ", i, ", ", length(x) - i, " remaining") - Tm <- NULL - REP<- 0 - while(is.null(Tm) & (REP<10)){ - REP <- REP+1 - suppressWarnings( - Tm <- tryCatch({loadECOMS(dataset, latLim = latLimchunk, var = "tas", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "mean", url = url, lonLim = lonLim)}, error = function(err){NULL}) - ) - } - H <- NULL - REP<- 0 - while(is.null(H) & (REP<10)){ - REP <- REP+1 - suppressWarnings( - H <- tryCatch({loadECOMS(dataset, latLim = latLimchunk, var = "hurs", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "min", url = url, lonLim = lonLim)}, error = function(err){NULL}) - ) - } - r <- NULL - REP<- 0 - while(is.null(r) & (REP<10)){ - REP <- REP+1 - suppressWarnings( - r <- tryCatch({loadECOMS(dataset, latLim = latLimchunk, var = "tp", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "sum", url = url, lonLim = lonLim)}, error = function(err){NULL}) - ) - } - W <- NULL - REP<- 0 - while(is.null(W) & (REP<10)){ - REP <- REP+1 - suppressWarnings( - W <- tryCatch({loadECOMS(dataset, latLim = latLimchunk, var = "wss", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "mean", url = url, lonLim = lonLim)}, error = function(err){NULL}) - ) - } - dimNames <- attr(W$Data, "dimensions") - initatr <- W$InitializationDates - mematr <- W$Members - datatr <- attr(W, "dataset") - dates <- W$Dates -# Tm <- downscaleR:::redim(Tm) -# H <- downscaleR:::redim(H) -# r <- downscaleR:::redim(r) -# W <- downscaleR:::redim(W) -# - W$Data <- W$Data*3.6 - attr(W$Data, "dimensions") <- attr(r$Data, "dimensions") - multigrid <- makeMultiGrid(Tm, H, r, W) - - - xx <- downscaleR:::getShape(Tm)[["lat"]]-1 - Tm <- H <- r <- W <- NULL - if(index == "fwi"){ - b <- fwi(multigrid, mask = msk, lat = lat, return.all = return.all, - parallel = parallel, init.pars = init.pars, - max.ncores = max.ncores, ncores = ncores)$Data[,,1:xx,,drop=FALSE] - } - gc() - - months <- as.integer(substr(multigrid$Dates[[1]]$start, start = 6, stop = 7)) - coords.x <- multigrid$xyCoords$x - coords.y[[i]] <- multigrid$xyCoords$y[-(length(multigrid$xyCoords$y))] - multigrid <- NULL - month.ind <- which(months == months[1]) - a[[i]] <- b[,-month.ind,,] - dates$start <- dates$start[-month.ind] - dates$end <- dates$end[-month.ind] - } - c.x <- coords.x - c.y <- unname(do.call("abind", list(coords.y))) - xy <- list("x" = c.x, "y" = c.y) - out <- unname(do.call("abind", list(a, along = 3))) -outgrid <- list() -outgrid$Variable <- list("varName" = index, "level" = NULL) -outgrid$Data <- out -attr(outgrid$Data, "dimensions") <- dimNames -outgrid$xyCoords <- xy -outgrid$Dates <- dates -outgrid$InitializationDates <- initatr -outgrid$Members <- mematr -attr(outgrid, "dataset") <- datatr -outgrid <- aggregateGrid(outgrid, aggr.mem = aggr.mem) - -# write.csv(out, file = paste(destdir, "/wfi_", dataset, "_", season[2], "_", season[length(season)], ".csv", sep="")) -# write.csv(xy, file = paste(destdir, "/coordinates_", dataset,"_", season[2], "_", season[length(season)], ".csv", sep="")) -return(outgrid) -} - - - diff --git a/R/parallelCheck.R b/R/parallelCheck.R deleted file mode 100644 index 25108a1..0000000 --- a/R/parallelCheck.R +++ /dev/null @@ -1,42 +0,0 @@ -#' @title Parallel availability check -#' @description Check availability of parallel package and set parameters -#' @param parallel Logical, should parallel execution be used? -#' @param maxcores upper bound for self-selected number of cores -#' @param ncores number of cores used in parallel computation, self-selected number of cores -#' is used when \code{is.null(ncpus)} (the default). -#' @details The function checks if package parallel is available. Then, it is checked whether the FORK nodes -#' can be initialized -#' @return A list with two elements: -#' \itemize{ -#' \item \code{hasparallel}, a logical flag indicating if parallelization is enabled and -#' \item \code{cl}: parallel socket cluster object, or NULL. -#' } -#' @author J. Bedia, relying on previous code by Jonas Bhend and Matteo de Felice -#' @importFrom parallel detectCores -#' @importFrom parallel makeCluster -#' @keywords internal - -parallelCheck <- function(parallel, max.ncores = 16, ncores = NULL) { - hasparallel <- FALSE - .cl <- NULL - if (parallel & grepl("windows", .Platform$OS.type, ignore.case = TRUE)) { - message("Parallelization is not supported on Windows machines") - } - if (parallel && requireNamespace("parallel", quietly = TRUE)) { - if (is.null(ncores)) { - ncores <- min(max(parallel::detectCores() - 1, 1), max.ncores) - } - if (ncores > 1) { - .cl <- try(parallel::makeCluster(ncores, type = 'FORK'), silent = TRUE) - if (!"try-error" %in% class(.cl)) { - hasparallel <- TRUE - message("Parallel computing enabled\nNumber of workers: ", ncores) - } else { - .cl <- NULL - } - } - } else if (parallel) { - message("Parallel computing not enabled (parallel package is not available)") - } - list("hasparallel" = hasparallel, "cl" = .cl) -} diff --git a/R/rdas.R b/R/rdas.R new file mode 100644 index 0000000..a2bb6f1 --- /dev/null +++ b/R/rdas.R @@ -0,0 +1,39 @@ +#' @title Fire weather index data from observations and reanalysis at 7 locations in Spain +#' @description Temperature, relative humidity, precipitation and wind velocity data from 7 locations in Spain, +#' as well as the resulting Fire Weather Index series, corresponding to both weather station observations +#' and reanalysis data (NCEP). +#' @format A list of two elements, containing data of the NCEP/NCAR reanalysis and observations data respectively. +#' For each element of the list, a second list of length 7 is provided, each corresponding to a particular location in Spain, +#' each of them containing a dataframe with the following fields: +#' \itemize{ +#' \item \code{fecha}. A vector of class Date with dates of the records +#' \item \code{T} A numeric vector of temperature records, in degree C +#' \item \code{H} A numeric vector of relative hunidity records, in degree \% +#' \item \code{P} A numeric vector of precipitation records, in mm, see details +#' \item \code{W} A numeric vector of wind speed records, in km/h +#' \item \code{FWI} A numeric vector with the Fire Weather Index series +#' } +#' @details Data correspond both to observations from the Spanish Meteorological Agency (AEMET, all recorded +#' at noon excepting precipitation, recorded at 07:00 UTC and corresponding to values +#' accumulated during the last 24h) and the NCEP reanalysis interpolated to the same locations (12:00 UTC), +#' encompassing a period of approximately 6 years (2006-2011). These records are therefore appropriate for the +#' calculation of several fire danger indices, requiring data measured around noon. +#' Further details on this dataset are provided in Bedia \emph{et al.} (2012). +#' @references +#' J. Bedia, S. Herrera, J.M. Gutierrez, G. Zavala, I. R. Urbieta and J.M. Moreno (2012). Sensitivity of Fire Weather +#' Index to different reanalysis products in the Iberian Peninsula. \emph{Nat. Hazards Earth Syst. Sci.}, 12, 699-708. +#' \url{http://www.nat-hazards-earth-syst-sci.net/12/699/2012/nhess-12-699-2012.html} +#' @name fwiSpain +#' @examples +#' data(fwiSpain) +#' str(fwiSpain) +NULL + +#' @title Time series of meteo station data from Spain +#' @description Daily precipitation, maximum and minimum temperature records. +#' @format A data.frame +#' @name meteoSpain +#' @examples +#' data(meteoSpain) +#' str(meteoSpain) +NULL \ No newline at end of file diff --git a/R/wfwibc.R b/R/wfwibc.R deleted file mode 100644 index f86ef93..0000000 --- a/R/wfwibc.R +++ /dev/null @@ -1,109 +0,0 @@ -#' @title World Bias Correction -#' -#' @description Application of different bias correction methods to seasonal forecasts covering the World. -#' -#' @param dataset A character string indicating the database to be accessed (partial matching is enabled). -#' Currently accepted values are "System4_seasonal_15" and "CFSv2_seasonal". -#' @param dictionary A logical flag indicating if a dictionary is used for variable homogenization. Default (strongly recommended) -#' is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -#' variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization. -#' @param members A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -#' (see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -#' members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -#' a forecast or the requested variable is static (e.g. orography) it will be ignored. -#' @param season An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -#' one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -#' the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -#' See details on the definition of temporal slices. -#' @param years Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -#' it will be ignored. See details on the definition of temporal slices. -#' @param leadMonth Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -#' season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -#' forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -#' case if its value is different from NULL. See details on initialization times. -#' @param lat Optional. Latitude of the records (in decimal degrees). Default to 46, -#' applying the default parameters of the original FWI System, developed in Canada. See details. -#' @param return.all Logical. Should all components of the FWI system be returned?. -#' Default to FALSE, indicating that only FWI is returned. -#' @param init.pars A numeric vector of length 3 with the initialization values for the -#' FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987). -#' @param parallel Logical. Should parallel execution be used? -#' @param max.ncores Integer. Upper bound for user-defined number of cores. -#' @param ncores Integer number of cores used in parallel computation. Self-selected number of -#' cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value. -#' -#' @return A vector of the same length as the input vectors (minus possible missing observations), -#' containing the requested components of the FWI system (either all or just FWI). See details. -#' -#' @section Daylength adjustment factors: -#' By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), -#' although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -#' The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -#' Lawson and Armitage (2008). -#' -#' @references -#' Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -#' -#' van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -#' -#' van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -#' -#' @author J. Bedia & M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -#' @importFrom abind abind -#' @importFrom downscaleR makeMultiGrid -#' @import loadeR.ECOMS - -wfwibc <- function(dataset, dictionary = TRUE, - members = NULL, season = NULL, - years = NULL, leadMonth = 1, - lat = 46, return.all = FALSE, init.pars = c(85, 6, 15), - bc.multigrid, - method = c("delta", "scaling", "eqm", "gqm", "gpqm"), - cross.val = c("none", "loocv", "kfold"), - folds = NULL, - window = NULL, - scaling.type = c("additive", "multiplicative"), - wet.threshold = 1, n.quantiles = NULL, extrapolation = c("none", "constant"), - theta = .95, - parallel = FALSE, - max.ncores = 16, - ncores = NULL){ - coords <- loadECOMS(dataset, var = "tas", dictionary = TRUE, - members = 1, season = 1, years = 1991, leadMonth = 1, time = "DD", - aggr.d = "mean", aggr.m = "mean")$xyCoords - - a <- list() - for(i in 1:length(coords$x)){ - lonLim <- c(coords$x[i], coords$x[i+1]) - if(is.na(lonLim[2])) lonLim[2] <- coords$x[1] - - Tm <- loadECOMS(dataset, lonLim = lonLim, var = "tas", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "mean") -# Tm <- biasCorrection(y = y, x = x, newdata = newdata, method = method, cross.val = cross.val, folds = folds,window = window, -# scaling.type = scaling.type, wet.threshold = wet.threshold, n.quantiles = n.quantiles, -# extrapolation = extrapolation, theta = theta) - H <- loadECOMS(dataset, lonLim = lonLim, var = "hurs", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "min") - r <- loadECOMS(dataset, lonLim = lonLim, var = "tp", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "sum") - W <- loadECOMS(dataset, lonLim = lonLim, var = "wss", dictionary = dictionary, - members = members, season = season, years = years, leadMonth = leadMonth, time = "DD", - aggr.d = "mean") - W$Data <- apply(W$Data, MARGIN = 1:4, function(x) x*3.6) - multigrid <- makeMultiGrid(Tm, H, r, W) - a[[i]] <- fwi(multigrid, lat = lat, return.all = return.all, - parallel = parallel, init.pars = init.pars, - max.ncores = max.ncores, ncores = ncores)$Data[,,,i] - - } - out <- W - out$Data <- do.call("abind", list(a, along = 4)) - attr(out$Data, "dimensions") <- attr(W$Data, "dimensions") - out$xyCoords$x <- coords$x - out$Variable <- list() - out$Variable$varName <- "fwi" - return(out) -} diff --git a/README.md b/README.md index aea5a83..a5d79b3 100644 --- a/README.md +++ b/README.md @@ -3,26 +3,20 @@ What is fireDanger? `fireDanger` is an R package for the Implementation of the Canadian Fire Weather Index System using as input seasonal forecast data and other climatic datasets. -###References -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). - -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. +*** +`fireDanger` is part of the [**loadeR**](https://github.com/SantanderMetGroup/loadeR) **bundle**. -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +*** Find out more about this package (including [installation information](https://github.com/SantanderMetGroup/fireDanger/wiki/Installation)) in the [fireDanger's WIKI](https://github.com/SantanderMetGroup/fireDanger/wiki). -# Other packages of the `fireDanger` bundle - * [`loadeR`](https://github.com/SantanderMetGroup/loadeR/) an R package for climate data data access and manipulation powered by NetCDF-Java (trough the `rJava` package). +### References - * [`loadeR.ECOMS`](https://github.com/SantanderMetGroup/loadeR.ECOMS/) extends `loadeR` by providing homogenized access to ***seasonal and decadal forecast datasets*** from the [ECOMS](http://www.eu-ecoms.eu) initiative. More information in the [ECOMS-UDG web](https://meteo.unican.es/trac/wiki/udg/ecoms). +Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). - * [`loadeR.2nc`](https://github.com/SantanderMetGroup/loadeR.2nc/) provides support for **exporting to NetCDF**. +van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. - * [`downscaleR`](https://github.com/SantanderMetGroup/downscaleR) is an R package for **empirical-statistical downscaling** of daily data, including bias correction techniques. - - * [`visualizeR`](https://github.com/SantanderMetGroup/visualizeR) is an R package implementing a set of advanced **visualization tools for forecast verification**. +van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. ---- diff --git a/man-roxygen/templateParallel.R b/man-roxygen/templateParallel.R new file mode 100644 index 0000000..e2fcbff --- /dev/null +++ b/man-roxygen/templateParallel.R @@ -0,0 +1,15 @@ +#' @section Parallel Processing: +#' +#' Parallel processing is enabled using the \pkg{parallel} package. +#' Parallelization is undertaken by a FORK-type parallel socket cluster formed by \code{ncores}. +#' If \code{ncores} is not specified (default), \code{ncores} will be one less than the autodetected number of cores. +#' The maximum number of cores used for parallel processing can be set with the \code{max.ncores} argument, +#' although this will be reset to the auto-detected number of cores minus 1 if this number is exceeded. Note that not all +#' code, but just some critical loops within the function are parallelized. +#' +#' In practice, parallelization does not always result in smaller execution times, due to the parallel overhead. +#' However, parallel computing may potentially provide a significant speedup for the +#' particular case of large multimember datasets or large grids. +#' +#' Parallel computing is currently not available for Windows machines. + diff --git a/man-roxygen/templateParallelParams.R b/man-roxygen/templateParallelParams.R new file mode 100644 index 0000000..d4c0739 --- /dev/null +++ b/man-roxygen/templateParallelParams.R @@ -0,0 +1,4 @@ +#' @param parallel Logical. Should parallel execution be used? +#' @param max.ncores Integer. Upper bound for user-defined number of cores. +#' @param ncores Integer number of cores used in parallel computation. Self-selected number of +#' cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value. diff --git a/man/fwi.Rd b/man/fwi.Rd deleted file mode 100644 index 834e8f5..0000000 --- a/man/fwi.Rd +++ /dev/null @@ -1,61 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/fwi.R -\name{fwi} -\alias{fwi} -\title{Fire Weather Index applied to multigrids} -\usage{ -fwi(multigrid, mask = NULL, lonLim = NULL, latLim = NULL, lat = 46, - return.all = FALSE, init.pars = c(85, 6, 15), parallel = FALSE, - max.ncores = 16, ncores = NULL) -} -\arguments{ -\item{multigrid}{containing Tm (temperature records in deg. Celsius); H (relative humidity records in \%); -r (last 24-h accumulated precipitation in mm); W (wind velocity records in Km/h).} - -\item{mask}{Optional. Binary (0 an 1) Grid.} - -\item{lonLim}{Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees,} - -\item{latLim}{Same as \code{lonLim} argument, but for latitude.} - -\item{lat}{Optional. Latitude of the records (in decimal degrees). Default to 46, -applying the default parameters of the original FWI System, developed in Canada. See details.} - -\item{return.all}{Logical. Should all components of the FWI system be returned?. -Default to FALSE, indicating that only FWI is returned.} - -\item{init.pars}{A numeric vector of length 3 with the initialization values for the -FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} - -\item{parallel}{Logical. Should parallel execution be used?} - -\item{max.ncores}{Integer. Upper bound for user-defined number of cores.} - -\item{ncores}{Integer number of cores used in parallel computation. Self-selected number of - cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value.} -} -\value{ -A vector of the same length as the input vectors (minus possible missing observations), -containing the requested components of the FWI system (either all or just FWI). See details. -} -\description{ -Implementation of the Canadian Fire Weather Index System for multigrids -} -\section{Daylength adjustment factors}{ - -By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), - although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -Lawson and Armitage (2008). -} -\author{ -J. Bedia & M. Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -} -\references{ -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). - -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. - -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -} - diff --git a/man/fwi1D.Rd b/man/fwi1D.Rd index 9e70a6d..7a95873 100644 --- a/man/fwi1D.Rd +++ b/man/fwi1D.Rd @@ -1,11 +1,11 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand +% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fwi1D.R \name{fwi1D} \alias{fwi1D} \title{Fire Weather Index applied to 1D data} \usage{ -fwi1D(months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars = c(85, - 6, 15)) +fwi1D(months, Tm, H, r, W, lat = 46, what = "FWI", init.pars = c(85, 6, + 15), spin.up = 0) } \arguments{ \item{months}{Vector of integers corresponding to the months in the data} @@ -19,36 +19,50 @@ fwi1D(months, Tm, H, r, W, lat = 46, return.all = FALSE, init.pars = c(85, \item{W}{Vector of wind velocity records (Km/h)} \item{lat}{Optional. Latitude of the records (in decimal degrees). Default to 46, -applying the default parameters of the original FWI System, developed in Canada. See details.} +applying the default parameters of the original FWI System, developed in Canada. See Daylength Adjustment details.} -\item{return.all}{Logical. Should all components of the FWI system be returned?. -Default to FALSE, indicating that only FWI is returned.} +\item{what}{Character vector, indicating the components of the FWI system to be returned. +Accepted values include any possible subset of the set \{\code{"FFMC"},\code{"DMC"},\code{"DC"} +,\code{"BUI"},\code{"ISI"},\code{"FWI"},\code{"DSR"}\}. Default to \code{"FWI"}.} \item{init.pars}{A numeric vector of length 3 with the initialization values for the - FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} +FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} + +\item{spin.up}{Non-negative integer indicating the number of days considered for FWI spin-up. +Default to 0 (i.e. no spin-up is considered). See the dedicated Section below for further details.} } \value{ -A vector of the same length as the input vectors (minus possible missing observations), -containing the requested components of the FWI system (either all or just FWI). See details. +A matrix with the time (days) arranged in rows and the components selected in \code{what} +in columns. The attribute \code{colnames} gives the component ordering. } \description{ Implementation of the Canadian Fire Weather Index System to 1D data } \section{Daylength adjustment factors}{ - + By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), although it is possible to adjust them by as a function of latitude through the argument \code{lat}. The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in Lawson and Armitage (2008). } + +\section{FWI spin-up}{ + +FWI is initialized with some values for FFMC, DMC and DC components. This means that the first values of the series are not reliable, + until the index is iterated over several time steps and stabilizes (typically a few days suffice). + Thus, the first index values can be optionally set to \code{NA}. The number of days at the beginning of the series to be set to \code{NA} + is controlled via the \code{spin.up} argument. +} \author{ J. Bedia, partially based on the original FORTRAN code by van Wagner and Pickett (1985) } \references{ -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). +\itemize{ +\item Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. +\item van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +\item van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +} } diff --git a/man/fwiGrid.Rd b/man/fwiGrid.Rd index 24ec6d5..f3d1880 100644 --- a/man/fwiGrid.Rd +++ b/man/fwiGrid.Rd @@ -1,51 +1,98 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand +% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fwiGrid.R \name{fwiGrid} \alias{fwiGrid} -\title{Fire Weather Index (FWI)} +\title{Fire Weather Index applied to multigrids} \usage{ -fwiGrid(multigrid, mask = NULL, return.all = FALSE, init.pars = c(85, 6, - 15), parallel = FALSE, max.ncores = 16, ncores = NULL) +fwiGrid(multigrid, mask = NULL, what = "FWI", nlat.chunks = NULL, + restart.annual = TRUE, parallel = FALSE, ncores = NULL, + max.ncores = 16, ...) } \arguments{ -\item{multigrid}{A multigrid of the variables needed to compute the FWI.} +\item{multigrid}{containing Tm (temperature records in deg. Celsius); H (relative humidity records in \%); +r (last 24-h accumulated precipitation in mm); W (wind velocity records in Km/h). See details.} -\item{mask}{Optional. Grid of the land mask to be applied to the data.} +\item{mask}{Optional. Binary grid (0 and 1, 0 for sea areas) with \code{dimensions} attribute \code{c("lat", "lon")}.} -\item{return.all}{Logical. Should all components of the FWI system be returned?. -Default to FALSE, indicating that only FWI is returned.} +\item{what}{Character string. What component of the FWI system is computed?. Default to \code{"FWI"}. +See \code{\link{fwi1D}} for details and possible values.} -\item{init.pars}{A numeric vector of length 3 with the initialization values for the -FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} +\item{nlat.chunks}{For an efficient memory usage, the computation of FWI can be split into +latitudinal bands (chunks) sepparately. The number of chunks is controlled here. +Default to \code{NULL} (i.e., no chunking applied).} + +\item{restart.annual}{Logical. Should the calculation be restarted at the beginning of every year? +If the grid encompasses just one season (e.g. JJA...), this is the recommended option. Default to \code{TRUE}.} \item{parallel}{Logical. Should parallel execution be used?} +\item{ncores}{Integer number of cores used in parallel computation. Self-selected number of +cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value.} + \item{max.ncores}{Integer. Upper bound for user-defined number of cores.} -\item{ncores}{Integer number of cores used in parallel computation. Self-selected number of - cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value.} +\item{...}{Further arguments passed to \code{\link{fwi1D}}.} } \value{ -A grid, containing the requested components of the FWI system (either all or just FWI). See details. +A grid corresponding to the variable defined in argument \code{what}. } \description{ -Implementation of the Canadian Fire Weather Index System +Implementation of the Canadian Fire Weather Index System for multigrids +} +\details{ +\strong{Variable names} + +The variables composing the input multigrid are expected to have standard names, as defined by the dictionary + (their names are stored in the \code{multigrid$Variable$varName} component). +These are: \code{"tas"} for temperature, \code{"tp"} for precipitation, \code{"wss"} for windspeed. In the case of relative humidity, +either \code{"hurs"} or \code{"hursmin"} are accepted, the latter in case of FWI calculations according to the \dQuote{proxy} version +described in Bedia \emph{et al} 2014. + +\strong{Landmask definition} + +The use of a landsmask is highly recommended when using RCM/GCM data becasue (i) there is no point in calculating +FWI over sea areas and (ii) for computational efficiency, as sea gridboxes will be skipped before calculations. + +The landmask must be a grid spatially consistent with the input multigrid. You can use +\code{\link[transformeR]{interpGrid}} in combination with the \code{getGrid} method to ensure this condition is fulfilled. . Its \code{data} component can be either a 2D or 3D array with the \code{dimensions} +attribute \code{c("lat","lon")} or \code{c("time","lat","lon")} respectively. In the latter case, the length of the time +dimension should be 1. Note that values of 0 correspond to sea areas (thus discarded for FWI calculation), being land areas any other +values different from 0 (tipically 1 or 100, corresponding to the land/sea area fraction). + +\strong{Latitudinal chunking} + +Splitting the calculation in latitudinal chunks is highly advisable, and absolutely necessary when +considering large spatial domains, otherwise running out of memory during the computation. The number +of latitudinal chunks need to be estimated on a case-by-case basis, but in general there are no restrictions in the +number of chunks that can be used, as long as it does not exceed the number of actual latitudes +in the model grid. } -\section{Daylength adjustment factors}{ +\section{Parallel Processing}{ -By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), - although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -Lawson and Armitage (2008). + +Parallel processing is enabled using the \pkg{parallel} package. +Parallelization is undertaken by a FORK-type parallel socket cluster formed by \code{ncores}. +If \code{ncores} is not specified (default), \code{ncores} will be one less than the autodetected number of cores. +The maximum number of cores used for parallel processing can be set with the \code{max.ncores} argument, +although this will be reset to the auto-detected number of cores minus 1 if this number is exceeded. Note that not all +code, but just some critical loops within the function are parallelized. + +In practice, parallelization does not always result in smaller execution times, due to the parallel overhead. +However, parallel computing may potentially provide a significant speedup for the +particular case of large multimember datasets or large grids. + +Parallel computing is currently not available for Windows machines. } \author{ -J. Bedia \& M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) +J. Bedia \& M. Iturbide } \references{ -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). +\itemize{ +\item Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. +\item van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +\item van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. +} } diff --git a/man/fwiSkill.Rd b/man/fwiSkill.Rd deleted file mode 100644 index a2bb194..0000000 --- a/man/fwiSkill.Rd +++ /dev/null @@ -1,35 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/fwiSkill.R -\name{fwiSkill} -\alias{fwiSkill} -\title{Skill calculation} -\usage{ -fwiSkill(obs, fcst, verifun = c(""), prob, threshold = NULL, - parallel = FALSE, na.rm = TRUE) -} -\arguments{ -\item{obs}{Grid of the observation data} - -\item{fcst}{Grid of the seasonal forecast data} - -\item{verifun}{Name of function to compute verification metric (score, skill score). -Type help(veriApply) for details.} - -\item{prob}{Probability threshold for category forecasts (Type help(veriApply) for details).} - -\item{threshold}{Aabsolute threshold for category forecasts (Type help(veriApply) for details).} - -\item{parallel}{Logical. Should parallel execution be used?} - -\item{na.rm}{Logical. Should incomplete forecasts be used?} -} -\value{ -A grid of the skill scores. -} -\description{ -Skill calculation with function veriApply -} -\author{ -M.Iturbide -} - diff --git a/man/fwiSpain.Rd b/man/fwiSpain.Rd new file mode 100644 index 0000000..d7ee560 --- /dev/null +++ b/man/fwiSpain.Rd @@ -0,0 +1,37 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/rdas.R +\name{fwiSpain} +\alias{fwiSpain} +\title{Fire weather index data from observations and reanalysis at 7 locations in Spain} +\format{A list of two elements, containing data of the NCEP/NCAR reanalysis and observations data respectively. +For each element of the list, a second list of length 7 is provided, each corresponding to a particular location in Spain, + each of them containing a dataframe with the following fields: + \itemize{ + \item \code{fecha}. A vector of class Date with dates of the records + \item \code{T} A numeric vector of temperature records, in degree C + \item \code{H} A numeric vector of relative hunidity records, in degree \% + \item \code{P} A numeric vector of precipitation records, in mm, see details + \item \code{W} A numeric vector of wind speed records, in km/h + \item \code{FWI} A numeric vector with the Fire Weather Index series + } + @details Data correspond both to observations from the Spanish Meteorological Agency (AEMET, all recorded + at noon excepting precipitation, recorded at 07:00 UTC and corresponding to values + accumulated during the last 24h) and the NCEP reanalysis interpolated to the same locations (12:00 UTC), + encompassing a period of approximately 6 years (2006-2011). These records are therefore appropriate for the + calculation of several fire danger indices, requiring data measured around noon. + Further details on this dataset are provided in Bedia \emph{et al.} (2012).} +\description{ +Temperature, relative humidity, precipitation and wind velocity data from 7 locations in Spain, + as well as the resulting Fire Weather Index series, corresponding to both weather station observations + and reanalysis data (NCEP). +} +\examples{ +data(fwiSpain) +str(fwiSpain) +} +\references{ +J. Bedia, S. Herrera, J.M. Gutierrez, G. Zavala, I. R. Urbieta and J.M. Moreno (2012). Sensitivity of Fire Weather +Index to different reanalysis products in the Iberian Peninsula. \emph{Nat. Hazards Earth Syst. Sci.}, 12, 699-708. +\url{http://www.nat-hazards-earth-syst-sci.net/12/699/2012/nhess-12-699-2012.html} +} + diff --git a/man/fwiWorld.Rd b/man/fwiWorld.Rd deleted file mode 100644 index b690996..0000000 --- a/man/fwiWorld.Rd +++ /dev/null @@ -1,82 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/fwiWorld.R -\name{fwiWorld} -\alias{fwiWorld} -\title{World Fire Weather Index} -\usage{ -fwiWorld(dataset = "WFDEI", dictionary = TRUE, years = NULL, - season = NULL, lonLim = NULL, latLim = NULL, members = NULL, - leadMonth = 0, mask = NULL, return.all = FALSE, init.pars = c(85, 6, - 15), parallel = FALSE, max.ncores = 16, ncores = NULL) -} -\arguments{ -\item{dataset}{A character string indicating the database to be accessed (partial matching is enabled). -Currently accepted values are "WFDEI, "CFSv2_seasonal" and "S4_seasonal_15members".} - -\item{dictionary}{A logical flag indicating if a dictionary is used for variable homogenization. Default (strongly recommended) -is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization.} - -\item{years}{Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -it will be ignored. See details on the definition of temporal slices.} - -\item{season}{An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -See details on the definition of temporal slices.} - -\item{lonLim}{Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees, of the bounding box selected. -For single-point queries, a numeric value with the longitude coordinate. If \code{NULL} (default), the whole longitudinal range - is selected (Note that this may lead to a large output object size).} - -\item{latLim}{Same as \code{lonLim}, but for the selection of the latitudinal range.} - -\item{members}{A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -(see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -a forecast or the requested variable is static (e.g. orography) it will be ignored.} - -\item{leadMonth}{Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -case if its value is different from NULL. See details on initialization times.} - -\item{mask}{Grid of the land mask to be applied to the data.} - -\item{return.all}{Logical. Should all components of the FWI system be returned?. -Default to FALSE, indicating that only FWI is returned.} - -\item{init.pars}{A numeric vector of length 3 with the initialization values for the -FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} - -\item{parallel}{Logical. Should parallel execution be used?} - -\item{max.ncores}{Integer. Upper bound for user-defined number of cores.} - -\item{ncores}{Integer number of cores used in parallel computation. Self-selected number of - cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value.} -} -\value{ -A grid, containing the requested components of the FWI system (either all or just FWI). See details. -} -\description{ -Implementation of the Canadian Fire Weather Index System -} -\section{Daylength adjustment factors}{ - -By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), - although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -Lawson and Armitage (2008). -} -\author{ -J. Bedia \& M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -} -\references{ -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). - -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. - -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -} - diff --git a/man/indexOperative.Rd b/man/indexOperative.Rd deleted file mode 100644 index 25e18d8..0000000 --- a/man/indexOperative.Rd +++ /dev/null @@ -1,99 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/indexOperative.R -\name{indexOperative} -\alias{indexOperative} -\title{Index calculation for CFS operative seasonal forecast and csv file generation} -\usage{ -indexOperative(dataset = "CFSv2_seasonal_operative", index = "fwi", - climdir = getwd(), destdir = getwd(), url, mask = NULL, - fwi.mask = TRUE, dictionary = TRUE, members = 1:24, - aggr.mem = list(FUN = NULL), season = NULL, lonLim = NULL, - latLim = NULL, years = NULL, leadMonth = 0, operative = NULL, - init.pars = c(85, 6, 15), parallel = FALSE, max.ncores = 16, - ncores = NULL) -} -\arguments{ -\item{dataset}{A character string indicating the database to be accessed (partial matching is enabled). -Currently accepted values are "CFSv2_seasonal".} - -\item{index}{Index to be computed, e.g. "fwi".} - -\item{climdir}{Directory where observational climatologies are stored.} - -\item{destdir}{Output directory.} - -\item{url}{ncml directory.} - -\item{mask}{Directory (including file name) of the land-mask grid (*.rda).} - -\item{fwi.mask}{Logical. If TRUE (default), a mask is applied to exclude -land areas which will most likely not burn, like deserts etc.} - -\item{dictionary}{Path to the dictionary for variable homogenization. -is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization.} - -\item{members}{A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -(see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -a forecast or the requested variable is static (e.g. orography) it will be ignored.} - -\item{aggr.mem}{Member aggregation function. A list indicating the name of the -aggregation function in first place, and other optional arguments to be passed to the aggregation function.} - -\item{season}{An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -See details on the definition of temporal slices.} - -\item{lonLim}{Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees, of the bounding box selected. -For single-point queries, a numeric value with the longitude coordinate. If \code{NULL} (default), the whole longitudinal range - is selected (Note that this may lead to a large output object size).} - -\item{latLim}{Same as \code{lonLim}, but for the selection of the latitudinal range.} - -\item{years}{Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -it will be ignored. See details on the definition of temporal slices.} - -\item{leadMonth}{Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -case if its value is different from NULL. See details on initialization times.} - -\item{operative}{Path of the R object that contains the fwi of the operative dataset. Default is NULL, so the load and fwi is computed.} - -\item{init.pars}{A numeric vector of length 3 with the initialization values for the -FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} - -\item{parallel}{Logical. Should parallel execution be used?} - -\item{max.ncores}{Integer. Upper bound for user-defined number of cores.} - -\item{ncores}{Integer number of cores used in parallel computation. Self-selected number of - cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value.} -} -\value{ -A vector of the same length as the input vectors (minus possible missing observations), -containing the requested components of the FWI system (either all or just FWI). See details. -} -\description{ -Implementation of the Canadian Fire Weather Index System -} -\section{Daylength adjustment factors}{ - -By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), - although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -Lawson and Armitage (2008). -} -\author{ -J. Bedia \& M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -} -\references{ -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). - -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. - -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -} - diff --git a/man/meteoSpain.Rd b/man/meteoSpain.Rd new file mode 100644 index 0000000..954dd53 --- /dev/null +++ b/man/meteoSpain.Rd @@ -0,0 +1,14 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/rdas.R +\name{meteoSpain} +\alias{meteoSpain} +\title{Time series of meteo station data from Spain} +\format{A data.frame} +\description{ +Daily precipitation, maximum and minimum temperature records. +} +\examples{ +data(meteoSpain) +str(meteoSpain) +} + diff --git a/man/parallelCheck.Rd b/man/parallelCheck.Rd deleted file mode 100644 index 5194705..0000000 --- a/man/parallelCheck.Rd +++ /dev/null @@ -1,35 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/parallelCheck.R -\name{parallelCheck} -\alias{parallelCheck} -\title{Parallel availability check} -\usage{ -parallelCheck(parallel, max.ncores = 16, ncores = NULL) -} -\arguments{ -\item{parallel}{Logical, should parallel execution be used?} - -\item{ncores}{number of cores used in parallel computation, self-selected number of cores -is used when \code{is.null(ncpus)} (the default).} - -\item{maxcores}{upper bound for self-selected number of cores} -} -\value{ -A list with two elements: -\itemize{ -\item \code{hasparallel}, a logical flag indicating if parallelization is enabled and -\item \code{cl}: parallel socket cluster object, or NULL. -} -} -\description{ -Check availability of parallel package and set parameters -} -\details{ -The function checks if package parallel is available. Then, it is checked whether the FORK nodes -can be initialized -} -\author{ -J. Bedia, relying on previous code by Jonas Bhend and Matteo de Felice -} -\keyword{internal} - diff --git a/man/plotFwiSkill.Rd b/man/plotFwiSkill.Rd deleted file mode 100644 index 864de25..0000000 --- a/man/plotFwiSkill.Rd +++ /dev/null @@ -1,18 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/fwiSkill.R -\name{plotFwiSkill} -\alias{plotFwiSkill} -\title{Plot grid returned by functionfFwiSkill} -\usage{ -plotFwiSkill(grid) -} -\arguments{ -\item{grid}{The grid object returned by function fwiSkill} -} -\description{ -Plot grid returned by functionfFwiSkill through function plotClimatology from package downscaleR -} -\author{ -M.Iturbide -} - diff --git a/man/wfwiOP.Rd b/man/wfwiOP.Rd deleted file mode 100644 index fede0de..0000000 --- a/man/wfwiOP.Rd +++ /dev/null @@ -1,87 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/indexOperative.R -\name{wfwiOP} -\alias{wfwiOP} -\title{Index calculation for CFS operative seasonal forecast} -\usage{ -wfwiOP(dataset = "CFSv2_seasonal_operative", index = "fwi", url, - mask = NULL, dictionary = TRUE, members = 1:24, aggr.mem = list(FUN = - NULL), season = NULL, years = NULL, lonLim = NULL, latLim = NULL, - leadMonth = 0, return.all = FALSE, init.pars = c(85, 6, 15), - parallel = FALSE, max.ncores = 16, ncores = NULL) -} -\arguments{ -\item{dataset}{A character string indicating the database to be accessed (partial matching is enabled). -Currently accepted values are "CFSv2_seasonal".} - -\item{index}{Index to be computed, e.g. "fwi".} - -\item{url}{ncml directory.} - -\item{mask}{Directory (including file name) of the land-mask grid (*.rda).} - -\item{dictionary}{A logical flag indicating if a dictionary is used for variable homogenization. Default (strongly recommended) -is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization.} - -\item{members}{A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -(see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -a forecast or the requested variable is static (e.g. orography) it will be ignored.} - -\item{aggr.mem}{Member aggregation function. A list indicating the name of the -aggregation function in first place, and other optional arguments to be passed to the aggregation function.} - -\item{season}{An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -See details on the definition of temporal slices.} - -\item{years}{Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -it will be ignored. See details on the definition of temporal slices.} - -\item{lonLim}{Vector of length = 2, with minimum and maximum longitude coordinates, in decimal degrees, of the bounding box selected. -For single-point queries, a numeric value with the longitude coordinate. If \code{NULL} (default), the whole longitudinal range - is selected (Note that this may lead to a large output object size).} - -\item{latLim}{Same as \code{lonLim}, but for the selection of the latitudinal range.} - -\item{leadMonth}{Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -case if its value is different from NULL. See details on initialization times.} - -\item{return.all}{Logical. Should all components of the FWI system be returned?.} - -\item{init.pars}{A numeric vector of length 3 with the initialization values for the -FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} - -\item{parallel}{Logical. Should parallel execution be used?} - -\item{max.ncores}{Integer. Upper bound for user-defined number of cores.} - -\item{ncores}{Integer number of cores used in parallel computation. Self-selected number of - cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value.} -} -\value{ -A vector of the same length as the input vectors (minus possible missing observations), -containing the requested components of the FWI system (either all or just FWI). See details. -} -\description{ -Implementation of the Canadian Fire Weather Index System -} -\section{Daylength adjustment factors}{ - -By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), - although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -Lawson and Armitage (2008). -} -\references{ -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). - -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. - -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -} - diff --git a/man/wfwibc.Rd b/man/wfwibc.Rd deleted file mode 100644 index b77587a..0000000 --- a/man/wfwibc.Rd +++ /dev/null @@ -1,82 +0,0 @@ -% Generated by roxygen2 (4.1.1): do not edit by hand -% Please edit documentation in R/wfwibc.R -\name{wfwibc} -\alias{wfwibc} -\title{World Bias Correction} -\usage{ -wfwibc(dataset, dictionary = TRUE, members = NULL, season = NULL, - years = NULL, leadMonth = 1, lat = 46, return.all = FALSE, - init.pars = c(85, 6, 15), bc.multigrid, method = c("delta", "scaling", - "eqm", "gqm", "gpqm"), cross.val = c("none", "loocv", "kfold"), - folds = NULL, window = NULL, scaling.type = c("additive", - "multiplicative"), wet.threshold = 1, n.quantiles = NULL, - extrapolation = c("none", "constant"), theta = 0.95, parallel = FALSE, - max.ncores = 16, ncores = NULL) -} -\arguments{ -\item{dataset}{A character string indicating the database to be accessed (partial matching is enabled). -Currently accepted values are "System4_seasonal_15" and "CFSv2_seasonal".} - -\item{dictionary}{A logical flag indicating if a dictionary is used for variable homogenization. Default (strongly recommended) -is set to TRUE, meaning that the function will internally perform the necessary homogenization steps to return the standard -variables defined in the vocabulary (e.g. variable transformation, deaccumulation...). See details on data homogenization.} - -\item{members}{A vector of integers indicating the members to be loaded. Default to NULL, which loads the default members -(see details for the particularities concerning the CFSv2 dataset). For instance, members=1:5 will retrieve the first five -members of the hindcast. Discontinuous member selection (e.g. members=c(1,5,7)) is allowed. If the requested dataset is not -a forecast or the requested variable is static (e.g. orography) it will be ignored.} - -\item{season}{An integer vector specifying the desired season (in months, January = 1 ..., December = 12). Options include -one to several (contiguous) months. For full year selections (not possible for all datasets, e.g. seasonal forecasts), -the argument value must be set to season = 1:12. If the requested variable is static (e.g. orography) it will be ignored. -See details on the definition of temporal slices.} - -\item{years}{Optional vector of years to select. Default to all available years. If the requested variable is static (e.g. orography) -it will be ignored. See details on the definition of temporal slices.} - -\item{leadMonth}{Integer value indicating the lead forecast time, relative to the first month of season. Note that leadMonth=1 for -season=1 (January) corresponds to the December initialization. Default to 1 (i.e., 1 lead month forecast). If the dataset is not a -forecast or the requested variable is static (e.g. orography) it will be ignored. A message will be printed on screen in the first -case if its value is different from NULL. See details on initialization times.} - -\item{lat}{Optional. Latitude of the records (in decimal degrees). Default to 46, -applying the default parameters of the original FWI System, developed in Canada. See details.} - -\item{return.all}{Logical. Should all components of the FWI system be returned?. -Default to FALSE, indicating that only FWI is returned.} - -\item{init.pars}{A numeric vector of length 3 with the initialization values for the -FFMC, DMC and DC components, in this order. Default values as proposed by van Wagner (1987).} - -\item{parallel}{Logical. Should parallel execution be used?} - -\item{max.ncores}{Integer. Upper bound for user-defined number of cores.} - -\item{ncores}{Integer number of cores used in parallel computation. Self-selected number of - cores is used when \code{ncpus = NULL} (the default), or when \code{maxcores} exceeds the default \code{ncores} value.} -} -\value{ -A vector of the same length as the input vectors (minus possible missing observations), -containing the requested components of the FWI system (either all or just FWI). See details. -} -\description{ -Application of different bias correction methods to seasonal forecasts covering the World. -} -\section{Daylength adjustment factors}{ - -By default, the function applies the original FWI daylength adjustment factors for DC and DMC (van Wagner 1987), - although it is possible to adjust them by as a function of latitude through the argument \code{lat}. -The reference values used for each latitudinal range are those indicated in p.71 and Tables A3.1 and A3.2 (p69) in -Lawson and Armitage (2008). -} -\author{ -J. Bedia & M.Iturbide, partially based on the original FORTRAN code by van Wagner and Pickett (1985) -} -\references{ -Lawson, B.D. & Armitage, O.B., 2008. Weather guide for the Canadian Forest Fire Danger Rating System. Northern Forestry Centre, Edmonton (Canada). - -van Wagner, C.E., 1987. Development and structure of the Canadian Forest Fire Weather Index (Forestry Tech. Rep. No. 35). Canadian Forestry Service, Ottawa, Canada. - -van Wagner, C.E., Pickett, T.L., 1985. Equations and FORTRAN program for the Canadian forest fire weather index system (Forestry Tech. Rep. No. 33). Canadian Forestry Service, Ottawa, Canada. -} -