knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

library("readxl")
library("tidyverse")
#library("cowplot")
#library("car")
#library("SchulzLabTools")

reload.data <-  FALSE
write.out.data <- TRUE

Note: This file should only be run with access to the Schulz lab shared drive.

Pull most up to date files into directory, wrangle, and merge ---------------

if (reload.data == TRUE){
  #Delete dirs/files in inst/extdata
  dirs.to.delete <- list.dirs(paste(getwd(),"inst","extdata", "",sep = "/"))
  dirs.to.delete <- dirs.to.delete[2:length(dirs.to.delete)] #Drop the root dir path
  unlink(dirs.to.delete, recursive = TRUE)

  if (Sys.info()[1] == "Darwin") {
    # on macos
    use.path <- "/Volumes/schulzlab/Data_Daniel/"
  } else if (Sys.info()[1] == c("Windows")) {
    # on windows
    use.path <- "S:/Data_Daniel/"
  } else {
    print(c("where should I look?"))
  }
  #Copy select files in legacy format:

  dir.create(file.path(paste(getwd(), "inst", "extdata", "phaseshift", "", sep="/")), showWarnings = TRUE)

  file.copy(paste0(use.path, "electrical_synapses_voltage_modification/experiments/180207_phase_shift_reorganized/data/current2.csv"),
            paste(getwd(), "inst", "extdata", "phaseshift", "", sep="/"))
  file.copy(paste0(use.path, "electrical_synapses_voltage_modification/experiments/180207_phase_shift_reorganized/data/iclamp2.csv"),
            paste(getwd(), "inst", "extdata", "phaseshift", "", sep="/"))
  file.copy(paste0(use.path, "electrical_synapses_voltage_modification/experiments/180207_phase_shift_reorganized/data/vclamp2.csv"),
            paste(getwd(), "inst", "extdata", "phaseshift", "", sep="/"))

  #Copy data in updated format:

  refresh_esynvmod_tabular_data(data.location = paste0(use.path,
  "electrical_synapses_voltage_modification/experiments/180308_Small_Phase_Angle/data/"),
                                sub.dir.name = "smallphaseshift")

  refresh_esynvmod_tabular_data(data.location = paste0(use.path, "electrical_synapses_voltage_modification/experiments/180117_inverted_wave/data/"),
                                sub.dir.name = "invwave")

  refresh_esynvmod_tabular_data(data.location = paste0(use.path, "electrical_synapses_voltage_modification/experiments/180205_TEA_wave_in_control/data/"),
                                sub.dir.name = "aberrantwave")

  refresh_esynvmod_tabular_data(data.location = paste0(use.path, "electrical_synapses_voltage_modification/experiments/180209_silent_time_control/data/"),
                                sub.dir.name = "ctrlsilent")

  refresh_esynvmod_tabular_data(data.location = paste0(use.path, "electrical_synapses_voltage_modification/experiments/180110_Blocker_washon_hold_to_ctrl/data/"),
                                sub.dir.name = "ctrltea")
}
#handle data with the old format (non data/metadata organized)
#i.e. 180207_phase_shift_reorganized
iclamp <- as.data.frame(read.csv(paste0(getwd(), "/inst/extdata/phaseshift/iclamp2.csv")))
vclamp <- as.data.frame(read.csv(paste0(getwd(), "/inst/extdata/phaseshift/vclamp2.csv")))
current <- as.data.frame(read.csv(paste0(getwd(), "/inst/extdata/phaseshift/current2.csv")))
#1.  transform iclamp into something that can be merged with tecc
iclamp <- iclamp[,c("experiment", "file", "trace", "trace_start",
                    "IN4_mean", "IN6_mean", "IN7_mean", "IN9_mean", "IN11_mean", "IN12_mean", 
                    "IN4_base", "IN6_base", "IN7_base", "IN9_base", "IN11_base", "IN12_base", 
                    "filepath", "time", "phase_offset", "IN4_id", "IN9_id")]

