R/build_specifications.R

Defines functions build_internal_data build_lookup_tables

#' Build the lookup tables from the specifications
#'
#' Converts the catalogues in `inst/spec` into the lookup tables shipped with
#'  the package (`STIR_values_LUT`, `C_input_crops_LUT`, `plant_cover_LUT`,
#'  `N_fixation_legumes_LUT`, `CN_input_amendments_LUT`, `mineral_fertilizers_LUT`). Used by
#'  `tools/build-specifications.R` and by the tests that check that the
#'  shipped datasets agree with the specifications.
#'
#' @param spec list of parsed specifications, see `read_specifications()`
#'
#' @return a named list of tibbles
#'
#' @md
#' @noRd
build_lookup_tables <- function(spec) {

  # numeric value, NA if unknown
  num <- function(x) if (is.null(x)) NA_real_ else as.numeric(x)
  lgl <- function(x) if (is.null(x)) NA else as.logical(x)
  chr <- function(x) if (is.null(x)) NA_character_ else as.character(x)
  rows <- function(entries, fn) {
    out <- lapply(entries, fn)
    tibble::as_tibble(do.call(rbind, lapply(Filter(Negate(is.null), out), as.data.frame, stringsAsFactors = FALSE)))
  }

  STIR_values_LUT <- rows(spec$devices$devices, function(d) {
    s <- d$stir
    if (is.null(s)) return(NULL)
    list(Operation = d$id, Speed = num(s$speed$default), Speed_MIN = num(s$speed$min), Speed_Max = num(s$speed$max),
         Surf_Disturbance = num(s$surface_disturbance), Depth = num(s$depth$default),
         Depth_MIN = num(s$depth$min), Depth_MAX = num(s$depth$max), TILLAGE_TYPE = chr(s$tillage_type),
         TILLAGE_TYPE_Modifier = num(s$tillage_type_modifier), STIR_original = num(s$stir_original),
         Diesel_use = num(d$diesel_use), Burial_Coefficient = num(d$burial_coefficient),
         Source = chr(s$source_label), Description = chr(s$source_note))
  })

  carbon_cols <- c("RP", "RS", "RR", "RE", "SP", "SS", "SR", "SE", "crop_product", "harvest_index",
                   "variable_harvest_index", "HI_intercept", "HI_slope", "shoot_root_ratio",
                   "root_exudation_factor", "fixed_belowground_input", "C_input_root")
  C_input_crops_LUT <- rows(spec$crops$crops, function(cr) {
    p <- cr$carbon
    if (is.null(p)) return(NULL)
    values <- lapply(carbon_cols, function(n) {
      if (n %in% c("variable_harvest_index", "fixed_belowground_input")) lgl(p[[n]]) else num(p[[n]])
    })
    c(list(Crop = cr$id), stats::setNames(values, carbon_cols), list(Source = chr(p$source_note)))
  })

  plant_cover_LUT <- rows(spec$crops$crops, function(cr) {
    p <- cr$plant_cover
    if (is.null(p)) return(NULL)
    list(Crop = cr$id, Slope_0_10 = num(p$slope_0_10), Slope_10_50 = num(p$slope_10_50),
         Slope_50_75 = num(p$slope_50_75), Slope_75_100 = num(p$slope_75_100), days_30 = num(p$days_30),
         Comments = chr(p$source_note))
  })

  N_fixation_legumes_LUT <- rows(spec$crops$crops, function(cr) {
    p <- cr$n_fixation
    if (is.null(p)) return(NULL)
    list(Crop = cr$id, crop_product = num(p$crop_product), alpha_crop = num(p$alpha_crop),
         beta_crop = num(p$beta_crop), N_con = num(p$N_con), NHI = num(p$NHI), BGNF = num(p$BGNF),
         N_fix = num(p$N_fix), Source = chr(p$source_note))
  })

  CN_input_amendments_LUT <- rows(spec$fertilizers$fertilizers, function(f) {
    if (f$type != "organic") return(NULL)
    list(Amendment = f$id, DMC = num(f$DMC), OM = num(f$composition$OM), C_content = num(f$composition$C),
         N_tot = num(f$N_tot), N_content = num(f$composition$N),
         animal_origin = chr(if (is.null(f$livestock_manure)) NULL else toupper(f$livestock_manure)),
         N_availability = num(f$N_availability), ISMO = num(f$ISMO$value), Comment = chr(f$source_note),
         ISMO_source = chr(f$ISMO$source_note))
  })

  # contents per product mass (the composition is given per dry matter)
  per_product <- function(f, n) num(f$composition[[n]]) * num(f$DMC) / 1000
  mineral_fertilizers_LUT <- rows(spec$fertilizers$fertilizers, function(f) {
    if (f$type != "mineral") return(NULL)
    list(Fertilizer = f$id, Label = chr(f$label), Operation = paste(unlist(f$operations), collapse = ", "),
         Physical_form = chr(f$physical_form), Density = num(f$density),
         N_content = per_product(f, "N"), P2O5_content = per_product(f, "P2O5"),
         K2O_content = per_product(f, "K2O"), Mg_content = per_product(f, "Mg"),
         S_content = per_product(f, "S"), CaO_content = per_product(f, "CaO"),
         Comment = chr(f$source_note))
  })

  list(STIR_values_LUT = STIR_values_LUT, C_input_crops_LUT = C_input_crops_LUT,
       plant_cover_LUT = plant_cover_LUT, N_fixation_legumes_LUT = N_fixation_legumes_LUT,
       CN_input_amendments_LUT = CN_input_amendments_LUT,
       mineral_fertilizers_LUT = mineral_fertilizers_LUT)
}

