R/paths.R

#' Generate segment list from direction list
#'
#' direction lists consists of vectors of "left" and "right".
#'
#' @param paths list of directions
#'
#' @return names list of segments
#' @export
#'
#' @examples
#' paths <- list(c("left", "left", "right", "right"),
#'               c("left", "left", "left", "right"),
#'               c("left", "left", "left", "left"))
#' directions_to_seqs(paths)
directions_to_seqs <- function(paths) {
  data <- unname(Reduce(rbind, paths))
  data_length <- ncol(data)
  result <- list()
  result$S <- list(i = 1,
                   seq = character(),
                   range = seq_len(nrow(data)))
  id <- "S"
  repeat {
    # step 0.5
    if (result[[id]]$i > data_length) {
      if (substr(id, nchar(id), nchar(id)) == "0") {
        id <- paste0(substr(id, 1, nchar(id) - 1), "1")
      } else { # == 1
        last_0 <- rev(gregexpr("0", id)[[1]])[1]

        id <- paste0(substr(id, 1, last_0 - 1), "1")
      }

      if (id == "1") break
    }

    # Step 1
    if (result[[id]]$i <= data_length) {

      if (all_same(data[result[[id]]$range, result[[id]]$i])) {
        result[[id]]$seq <- c(result[[id]]$seq, data[1, result[[id]]$i])
        result[[id]]$i <- result[[id]]$i + 1
      } else {
        result[[paste0(id, "0")]] <-
          list(i = result[[id]]$i + 1,
               seq = "left",
               range = intersect(result[[id]]$range,
                                 which(data[, result[[id]]$i] == "left")))
        result[[paste0(id, "1")]] <-
          list(i = result[[id]]$i + 1,
               seq = "right",
               range = intersect(result[[id]]$range,
                                 which(data[, result[[id]]$i] == "right")))
        id <- paste0(id, 0)
      }
    }
  }
  lapply(result, function(x) list(seq = x$seq,
                                  path = x$range))
}



#' convert a list of sequences to a lsit of paths
#'
#' @param paths a list created by directions_to_seqs()
#'
#' @return a list of paths
#' @export
#'
#' @examples
#' paths <- list(c("left", "left", "right", "right"),
#'               c("left", "left", "left", "right"),
#'               c("left", "left", "left", "left"))
#' seqs <- directions_to_seqs(paths)
#' seqs_to_paths(seqs)
seqs_to_paths <- function(paths) {
  ids <- which(lapply(paths, function(x) length(x$path)) == 1)
  out <- list()
  for (i in seq_len(length(ids))) {

    end <- names(ids[i])
    out[[paths[[end]]$path]] <- sapply(seq_len(nchar(end)),
                                       function(x) substr(end, 1, x))
  }
  out
}
EmilHvitfeldt/cell documentation built on May 5, 2019, 7:03 p.m.