# packages
library(metaDigitise)
library(magrittr)
library(tibble)
library(dplyr)
library(lubridate)
library(dpeatdecomposition)
library(dm)
library(RMariaDB)

1 Preparations

Connect to database

# connect to database
con <-
  RMariaDB::dbConnect(
    drv = RMariaDB::MariaDB(),
    dbname = "dpeatdecomposition",
    default.file = "~/my.cnf"
  )

# get database as dm object
dm_dpeatdecomposition <-
  dpeatdecomposition::dp_get_dm(con, learn_keys = TRUE)

Get most current IDs

id_last <- 
  list(
    id_dataset = 
      dm_dpeatdecomposition %>%
      dm::pull_tbl(datasets) %>%
      dplyr::pull(id_dataset) %>%
      tail(1),
    id_sample = 
      dm_dpeatdecomposition %>%
      dm::pull_tbl(samples) %>%
      dplyr::pull(id_sample) %>%
      tail(1),
    id_measurement = 
      dm_dpeatdecomposition %>%
      dm::pull_tbl(data) %>%
      dplyr::pull(id_measurement) %>%
      tail(1)
    ) %>%
  purrr::map(function(.x) {
    if(length(.x) == 0) {
      0L
    } else {
      .x
    }
  })

Create directories

dir_name <- "d53"
dir_source <- "../raw_data/data/d53"
dir_target <- paste0("../derived_data/", id_last$id_dataset + 1L)

if(!dir.exists(dir_target)) {
  dir.create(dir_target)
}

2 Data wrangling

2.1 dataset

datasets <- 
  tibble::tibble(
    id_dataset = id_last$id_dataset + 1L
  )

2.2 citations_to_datasets

citations_to_datasets <- 
  dplyr::bind_rows(
    db_template_tables$citations_to_datasets,
    tibble::tibble(
      id_dataset = datasets$id_dataset,
      id_citation = c("Bengtsson.2017", "Bengtsson.2016") 
    )
  )

2.3 samples