#' Build the internal data from the specifications
#'
#' Creates the internal tables stored in `R/sysdata.rda`: allowed operations
#'  per category, aliases, the behaviour flags of devices and products, the
#'  components of the seed mixtures and the rules for management records.
#'
#' @param spec list of parsed specifications, see `read_specifications()`
#'
#' @return a named list
#'
#' @md
#' @noRd
build_internal_data <- function(spec) {

  categories <- vapply(spec$operations$categories, function(x) x$id, character(1))
  operations <- spec$operations$operations
  choice_list_operations <- lapply(stats::setNames(categories, categories), function(cat) {
    vapply(Filter(function(o) o$category == cat, operations), function(o) o$id, character(1))
  })

  alias_rows <- function(entries, attribute) {
    do.call(rbind, lapply(entries, function(e) {
      if (length(e$aliases) == 0) return(NULL)
      data.frame(attribute = attribute, alias = unlist(e$aliases), id = e$id, stringsAsFactors = FALSE)
    }))
  }
  spec_aliases <- rbind(
    alias_rows(spec$crops$crops, "crop"),
    alias_rows(spec$devices$devices, "device"),
    alias_rows(spec$operations$operations, "operation"),
    alias_rows(spec$operations$categories, "category"),
    alias_rows(spec$fertilizers$fertilizers, "product"),
    alias_rows(spec$products$products, "product"),
    alias_rows(spec$seed_mixtures$seed_mixtures, "product"),
    data.frame(attribute = character(), alias = character(), id = character())
  )

  flag <- function(x, name) if (is.null(x[[name]])) NA else as.logical(x[[name]])
  spec_device_flags <- data.frame(
    device = vapply(spec$devices$devices, function(d) d$id, character(1)),
    terminates_main_crop = vapply(spec$devices$devices, function(d) flag(d$flags, "terminates_main_crop"), logical(1)),
    terminates_cover_crop = vapply(spec$devices$devices, function(d) flag(d$flags, "terminates_cover_crop"), logical(1)),
    stir_not_applicable = vapply(spec$devices$devices, function(d) isTRUE(d$stir_not_applicable), logical(1)),
    stringsAsFactors = FALSE)

  spec_product_flags <- data.frame(
    product = vapply(spec$products$products, function(p) p$id, character(1)),
    terminates_vegetation = vapply(spec$products$products, function(p) isTRUE(p$flags$terminates_vegetation), logical(1)),
    stringsAsFactors = FALSE)

  # products of the catalogues per operation
  spec_product_operations <- do.call(rbind, c(
    lapply(c("fertilizers", "products", "seed_mixtures"), function(catalogue) {
      do.call(rbind, lapply(spec[[catalogue]][[catalogue]], function(p) {
        data.frame(product = p$id, operation = unlist(p$operations), catalogue = catalogue, stringsAsFactors = FALSE)
      }))
    }),
    list(data.frame(product = character(), operation = character(), catalogue = character(),
                    stringsAsFactors = FALSE))))

  # one row per component of the seed mixtures
  spec_seed_mixtures <- do.call(rbind, c(
    lapply(spec$seed_mixtures$seed_mixtures, function(m) {
      data.frame(mixture = m$id, crop = vapply(m$components, function(x) x$crop, character(1)),
                 amount = vapply(m$components, function(x) as.numeric(x$amount), numeric(1)),
                 basis = m$basis, stringsAsFactors = FALSE)
    }),
    list(data.frame(mixture = character(), crop = character(), amount = numeric(), basis = character(),
                    stringsAsFactors = FALSE))))

  list(spec_version = spec$manifest$spec_version,
       choice_list_operations = choice_list_operations,
       spec_aliases = spec_aliases,
       spec_device_flags = spec_device_flags,
       spec_product_flags = spec_product_flags,
       spec_product_operations = spec_product_operations,
       spec_seed_mixtures = spec_seed_mixtures,
       spec_management_rules = management_rules(spec))
}

Try the SoilManageR package in your browser

Any scripts or data that you put into this service are public.

SoilManageR documentation built on Nov. 17, 2026, 5:08 p.m.