NcDataReader.R 2.12 KB
Newer Older
# Parameter 'file_selectos' expects a named character vector of single
# file dimension selectors.
# Parameter 'inner_indices' expects a named list of numeric vectors.
NcDataReader <- function(file_path = NULL, file_object = NULL, 
                         file_selectors = NULL, inner_indices) {
  if (!is.null(file_object)) {
    file_to_read <- file_object
Nicolau Manubens Gil's avatar
Nicolau Manubens Gil committed
    file_path <- file_object$filename
  } else if (!is.null(file_path)) {
Nicolau Manubens Gil's avatar
Nicolau Manubens Gil committed
    file_to_read <- NcOpener(file_path)
  } else {
    stop("Either 'file_path' or 'file_object' must be provided.")
  }

Nicolau Manubens Gil's avatar
Nicolau Manubens Gil committed
  drop_var_dim <- FALSE
  if (any(c('var', 'variable') %in% names(file_selectors))) {
    if (!any(c('var', 'variable') %in% names(inner_indices))) {
      inner_indices[['var']] <- file_selectors[[which(names(file_selectors) %in% c('var', 'variable'))[1]]]
Nicolau Manubens Gil's avatar
Nicolau Manubens Gil committed
      drop_var_dim <- TRUE
Nicolau Manubens Gil's avatar
Nicolau Manubens Gil committed
  if (any(names(inner_indices) %in% c('var', 'variable'))) {
    position_of_var <- which(names(inner_indices) %in% c('var', 'variable'))[1]
  } else {
    stop("A 'var'/'variable' file or inner dimension must be requested for ",
         "Start() to read NetCDF files.")
  }
  inner_dims <- NcDimReader(NULL, file_to_read, NULL, inner_indices[position_of_var])
  if (drop_var_dim) {
    inner_dims <- inner_dims[-which(names(inner_dims) %in% c('var', 'variable'))]
  }
  singleton_unspecified_dims <- which((inner_dims == 1) & 
                                      !(names(inner_dims) %in% names(inner_indices)))
  if (length(singleton_unspecified_dims) > 0) {
    inner_dims <- inner_dims[-singleton_unspecified_dims]
  }
  if (any(!(names(inner_dims) %in% names(inner_indices)))) {
    expected_dim_names <- names(inner_indices)
    if (drop_var_dim) {
      expected_dim_names <- expected_dim_names[-position_of_var]
    }
    stop("Unexpected extra dimensions (of length > 1) in the file.\nExpected: ",
         paste(expected_dim_names, collapse = ', '), "\n",
         "Found: ", paste(names(inner_dims), collapse = ', '), "\n",
         file_path)
  }
  easyNCDF::NcToArray(file_to_read, inner_indices, drop_var_dim = drop_var_dim,
                      expect_all_indices = TRUE, allow_out_of_range = TRUE)
}