# mass remaining
samples3 <- 
  read.csv(paste0(dir_source, "/raw/bengtsson_etal_2016_traits.csv")) %>%
  dplyr::select(-c(6:7, 11, 16:ncol(.))) %>%
  dplyr::rename(
    sample_label = "sample",
    site_name = "site",
    sampling_latitude = "latitude",
    sampling_longitude = "longitude",
    taxon_rank_value = "species.name",
    site_type = "vegetation.type",
    origin_sample_microhabitat = "microtopographical.position"
  ) %>%
  tidyr::pivot_longer(
    cols = dplyr::starts_with("loss"), 
    values_to = "mass_remaining",
    names_to = "name"
  ) %>%
  dplyr::mutate(
    mass_absolute = NA_real_,
    sample_treatment =
      dplyr::case_when(
        stringr::str_detect(name, "losslab") ~ "laboratory incubation",
      stringr::str_detect(name, "lossfield") ~ "control"
      ),
    id_dataset = datasets$id_dataset[[1]],
    is_incubated = TRUE,
    origin_plot_label = sample_label,
    origin_site_name = site_name,
    origin_sampling_longitude = sampling_longitude,
    origin_sampling_latitude = sampling_latitude,
    site_name =
      dplyr::case_when(
        sample_treatment == "control" ~ origin_site_name,
        TRUE ~ NA_character_
      ),
    plot_label =
      dplyr::case_when(
        sample_treatment == "control" ~ origin_plot_label,
        TRUE ~ NA_character_
      ),
    sampling_longitude =
      dplyr::case_when(
        sample_treatment == "control" ~ origin_sampling_longitude,
        TRUE ~ NA_real_
      ),
    sampling_latitude =
      dplyr::case_when(
        sample_treatment == "control" ~ origin_sampling_latitude,
        TRUE ~ NA_real_
      ),
    sample_depth_upper =
      dplyr::case_when(
        sample_treatment == "control" ~ 5,
        TRUE ~ NA_real_
      ),
    sample_depth_lower =
      dplyr::case_when(
        sample_treatment == "control" ~ 5,
        TRUE ~ NA_real_
      ),
    incubation_environment =
      dplyr::case_when(
        sample_treatment == "control" ~ "peat",
        TRUE ~ "container"
      ),
    mesh_size_absolute = 0.3,
    mass_relative_mass = 1 - mass_remaining/100,
    sampling_date = dplyr::case_when(
      stringr::str_detect(name, "losslab1") ~ as.Date("2012-09-10") + lubridate::dmonths(7),
      stringr::str_detect(name, "losslab2b") ~ as.Date("2012-09-10") + lubridate::dmonths(14),
      stringr::str_detect(name, "lossfield") ~ as.Date("2012-07-9") + lubridate::dmonths(14),
      TRUE ~ NA_real_
    ) %>%
      as.Date(),
    taxon_rank_value = 
      taxon_rank_value %>%
      stringr::str_replace(pattern = "_", replacement = " "),
    taxon_rank_name = "species",
    shade = 
      dplyr::case_when(
        shade == "1open" ~ "open",
        shade == "2semi" ~ "semi-open",
        shade == "3dark" ~ "shaded"
      ),
    sampling_year = lubridate::year(sampling_date),
    sampling_month = lubridate::month(sampling_date),
    sampling_day = lubridate::day(sampling_date),
    incubation_duration = 
      lubridate::time_length(sampling_date - as.Date("2012-09-10"), unit = "days"),
    sample_type = "litter",
    taxon_organ = "shoots",
    origin_sample_depth_upper = 1,
    origin_sample_depth_lower = 4,
    dplyr::across(dplyr::any_of(c("site_type", "sample_microhabitat")), tolower),
    comments_samples = "Coordinates are only the approximate location of the study site, but not sampling points. Each sample corresponds to one separate patch (plot, identified by `plot_label`) on the peatlands from which samples were taken. Samples were collected at the same patches as samples from @Bengtsson.2018, but are not the same samples. I assumed that the capitulum of moss shoots had a length of 1 cm.",
    experimental_design =
      paste0(
        as.numeric(as.factor(sample_treatment)), "_",
        as.numeric(as.factor(origin_site_name)), "_",
        as.numeric(as.factor(site_name)), "_",
        as.numeric(as.factor(origin_plot_label)), "_",
        as.numeric(as.factor(plot_label))
      )
  ) %>%
  dplyr::filter(name != "losslab2a")

# initial mass
samples2 <- 
  samples3 %>%
  dplyr::filter(name != "losslab2b") %>%
  dplyr::mutate(
    mass_relative_mass = 1.0,
    sampling_date = dplyr::case_when(
      stringr::str_detect(name, "losslab1") ~ as.Date("2012-09-10"),
      stringr::str_detect(name, "lossfield") ~ as.Date("2012-07-9"),
      TRUE ~ NA_real_
    ),
    sampling_year = lubridate::year(sampling_date),
    sampling_month = lubridate::month(sampling_date),
    sampling_day = lubridate::day(sampling_date),
    incubation_duration = 0
  )

# litter collection
samples1 <- 
  samples2 %>%
  dplyr::filter(! stringr::str_detect(name, "losslab")) %>%
  dplyr::mutate(
    id_sample = seq_len(nrow(.)) + id_last$id_sample,
    id_sample_origin = id_sample,
    id_sample_parent = id_sample,
    id_sample_incubation_start = NA_integer_,
    is_incubated = FALSE,
    sampling_date =
      dplyr::case_when(
        site_name == "Kulflyten" ~ "2012-06-12",
        site_name == "Glon" ~ "2012-07-01"
      ) %>%
      as.Date(),
    sampling_year = lubridate::year(sampling_date),
    sampling_month = lubridate::month(sampling_date),
    sampling_day = lubridate::day(sampling_date),
    incubation_environment = NA_character_,
    site_name = origin_site_name,
    sampling_longitude = origin_sampling_longitude,
    sampling_latitude = origin_sampling_latitude,
    sample_depth_upper = origin_sample_depth_upper,
    sample_depth_lower = origin_sample_depth_lower,
    plot_label = origin_plot_label,
    sample_treatment = "control",
    experimental_design =
      paste0(
        as.numeric(as.factor(sample_treatment)), "_",
        as.numeric(as.factor(origin_site_name)), "_",
        as.numeric(as.factor(site_name)), "_",
        as.numeric(as.factor(origin_plot_label)), "_",
        as.numeric(as.factor(plot_label))
      )
  )


# add missing ids
samples2 <- 
  dplyr::bind_rows(
    samples2 %>%
      dplyr::mutate(
        type = "samples2"
      ), 
    samples3 %>%
      dplyr::mutate(
        type = "samples3"
      )
  )

samples2 <- 
  samples2 %>%
  dplyr::mutate(
    id_sample = seq_len(nrow(.)) + max(samples1$id_sample),
    id_sample_origin = 
      dplyr::left_join(
        samples2 %>% 
          dplyr::select(origin_site_name, origin_plot_label, taxon_rank_value) %>%
          dplyr::rename(
            site_name = "origin_site_name",
            plot_label = "origin_plot_label"
          ),
        samples1 %>% dplyr::select(site_name, plot_label, taxon_rank_value, id_sample),
        by = c("site_name", "plot_label", "taxon_rank_value")
      ) %>%
      dplyr::pull(id_sample),
    id_sample_incubation_start = 
      purrr::map_int(seq_len(nrow(.)), function(i) {
        index <- paste0(taxon_rank_value, "_", site_name, "_", taxon_organ) == paste0(taxon_rank_value, "_", site_name, "_", taxon_organ)[[i]] & experimental_design == experimental_design[[i]] & incubation_duration == 0.0
        id_sample[index]
      }),
    id_sample_parent = 
      purrr::map_int(seq_len(nrow(.)), function(i) {
        index <- paste0(taxon_rank_value, "_", site_name, "_", taxon_organ) == paste0(taxon_rank_value, "_", site_name, "_", taxon_organ)[[i]] & experimental_design == experimental_design[[i]] & incubation_duration < incubation_duration[[i]]
        if(! any(index)) {
          id_sample_origin[[i]]
        } else {
          target_incubation_duration <- max(incubation_duration[index])
          index <- index & incubation_duration == target_incubation_duration
          id_sample[index]
        }
      })
  )


## water table depth
samples4 <- 
  read.csv(paste0(dir_source, "/raw/bengtsson_etal_2016_traits.csv")) %>%
  dplyr::select(-c(5:7, 11:22, 24:ncol(.))) %>%
  dplyr::rename(
    sample_label = "sample",
    site_name = "site",
    sampling_latitude = "latitude",
    sampling_longitude = "longitude",
    site_type = "vegetation.type",
    sample_microhabitat = "microtopographical.position",
    water_table_depth = "HWT2012"
  ) %>%
  dplyr::mutate(
    incubation_duration = 0.0,
    id_dataset = datasets$id_dataset[[1]],
    id_sample = seq_len(nrow(.)) + max(samples2$id_sample),
    id_sample_origin = id_sample,
    id_sample_parent = id_sample,
    id_sample_incubation_start = NA_integer_,
    is_incubated = FALSE,
    incubation_environment = NA_character_,
    water_table_depth = 
      water_table_depth %>%
      units::set_units("mm") %>%
      units::set_units("cm") %>%
      as.numeric(),
    plot_label = sample_label,
    sample_type = "peat",
    sample_depth_upper = 0,
    sample_depth_lower = 0,
    sampling_year = 2012,
    sampling_month = 6,
    sampling_day = NA_integer_,
    shade = 
      dplyr::case_when(
        shade == "1open" ~ "open",
        shade == "2semi" ~ "semi-open",
        shade == "3dark" ~ "shaded"
      ),
    dplyr::across(dplyr::any_of(c("site_type", "sample_microhabitat")), tolower),
    comments_samples = "Coordinates are only the approximate location of the study site, but not sampling points. Each sample corresponds to one separate patch (plot, identified by `plot_label`) on the peatlands from which samples were taken.",
    sample_treatment = "control",
    origin_site_name = site_name,
    origin_plot_label = plot_label,
    experimental_design =
      paste0(
        as.numeric(as.factor(sample_treatment)), "_",
        as.numeric(as.factor(origin_site_name)), "_",
        as.numeric(as.factor(site_name)), "_",
        as.numeric(as.factor(origin_plot_label)), "_",
        as.numeric(as.factor(plot_label))
      )
  )


