R/grads_wraper_jra55_minmax_surf.R

grads_wraper_jra55_minmax_surf <- function(
                                    start_date, end_date,
                                    output.dir, grads.bin
                                )
{
    hours <- time_step_3hour(start_date, end_date)
    dir.month <- format(hours, "%Y%m")

    ret <- lapply(unique(dir.month), function(mo){
        dir.mon <- file.path(output.dir, "GRIB", mo)

        file.tx.nc <- file.path(dir.mon, "tmax.nc")
        file.tn.nc <- file.path(dir.mon, "tmin.nc")
        file.grads <- file.path(dir.mon, "script.gs")
        file.ctl <- file.path(dir.mon, "minmax_surf.ctl")

        dctl <- readLines(file.ctl)
        it <- grep("tdef", dctl, ignore.case = TRUE)
        dctl <- strsplit(dctl[it], " ")[[1]]
        dctl <- dctl[dctl != ""]
        nl <- as.numeric(dctl[2])
        orig <- as.POSIXct(dctl[4], tz = "GMT", format = "%HZ%d%b%Y")

        day.d <- format(hours[dir.month == mo], "%Y%m%d")
        day.g <- format(seq(orig, length.out = nl, by = "3 hours"), "%Y%m%d")
        rg <- range(which(day.g %in% day.d))

        file.gs <- c(
                paste0("'", "open ", file.ctl, "'"),
                paste0("'", "set t ", rg[1], " ", rg[2], "'"),
                paste0("'", "set sdfwrite -4d ", file.tx.nc, "'"),
                "'define var = tmax2m'",
                "'sdfwrite var'",
                paste0("'", "set sdfwrite -4d ", file.tn.nc, "'"),
                "'define var = tmin2m'",
                "'sdfwrite var'"
            )
        file.gs <- paste0(file.gs, collapse = "\n")
        cat(file.gs, file = file.grads, sep = "\n")
        log.file <- file.path(dir.mon, "log.txt")
        system2(grads.bin, paste("-lbcx", file.grads),
                stdout = log.file, stderr = log.file)
        return(0)
    })

    invisible()
}
rijaf-iri/CDTDownload documentation built on June 5, 2019, 12:37 a.m.