reading_funs.R 2.62 KB

#' @export
SWITCHING_FREQUENCY <- 10e3

#' @export
SWITCHING_PERIOD <- 1/10e3

get_times <- function(start_from_period, how_many_periods) {
  fc <- 10e3
  pc <- 1/fc
  start_time <- start_from_period * pc
  end_time <- start_time + how_many_periods * pc
  return(list(start_time = start_time, end_time = end_time))
}

#' Read data with interference
#'
#' Reads data from the experiment.
#'
#' @param which number (should be from 0 to 16) which measurement to take
#' @param start_from_period
#' @param how_many_periods
#' @param add_no_interference
#'
#' @return
#' @export
#'
#' @importFrom dplyr filter mutate bind_rows between
#' @importFrom feather read_feather
#' @importFrom tibble tibble
#' @importFrom purrr map_chr
#' @importFrom stringr str_interp
#'
#'
#' @examples
#'
#' T1 <- read_interference("/Users/karolniewiadomski/Documents/SCENT/Simulations/ExperimentsUZ/ErrorModelsDataClean/",
#'  which = c(2, 13), start_from_period=3, how_many_periods=1, add_no_interference=TRUE)
#' head(T1)
#'
read_interference <- function(
  data_path, which = 0, start_from_period = 2, how_many_periods = 2, add_no_interference = FALSE) {
  times <- get_times(start_from_period, how_many_periods)

  if(min(which) < 0 || max(which) > 16) stop("Which between 0 and 16.")
  filenames <- map_chr(which, function(x)
    file.path(data_path, str_interp("data_$[.5d]{x}.feather") ))

  TD <- tibble()
  i <- 1
  for(.filename in filenames) {
    T1 <- read_feather(.filename)
    T1 <- filter(T1, between(time, times$start_time, times$end_time))
    T1 <- mutate(T1, measurement_no = which[i])
    TD <- bind_rows(TD, T1)
    i <- i + 1
  }

  # No interference is declared as measurement_no -1.
  if(add_no_interference) {
    T2 <- read_no_interference(data_path, start_from_period, how_many_periods)
    TD <- bind_rows(TD, T2)
  }

  return(TD)

}



#' Read data with no interference
#'
#' Reads data from measurements, without interference.
#'
#' @param start_from_period from which
#' @param how_many_periods
#'
#' @return
#' @export
#'
#' @importFrom feather read_feather
#' @importFrom dplyr filter mutate between
#'
#' @examples
#'
#' T1 <- read_no_interference("/Users/karolniewiadomski/Documents/SCENT/Simulations/ExperimentsUZ/ErrorModelsDataClean/", 2, 2)
#' head(T1)
#'
read_no_interference <- function(
  data_path, start_from_period = 2, how_many_periods = 2) {

  times <- get_times(start_from_period, how_many_periods)
  filename <- file.path(data_path, "data_no.feather")
  TD <- read_feather(filename)
  TD <- filter(TD, between(time, times$start_time, times$end_time))
  TD <- mutate(TD, measurement_no = -1) # To be consistent measurement_no is -1.
  return(TD)
}