## combine
samples <- 
  dplyr::bind_rows(
    db_template_tables$samples,
    samples1 %>%
      dplyr::mutate(
        type = "samples1"
      ),
    samples2,
    samples4 %>%
      dplyr::mutate(
        type = "samples4"
      )
  )

2.4 samples_to_samples

samples_to_samples <- 
  samples %>%
  dplyr::filter(! id_sample %in% id_sample_origin) %>%
  dplyr::mutate(
    transition_description =
      dplyr::case_when(
        type %in% c("samples2") ~ "translocate",
        type %in% c("samples3") ~ "wait",
        TRUE ~ NA_character_
      )
  ) %>%
  dplyr::select(id_sample_parent, id_sample, transition_description) %>%
  dplyr::rename(
    id_sample_child = "id_sample"
  )

2.5 data

d2 <- 
  samples2 %>%
  tidyr::pivot_longer(
    cols = dplyr::any_of(c("mass_absolute", "mass_relative_mass", "mesh_size_absolute", paste0(PeriodicTable:::periodicTable$symb, "_relative_mass"), paste0(PeriodicTable:::periodicTable$symb, "_absolute"))),
    names_to = "attribute_name",
    values_to = "value"
  ) %>%
  dplyr::mutate(
    id_measurement = seq_len(nrow(.)) + id_last$id_measurement,
    id_measurement_numerator =
      purrr::map_int(seq_len(nrow(.)), function(i) {
        if(attribute_name[[i]] == "mass_relative_mass") {
          id_measurement[id_sample == id_sample[[i]] & attribute_name == "mass_absolute"]
        } else if (stringr::str_detect(attribute_name[[i]], pattern = "_relative_mass$")) {
          id_measurement[id_sample == id_sample[[i]] & attribute_name == stringr::str_replace(attribute_name[[i]], "_relative_mass2?", "_absolute")]
        } else {
          NA_integer_
        }
      }),
    id_measurement_denominator =
      purrr::map_int(seq_len(nrow(.)), function(i) {
        if(attribute_name[[i]] == "mass_relative_mass") {
          id_measurement[id_sample == id_sample_incubation_start[[i]] & attribute_name == "mass_absolute"]
        } else if (stringr::str_detect(attribute_name[[i]], pattern = "_relative_mass$")) {
          id_measurement[id_sample == id_sample[[i]] & attribute_name == "mass_absolute"]
        } else {
          NA_integer_
        }
      }),
    value_type = "point",
    sample_size = 1L
  )


 d4 <- 
  samples4 %>%
  tidyr::pivot_longer(
    cols = dplyr::any_of(c("water_table_depth")),
    names_to = "attribute_name",
    values_to = "value"
  ) %>%
  dplyr::mutate(
    id_measurement = seq_len(nrow(.)) + max(d2$id_measurement),
    id_measurement_numerator =
      purrr::map_int(seq_len(nrow(.)), function(i) {
        if(attribute_name[[i]] == "mass_relative_mass") {
          id_measurement[id_sample == id_sample[[i]] & attribute_name == "mass_absolute"]
        } else if (stringr::str_detect(attribute_name[[i]], pattern = "_relative_mass$")) {
          id_measurement[id_sample == id_sample[[i]] & attribute_name == stringr::str_replace(attribute_name[[i]], "_relative_mass2?", "_absolute")]
        } else {
          NA_integer_
        }
      }),
    id_measurement_denominator =
      purrr::map_int(seq_len(nrow(.)), function(i) {
        if(attribute_name[[i]] == "mass_relative_mass") {
          id_measurement[id_sample == id_sample_incubation_start[[i]] & attribute_name == "mass_absolute"]
        } else if (stringr::str_detect(attribute_name[[i]], pattern = "_relative_mass$")) {
          id_measurement[id_sample == id_sample[[i]] & attribute_name == "mass_absolute"]
        } else {
          NA_integer_
        }
      }),
    value_type = "mean",
    sample_size = NA_integer_
  )


# combine
d <- 
  dplyr::bind_rows(
    db_template_tables$data,
    d2,
    d4
  ) %>%
  dplyr::select(dplyr::all_of(colnames(db_template_tables$data)))

2.6 experimental_design_format

experimental_design_format <- 
  tibble::tibble(
    id_dataset = datasets$id_dataset,
    file = paste0(id_last$id_dataset + 1L, "/experimental_design_format.csv"),
    experimental_design_description = "`sample_treatment`: Character value. One of: `laboratory incubation`: Incubated in containers in a laboratory with a nutrient solution (see @Bengtsson.2016). `control`: Incubated in the plots where the samples were harvested. `origin_site_name`: Character value: Site where the samples grew. `site_name`: Character value. Site where the sample was collected (for samples which were not incubated, this is the same as `origin_site_name`). `origin_plot_label`: Character value. Plot label where the samples grew. `plot_label`: Character value. Plot where the sample was collected (for samples which were not incubated, this is the same as `origin_plot_label`). `site_type`: Character type describing the peatland type. `shade`: Character value describing how much the floow is shaded by trees/shrubs."
  )

# csv file to export
experimental_design_format2 <- 
  samples %>%
  dplyr::filter(! is.na(experimental_design)) %>%
  dplyr::filter(! duplicated(experimental_design)) %>%
  dplyr::select(experimental_design, sample_treatment, origin_site_name, site_name, plot_label, origin_plot_label, site_type, shade)

# export
write.csv(experimental_design_format2, paste0(dir_target, "/experimental_design_format.csv"), row.names = FALSE)

3 Export to database

# list all tables
dm_insert_in <-
  list(
    datasets = 
      datasets %>% 
      dplyr::select(dplyr::all_of(colnames(dm_dpeatdecomposition$datasets))),
    samples = 
      samples %>% 
      dplyr::select(dplyr::all_of(colnames(dm_dpeatdecomposition$samples))),
    data = 
      d %>% 
      dplyr::select(dplyr::all_of(colnames(dm_dpeatdecomposition$data))),
    samples_to_samples = 
      samples_to_samples %>% 
      dplyr::select(dplyr::all_of(colnames(dm_dpeatdecomposition$samples_to_samples))),
    citations_to_datasets = 
      citations_to_datasets %>% 
      dplyr::select(dplyr::all_of(colnames(dm_dpeatdecomposition$citations_to_datasets))),
    experimental_design_format = 
      experimental_design_format %>% 
      dplyr::select(dplyr::all_of(colnames(dm_dpeatdecomposition$experimental_design_format)))
  )

# check whether all column names as present in table attributes
all_column_names <- 
  purrr::map(dm_insert_in, colnames) %>%
  unlist() %>%
  unique()

if(! all(all_column_names %in% (dm_dpeatdecomposition %>% dm::pull_tbl(attributes) %>% dplyr::pull(attribute_name)))) {
  cond <- purrr::map_lgl(all_column_names, function(.x) ! .x %in% (dm_dpeatdecomposition %>% dm::pull_tbl(attributes) %>% dplyr::pull(attribute_name)))
  RMariaDB::dbDisconnect(con)
  stop(paste0("New `attribute_name`s discovered: ", paste(all_column_names[cond], collapse = ", ")))
}

all_data_attributes <- unique(dm_insert_in$data$attribute_name)

if(! all(all_data_attributes %in% (dm_dpeatdecomposition %>% dm::pull_tbl(attributes) %>% dplyr::pull(attribute_name)))) {
  cond <- purrr::map_lgl(all_data_attributes, function(.x) ! .x %in% (dm_dpeatdecomposition %>% dm::pull_tbl(attributes) %>% dplyr::pull(attribute_name)))
  stop(paste0("New `attribute_name`s discovered: ", paste(all_data_attributes[cond], collapse = ", ")))
  RMariaDB::dbDisconnect(con)
}


# filter empty tables
dm_insert_in_check <-
  dm_insert_in[purrr::map_lgl(dm_insert_in, function(x) nrow(x) > 0)] %>%
  dm::as_dm() %>%
  dp_dm_add_keys(dm_dpeatdecomposition)

# copy into dm_pmird
for(i in seq_along(dm_insert_in)) {
  RMariaDB::dbAppendTable(con, name = names(dm_insert_in)[[i]], value = dm_insert_in[[i]])
}

RMariaDB::dbDisconnect(con)

4 Notes