#alter file col so that it has just the suffix of the filename (tevc$Recording)
iclamp$file <- gsub(pattern = ".+_", replacement = "", iclamp$file)
iclamp$file <- gsub(pattern = "\\.abf", replacement = "", iclamp$file)

#rename everything in `phase_offset` so that it can be converted to `condition`
iclamp[iclamp$phase_offset == 0, "phase_offset"] <- "Phase Offset 0 Degrees"
iclamp[iclamp$phase_offset == 45, "phase_offset"] <- "Phase Offset 45 Degrees"
iclamp[iclamp$phase_offset == 90, "phase_offset"] <- "Phase Offset 90 Degrees"
iclamp[iclamp$phase_offset == 180, "phase_offset"] <- "Phase Offset 180 Degrees"

#rename cols to match tevc
iclamp <- iclamp %>% 
  rename(Experiment = experiment) %>% rename(Recording = file) %>% 
  rename(Trace = trace) %>% rename(`Trace Start` = trace_start) %>% 
  rename(IN4_baseline = IN4_base) %>% rename(IN6_baseline = IN6_base) %>% 
  rename(IN7_baseline = IN7_base) %>% 
  rename(IN9_baseline = IN9_base) %>% rename(IN11_baseline = IN11_base) %>% 
  rename(IN12_baseline = IN12_base) %>% 
  rename(path = filepath) %>% rename(`Time Exposed` = time) %>% 
  rename(Condition = phase_offset) %>% 
  rename(IN4 = IN4_id) %>% rename(IN9 = IN9_id)

#add a Treatment col
iclamp$Treatment <- "Phase Shift"
#ready to rbind into dataset

# 2. transform vclamp into something that can be merged with tevc
#rearrange to get cols close to target str
vclamp <- vclamp[,c("experiment",
                    "file",
                    "trace",
                    "trace_start",
                    "IN4_mean",
                    "IN7_mean",
                    "IN9_mean",
                    "IN12_mean",
                    "IN4_base",
                    "IN7_base",
                    "IN9_base",
                    "IN12_base",
                    "filepath",
                    "time",
                    "phase_offset",
                    "IN4_id",
                    "IN9_id",

                    "injection",
                    "notes",
                    "X")]
#drop cols not in tevc (we'll infer injected cell later)
vclamp <- vclamp[, -which(names(vclamp) %in% c("injection", "notes", "X"))] 

#alter file col so that it has just the suffix of the filename (tevc$Recording)
vclamp$file <- gsub(pattern = ".+_", replacement = "", vclamp$file)
vclamp$file <- gsub(pattern = "\\.abf", replacement = "", vclamp$file)
vclamp$file <- as.character(vclamp$file)

#rename everything in `phase_offset` so that it can be converted to `condition`
vclamp[vclamp$phase_offset == 0, "phase_offset"] <- "Phase Offset 0 Degrees"
vclamp[vclamp$phase_offset == 45, "phase_offset"] <- "Phase Offset 45 Degrees"
vclamp[vclamp$phase_offset == 90, "phase_offset"] <- "Phase Offset 90 Degrees"
vclamp[vclamp$phase_offset == 180, "phase_offset"] <- "Phase Offset 180 Degrees"

#rename cols to match tevc
vclamp <- vclamp %>% 
  rename(Experiment = experiment) %>% rename(Recording = file) %>% 
  rename(Trace = trace) %>% rename(`Trace Start` = trace_start) %>% 
  rename(IN4_baseline = IN4_base) %>% rename(IN7_baseline = IN7_base) %>% 
  rename(IN9_baseline = IN9_base) %>% rename(IN12_baseline = IN12_base) %>% 
  rename(path = filepath) %>% rename(`Time Exposed` = time) %>% 
  rename(Condition = phase_offset) %>% 
  rename(IN4 = IN4_id) %>% rename(IN9 = IN9_id)

#add a Treatment col
vclamp$Treatment <- "Phase Shift"
#ready to rbind into dataset

