Skip to content

Instantly share code, notes, and snippets.

@eliocamp
Last active March 14, 2020 23:09
Show Gist options
  • Save eliocamp/6f03d599eba961c88c9b0b6791bc389f to your computer and use it in GitHub Desktop.
Save eliocamp/6f03d599eba961c88c9b0b6791bc389f to your computer and use it in GitHub Desktop.
Possible cdo wrapper in R.
# This is an experiment to wrap CDO in R in a intuitive and pipe friendly way.
# Usage:
# cdo_* will create a string with a commmand. If any of the "input_file" arguments
# is a cdo command, it will append "-" to it so that it can be chained.
# This is good for efficiency as it will allow you to apply multiple
# operations without having to write to disk the intermediate files.
## "Internal" functions in which the magic happens
.enchain <- function(input) {
if (inherits(input, "cdo_output")) {
stop("This operation has output and thus cannot be chained:\n", input)
}
if (inherits(input, "cdo_operator")) {
input <- paste0("-", input)
}
return(input)
}
.build_command <- function(operator, inputs, outputs = NULL) {
if (!is.null(outputs)) {
command <- paste0("cdo ", operator, " ",
paste(inputs, collapse = " "), " ",
paste(outputs, collapse = " "))
class(command) <- c("cdo_output", class(command))
return(command)
} else {
command <- paste0(operator, " ",
paste(inputs, collapse = " "))
class(command) <- c("cdo_operator", class(command))
return(command)
}
}
# Define a couple of operators.
# This has to be done for the ~700 operators. Ideally, automatically.
cdo_sub <- function(input_file_1, input_file_2, output_file = NULL) {
input_file_1 <- .enchain(input_file_1)
input_file_2 <- .enchain(input_file_2)
.build_command("sub", c(input_file_1, input_file_2), output_file)
}
cdo_dayavg <- function(input_file, output_file = NULL) {
input_file <- .enchain(input_file)
.build_command("dayavg", input_file, output_file)
}
cdo_timavg <- function(input_file, output_file = NULL) {
input_file <- .enchain(input_file)
.build_command("timavg", input_file, output_file)
}
cdo_abs <- function(input_file, output_file = NULL) {
input_file <- .enchain(input_file)
.build_command("timabs", input_file, output_file)
}
cdo_output <- function(command, output_file) {
paste0("cdo ", command, " ", output_file)
}
cdo_run <- function(command) {
system(command)
}
## Mock examples (should end with `cdo_run()` to be performed)
library(magrittr)
cdo_sub(input_file_1 = cdo_dayavg("file1"),
input_file_2 = cdo_timavg("file2"),
output_file = "file3")
"file" %>%
cdo_dayavg() %>%
cdo_abs() %>%
cdo_output("file2")
# Error
cdo_dayavg("file", "outfile") %>%
cdo_abs()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment