R/plot_ggsweeps.R

Defines functions ggsweeps tidytraces tidy_cursorresults downsample

#' ggsweeps
#'
#' @param s 
#' @param sweeps 
#' @param max.points 
#'
#' @return
#' @export
#'
#' @examples
ggsweeps <-function(s, sweeps=c("all", "labeled", "last_lp" ), max.points=50000, color=c("none", "swp", "concentration"), title=F){
  
  
  if(is.character(sweeps))
    sweeps=match.arg(sweeps)
  
  color=match.arg(color)
  
  if(is.character(sweeps) && sweeps=="last_lp"){
   sweeps<- s$results() %>% group_by(Concentration) %>% filter(swp==max(swp)) %$% swp
  }
  
  if(is.numeric(sweeps)){
    s %>% tidytraces %>% filter(swpnr %in% sweeps) %>% downsample(max.points) %>%
      ggplot(aes(x=seconds, y=current)) ->p
   
    if(color=="none")
      p <- p + geom_line( aes(group=swp) )
    
    if(color=="swp")
      p <- p + geom_line( aes(color=swp) )
    
    if(color=="concentration")
      p <- p + geom_line( aes(group=swp, color=Concentration) )
  }
  
  if(is.character(sweeps) && sweeps=="all"){
    s %>% tidytraces %>%  downsample(max.points) %>%
      ggplot(aes(x=seconds, y=current)) ->p
    p <- p + geom_line( aes(group=swp) ) 
  }
  
  if(is.character(sweeps) && sweeps=="labeled"){
    s %>% tidytraces %>% filter( swplabel!="") %>% downsample(max.points) %>%
      ggplot(aes(x=seconds, y=current)) ->p
    p <- p + geom_line( aes(group=swp, color=paste(swpnr, swplabel) )) 
  }
  
  if(title){
    title_ <- paste( basename(s$sweeps$filename), s$sweeps$exp )
    p<-p+ggtitle(title_)
  }
    
    
  p
  
}

tidytraces <- function(s){
  Y<-  s$sweeps$y %>%                                  as_tibble() %>% tidyr::gather( swp, current )
  X<-  s$sweeps$x %>% set_names(names(s$sweeps$y)) %>% as_tibble() %>% tidyr::gather( swp, seconds )
  mutate(Y, 
         seconds=X$seconds, 
         swp=haven::as_factor(swp), 
         swpnr=as.numeric(swp), 
         swplabel=s$results()$swplabel[swp],
         Concentration=haven::as_factor(s$results()$Concentration[swp])
  ) 
  
}
#calculate tidy cursor results data (only min and max, not mean, cause mean has x1 and x2 instead of x (todo))
library(tidyr)
tidy_cursorresults<-function(s){
  s$results() %>% 
    select(-(1:14), -CompoundName, swp, swplabel ) %>% 
    group_by(swp, swplabel)%>% 
    tidyr::gather(,,-swp, -swplabel) %>% 
    tidyr::separate(key, c("cursor", "suffix")) %>% 
    tidyr::spread(suffix,value) %>% dplyr::rename(y='<NA>') %>% 
    filter(!is.na(x)) 
  
}


downsample<-function(traces, max.points){
  take_every_nth = ceiling( length(traces$current) / max.points )
  #if(take_every_nth > 1)
    #warning("auto-reducing number of samples!")
  traces %>% filter(row_number() %% take_every_nth ==0 )
}
tdanker/ephys2 documentation built on Aug. 11, 2019, 12:12 p.m.