#3. split current into two df that can be merged with `a` and `htk`
phase.a <- current[,c("experiment",
                      "a.file", 
                      "IN4.a.peak_mV", "IN4.a.peak_nA", 
                      "IN9.a.peak_mV", "IN9.a.peak_nA",
                      "IN4.a.end_mV", "IN4.a.end_nA", 
                      "IN9.a.end_mV", "IN9.a.end_nA", 
                      "time", 
                      "phase_offset", 
                      "IN4_id", 
                      "IN9_id")]

phase.htk <- current[,c("experiment",
                        "htk.file", 
                        "IN4.htk.peak_mV", "IN4.htk.peak_nA", 
                        "IN9.htk.peak_mV", "IN9.htk.peak_nA",
                        "IN4.htk.end_mV",  "IN4.htk.end_nA", 
                        "IN9.htk.end_mV", "IN9.htk.end_nA", 
                        "IN4.rin_used", 
                        "IN9.rin_used", 
                        "time", 
                        "phase_offset", 
                        "IN4_id", 
                        "IN9_id")]
#rename everything in `phase_offset` so that it can be converted to `condition`
phase.a[phase.a$phase_offset == 0, "phase_offset"] <- "Phase Offset 0 Degrees"
phase.a[phase.a$phase_offset == 45, "phase_offset"] <- "Phase Offset 45 Degrees"
phase.a[phase.a$phase_offset == 90, "phase_offset"] <- "Phase Offset 90 Degrees"
phase.a[phase.a$phase_offset == 180, "phase_offset"] <- "Phase Offset 180 Degrees"

phase.htk[phase.htk$phase_offset == 0, "phase_offset"] <- "Phase Offset 0 Degrees"
phase.htk[phase.htk$phase_offset == 45, "phase_offset"] <- "Phase Offset 45 Degrees"
phase.htk[phase.htk$phase_offset == 90, "phase_offset"] <- "Phase Offset 90 Degrees"
phase.htk[phase.htk$phase_offset == 180, "phase_offset"] <- "Phase Offset 180 Degrees"

#rename cols to match a/htk
phase.a <- phase.a %>% 
  rename(Experiment = experiment) %>% rename(Recording = a.file) %>% 
  rename(IN4_mV_peak = IN4.a.peak_mV) %>% rename(IN7_nA_peak = IN4.a.peak_nA) %>% 
  rename(IN9_mV_peak = IN9.a.peak_mV) %>% rename(IN12_nA_peak = IN9.a.peak_nA) %>% 
  rename(IN4_mV_end = IN4.a.end_mV) %>% rename(IN7_nA_end = IN4.a.end_nA) %>% 
  rename(IN9_mV_end = IN9.a.end_mV) %>% rename(IN12_nA_end = IN9.a.end_nA) %>% 
  rename(`Time Exposed` = time) %>% 
  rename(Condition = phase_offset) %>% 
  rename(IN4 = IN4_id) %>% rename(IN9 = IN9_id)

phase.htk <- phase.htk %>% 
  rename(Experiment = experiment) %>% rename(Recording = htk.file) %>% 
  rename(IN4_mV_peak = IN4.htk.peak_mV) %>% rename(IN7_nA_peak = IN4.htk.peak_nA) %>% 
  rename(IN9_mV_peak = IN9.htk.peak_mV) %>% rename(IN12_nA_peak = IN9.htk.peak_nA) %>% 
  rename(IN4_mV_end = IN4.htk.end_mV) %>% rename(IN7_nA_end = IN4.htk.end_nA) %>% 
  rename(IN9_mV_end = IN9.htk.end_mV) %>% rename(IN12_nA_end = IN9.htk.end_nA) %>% 
  rename(IN4_rin = IN4.rin_used) %>% rename(IN9_rin = IN9.rin_used) %>% 
  rename(`Time Exposed` = time) %>% 
  rename(Condition = phase_offset) %>% 
  rename(IN4 = IN4_id) %>% rename(IN9 = IN9_id)

#ensure that Recording is char
phase.a$Recording <- as.character(phase.a$Recording)
phase.htk$Recording <- as.character(phase.htk$Recording)

