R/read_reorder_tree.R

Defines functions reorder_tree

# new concept: 
channels=list(
  "1"= c("Imon-1", "Vmon-1"), 
  "2"= c("Imon-2", "Vmon-2"), 
  "3"= c("Imon-3", "Vmon-3"), 
  "4"= c("Imon-4", "Vmon-4") 
)

#' Reorder Patchserver / Patchliner trees
#' 
#' Reorder branches so that each trace that belongs to a user defined "channel" is isolated in a new
#' experiment-branch. This is useful for Patserver and Patchliner experiments.
#' 
#'
#' @param tree        tree to reorder
#' @param channels   list of channels to create 
#'
#' @return The reordered tree
#' @export
#'
#' @examples
#' tree<-reorder_tree(get_treeinfo(examplefile("NaV")), 1:8)
#' tree<-reorder_tree(get_treeinfo(examplefile("NaV")), list(
#' "1"= c("Imon-1", "Vmon-1"), 
#' "2"= c("Imon-2", "Vmon-2"), 
#' "3"= c("Imon-3", "Vmon-3"), 
#' "4"= c("Imon-4", "Vmon-4") 
#' ))
#' #showtree(tree)
reorder_tree <- function(tree, channels) {
  # if channels is in the 
  if(!is.list(channels) & is.numeric(channels)){
    channels_<-lapply(channels, function(ch){paste0("Imon-", ch)})
  names(channels_)<-channels
  channels<-channels_
  }
  
  lapply(names(tree), function(file) {
    lapply(names(tree[[file]]), function(exp) {
      lapply(names(channels), function(channelName) {
        # make branchname for branch containing only the current trace
        expname = paste(exp, channelName, sep = "#")
        # copy original branch to new branch
        tree[[c(file, expname)]] <<- tree[[c(file, exp)]]
        lapply(names(tree[[c(file, expname)]]), function(ser) {
          lapply(names(tree[[c(file, expname, ser)]]), function(sw) {
            
            tracenames<-names(tree[[c(file, expname, ser, sw)]])
            traces_to_delete <-! tracenames %in% channels[[channelName]]
            # remove all but current trace
            tree[[c(file, expname, ser, sw)]][traces_to_delete] <<- NULL
            # remove empty sweeps
            if (length(tree[[c(file, expname, ser, sw)]]) == 0)
              tree[[c(file, expname, ser, sw)]] <<- NULL
          })
          # remove empty series
          if (length(tree[[c(file, expname, ser)]]) == 0) {
            tree[[c(file, expname, ser)]] <<- NULL
          }
        })
        # remove empty experiements
        if (length(tree[[c(file, expname)]]) == 0)
          tree[[c(file, expname)]] <<- NULL
      })
      # remove original experiment branch
      tree[[c(file, exp)]] <<- NULL
      # remove empty files
      if (length(tree[[c(file)]]) == 0)
        tree[[c(file)]] <<- NULL
    })
  })
  tree
}
tdanker/ephys2 documentation built on Aug. 11, 2019, 12:12 p.m.