#add a Treatment col
phase.a$Treatment <- "Phase Shift"
phase.htk$Treatment <- "Phase Shift"
#ready to rbind into datasets
print("Phase shift data is ready to rbind!")
inverted.wave <- condense_data_to_lists(use.path = paste0(getwd(),"/inst/extdata/"),
                               dir.name = "invwave",
                               treatment.name = "Inverted Wave")
ctrl.tea <- condense_data_to_lists(use.path = paste0(getwd(),"/inst/extdata/"),
                               dir.name = "ctrltea",
                               treatment.name = "Control Wave + TEA")
aberrant.wave <- condense_data_to_lists(use.path = paste0(getwd(),"/inst/extdata/"),
                               dir.name = "aberrantwave",
                               treatment.name = "Aberrant Wave")
ctrl.silent <- condense_data_to_lists(use.path = paste0(getwd(),"/inst/extdata/"),
                               dir.name = "ctrlsilent",
                               treatment.name = "Silent Control")
small.phase.angle <- condense_data_to_lists(use.path = paste0(getwd(),"/inst/extdata/"),
                               dir.name = "smallphaseshift",
                               treatment.name = "Small Phase Angle")
#3. combine into a single df based on data type (e.g. tevc_a)
tecc    <- rbind(iclamp, inverted.wave[[1]], ctrl.tea[[1]], aberrant.wave[[1]], ctrl.silent[[1]], small.phase.angle[[1]])
tevc    <- rbind(vclamp, inverted.wave[[2]], ctrl.tea[[2]], aberrant.wave[[2]], ctrl.silent[[2]], small.phase.angle[[2]])
a       <- rbind(phase.a, inverted.wave[[3]], ctrl.tea[[3]], aberrant.wave[[3]], ctrl.silent[[3]], small.phase.angle[[3]])
htk     <- rbind(phase.htk, inverted.wave[[4]], ctrl.tea[[4]], aberrant.wave[[4]], ctrl.silent[[4]], small.phase.angle[[4]])
htk.ls  <- rbind(inverted.wave[[5]], ctrl.tea[[5]], aberrant.wave[[5]], ctrl.silent[[5]], small.phase.angle[[5]])
if (TRUE == FALSE){
  possible.treatments <- c("Phase Shift","Inverted Wave","Control Wave + TEA","Aberrant Wave","Silent Control","Small Phase Angle")

  current.treatment <- possible.treatments[1]

  tecc <- tecc[tecc$Treatment == current.treatment,]
  tevc <- tevc[tevc$Treatment == current.treatment,]
  a <- a[a$Treatment == current.treatment,]
  htk <- htk[htk$Treatment == current.treatment,]
  htk.ls <- htk.ls[htk.ls$Treatment == current.treatment,]
}

Clean the data --------------------------------------------------------------

# Drop timepoints that were only collected in early experiments
tecc <- tecc[tecc$`Time Exposed` != 10 &
               tecc$`Time Exposed` != 30 &
               tecc$`Time Exposed` != 50, ]

tevc <- tevc[tevc$`Time Exposed` != 10 &
               tevc$`Time Exposed` != 30 &
               tevc$`Time Exposed` != 50, ]

a <- a[a$`Time Exposed` != 10 &
               a$`Time Exposed` != 30 &
               a$`Time Exposed` != 50, ]

htk <- htk[htk$`Time Exposed` != 10 &
               htk$`Time Exposed` != 30 &
               htk$`Time Exposed` != 50, ]

tecc <- tecc[!(tecc$Treatment == "Phase Shift" & tecc$`Time Exposed` > 90) &
       !(tecc$Treatment == "Small Phase Angle" & tecc$`Time Exposed` > 160) &
       !(tecc$Treatment == "Inverted Wave" & tecc$`Time Exposed` > 90) &
       !(tecc$Treatment == "Control Wave + TEA" & tecc$`Time Exposed` > 90) &
       !(tecc$Treatment == "Aberrant Wave" & tecc$`Time Exposed` > 90) &
       !(tecc$Treatment == "PhaseShift" & tecc$`Time Exposed` > 90) &
       !(tecc$Treatment == "Silent Control" & tecc$`Time Exposed` > 90),]

tevc <- tevc[!(tevc$Treatment == "Phase Shift" & tevc$`Time Exposed` > 90) &
       !(tevc$Treatment == "Small Phase Angle" & tevc$`Time Exposed` > 160) &
       !(tevc$Treatment == "Inverted Wave" & tevc$`Time Exposed` > 90) &
       !(tevc$Treatment == "Control Wave + TEA" & tevc$`Time Exposed` > 90) &
       !(tevc$Treatment == "Aberrant Wave" & tevc$`Time Exposed` > 90) &
       !(tevc$Treatment == "PhaseShift" & tevc$`Time Exposed` > 90) &
       !(tevc$Treatment == "Silent Control" & tevc$`Time Exposed` > 90),]

a <- a[!(a$Treatment == "Phase Shift" & a$`Time Exposed` > 90) &
       !(a$Treatment == "Small Phase Angle" & a$`Time Exposed` > 160) &
       !(a$Treatment == "Inverted Wave" & a$`Time Exposed` > 90) &
       !(a$Treatment == "Control Wave + TEA" & a$`Time Exposed` > 90) &
       !(a$Treatment == "Aberrant Wave" & a$`Time Exposed` > 90) &
       !(a$Treatment == "PhaseShift" & a$`Time Exposed` > 90) &
       !(a$Treatment == "Silent Control" & a$`Time Exposed` > 90),]

htk <- htk[!(htk$Treatment == "Phase Shift" & htk$`Time Exposed` > 90) &
       !(htk$Treatment == "Small Phase Angle" & htk$`Time Exposed` > 160) &
       !(htk$Treatment == "Inverted Wave" & htk$`Time Exposed` > 90) &
       !(htk$Treatment == "Control Wave + TEA" & htk$`Time Exposed` > 90) &
       !(htk$Treatment == "Aberrant Wave" & htk$`Time Exposed` > 90) &
       !(htk$Treatment == "PhaseShift" & htk$`Time Exposed` > 90) &
       !(htk$Treatment == "Silent Control" & htk$`Time Exposed` > 90),]

htk.ls <- htk.ls[!(htk.ls$Treatment == "Phase Shift" & htk.ls$`Time Exposed` > 90) &
       !(htk.ls$Treatment == "Small Phase Angle" & htk.ls$`Time Exposed` > 160) &
       !(htk.ls$Treatment == "Inverted Wave" & htk.ls$`Time Exposed` > 90) &
       !(htk.ls$Treatment == "Control Wave + TEA" & htk.ls$`Time Exposed` > 90) &
       !(htk.ls$Treatment == "Aberrant Wave" & htk.ls$`Time Exposed` > 90) &
       !(htk.ls$Treatment == "PhaseShift" & htk.ls$`Time Exposed` > 90) &
       !(htk.ls$Treatment == "Silent Control" & htk.ls$`Time Exposed` > 90),]

Prep two electrode current clamp data ======================================

tecc <- tecc[(tecc$IN4 == "LC4" | tecc$IN4 == "LC5") &
       (tecc$IN4 == "LC4" | tecc$IN4 == "LC5"),]
#Silent Control, Aberrant Wave, and Control Wave + TEA:
#IN7_mean and IN12_mean show POSITIVE values instead of negative. This is a problem in the xlsx which since I copied directly from clampfit means the error is coming from there.
#Inverted Wave
#IN7_mean and IN12_mean include values around POSITIVE and NEGATIVE 2. If something chaned in clampfit, it may have been over the course of working with these files.
#Phase Shift
#Only negative values. No problems here.

#to solve for the above, we'll take all injections with an absolute value above threshfold and set them as negative. Since this is current clamp anything positive should be dropped (from depricated protocols that stepped to positive voltages) or noise anyway

threshold.nA <- -0.9
#fix positive entries
tecc[abs(tecc$IN7_mean) > abs(threshold.nA), "IN7_mean"] <- 
  (abs(tecc[abs(tecc$IN7_mean) > abs(threshold.nA), "IN7_mean"]) * -1)

tecc[abs(tecc$IN12_mean) > abs(threshold.nA), "IN12_mean"] <- 
  (abs(tecc[abs(tecc$IN12_mean) > abs(threshold.nA), "IN12_mean"]) * -1)
#Looks like the same problem exists with IN4_mean and IN9_mean: postive and negative values. Setting everything to negative to fix this. 
tecc[, "IN4_mean"] <- (abs(tecc[, "IN4_mean"]) * -1)
tecc[, "IN9_mean"] <- (abs(tecc[, "IN9_mean"]) * -1)

#drop rows where neither electrode was injecting current
tecc <- tecc[tecc$IN7_mean < threshold.nA | tecc$IN12_mean < threshold.nA, ]
tecc$IN4 <- as.character(tecc$IN4)
tecc$IN9 <- as.character(tecc$IN9)

tecc[,"Inj_Cell"] <- "LC0"
tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "Inj_Cell"] <- as.character(tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN4"])
tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "Inj_Cell"] <- as.character(tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN9"])
tecc <- check_start_end(input.df = tecc, start.time = 0, end.time = 60)
Sys.sleep(10)
#Differs from take 3 in that this iterates over the time column instead of the recording col.
tick <- Sys.time()

aa <- find_median_deflections(input.df = tecc[tecc$Treatment == "Phase Shift",])
bb <- find_median_deflections(input.df = tecc[tecc$Treatment == "Inverted Wave",])
cc <- find_median_deflections(input.df = tecc[tecc$Treatment == "Control Wave + TEA",])
dd <- find_median_deflections(input.df = tecc[tecc$Treatment == "Aberrant Wave",])
ee <- find_median_deflections(input.df = tecc[tecc$Treatment == "Silent Control",])
ff <- find_median_deflections(input.df = tecc[tecc$Treatment == "Small Phase Angle",])

output.df <- full_join(aa, bb)
output.df <- full_join(output.df, cc)
output.df <- full_join(output.df, dd)
output.df <- full_join(output.df, ee)
output.df <- full_join(output.df, ff)

print(Sys.time()-tick)
#41 sec
tecc <- output.df

Calculate Resistances per Bennett 1966

Apparant Cell resistances: $$r_{11}=\frac{v_1}{i_1}$$

#when inj IN7...
tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "r11"] <- tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN4_mean"] / tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN7_mean"]

#when inj IN12...
tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "r11"] <- tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN9_mean"] / tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN12_mean"]

Transfer resistances: $$r_{12}=\frac{v_2}{i_1}$$

#when inj IN7...
tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "r12"] <- tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN9_mean"] / tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN7_mean"]

#when inj IN12...
tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "r12"] <- tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN4_mean"] / tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN12_mean"]

$$r_1= \frac{r_{11}r_{22} - r_{12}^2}{r_{22} - r_{12}}$$ $$r_c = \frac{r_{11}r_{22} - r_{12}^2}{r_{12}}$$

tic <- Sys.time()
tecc <- solve_for_resistances(input.df = tecc)
print(Sys.time() - tic)
tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "Coupling Coefficient"] <- 
  tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN9_mean"] /
  tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN4_mean"]

tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "Coupling Coefficient"] <- 
  tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN4_mean"] / 
  tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN9_mean"]


tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "Input Resistance"] <- 
  tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN4_mean"] / 
  tecc[abs(tecc$IN7_mean) > abs(tecc$IN12_mean), "IN7_mean"]

tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "Input Resistance"] <- 
  tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN9_mean"] / 
  tecc[abs(tecc$IN7_mean) < abs(tecc$IN12_mean), "IN12_mean"]
tecc$r11.0 <- 0
tecc$r12.0 <- 0
tecc$r1.0 <- 0
tecc$rc.0 <- 0
tecc$`Coupling Coefficient.0` <- 0
tecc$`Input Resistance.0` <- 0

tecc$interact <- interaction(tecc$Experiment, tecc$Inj_Cell)
tic <- Sys.time()
for(INTERACT in unique(tecc$interact)){
  #INTERACT =  "170623b.LC5"
  #INTERACT = "180110.LC4"
  #print(INTERACT)
  tecc[tecc$interact ==  INTERACT, c("r11.0", "r12.0", "r1.0", "rc.0", "Coupling Coefficient.0", "Input Resistance.0")] <- lapply(tecc[tecc$interact ==  INTERACT & tecc$`Time Exposed` == 0, c("r11", "r12", "r1", "rc", "Coupling Coefficient", "Input Resistance")], mean)
}
print(Sys.time() - tic)
tecc$Condition <- factor(tecc$Condition, c("Phase Offset 0 Degrees", "11.2_degrees", "22.5_degrees", "Phase Offset 45 Degrees" , "Phase Offset 90 Degrees" ,"Phase Offset 180 Degrees","Inverted Wave","TEA_ControlWave", "TEA_Silent","Aberrant Depol" ,"hold_at_-53mV"))

Prep two electrode voltage clamp data ======================================

tevc <- tevc[(tevc$IN4 == "LC4" | tevc$IN4 == "LC5") &
       (tevc$IN4 == "LC4" | tevc$IN4 == "LC5"),]
#Ensure channel cell ids are characters, not factors
tevc$IN4 <- as.character(tevc$IN4)
tevc$IN9 <- as.character(tevc$IN9)
tevc <- find_and_fix_switched_cols(input.df = tevc)
tic <- Sys.time()
outputs <- process_tevc(input.df = tevc)

#cowplot::ggsave("val.tevc.all.png", plot = cowplot::plot_grid(plotlist = outputs[[2]]), 
#                device = NULL, path = paste0(
#                  use.path, "180315_act_dept_report/figures/"), 
#                scale = 1, 
#                width = 12, 
#                height = 8.83,
#                dpi = 300, limitsize = TRUE)

tevc <- outputs[[1]]

print(Sys.time() - tic)
tevc <- check_start_end(input.df = tevc, start.time = 0, end.time = 60)
Sys.sleep(10)
tevc[tevc$Inj_Cell == "LC4", "Direction"] <- "LC4 -> LC5"
tevc[tevc$Inj_Cell == "LC5", "Direction"] <- "LC5 -> LC4"

tevc[, "interact"] <- interaction(tevc$Experiment, tevc$Direction)
#Experiment 170817b has a slope greater than 9. Dropping this experiment's data
tevc <- tevc[tevc$Experiment != "170817b",]
tevc <- tevc[!is.na(tevc),]

Prepare A type =============================================================

a <- a[(a$IN4 == "LC4" | a$IN4 == "LC5") &
       (a$IN4 == "LC4" | a$IN4 == "LC5"),]
#read in data
#drop entries that don't go the full lenght of the experiment

a.peak <- sep_peak_end(input.df = a, current.type = "a")[[1]] %>% 
  simplify_df() %>% 
  stack_channels()

a.peak$Inj_Cell <- a.peak$Cell #needed for check_start_end
a.peak <- check_start_end(input.df = a.peak, start.time = 0, end.time = 60)
Sys.sleep(10)
a.peak <- a.peak[, !(names(a.peak) %in% c("Inj_Cell"))]

a.end <- sep_peak_end(input.df = a, current.type = "a")[[2]] %>%
  simplify_df() %>% 
  stack_channels()

a.end$Inj_Cell <- a.end$Cell #needed for check_start_end
a.end <- check_start_end(input.df = a.end, start.time = 0, end.time = 60)
Sys.sleep(10)
a.end <- a.end[, !(names(a.end) %in% c("Inj_Cell"))]

a.peak$interact <- interaction(a.peak$Experiment, a.peak$Cell)
a.end$interact <- interaction(a.end$Experiment, a.end$Cell)

Prepare HTK ================================================================

htk <- htk[(htk$IN4 == "LC4" | htk$IN4 == "LC5") &
       (htk$IN4 == "LC4" | htk$IN4 == "LC5"),]
#htk <- check_start_end(input.df = htk, start.time = 0, end.time = 60)

htk.peak <- sep_peak_end(input.df = htk, current.type = "htk")[[1]] %>% 
  simplify_df() %>%
  stack_channels()

htk.peak$Inj_Cell <- htk.peak$Cell #needed for check_start_end
htk.peak <- check_start_end(input.df = htk.peak, start.time = 0, end.time = 60)
Sys.sleep(10)
htk.peak <- htk.peak[, !(names(htk.peak) %in% c("Inj_Cell"))]

htk.end <- sep_peak_end(input.df = htk, current.type = "htk")[[2]] %>%
  simplify_df() %>% 
  stack_channels()

htk.end$Inj_Cell <- htk.end$Cell #needed for check_start_end
htk.end <- check_start_end(input.df = htk.end, start.time = 0, end.time = 60)
Sys.sleep(10)
htk.end <- htk.end[, !(names(htk.end) %in% c("Inj_Cell"))]

htk.peak$interact <- interaction(htk.peak$Experiment, htk.peak$Cell)
htk.end$interact <- interaction(htk.end$Experiment, htk.end$Cell)

Prepare HTK LS =============================================================

htk.ls <- htk.ls[(htk.ls$IN4 == "LC4" | htk.ls$IN4 == "LC5") &
       (htk.ls$IN4 == "LC4" | htk.ls$IN4 == "LC5"),]
htk.ls.peak <- sep_peak_end(input.df = htk.ls, current.type = "htk.ls")[[1]] %>% simplify_df() %>% 
  stack_channels()

htk.ls.peak$Inj_Cell <- htk.ls.peak$Cell #needed for check_start_end
htk.ls.peak <- check_start_end(input.df = htk.ls.peak, start.time = 0, end.time = 60)
Sys.sleep(10)
htk.ls.peak <- htk.ls.peak[, !(names(htk.ls.peak) %in% c("Inj_Cell"))]

htk.ls.end <- sep_peak_end(input.df = htk.ls, current.type = "htk.ls")[[2]] %>%
  simplify_df() %>% 
  stack_channels()

htk.ls.end$Inj_Cell <- htk.ls.end$Cell #needed for check_start_end
htk.ls.end <- check_start_end(input.df = htk.ls.end, start.time = 0, end.time = 60)
Sys.sleep(10)
htk.ls.end <- htk.ls.end[, !(names(htk.ls.end) %in% c("Inj_Cell"))]

htk.ls.peak$interact <- interaction(htk.ls.peak$Experiment, htk.ls.peak$Cell)
htk.ls.end$interact <- interaction(htk.ls.end$Experiment, htk.ls.end$Cell)

Write out cleaned data ------------------------------------------------------

if (write.out.data == TRUE){
  files.to.replace <- paste0(getwd(),"/data/", 
                             c("tecc.rds", "tevc.rds", "a.peak.rds", "a.end.rds", "htk.peak.rds", "htk.end.rds", "htk.ls.peak.rds", "htk.ls.end.rds")
                             )
  file.remove(files.to.replace)

  saveRDS(tecc, file = paste0(getwd(),"/data/tecc.rds"))
  saveRDS(tevc, file = paste0(getwd(),"/data/tevc.rds"))

  saveRDS(a.peak, file = paste0(getwd(),"/data/a.peak.rds"))
    saveRDS(a.end, file = paste0(getwd(),"/data/a.end.rds"))
  saveRDS(htk.peak, file = paste0(getwd(),"/data/htk.peak.rds"))
  saveRDS(htk.end, file = paste0(getwd(),"/data/htk.end.rds"))
  saveRDS(htk.ls.peak, file = paste0(getwd(),"/data/htk.ls.peak.rds"))  
  saveRDS(htk.ls.end, file = paste0(getwd(),"/data/htk.ls.end.rds"))  
}


danielkick/esynvmod documentation built on May 17, 2019, 7:02 p.m.