OSCR

Sleep increases firing rate modulation during interictal epileptiform discharges in mesial temporal structures.

Code ↔ Paper

8 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 8 matches · 2 of them tie a paragraph to a whole file, not to given lines: weak matches, whose lines are not tinted
  1. [1] § Results › Increased IED rate with increased slow wave activity and delta power ↔ projects/hspike/analysis.R, lines 1279–1365 · score 0.76 · post hoc comparisons, delta power, 2.5–4 Hz, 0.1–2.5 Hz, IED rate, sleep stage
  2. [2] § Results › Increased IED rate with deeper stages of NREM sleep ↔ projects/hspike/analysis.R, lines 1279–1365 · score 0.72 · post hoc comparisons, delta power, slow wave activity, 2.5–4 Hz, 0.1–2.5 Hz, interictal epileptiform
  3. [3] § Results › Increased IED rate with deeper stages of NREM sleep ↔ projects/hspike/analysis_12122022.R, lines 1126–1168 · score 0.61 · delta power, slow wave activity, 2.5–4 Hz, 0.1–2.5 Hz, interictal epileptiform, mixed
  4. [4] § Methods and materials › Sliding window analyses ↔ trash/ft_spike_isi_edited.m, lines 1–42 · score 0.59 · Interspike intervals, spike train, windows, firing, 0.1 Hz
  5. [5] § Methods and materials › Spike sorting ↔ trash/pnh_seizures/mlib6/mcheck.m, lines 1–64 · score 0.56 · refractory period, violations, noise, signal, matching, ISI
  6. [6] § Methods and materials › Statistics ↔ projects/hspike/analysis.R, lines 953–1002 · score 0.54 · emmeans, post hoc, lmer, coefficients, Tukey, Models
  7. [7] § Methods and materials › Sliding window analyses ↔ shared/addSlidingWindows.m, the whole file · a weak match · score 0.51 · window overlapped, Sliding, FFT, segmentation, event, 0.5 Hz
  8. [8] § Methods and materials › Time-locked analyses ↔ trash/pnh_seizures/mlib6/mpsth.m, the whole file · a weak match · score 0.50 · peri stimulus, firing rate, PSTH, histogram, bin, width

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

R · 3,194 lines · 144 KB · GPL-3.0 · 3 matches

  1. install.packages("circular")
  2. install.packages("ggplot2")
  3. install.packages("units")
  4. install.packages("reshape2")
  5. install.packages("circlize")
  6. install.packages("ggthemes")
  7. install.packages("lemon")
  8. install.packages("egg")
  9. install.packages("readxl")
  10. install.packages('Rcpp')
  11. install.packages("equatiomatic")
  12. install.packages("kableExtra")
  13. install.packages("CircStats")
  14. install.packages("emmeans")
  15. install.packages("lmerTest")
  16. install.packages("devtools")
  17. install.packages("sjPlot")
  18. install.packages("ggpubr")
  19. install.packages("viridis")
  20. install.packages("latex2exp")
  21. #if(!require(devtools)) install.packages("devtools")
  22. #devtools::install_github("kassambara/ggpubr")
  23. #setTimeLimit(100000); setSessionTimeLimit(10000)
  24. #devtools::install_github("strengejacke/sjPlot")
  25. # ggpval
  26. # install.packages("spiralize")
  27. # library(spiralize)
  28. library(ggplot2)
  29. #library("cowplot")
  30. #library("gridExtra")
  31. library(plyr)
  32. library(reshape2)
  33. library(RColorBrewer)
  34. #library("ggthemes")
  35. #library(lemon)
  36. # library("sjPlot")
  37. library(emmeans)
  38. library(gridExtra)
  39. library(gtable)
  40. library(grid)
  41. library(egg)
  42. library(ggpubr)
  43. require(dplyr)
  44. library(xtable)
  45. library("readxl")
  46. library(Rcpp)
  47. library(equatiomatic)
  48. # library(CircStats)
  49. library(circular)
  50. library(kableExtra)
  51. library("sjPlot") # plot_model
  52. library(viridis)
  53. library(latex2exp)
  54. #####################
  55. ## Support function #
  56. #####################
  57. # replace subsequent fields with NAN for visualization purposes
  58. cleanf <- function(x){
  59. oldx <- c(FALSE, x[-1]==x[-length(x)]) # is the value equal to the previous?
  60. res <- x
  61. res[oldx] <- NA
  62. res}
  63. ###############################
  64. # Latex table: Clinical table #
  65. ###############################
  66. data_clinical <- read.csv("D:/Dropbox/Apps/Overleaf/Hspike/tables/clinical.csv")
  67. data_clinical$ID <- NULL
  68. data_clinical$Label <- NULL
  69. colnames(data_clinical) <- c("Patient","Sex","Age","Onset","Type","SOZ","MRI","PET","SPECT","Medication","Implantation","Pre-implantation surgery" )
  70. kbl(data_clinical, "latex", booktabs = T, label = "clinical",
  71. caption = "Clinical summary")%>%
  72. kable_styling(latex_options = c("scale_down"))%>%
  73. kable_styling(latex_options = c("HOLD_position"))%>%
  74. column_spec(1, width = "3em") %>%
  75. column_spec(2, width = "1em") %>%
  76. column_spec(3, width = "1em") %>%
  77. column_spec(4, width = "2em") %>%
  78. column_spec(5, width = "5em") %>%
  79. column_spec(6, width = "5em") %>%
  80. column_spec(7, width = "5em") %>%
  81. column_spec(8, width = "5em") %>%
  82. column_spec(9, width = "5em") %>%
  83. column_spec(10, width = "5em") %>%
  84. column_spec(11, width = "5em") %>%
  85. collapse_rows(columns = 1) %>%
  86. footnote(general_title = "",
  87. footnote_as_chunk = TRUE,
  88. threeparttable = TRUE,
  89. escape = FALSE,
  90. general = c("
  91. AED: Antiepileptic drugs,
  92. CBZ: Carbamazepine,
  93. ESL: Eslicarabazepine,
  94. FBTCS: Focal to Bilateral Tonic-Clonic Seizures,
  95. FIAS: Focal Impaired Awareness Seizure,
  96. FSWLA: Focal seizures without loss of awareness,
  97. IEDs: Interictal Epileptiform discharges,
  98. LCS: Lacosamide,
  99. LTG: Lamotrigine,
  100. MRI: Indications from Magnetic Resonance Imaging,
  101. OXC: Oxicarbazepine,
  102. PER: Perampanel,
  103. PMG: Polymicrogyria,
  104. PNH: Periventricular Nodular Heterotopia,
  105. SNH: Subcortical Nodular Heterotopia,
  106. SOZ: Seizure Onset Zone,
  107. TPM: Topiramate
  108. VPA: Valproic Acid,
  109. ZNG: Zonisamide."))%>%
  110. save_kable("D:/Dropbox/Apps/Overleaf/Hspike/tables/clinical.tex")
  111. ###############################################
  112. # Latex table: electrode anatomical locations #
  113. ###############################################
  114. options(knitr.kable.NA = '')
  115. macro <- read.csv("D:/Dropbox/Apps/Overleaf/Hspike/tables/macro_anatomical.csv", fileEncoding = 'UTF-8-BOM')
  116. macro$ID <- NULL
  117. macro$Label <- NULL
  118. # clean.cols <- c("Patient")
  119. # macro[clean.cols] <- lapply(macro[clean.cols], cleanf)
  120. micro <- read.csv("D:/Dropbox/Apps/Overleaf/Hspike/tables/micro_anatomical.csv", fileEncoding = 'UTF-8-BOM')
  121. micro$ID <- NULL
  122. micro$Label <- NULL
  123. # clean.cols <- c("Patient")
  124. # micro[clean.cols] <- lapply(micro[clean.cols], cleanf)
  125. locations <- bind_rows(macro,micro)
  126. kbl(locations, "latex", booktabs = T, linesep = "", label = 'anatomical',
  127. caption = "Anatomical locations of macro and micro electrodes")%>%
  128. kable_styling(latex_options = c("HOLD_position"))%>%
  129. pack_rows("Macro contacts", 1, 14) %>% # latex_gap_space = "2em"
  130. pack_rows("Micro electrodes", 15, 27) %>%
  131. row_spec(1, extra_latex_after = "\\cline{2-5}") %>%
  132. row_spec(3, extra_latex_after = "\\cline{2-5}") %>%
  133. row_spec(5, extra_latex_after = "\\cline{2-5}") %>%
  134. row_spec(7, extra_latex_after = "\\cline{2-5}") %>%
  135. row_spec(9, extra_latex_after = "\\cline{2-5}") %>%
  136. row_spec(11, extra_latex_after = "\\cline{2-5}") %>%
  137. row_spec(13, extra_latex_after = "\\cline{2-5}") %>%
  138. row_spec(15, extra_latex_after = "\\cline{2-5}") %>%
  139. row_spec(16, extra_latex_after = "\\cline{2-5}") %>%
  140. row_spec(18, extra_latex_after = "\\cline{2-5}") %>%
  141. row_spec(20, extra_latex_after = "\\cline{2-5}") %>%
  142. row_spec(21, extra_latex_after = "\\cline{2-5}") %>%
  143. row_spec(23, extra_latex_after = "\\cline{2-5}") %>%
  144. row_spec(24, extra_latex_after = "\\cline{2-5}") %>%
  145. row_spec(25, extra_latex_after = "\\cline{2-5}") %>%
  146. save_kable("D:/Dropbox/Apps/Overleaf/Hspike/tables/anatomical.tex")
  147. #########################
  148. # Detection performance #
  149. #########################
  150. options(knitr.kable.NA = '')
  151. data <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/performance.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  152. data$Patient[9] = "\\textit{Mean}"
  153. data$Patient[10] = "\\textit{Std.}"
  154. data[,2] = round(data[,2],digits=0)
  155. data[,3] = round(data[,3],digits=0)
  156. data[,4] = round(data[,4],digits=1)
  157. data[,5] = round(data[,5],digits=1)
  158. data[,6] = round(data[,6],digits=0)
  159. data[,7] = round(data[,7],digits=1)
  160. #data[,8] = round(data[,8],digits=1)
  161. #data[,9] = round(data[,9],digits=1)
  162. #data[,10] = round(data[,10],digits=0)
  163. #data[,11] = round(data[,11],digits=1)
  164. kbl(data, "latex", booktabs = T, linesep = "", label = 'performance', escape = FALSE,
  165. col.names = c("Patient","24 hrs.", "24 hrs.","Hit (\\%)","FA (\\%)", "Total", "Total hrs."),
  166. # col.names = c("Patient","24hrs", "24hrs","Hit (\\%)","FA (\\%)", "Total","24hrs","Hit (\\%)","FA (\\%)", "Total", "Total hrs."),
  167. caption = "Automatic IED detection performance")%>%
  168. kable_styling(latex_options = c("HOLD_position"))%>%
  169. # kable_styling(latex_options = c("scale_down"))%>%
  170. row_spec(8, hline_after = TRUE)%>%
  171. add_header_above(c(" " = 1, "Visual" = 1, "Automatic detection" = 4)) %>%
  172. # add_header_above(c(" " = 1, "Visual" = 1, "All templates" = 4, "Selected templates" = 4)) %>%
  173. save_kable("D:/Dropbox/Apps/Overleaf/Hspike/tables/performance.tex")
  174. ########################################
  175. # Latex table: Electrode locations MNI #
  176. ########################################
  177. options(knitr.kable.NA = '')
  178. data <- read.csv(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/data/hspike/MNI_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  179. data <- data[!data$color == 0, ] # only make table of used contacts
  180. data <- data[, c('patient','electrode','contact','X','Y','Z')]
  181. colnames(data) = c('Patient','Electrode','Contact', 'X', 'Y', 'Z')
  182. rownames(data) <- NULL
  183. clean.cols <- c("Patient","Electrode")
  184. data[clean.cols] <- lapply(data[clean.cols], cleanf)
  185. kbl(data, "latex", booktabs = T, linesep = "", label = 'MNI',
  186. caption = "Anatomical locations of micro electrodes") %>%
  187. kable_styling(font_size = 6) %>%
  188. kable_styling(latex_options = c("HOLD_position"))%>%
  189. row_spec(5, extra_latex_after = "\\cline{1-6}") %>%
  190. row_spec(10, extra_latex_after = "\\cline{2-6}") %>%
  191. row_spec(14, extra_latex_after = "\\cline{1-6}") %>%
  192. row_spec(19, extra_latex_after = "\\cline{1-6}") %>%
  193. row_spec(24, extra_latex_after = "\\cline{2-6}") %>%
  194. row_spec(29, extra_latex_after = "\\cline{1-6}") %>%
  195. row_spec(34, extra_latex_after = "\\cline{2-6}") %>%
  196. row_spec(39, extra_latex_after = "\\cline{1-6}") %>%
  197. row_spec(44, extra_latex_after = "\\cline{2-6}") %>%
  198. row_spec(49, extra_latex_after = "\\cline{1-6}") %>%
  199. row_spec(54, extra_latex_after = "\\cline{1-6}") %>%
  200. row_spec(59, extra_latex_after = "\\cline{2-6}") %>%
  201. save_kable("D:/Dropbox/Apps/Overleaf/Hspike/tables/MNI.tex")
  202. ###################################
  203. # Latex table: Time in sleepstage #
  204. ###################################
  205. options(knitr.kable.NA = '')
  206. # normalize by time spend in sleep stages
  207. data <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/hypnogram_duration.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  208. data <- data[, c("patient", "part", "TOTAL", "pPHASE_3", "pPHASE_2", "pPHASE_1", "pREM", "pWASO")]
  209. colnames(data) = c("Patient", "Night","Total (hrs.)", "S3", "S2", "S1", "REM", "WASO")
  210. data <- round(data, digits=1)
  211. df <- c("\\textit{Mean}", NA, round(mean(data$Total), digits = 1), round(mean(data$S3), digits = 1), round(mean(data$S2), digits = 1), round(mean(data$S1), digits = 1), round(mean(data$REM), digits = 1), round(mean(data$WASO), digits = 1))
  212. data <- rbind(data, df)
  213. # df <- c("\\textit{Std.}", NA, round(mean(data$Total), digits = 1), round(sd(data$S3), digits = 0), round(sd(data$S2), digits = 0), round(sd(data$S1), digits = 0), round(sd(data$REM), digits = 0), round(sd(data$WASO), digits = 0))
  214. # data <- rbind(data, df)
  215. clean.cols <- c("Patient")
  216. data[clean.cols] <- lapply(data[clean.cols], cleanf)
  217. library(dplyr)
  218. kbl(data, "latex", booktabs = T, linesep = "", label = 'stageduration', escape = FALSE,
  219. caption = "Time spend in sleep stages.", digits=2) %>%
  220. kable_styling(latex_options = c("HOLD_position"))%>%
  221. add_header_above(c(" " = 3, "Sleep stage (%)" = 5)) %>%
  222. row_spec(3, extra_latex_after = "\\cline{2-8}") %>%
  223. row_spec(6, extra_latex_after = "\\cline{2-8}") %>%
  224. row_spec(9, extra_latex_after = "\\cline{2-8}") %>%
  225. row_spec(12, extra_latex_after = "\\cline{2-8}") %>%
  226. row_spec(15, extra_latex_after = "\\cline{2-8}") %>%
  227. row_spec(18, extra_latex_after = "\\cline{2-8}") %>%
  228. row_spec(21, extra_latex_after = "\\cline{2-8}") %>%
  229. row_spec(24, hline_after = TRUE) %>%
  230. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/stageduration.tex")
  231. ####################################
  232. # Latex table: number of SUA / MUA #
  233. ####################################
  234. #
  235. # options(knitr.kable.NA = '')
  236. #
  237. # data_MUA <- read.csv(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/data/hspike/DataMUASUA.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  238. # data_MUA <- data_MUA[, c("PatientNr", "Part", "nrSUA", "nrMUA")]
  239. # colnames(data_MUA) = c("Patient", "Night","SUA", "MUA")
  240. # df <- c("\\textit{Sum}", NA, sum(data_MUA$SUA), sum(data_MUA$MUA))
  241. # data_MUA <- rbind(data_MUA, df)
  242. #
  243. # clean.cols <- c("Patient")
  244. # data_MUA[clean.cols] <- lapply(data_MUA[clean.cols], cleanf)
  245. #
  246. # kbl(data_MUA, "latex", booktabs = T, linesep = "", label = 'SUAMUA', escape = FALSE,
  247. # caption = "Number of putatively isolated single units (SUA) and number of multiunits (MUA)")%>%
  248. # kable_styling(latex_options = c("HOLD_position"))%>%
  249. # row_spec(3, extra_latex_after = "\\cline{2-4}") %>%
  250. # row_spec(6, extra_latex_after = "\\cline{2-4}") %>%
  251. # row_spec(9, extra_latex_after = "\\cline{2-4}") %>%
  252. # row_spec(12, extra_latex_after = "\\cline{2-4}") %>%
  253. # row_spec(15, extra_latex_after = "\\cline{2-4}") %>%
  254. # row_spec(18, extra_latex_after = "\\cline{2-4}") %>%
  255. # row_spec(21, extra_latex_after = "\\cline{2-4}") %>%
  256. # row_spec(24, hline_after = TRUE)%>%
  257. # save_kable("D:/Dropbox/Apps/Overleaf/Hspike/tables/SUAMUA.tex")
  258. #
  259. #### ADD RESPONSIVE UNITS #######
  260. library(tidyr)
  261. # prepare data
  262. data_psth <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/psth_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  263. data_psth$hyplabel <- factor(data_psth$hyplabel, levels = c("Pre", "Post", "REM", "Wake", "S1", "S2", "S3"))
  264. data_psth$Type <- factor(data_psth$SUA)
  265. data_sel <- setNames(aggregate(data_psth$responsive, by = c(list(data_psth$Patient, data_psth$part, data_psth$unit, data_psth$Type)), mean), c("Patient", "part", "unit", "Type", "responsive"))
  266. data_sel$responsive = as.integer(data_sel$responsive > 0)
  267. t = data_sel %>% count(Patient, part, responsive, Type)
  268. t2 <- pivot_wider(t, names_from = "Type", names_prefix = "SUA", values_from = "n")
  269. t3 <- pivot_wider(t2, names_from = "responsive", names_prefix = "responsive", values_from = c("SUA1", "SUA0"))
  270. t3[is.na(t3)] <- 0
  271. df <- c("\\textit{Sum}", NA, sum(t3$SUA1_responsive1), sum(t3$SUA1_responsive0), sum(t3$SUA0_responsive1), sum(t3$SUA0_responsive0))
  272. data_MUA <- rbind(t3, df)
  273. colnames(data_MUA) = c("Patient", "Night","Responsive", "Unresponsive", "Responsive", "Unresponsive")
  274. clean.cols <- c("Patient")
  275. data_MUA[clean.cols] <- lapply(data_MUA[clean.cols], cleanf)
  276. kbl(data_MUA, "latex", booktabs = T, linesep = "", label = 'SUAMUA', escape = FALSE,
  277. caption = "Number of responsive or unresponsive putatively isolated single units (SUA) and multiunits (MUA)")%>%
  278. kable_styling(latex_options = c("HOLD_position"))%>%
  279. add_header_above(c(" ", " ", "SUA" = 2, "MUA" = 2)) %>%
  280. row_spec(3, extra_latex_after = "\\cline{1-6}") %>%
  281. row_spec(6, extra_latex_after = "\\cline{1-6}") %>%
  282. row_spec(9, extra_latex_after = "\\cline{1-6}") %>%
  283. row_spec(12, extra_latex_after = "\\cline{1-6}") %>%
  284. row_spec(15, extra_latex_after = "\\cline{1-6}") %>%
  285. row_spec(18, extra_latex_after = "\\cline{1-6}") %>%
  286. row_spec(21, extra_latex_after = "\\cline{1-6}") %>%
  287. row_spec(24, hline_after = TRUE) %>%
  288. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/SUAMUA.tex")
  289. #######################
  290. # LFP power circadian #
  291. #######################
  292. # prepare data
  293. data_power <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/power_table_long.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  294. data_power$hyplabel <- factor(data_power$hyplabel, ordered = TRUE, levels = c("NO_SCORE", "REM", "AWAKE", "PHASE_1", "PHASE_2", "PHASE_3"))
  295. # data_power$band <- factor(data_power$band, ordered = TRUE, levels = c("delta", "theta", "alpha", "beta", "delta_div_alpha"))
  296. data_power$band <- factor(data_power$band, ordered = TRUE, levels = c("Delta1", "Delta2"))
  297. data_power$Patient <- factor(data_power$patient, levels = c(8:1))
  298. data_power$part <- factor(data_power$part)
  299. # for finding the median for plotting
  300. # data_power$bin <- as.integer(cut(data_power$minute, seq(0, 60*24, by = 1)))
  301. # data_binned_fine <- setNames(aggregate(data_power$power, c(list(data_power$Patient), list(data_power$bin), list(data_power$band)), mean), c("Patient", "bin", "band", "power"))
  302. # data_binned_fine <- as.data.frame(data_binned_fine %>% group_by(Patient, band) %>% mutate(Npower = (power-min(power))/max(power-min(power))))
  303. # ggplot(data=data_binned_fine[data_binned_fine$band == "Delta1" & data_binned_fine$Patient == 7, ], aes(x = bin, y = power, fill=Patient, col=Patient)) + geom_smooth()
  304. # bin for polar representation
  305. data_power$bin <- as.integer(cut(data_power$minute, seq(0, 24*60, by = 60)))
  306. # duplicate midnight to connect in figure
  307. temp <- subset(data_power, bin == 24)
  308. temp$bin <- 0
  309. data_power <- bind_rows(data_power, temp)
  310. data_binned <- setNames(aggregate(data_power$power, c(list(data_power$Patient), list(data_power$bin), list(data_power$band)), mean), c("Patient", "bin", "band", "power"))
  311. data_binned <- as.data.frame(data_binned %>% group_by(Patient, band) %>% mutate(Npower = (power-min(power))/max(power-min(power))))
  312. # data_binned$rad <- data_binned$bin / 24 * pi
  313. # c <- circular(control, units = "degrees", template = "geographics")
  314. # data_binned$rad
  315. # d <- density.circular(data_binned$bin[data_binned$patient == 1], bw = 50)
  316. ###
  317. # data_binned <- as.data.frame(data_binned %>% group_by(Patient, band) %>% mutate(Npower = (mean(power)-power)/sd(power)))
  318. ####
  319. # getCentroid <- function(x, width = 1) {
  320. # A <- x * width # area of each bar
  321. # xc <- seq(width/2, length(x), 1) # x coordinates of center of bars
  322. # yc <- x/2 # y coordinatey
  323. #
  324. # cx <- sum(xc * A) / sum(A)
  325. # cy <- sum(yc * A) / sum(A)
  326. # return(list(x = cx, y = cy))
  327. # }
  328. # points(getCentroid(x), col = 'red', pch = 19)
  329. ####
  330. # plot
  331. data_binned$title1 = "Slow waves (0.1-2.5 Hz)"
  332. data_binned$title2 = "Delta (2.5-4 Hz)"
  333. # data_binned$title2 = "Theta (5-7Hz)"
  334. # data_binned$title3 = "Alpha (8-14Hz)"
  335. # data_binned$title4 = "Delta (1-4Hz) / Alpha (8-14Hz)"
  336. polarpowerplots <- list()
  337. polarpowerplots[[1]] <-
  338. ggplot(data=data_binned[data_binned$band == "delta", ], aes(x = bin, y = Npower, fill=Patient, col=Patient)) +
  339. scale_fill_brewer(palette = "Set2", direction = -1) + scale_color_brewer(palette = "Set2", direction = -1) +
  340. geom_vline(xintercept = seq(0, 24, by = 3), colour = "grey90") +
  341. geom_hline(yintercept = seq(1, 8, by = 1), colour = "grey90") +
  342. geom_ribbon(aes(ymin = (9-as.numeric(Patient)), ymax=Npower*2+(9-as.numeric(Patient))), alpha=0.8, colour = NA) +
  343. theme_article() +
  344. theme(
  345. panel.border = element_blank(),
  346. legend.text = element_blank(),
  347. axis.ticks = element_blank(),
  348. axis.text.x = element_blank(),
  349. axis.text.y = element_blank(),
  350. axis.title.x = element_blank(),
  351. axis.title.y = element_blank()) +
  352. scale_x_continuous(breaks=seq(0, 21, by = 3),
  353. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  354. coord_polar(theta = "x", start = 0, clip="off") +
  355. ylim(-2, 10) +
  356. facet_wrap(~title1)
  357. polardelta1power <-
  358. ggplot(data=data_binned[data_binned$band == "Delta1", ], aes(x = bin, y = Npower, fill=Patient, col=Patient)) +
  359. scale_fill_brewer(palette = "Set2", direction = -1) + scale_color_brewer(palette = "Set2", direction = -1) +
  360. geom_vline(xintercept = seq(0, 24, by = 3), colour = "grey90") +
  361. geom_hline(yintercept = seq(1, 8, by = 1), colour = "grey90") +
  362. geom_ribbon(aes(ymin = (9-as.numeric(Patient)), ymax=Npower*1.5+(9-as.numeric(Patient))), alpha=1, colour = NA) +
  363. theme_article() +
  364. theme(
  365. panel.border = element_blank(),
  366. legend.text = element_blank(),
  367. axis.ticks = element_blank(),
  368. axis.text.x = element_blank(),
  369. axis.text.y = element_blank(),
  370. axis.title.x = element_blank(),
  371. axis.title.y = element_blank()) +
  372. scale_x_continuous(breaks=seq(0, 21, by = 3),
  373. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  374. coord_polar(theta = "x", start = 0, clip="off") +
  375. ylim(-2, 10)
  376. polardelta2power <-
  377. ggplot(data=data_binned[data_binned$band == "Delta2", ], aes(x = bin, y = Npower, fill=Patient, col=Patient)) +
  378. scale_fill_brewer(palette = "Set2", direction = -1) + scale_color_brewer(palette = "Set2", direction = -1) +
  379. geom_vline(xintercept = seq(0, 24, by = 3), colour = "grey90") +
  380. geom_hline(yintercept = seq(0, 8, by = 1), colour = "grey90") +
  381. geom_ribbon(aes(ymin = (9-as.numeric(Patient)), ymax=Npower*1.5+(9-as.numeric(Patient))), alpha=1, colour = NA) +
  382. theme_article() +
  383. theme(
  384. panel.border = element_blank(),
  385. legend.text = element_blank(),
  386. axis.ticks = element_blank(),
  387. axis.text.x = element_blank(),
  388. axis.text.y = element_blank(),
  389. axis.title.x = element_blank(),
  390. axis.title.y = element_blank()) +
  391. scale_x_continuous(breaks=seq(0, 21, by = 3),
  392. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  393. coord_polar(theta = "x", start = 0, clip="off") +
  394. ylim(-1, 10)
  395. polarpowerplots[[2]] <-
  396. ggplot(data=data_binned[data_binned$band == "theta", ], aes(x = bin, y = Npower, fill=Patient, col=Patient)) +
  397. scale_fill_brewer(palette = "Set2", direction = -1) + scale_color_brewer(palette = "Set2", direction = -1) +
  398. geom_vline(xintercept = seq(0, 24, by = 3), colour = "grey90") +
  399. geom_hline(yintercept = seq(0, 8, by = 1), colour = "grey90") +
  400. geom_ribbon(aes(ymin = (9-as.numeric(Patient)), ymax=Npower*2+(9-as.numeric(Patient))), alpha=0.8, colour = NA) +
  401. theme_article() +
  402. theme(
  403. panel.border = element_blank(),
  404. legend.text = element_blank(),
  405. axis.ticks = element_blank(),
  406. axis.text.x = element_blank(),
  407. axis.text.y = element_blank(),
  408. axis.title.x = element_blank(),
  409. axis.title.y = element_blank()) +
  410. scale_x_continuous(breaks=seq(0, 21, by = 3),
  411. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  412. coord_polar(theta = "x", start = 0, clip="off") +
  413. ylim(0, 10) +
  414. facet_wrap(~title2)
  415. polarpowerplots[[3]] <-
  416. ggplot(data=data_binned[data_binned$band == "alpha", ], aes(x = bin, y = Npower, fill=Patient, col=Patient)) +
  417. scale_fill_brewer(palette = "Set2", direction = -1) + scale_color_brewer(palette = "Set2", direction = -1) +
  418. geom_vline(xintercept = seq(0, 24, by = 3), colour = "grey90") +
  419. geom_hline(yintercept = seq(0, 8, by = 1), colour = "grey90") +
  420. geom_ribbon(aes(ymin = (9-as.numeric(Patient)), ymax=Npower*2+(9-as.numeric(Patient))), alpha=0.8, colour = NA) +
  421. theme_article() +
  422. theme(
  423. panel.border = element_blank(),
  424. legend.text = element_blank(),
  425. axis.ticks = element_blank(),
  426. axis.text.x = element_blank(),
  427. axis.text.y = element_blank(),
  428. axis.title.x = element_blank(),
  429. axis.title.y = element_blank()) +
  430. scale_x_continuous(breaks=seq(0, 21, by = 3),
  431. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  432. coord_polar(theta = "x", start = 0, clip="off") +
  433. ylim(0, 10) +
  434. facet_wrap(~title3)
  435. polarpowerplots[[4]] <-
  436. ggplot(data=data_binned[data_binned$band == "delta_div_alpha", ], aes(x = bin, y = Npower, fill=Patient, col=Patient)) +
  437. scale_fill_brewer(palette = "Set2", direction = -1) + scale_color_brewer(palette = "Set2", direction = -1) +
  438. geom_vline(xintercept = seq(0, 24, by = 3), colour = "grey90") +
  439. geom_hline(yintercept = seq(0, 8, by = 1), colour = "grey90") +
  440. geom_ribbon(aes(ymin = (9-as.numeric(Patient)), ymax=Npower*2+(9-as.numeric(Patient))), alpha=0.8, colour = NA) +
  441. theme_article() +
  442. theme(
  443. panel.border = element_blank(),
  444. legend.text = element_blank(),
  445. axis.ticks = element_blank(),
  446. axis.text.y = element_blank(),
  447. axis.text.x = element_blank(),
  448. axis.title.x = element_blank(),
  449. axis.title.y = element_blank()) +
  450. scale_x_continuous(breaks=seq(0, 21, by = 3),
  451. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  452. coord_polar(theta = "x", start = 0, clip="off") +
  453. ylim(0, 10) +
  454. facet_wrap(~title4)
  455. powerplots <- ggarrange(plotlist=polarpowerplots[c(1,2,3)], widths = c(1,1,1,1), heights = c(1,1,1,1), nrow = 1,
  456. labels = c("D","E","F"), vjust = 18, hjust = -1,
  457. legend = "right", common.legend = TRUE,
  458. font.label = list(size = 14, color = "black", face = "bold"))
  459. ggarrange(plotlist=polarpowerplots[c(1,2,3)], widths = c(1,1,1,1), heights = c(1,1,1,1), nrow = 1,
  460. labels = c("A","B","C"), vjust = 18, hjust = -1,
  461. legend = "right", common.legend = TRUE,
  462. font.label = list(size = 14, color = "black", face = "bold")) %>%
  463. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Hspike/images/polar_power_band.pdf")
  464. ######################
  465. # IED rate circadian #
  466. ######################
  467. data_IED <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/IED_table_PSG.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  468. data_IED[data_IED$hyplabel == "PRE_SLEEP", ] = "AWAKE"
  469. data_IED[data_IED$hyplabel == "POST_SLEEP", ] = "AWAKE"
  470. data_IED$hyplabel <- factor(data_IED$hyplabel, ordered = TRUE, levels = c("REM", "AWAKE", "PHASE_1", "PHASE_2", "PHASE_3"))
  471. data_IED$Patient <- factor(data_IED$patient, levels = c(8:1)) # same order in plot
  472. data_IED$part <- factor(data_IED$part)
  473. data_IED$marker <- factor(data_IED$marker)
  474. data_IED$hour <- data_IED$minute / (60)
  475. data_IED$rad <- data_IED$theta
  476. # extract distribution statistics
  477. dist_IED <- data.frame()
  478. d <- list()
  479. stat_IED <- list()
  480. for (ipatient in 1:8) {
  481. d <- density.circular(data_IED$rad[data_IED$patient == ipatient], bw = 100)
  482. temp = list()
  483. temp$x = as.numeric(d$x)
  484. temp$y = d$y
  485. le <- lengths(temp)
  486. temp$patient <- rep(ipatient,le[1])
  487. tempdf <- as.data.frame(temp)
  488. colnames(tempdf) = c('rad','density','Patient')
  489. dist_IED <- bind_rows(dist_IED, tempdf)
  490. temp = list()
  491. # Rayleigh Test of Uniformity: General Unimodal Alternative
  492. temp <- rayleigh.test(data_IED$rad[data_IED$patient == ipatient])
  493. stat_IED$Patient[ipatient] = ipatient
  494. stat_IED$p[ipatient] = temp$p.value
  495. stat_IED$Rayleigh_stat[ipatient] = temp$statistic
  496. # Rayleigh Test of Uniformity: General Unimodal Alternative
  497. stat_IED$median[ipatient] <- as.numeric(median(circular(data_IED$rad[data_IED$patient == ipatient]))) / (pi * 2) * 24
  498. if (stat_IED$median[ipatient] < 0) {
  499. stat_IED$median[ipatient] = stat_IED$median[ipatient] + 24
  500. }
  501. }
  502. # format data for plotting
  503. dist_IED$Khour = dist_IED$rad / (pi * 2) * 24
  504. dist_IED$Patient = factor(dist_IED$Patient, levels = c(8:1)) # reversed order in plot
  505. stat_IED <- as.data.frame(stat_IED)
  506. stat_IED$Patient <- factor(stat_IED$Patient, levels = c(8:1))
  507. # add some offset in degrees so it shows up from behind the rest
  508. stat_IED$medianplot <- stat_IED$median
  509. stat_IED$medianplot[1] = stat_IED$median[1] - 0.25
  510. stat_IED$medianplot[6] = stat_IED$median[6] + 0.2
  511. stat_IED$medianplot[stat_IED$p >= 0.05] = NA # all are significant though
  512. IEDpolarplot <-
  513. ggplot(data=data_IED, aes(x=hour, y = as.numeric(Patient), fill=Patient)) +
  514. geom_vline(xintercept = seq(0, 21, by = 3), colour = "grey90") +
  515. geom_hline(yintercept = seq(1, 8, by = 1), colour = "grey90") +
  516. geom_ribbon(data=dist_IED, alpha = 1, colour = NA, aes(x = Khour,
  517. ymin = (9-as.numeric(Patient)),
  518. ymax = density*3 + (9-as.numeric(Patient)),
  519. col = Patient), show.legend = TRUE) +
  520. geom_segment(data=stat_IED, aes(x=medianplot, y=9.5, xend=medianplot, yend=10, col=Patient),
  521. arrow = arrow(length = unit(0.25, "cm"), type="closed"), size = 0.5, show.legend = FALSE) +
  522. coord_polar(theta = "x", start = 0, direction = 1, clip = 'off') +
  523. scale_x_continuous(breaks = seq(0, 21, by = 3),
  524. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  525. scale_fill_brewer(palette = "Set2", direction=1) + scale_color_brewer(palette = "Set2", direction=1) +
  526. theme_article() +
  527. theme(panel.border = element_blank(),
  528. #legend.key = element_blank(),
  529. axis.ticks = element_blank(),
  530. axis.text.y = element_blank(),
  531. #axis.text.x = element_blank(),
  532. panel.grid = element_blank(),
  533. axis.title.x = element_blank(),
  534. #legend.text = element_blank(),
  535. axis.title.y = element_blank()) +
  536. ylim(-2, 10)
  537. # LaTeX table
  538. library(stringr)
  539. stat_IED$time = paste(str_pad( floor(stat_IED$median), 2, pad = "0"), ":", str_pad(floor((stat_IED$median- floor(stat_IED$median)) * 60), 2, pad = "0"), sep = "")
  540. stat_IED <- stat_IED[, c("Patient", "time", "Rayleigh_stat", "p")]
  541. stat_IED[,4] = ifelse(stat_IED[,4] > .05, paste(round(stat_IED[,4],digits=2),sep=""), ifelse(stat_IED[,4] < .0001, "<.0001\\textsuperscript{***}", ifelse(stat_IED[,4] < .001,"<.001\\textsuperscript{**}", ifelse(stat_IED[,4] < .01, "<.01\\textsuperscript{*}", "<.05"))))
  542. kbl(stat_IED, "latex", booktabs = T, linesep = "", label = 'circstat_IED',
  543. col.names = c("Patient","Median angle (HH:mm)","Rayleigh", "\\textit{p}"),
  544. escape = FALSE, digits = 2,
  545. caption = "Circular statistics of circadian IED rate") %>%
  546. footnote(general_title = "",
  547. footnote_as_chunk = TRUE,
  548. threeparttable = TRUE,
  549. escape = FALSE,
  550. general = c("$. = p<0.05$, $* = p<0.01$, $** = p<0.001$, $*** = p<0.0001$"))%>%
  551. kable_styling(latex_options = c("HOLD_position")) %>%
  552. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/circstat_IED.tex")
  553. ######################
  554. # Seizures circadian #
  555. ######################
  556. # load data: Patients x Units x time window
  557. data_seizures <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/seizuredata_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  558. # prepare data
  559. data_seizures$Patient <- factor(data_seizures$patient, levels = c(1:8))
  560. data_seizures$hour <- data_seizures$minute / 60
  561. data_seizures$rad <- data_seizures$minute / 60 / 24 * pi * 2
  562. # extract distribution statistics
  563. dist_seizures <- data.frame()
  564. d <- list()
  565. stat_seizures <- list()
  566. for (ipatient in 1:8) {
  567. d <- density.circular(data_seizures$rad[data_seizures$patient == ipatient], bw = 50)
  568. temp = list()
  569. temp$x = as.numeric(d$x)
  570. temp$y = d$y
  571. le <- lengths(temp)
  572. temp$patient <- rep(ipatient,le[1])
  573. tempdf <- as.data.frame(temp)
  574. colnames(tempdf) = c('rad','density','Patient')
  575. dist_seizures <- bind_rows(dist_seizures, tempdf)
  576. # Rayleigh Test of Uniformity: General Unimodal Alternative
  577. temp = list()
  578. temp <- rayleigh.test(data_seizures$rad[data_seizures$patient == ipatient])
  579. stat_seizures$Patient[ipatient] = ipatient
  580. stat_seizures$p[ipatient] = temp$p.value
  581. stat_seizures$Rayleigh_stat[ipatient] = temp$statistic
  582. # Rayleigh Test of Uniformity: General Unimodal Alternative
  583. stat_seizures$median[ipatient] <- as.numeric(median(circular(data_seizures$rad[data_seizures$patient == ipatient]))) / (pi * 2) * 24
  584. if (stat_seizures$median[ipatient] < 0) {
  585. stat_seizures$median[ipatient] = stat_seizures$median[ipatient] + 24
  586. }
  587. }
  588. # format data for plotting
  589. dist_seizures$Khour = dist_seizures$rad / (pi * 2) * 24
  590. dist_seizures$Patient = factor(dist_seizures$Patient, levels = c(8:1))
  591. stat_seizures <- as.data.frame(stat_seizures)
  592. stat_seizures$Patient = factor(stat_seizures$Patient, levels = c(8:1))
  593. stat_seizures$significant = stat_seizures$p < 0.05
  594. stat_seizures$median_sel = stat_seizures$median
  595. stat_seizures$median_sel[stat_seizures$p >= 0.05] = NA # all are significant though
  596. # tiny adjustment to make axes line out properly and arrows not overlap
  597. data_seizures$hourplot <- data_seizures$hour
  598. data_seizures$hourplot[which(data_seizures$hour==max(data_seizures$hour))] = 24
  599. # add jitter function for points
  600. jitter <- position_jitter(width = 0, height = 0.4)
  601. # plot
  602. Seizurepolarplot <-
  603. ggplot(data=data_seizures, aes(x=hourplot, y = as.numeric(Patient), fill=Patient)) +
  604. geom_vline(xintercept = seq(0, 21, by = 3), colour = "grey90") +
  605. geom_hline(yintercept = seq(1, 8, by = 1), colour = "grey90") +
  606. geom_ribbon(data=dist_seizures, alpha = 1, colour = NA, aes(x=Khour,
  607. ymin = (9-as.numeric(Patient)),
  608. ymax = density*1.3 + (9-as.numeric(Patient)),
  609. col = Patient), show.legend = FALSE) +
  610. geom_segment(data=stat_seizures, aes(x=median_sel, y=9.5, xend=median_sel, yend=10, col=Patient),
  611. arrow = arrow(length = unit(0.25, "cm"), type="closed"), size = 1, show.legend = FALSE) +
  612. geom_point(colour="black", pch=21, size=1, position = jitter) +
  613. coord_polar(theta = "x", start = 0, direction = 1, clip = 'off') +
  614. scale_x_continuous(breaks = seq(0, 21, by = 3),
  615. labels = c("0" = "00:00", "3" = "", "6" = "06:00", "9" = "", "12" = "12:00", "15" = "", "18" = "18:00", "21" = "")) +
  616. scale_fill_brewer(palette = "Set2", direction = 1) + scale_color_brewer(palette = "Set2", direction = 1) +
  617. theme_article() +
  618. theme(panel.border = element_blank(),
  619. #legend.key = element_blank(),
  620. axis.ticks = element_blank(),
  621. axis.text.y = element_blank(),
  622. axis.text.x = element_blank(),
  623. panel.grid = element_blank(),
  624. axis.title.x = element_blank(),
  625. #legend.text = element_blank(),
  626. axis.title.y = element_blank()) +
  627. ylim(-2, 10)
  628. # save combined to pdf
  629. # ggarrange(IEDpolarplot, Seizurepolarplot,
  630. # labels = c("A","B"),
  631. # vjust = 15, hjust = -1,
  632. # legend = "right",
  633. # common.legend = TRUE,
  634. # font.label = list(size = 14, color = "black", face = "bold")) %>%
  635. # ggexport(filename = "D:/Dropbox/Apps/Overleaf/Hspike/images/polar_density_seizures.pdf")
  636. # save combined to pdf, with power
  637. # ggarrange(IEDpolarplot, Seizurepolarplot, polardelta1power, polardelta2power,
  638. # labels = c("A","B","C", "D"),
  639. # vjust = 3, hjust = -1,
  640. # legend = "right",
  641. # common.legend = TRUE,
  642. # font.label = list(size = 14, color = "black", face = "bold")) %>%
  643. # ggexport(filename = "D:/Dropbox/Apps/Overleaf/Hspike/images/polar.pdf")
  644. # save combined to pdf
  645. ggarrange(IEDpolarplot, Seizurepolarplot,
  646. labels = c("A","B"),
  647. vjust = 15, hjust = -1,
  648. ncol = 2, nrow = 1,
  649. legend = "right",
  650. common.legend = TRUE,
  651. font.label = list(size = 14, color = "black", face = "bold")) %>%
  652. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/polar.pdf")
  653. # LaTeX table
  654. library(stringr)
  655. stat_seizures$time = paste(str_pad( floor(stat_seizures$median), 2, pad = "0"), ":", str_pad(floor((stat_seizures$median- floor(stat_seizures$median)) * 60), 2, pad = "0"), sep = "")
  656. stat_seizures <- stat_seizures[, c("Patient", "time", "Rayleigh_stat", "p")]
  657. stat_seizures[,4] = ifelse(stat_seizures[,4] > .05, paste(round(stat_seizures[,4],digits=2),sep=""), ifelse(stat_seizures[,4] < .0001, "<.0001\\textsuperscript{***}", ifelse(stat_seizures[,4] < .001,"<.001\\textsuperscript{**}", ifelse(stat_seizures[,4] < .01, "<.01\\textsuperscript{*}", "<.05"))))
  658. kbl(stat_seizures, "latex", booktabs = T, linesep = "", label = 'circstat_seizures',
  659. col.names = c("Patient","Median angle (HH:mm)","Rayleigh", "\\textit{p}"),
  660. escape = FALSE, digits = 2,
  661. caption = "Circular statistics of circadian seizure occurance")%>%
  662. footnote(general_title = "",
  663. footnote_as_chunk = TRUE,
  664. threeparttable = TRUE,
  665. escape = FALSE,
  666. general = c("$. = p<0.05$, $* = p<0.01$, $** = p<0.001$, $*** = p<0.0001$"))%>%
  667. kable_styling(latex_options = c("HOLD_position"))%>%
  668. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/circstat_seizures.tex")
  669. # combined table
  670. temp <- stat_seizures
  671. colnames(temp) <- c("Patient","time2","Rayleigh_stat2","p2")
  672. combined = merge(stat_IED,temp)
  673. kbl(combined, "latex", booktabs = T, linesep = "", label = 'circstats',
  674. col.names = c("Patient","Time","Rayleigh", "\\textit{p}","Time","Rayleigh", "\\textit{p}"),
  675. escape = FALSE, digits = 2,
  676. caption = "Circular statistics of circadian epileptic activity")%>%
  677. add_header_above(c(" ", "Interictal activity" = 3, "Seizures" = 3)) %>%
  678. kable_styling(latex_options = c("HOLD_position"))%>%
  679. footnote(general_title = "",
  680. footnote_as_chunk = TRUE,
  681. threeparttable = TRUE,
  682. escape = FALSE,
  683. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  684. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/circstats.tex")
  685. #############################
  686. # LFP power per sleep stage #
  687. #############################
  688. # prepare data
  689. data_pow <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/power_table_long.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  690. data_pow <- data_pow[!data_pow$part > 3, ] # hypnogram is only scored on first three nights
  691. data_pow <- data_pow[!data_pow$hyplabel == "NO_SCORE", ]
  692. data_pow$hyplabel[data_pow$hyplabel == "PHASE_1"] = "S1"
  693. data_pow$hyplabel[data_pow$hyplabel == "PHASE_2"] = "S2"
  694. data_pow$hyplabel[data_pow$hyplabel == "PHASE_3"] = "S3"
  695. data_pow$hyplabel[data_pow$hyplabel == "AWAKE"] = "WASO"
  696. data_pow$hyplabel[data_pow$hyplabel == "PRESLEEP"] = "Pre"
  697. data_pow$hyplabel[data_pow$hyplabel == "POSTSLEEP"] = "Post"
  698. data_pow$hyplabel <- factor(data_pow$hyplabel, levels = c("Pre", "Post", "REM", "WASO", "S1", "S2", "S3"))
  699. data_pow$band <- factor(data_pow$band, ordered = TRUE, levels = c("Delta1", "Delta2"))
  700. data_pow$patient <- factor(data_pow$patient, levels = c(8:1))
  701. data_pow$part <- factor(data_pow$part)
  702. # relative to pre-sleep
  703. temp <- setNames(aggregate(data_pow$power, by = list(data_pow$patient, data_pow$part, data_pow$band, data_pow$hyplabel), mean), c("patient", "part", "band", "hyplabel", "Pre"))
  704. temp <- temp[temp$hyplabel=="Pre", ]
  705. temp <- subset(temp, select = -c(hyplabel))
  706. data_pow <- merge(data_pow, temp)
  707. data_pow$Zpower <- (data_pow$power-data_pow$Pre) / (data_pow$power+data_pow$Pre)
  708. data_pow$Zpower <- (data_pow$power/data_pow$Pre)
  709. data_pow_sel <- data_pow[!data_pow$hyplabel=="Pre", ]
  710. # averages for plotting
  711. data_pow_avg <- setNames(aggregate(data_pow_sel$Zpower, by = list(data_pow_sel$patient, data_pow_sel$part, data_pow_sel$band, data_pow_sel$hyplabel), mean), c("patient", "part", "band", "hyplabel", "power_avg"))
  712. data_pow_avg$patient <- factor(data_pow_avg$patient, levels = c(8:1))
  713. data_pow_avg$part <- factor(data_pow_avg$part)
  714. # plot
  715. data_pow_sel$title1 = "SWA (0.1-2.5 Hz) power"
  716. data_pow_sel$title2 = "Delta (2.5-4.0 Hz) power"
  717. plot_delta1 <-
  718. ggplot(data=data_pow_sel[data_pow_sel$band == "Delta1",], aes(y = hyplabel, x = Zpower)) +
  719. geom_boxplot(outlier.shape = NA) +
  720. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  721. geom_point(data = data_pow_avg[data_pow_avg$band == "Delta1",], aes(group = interaction(patient, part), x = power_avg, y = hyplabel, col = patient),
  722. position=position_dodge(width=0.5)) +
  723. guides(colour = "none") +
  724. coord_cartesian(xlim = c(0, 20)) +
  725. scale_x_continuous(breaks=c(0, 20)) +
  726. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  727. theme_article() +
  728. ylab(NULL) + xlab(NULL) +
  729. facet_wrap(~title1)
  730. plot_delta2 <-
  731. ggplot(data=data_pow_sel[data_pow_sel$band == "Delta2",], aes(y = hyplabel, x = Zpower)) +
  732. geom_boxplot(outlier.shape = NA) +
  733. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  734. geom_point(data = data_pow_avg[data_pow_avg$band == "Delta2",], aes(group = interaction(patient, part), x = power_avg, y = hyplabel, col = patient),
  735. position=position_dodge(width=0.5)) +
  736. guides(colour = "none") +
  737. coord_cartesian(xlim = c(0, 10)) +
  738. scale_x_continuous(breaks=c(0, 10)) +
  739. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  740. theme_article() +
  741. ylab(NULL) + xlab(NULL) +
  742. facet_wrap(~title2)
  743. ##########################
  744. # IED rate & sleep stage #
  745. ##########################
  746. # prepare data
  747. data_IED <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/IED_table_PSG.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  748. data_IED <- data_IED[!data_IED$hyplabel == "NO_SCORE", ]
  749. data_IED$hyplabel[data_IED$hyplabel == "PHASE_1"] = "S1"
  750. data_IED$hyplabel[data_IED$hyplabel == "PHASE_2"] = "S2"
  751. data_IED$hyplabel[data_IED$hyplabel == "PHASE_3"] = "S3"
  752. data_IED$hyplabel[data_IED$hyplabel == "AWAKE"] = "WASO"
  753. data_IED$hyplabel[data_IED$hyplabel == "PRESLEEP"] = "Pre"
  754. data_IED$hyplabel[data_IED$hyplabel == "POSTSLEEP"] = "Post"
  755. data_IED$hyplabel <- factor(data_IED$hyplabel, levels = c("Pre", "Post", "REM", "WASO", "S1", "S2", "S3"))
  756. data_IED$Patient <- factor(data_IED$patient, levels = c(8:1))
  757. data_IED$part <- factor(data_IED$part)
  758. data_IED$marker <- factor(data_IED$marker)
  759. data_IED$hour <- data_IED$minute / (60)
  760. # normalize by time spend in sleep stages
  761. data_duration <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/hypnogram_duration.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  762. data_duration <- data_duration %>% rename(
  763. 'S1' = 'PHASE_1',
  764. 'S2' = 'PHASE_2',
  765. 'S3' = 'PHASE_3',
  766. 'Pre' = 'PRESLEEP',
  767. 'Post' = 'POSTSLEEP',
  768. 'Total' = 'TOTAL')
  769. data_duration <- melt(data_duration, id = c('patient','part'))
  770. colnames(data_duration) = c('Patient','part','hyplabel','duration')
  771. # count IEDs per sleepstage
  772. data_IEDrate <- na.omit(data_IED %>% dplyr::count(Patient, part, hyplabel))
  773. # normalize by time spend in sleep stages
  774. data_IEDrate <- merge(data_IEDrate, data_duration)
  775. data_IEDrate$IEDrate = data_IEDrate$n / data_IEDrate$duration / 60 # original rate is in Hz, now in minute
  776. # normalize rate by Pre rate
  777. i <- data_IEDrate[data_IEDrate$hyplabel == 'Pre',]
  778. i <- i[, c('Patient','part','IEDrate')]
  779. colnames(i) = c('Patient','part','Prerate')
  780. data_IEDrate <- merge(data_IEDrate, i)
  781. data_IEDrate$IEDrateNorm <- data_IEDrate$IEDrate - data_IEDrate$Prerate
  782. data_IEDrate_sel <- data_IEDrate[!data_IEDrate$hyplabel=="Pre", ]
  783. # plot
  784. data_IEDrate_sel$title1 = "IED count"
  785. data_IEDrate_sel$title2 = "IED rate (count/minute)"
  786. data_IEDrate_sel$title3 = "IED rate - IED rate Pre-sleep (count/min)"
  787. plot_IED_count <- ggplot(data=data_IEDrate_sel, aes(y=hyplabel, x=n)) +
  788. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  789. geom_boxplot(outlier.shape = NA) +
  790. geom_point(aes(group = interaction(Patient, part), col = Patient), position=position_dodge(width=0.5)) +
  791. # guides(colour = "none") +
  792. ylab(NULL) + xlab(NULL) +
  793. theme_article() +
  794. coord_cartesian(xlim = c(1, 3000)) +
  795. scale_x_continuous(breaks=c(0, 3000)) +
  796. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  797. theme(legend.position="right") +
  798. facet_wrap(~title1)
  799. plot_IED_rate <- ggplot(data=data_IEDrate_sel, aes(y=hyplabel, x=IEDrate)) +
  800. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  801. geom_boxplot(outlier.shape = NA) +
  802. geom_point(aes(group = interaction(Patient, part), col = Patient), position=position_dodge(width=0.5)) +
  803. # guides(colour = "none") +
  804. ylab(NULL) + xlab(NULL) +
  805. theme_article() +
  806. coord_cartesian(xlim = c(0, 20)) +
  807. scale_x_continuous(breaks=c(0, 20)) +
  808. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  809. theme(legend.position="right") +
  810. facet_wrap(~title2)
  811. plot_IED_norm <- ggplot(data=data_IEDrate_sel, aes(y=hyplabel, x=IEDrateNorm)) +
  812. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  813. geom_boxplot(outlier.shape = NA) +
  814. geom_point(aes(group = interaction(Patient, part), col = Patient), position=position_dodge(width=0.5)) +
  815. ylab(NULL) + xlab(NULL) +
  816. theme(axis.text.y = element_blank()) +
  817. theme_article() +
  818. coord_cartesian(xlim = c(0, 20)) +
  819. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  820. scale_x_continuous(breaks=c(0, 20)) +
  821. # theme(legend.position ="bottom") +
  822. # guides(colour = guide_legend(ncol = 1)) +
  823. # guides(fill=guide_legend(title="Patient")) +
  824. theme(legend.position="right") +
  825. labs(color='Patient') +
  826. facet_wrap(~title3)
  827. #####################################
  828. # IED rate explained by sleep stage #
  829. #####################################
  830. # to create p-values
  831. detach(package:lmerTest)
  832. library(lmerTest)
  833. library(lme4)
  834. # determine reference level
  835. data_IEDrate$hyplabel <- factor(data_IEDrate$hyplabel, levels = c("Pre","S3", "S2", "S1", "Wake", "REM", "Post"))
  836. data_IEDrate$hyplabel = relevel(data_IEDrate$hyplabel, ref="Pre")
  837. lIEDrate <- lmer(IEDrate ~ hyplabel + (1 | part) + (1 | Patient), data_IEDrate, control = lmerControl(optimizer ='Nelder_Mead'))
  838. summary(lIEDrate)
  839. plot_model(lIEDrate)
  840. # Coefficients
  841. temp = summary(lIEDrate)
  842. coefs <- as.data.frame(temp$coefficients)
  843. coefs[,5] = ifelse(coefs[,5] > .05, paste(round(coefs[,5],digits=2),sep=""), ifelse(coefs[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(coefs[,5] < .001,"<.001\\textsuperscript{**}", ifelse(coefs[,5] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  844. rownames(coefs) <- c("\\textit{Intercept}", "S3", "S2", "S1", "Wake", "REM", "Post")
  845. # Post-hoc tests
  846. temp = emmeans(lIEDrate, list(pairwise ~ hyplabel), adjust = "tukey")
  847. phIEDrate <- as.data.frame(temp$`pairwise differences of hyplabel`)
  848. phIEDrate <- phIEDrate[, -4] # remove df since they are at inf
  849. phIEDrate[,5] = ifelse(phIEDrate[,5] > .05, paste(round(phIEDrate[,5],digits=2),sep=""), ifelse(phIEDrate[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(phIEDrate[,5] < .001,"<.001\\textsuperscript{**}", ifelse(phIEDrate[,5] < .01, "<.01\\textsuperscript{*}", "<.05"))))
  850. # Concatenate in one LaTeX table
  851. coefs <- data.frame(Predictor = row.names(coefs), coefs);
  852. rownames(coefs) <- NULL
  853. colnames(phIEDrate) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","z", "\\textit{p}")
  854. colnames(coefs) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)", "df", "z","\\textit{p}")
  855. stats_IEDrate <- bind_rows(coefs,phIEDrate)
  856. options(knitr.kable.NA = '')
  857. kbl(stats_IEDrate, "latex", booktabs = T, linesep = "", label = 'stats_IEDrate',
  858. escape = FALSE, digits = 2,
  859. caption = "Effect of sleep stages on Slow Wave activity (0.1-2.5Hz)")%>%
  860. pack_rows("Coefficients", 1, 7) %>%
  861. pack_rows("Post-hoc comparisons", 8, 28) %>%
  862. kable_styling(latex_options = c("HOLD_position"))%>%
  863. footnote(general_title = "",
  864. footnote_as_chunk = TRUE,
  865. threeparttable = TRUE,
  866. escape = FALSE,
  867. general = c("$. = p<0.05$, $* = p<0.01$, $** = p<0.001$, $*** = p<0.0001$"))%>%
  868. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/stats_IEDrate.tex")
  869. #################################
  870. # IED rate vs. power STATISTICS #
  871. #################################
  872. # prepare data
  873. data_pow_wide <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/power_table_wide.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  874. data_pow_wide <- data_pow_wide[!data_pow_wide$hyplabel == "NO_SCORE", ]
  875. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PHASE_1"] = "S1"
  876. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PHASE_2"] = "S2"
  877. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PHASE_3"] = "S3"
  878. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "AWAKE"] = "WASO"
  879. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PRESLEEP"] = "Pre"
  880. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "POSTSLEEP"] = "Post"
  881. data_pow_wide$hyplabel <- factor(data_pow_wide$hyplabel, levels = c("Pre","S3", "S2", "S1", "WASO", "REM", "Post"))
  882. data_pow_wide$stage <- data_pow_wide$hyplabel
  883. data_pow_wide$Patient <- factor(data_pow_wide$patient, levels = c(8:1))
  884. data_pow_wide$night <- factor(data_pow_wide$part)
  885. # to create p-values
  886. detach(package:lmerTest)
  887. library(lmerTest)
  888. library(lme4)
  889. ###################################
  890. # Delta1 explained by sleep stage #
  891. ###################################
  892. lDelta1 <- lmer(Delta1 ~ stage + (1 | night) + (1 | Patient), data_pow_wide, control = lmerControl(optimizer ='Nelder_Mead'))
  893. summary(lDelta1)
  894. plot_model(lDelta1)
  895. # Coefficients
  896. temp = summary(lDelta1)
  897. coefs <- as.data.frame(temp$coefficients)
  898. coefs[,5] = ifelse(coefs[,5] > .05, paste(round(coefs[,5],digits=2),sep=""), ifelse(coefs[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(coefs[,5] < .001,"<.001\\textsuperscript{**}", ifelse(coefs[,5] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  899. rownames(coefs) <- c("\\textit{Intercept}", "S3", "S2", "S1", "WASO", "REM", "Post")
  900. # Post-hoc tests
  901. temp = emmeans(lDelta1, list(pairwise ~ stage), adjust = "tukey")
  902. phDelta1 <- as.data.frame(temp$`pairwise differences of stage`)
  903. phDelta1 <- phDelta1[, -4] # remove df since they are at inf
  904. phDelta1[,5] = ifelse(phDelta1[,5] > .05, paste(round(phDelta1[,5],digits=2),sep=""), ifelse(phDelta1[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(phDelta1[,5] < .001,"<.001\\textsuperscript{**}", ifelse(phDelta1[,5] < .01, "<.01\\textsuperscript{*}", "<.05"))))
  905. # Concatenate in one LaTeX table
  906. coefs <- data.frame(Predictor = row.names(coefs), coefs);
  907. rownames(coefs) <- NULL
  908. colnames(phDelta1) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","z", "\\textit{p}")
  909. colnames(coefs) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)", "df", "z","\\textit{p}")
  910. stats_delta1 <- bind_rows(coefs,phDelta1)
  911. options(knitr.kable.NA = '')
  912. kbl(stats_delta1, "latex", booktabs = T, linesep = "", label = 'stats_delta1',
  913. escape = FALSE, digits = 2,
  914. caption = "Effect of sleep stage on Slow Wave (0.1-2.5Hz) power")%>%
  915. pack_rows("Coefficients", 1, 7) %>%
  916. pack_rows("Post-hoc comparisons", 8, 28) %>%
  917. kable_styling(latex_options = c("HOLD_position"))%>%
  918. footnote(general_title = "",
  919. footnote_as_chunk = TRUE,
  920. threeparttable = TRUE,
  921. escape = FALSE,
  922. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  923. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/stats_delta1.tex")
  924. ###################################
  925. # Delta2 explained by sleep stage #
  926. ###################################
  927. lDelta2 <- lmer(Delta2 ~ stage + (1 | night) + (1 | Patient), data_pow_wide, control = lmerControl(optimizer ='Nelder_Mead'))
  928. summary(lDelta2)
  929. plot_model(lDelta2)
  930. # Coefficients
  931. temp = summary(lDelta2)
  932. coefs <- as.data.frame(temp$coefficients)
  933. coefs[,5] = ifelse(coefs[,5] > .05, paste(round(coefs[,5],digits=2),sep=""), ifelse(coefs[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(coefs[,5] < .001,"<.001\\textsuperscript{**}", ifelse(coefs[,5] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  934. rownames(coefs) <- c("\\textit{Intercept}", "S3", "S2", "S1", "WASO", "REM", "Post")
  935. # Post-hoc tests
  936. temp = emmeans(lDelta2, list(pairwise ~ stage), adjust = "tukey")
  937. phDelta2 <- as.data.frame(temp$`pairwise differences of stage`)
  938. phDelta2 <- phDelta2[, -4] # remove df since they are at inf
  939. phDelta2[,5] = ifelse(phDelta2[,5] > .05, paste(round(phDelta2[,5],digits=2),sep=""), ifelse(phDelta2[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(phDelta2[,5] < .001,"<.001\\textsuperscript{**}", ifelse(phDelta2[,5] < .01, "<.01\\textsuperscript{*}", "<.05"))))
  940. # Concatenate in one LaTeX table
  941. coefs <- data.frame(Predictor = row.names(coefs), coefs);
  942. rownames(coefs) <- NULL
  943. colnames(phDelta2) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","z", "\\textit{p}")
  944. colnames(coefs) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)", "df", "z","\\textit{p}")
  945. stats_delta2 <- bind_rows(coefs,phDelta2)
  946. options(knitr.kable.NA = '')
  947. kbl(stats_delta2, "latex", booktabs = T, linesep = "", label = 'stats_delta2',
  948. escape = FALSE, digits = 2,
  949. caption = "Effect of sleep stage on Delta (2.5-4 Hz) power")%>%
  950. pack_rows("Coefficients", 1, 7) %>%
  951. pack_rows("Post-hoc comparisons", 8, 28) %>%
  952. kable_styling(latex_options = c("HOLD_position"))%>%
  953. footnote(general_title = "",
  954. footnote_as_chunk = TRUE,
  955. threeparttable = TRUE,
  956. escape = FALSE,
  957. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  958. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/stats_delta2.tex")
  959. ####################################################
  960. # Mixed model with sleep stage explaining IED rate #
  961. ####################################################
  962. # to create p-values
  963. detach(package:lmerTest)
  964. library(lmerTest)
  965. library(lme4)
  966. # determine reference level
  967. data_pow_wide$hyplabel = relevel(data_pow_wide$stage, ref="Pre")
  968. l1 <- lmer(IEDsum ~ stage + (1 | night) + (1 | patient), data_pow_wide)
  969. summary(l1)
  970. plot_model(l1)
  971. # get mathematical description of the model and write to latex
  972. # eq <- equatiomatic::extract_eq(l1)
  973. # fileConn<-file("D:/Dropbox/Apps/Overleaf/Hspike/formula/model1.tex")
  974. # writeLines(c("$$",eq,"$$"), fileConn)
  975. # close(fileConn)
  976. # Coefficients to LaTeX table
  977. temp = summary(l1)
  978. coefs <- as.data.frame(temp$coefficients)
  979. coefs[,5] = ifelse(coefs[,5] > .05, paste(round(coefs[,5],digits=2),sep=""), ifelse(coefs[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(coefs[,5] < .001,"<.001\\textsuperscript{**}", ifelse(coefs[,5] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  980. rownames(coefs) <- c("\\textit{Intercept}", "S3", "S2", "S1", "WASO", "REM", "Post")
  981. # Post-hoc tests to LaTeX table
  982. temp = emmeans(l1, list(pairwise ~ stage), adjust = "tukey")
  983. ph1 <- as.data.frame(temp$`pairwise differences of stage`)
  984. ph1 <- ph1[, -4] # remove df since they are at inf
  985. ph1[,5] = ifelse(ph1[,5] > .05, paste(round(ph1[,5],digits=2),sep=""), ifelse(ph1[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(ph1[,5] < .001,"<.001\\textsuperscript{**}", ifelse(ph1[,5] < .01, "<.01\\textsuperscript{*}", "<.05"))))
  986. # Concatenate in one LaTeX table
  987. coefs <- data.frame(Predictor = row.names(coefs), coefs);
  988. rownames(coefs) <- NULL
  989. colnames(ph1) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","z", "\\textit{p}")
  990. colnames(coefs) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)", "df", "z","\\textit{p}")
  991. stats_IEDsum <- bind_rows(coefs,ph1)
  992. kbl(stats_IEDsum, "latex", booktabs = T, linesep = "", label = 'stats_IEDsum',
  993. escape = FALSE, digits = 2,
  994. caption = "Effect of sleep stage on IEDs rate")%>%
  995. kable_styling(latex_options = c("HOLD_position"))%>%
  996. pack_rows("Sleep stages", 1, 7) %>% # latex_gap_space = "2em"
  997. pack_rows("Post-hoc comparisons", 8, 28) %>%
  998. footnote(general_title = "",
  999. footnote_as_chunk = TRUE,
  1000. threeparttable = TRUE,
  1001. escape = FALSE,
  1002. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  1003. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/stats_IEDsum.tex")
  1004. #########################################
  1005. # correlation between power and IEDrate #
  1006. #########################################
  1007. # prepare data
  1008. data_pow_wide <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/power_table_wide.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  1009. data_pow_wide <- data_pow_wide[!data_pow_wide$hyplabel == "NO_SCORE", ]
  1010. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PHASE_1"] = "S1"
  1011. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PHASE_2"] = "S2"
  1012. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PHASE_3"] = "S3"
  1013. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "AWAKE"] = "WASO"
  1014. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "PRESLEEP"] = "Pre"
  1015. data_pow_wide$hyplabel[data_pow_wide$hyplabel == "POSTSLEEP"] = "Post"
  1016. data_pow_wide$hyplabel <- factor(data_pow_wide$hyplabel, levels = c("Pre","S3", "S2", "S1", "WASE", "REM", "Post"))
  1017. data_pow_wide$stage <- data_pow_wide$hyplabel
  1018. data_pow_wide$Patient <- factor(data_pow_wide$patient)
  1019. data_pow_wide$night <- factor(data_pow_wide$part)
  1020. data_pow_wide$Delta1_log <- log(data_pow_wide$Delta1)
  1021. data_pow_wide$Delta2_log <- log(data_pow_wide$Delta2)
  1022. data_pow_wide$IEDsum_log <- log(data_pow_wide$IEDsum)
  1023. data_pow_wide$Patient <- factor(data_pow_wide$patient, levels = c(8:1))
  1024. # Delta 1
  1025. data_pow_wide2 <- data_pow_wide %>% mutate(Delta_log_bin = cut(Delta1_log, breaks=seq(-1.5,10.5,1)))
  1026. levels(data_pow_wide2$Delta_log_bin) <- seq(1:12)-2
  1027. data_pow_wide2 <- data_pow_wide2 %>% group_by(Delta_log_bin, IEDsum)
  1028. data_pow_wide2 <- data_pow_wide2 %>% summarise(count = n(), Patient)
  1029. data_pow_wide2 <- data_pow_wide2[order(data_pow_wide2$Patient), ]
  1030. # # Delta 1 for S3
  1031. # data_pow_wide2 <- data_pow_wide[data_pow_wide$hyplabel == "S3", ] %>% mutate(Delta_log_bin = cut(Delta1_log, breaks=seq(-1.5,10.5,1)))
  1032. # levels(data_pow_wide2$Delta_log_bin) <- seq(1:12)-2
  1033. # data_pow_wide2 <- data_pow_wide2 %>% group_by(Delta_log_bin, IEDsum)
  1034. # data_pow_wide2 <- data_pow_wide2 %>% summarise(count = n(), Patient)
  1035. # data_pow_wide2 <- data_pow_wide2[order(data_pow_wide2$Patient), ]
  1036. # ggplot(data=data_pow_wide2[data_pow_wide2$IEDsum > 0, ], aes(x=Delta1_log_bin, y=IEDsum*6)) +
  1037. D1 <- ggplot(data=data_pow_wide2, aes(x=Delta_log_bin, y=IEDsum*6, color = Patient)) +
  1038. geom_count() +
  1039. # geom_count(aes(size = after_stat(prop), group = Delta_log_bin, color = Patient)) +
  1040. # scale_size_area(max_size = 3) +
  1041. # geom_smooth(data=data_pow_wide, aes(x=Delta1_log, y=IEDsum), method="lm", fullrange = FALSE, color="red") +
  1042. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1043. theme(axis.text.y = element_blank()) +
  1044. theme_article() +
  1045. theme(
  1046. strip.background = element_blank(),
  1047. strip.text.x = element_blank()
  1048. ) +
  1049. xlab("") +
  1050. ylab("IEDs per minute") +
  1051. # labs(size = "Proportion") +
  1052. # coord_cartesian(xlim = c(2,11)) +
  1053. # coord_cartesian(ylim = c(2,11)) +
  1054. # facet_wrap(~Patient, ncol = 4, scales="free_x")
  1055. facet_wrap(~Patient, ncol = 4)
  1056. # ggsave("D:/Dropbox/Apps/Overleaf/Hspike/images/IEDrate_Delta1_count.pdf", width = 7, height = 4, units = "in")
  1057. # Delta 2
  1058. data_pow_wide2 <- data_pow_wide %>% mutate(Delta_log_bin = cut(Delta2_log, breaks=seq(-1.5,10.5,1)))
  1059. levels(data_pow_wide2$Delta_log_bin) <- seq(1:12)-2
  1060. data_pow_wide2 <- data_pow_wide2 %>% group_by(Delta_log_bin, IEDsum)
  1061. data_pow_wide2 <- data_pow_wide2 %>% summarise(count = n(), Patient)
  1062. data_pow_wide2 <- data_pow_wide2[order(data_pow_wide2$Patient), ]
  1063. # ggplot(data=data_pow_wide2[data_pow_wide2$IEDsum > 0, ], aes(x=Delta1_log_bin, y=IEDsum*6)) +
  1064. D2 <- ggplot(data=data_pow_wide2, aes(x=Delta_log_bin, y=IEDsum*6, color = Patient)) +
  1065. # geom_count(aes(size = after_stat(prop), group = Delta_log_bin, color = Patient)) +
  1066. geom_count() +
  1067. # scale_size_area(max_size = 3) +
  1068. # geom_smooth(data=data_pow_wide, aes(x=Delta1_log, y=IEDsum), method="lm", fullrange = FALSE, color="red") +
  1069. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1070. theme(axis.text.y = element_blank()) +
  1071. theme_article() +
  1072. theme(
  1073. strip.background = element_blank(),
  1074. strip.text.x = element_blank()
  1075. ) +
  1076. # xlab("Delta2 power (log)")
  1077. #xlab = expression(mu "Volts" / "Hertz" ^ 2) +
  1078. # xlab = expression("Force spaces with ~" ~ mu ~ pi * sigma ~ pi) +
  1079. # ylab( units~are~(mu*g)/L )
  1080. # xlab(TeX(r'($\alpha x^\alpha$, where $\alpha \in \{1 \ldots 5\}$)')) +
  1081. # xlab(TeX(r'($log(\mu V/Hz^2$))')) +
  1082. xlab(TeX(r'($log(\mu V^2/Hz$))')) +
  1083. ylab("IEDs per minute") +
  1084. labs(size = "Observations") +
  1085. # coord_cartesian(xlim = c(2,11)) +
  1086. # coord_cartesian(ylim = c(2,11)) +
  1087. # facet_wrap(~Patient, ncol = 4, scales="free_x")
  1088. facet_wrap(~Patient, ncol = 4)
  1089. # ggsave("D:/Dropbox/Apps/Overleaf/Hspike/images/IEDrate_Delta2_count.pdf", width = 7, height = 4, units = "in")
  1090. ggarrange(D1, D2,
  1091. ncol = 1, nrow = 2,
  1092. vjust = 1, hjust = 0,
  1093. labels = c("A","B"),
  1094. legend = "right",
  1095. common.legend = TRUE,
  1096. font.label = list(size = 14, color = "black", face = "bold")) %>%
  1097. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/images/IEDrate_Delta_count.pdf")
  1098. ###############################################
  1099. # Mixed model with power explaining IED rate #
  1100. ###############################################
  1101. # to create p-values
  1102. detach(package:lmerTest)
  1103. library(lmerTest)
  1104. library(lme4)
  1105. # determine reference level
  1106. data_pow_wide$hyplabel = relevel(data_pow_wide$stage, ref="Pre")
  1107. l1 <- lmer(IEDsum ~ Delta1 + Delta2 + (1 | night) + (1 | patient), data_pow_wide)
  1108. summary(l1)
  1109. plot_model(l1)
  1110. # # get mathematical description of the model and write to latex
  1111. # eq <- equatiomatic::extract_eq(l1)
  1112. # fileConn<-file("D:/Dropbox/Apps/Overleaf/Hspike/formula/model1.tex")
  1113. # writeLines(c("$$",eq,"$$"), fileConn)
  1114. # close(fileConn)
  1115. # Coefficients to LaTeX table
  1116. temp = summary(l1)
  1117. coefs <- as.data.frame(temp$coefficients)
  1118. coefs[,5] = ifelse(coefs[,5] > .05, paste(round(coefs[,5],digits=2),sep=""), ifelse(coefs[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(coefs[,5] < .001,"<.001\\textsuperscript{**}", ifelse(coefs[,5] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1119. rownames(coefs) <- c("\\textit{Intercept}", "Slow Wave", "Delta")
  1120. kbl(coefs, "latex", booktabs = T, linesep = "", label = 'stats_IEDsum_vs_power',
  1121. escape = FALSE, digits = 2,
  1122. caption = "Effect of Slow Wave activity (0.1-2.5Hz) and Delta power (2.5-4Hz) on rate of IEDs")%>%
  1123. kable_styling(latex_options = c("HOLD_position")) %>%
  1124. footnote(general_title = "",
  1125. footnote_as_chunk = TRUE,
  1126. threeparttable = TRUE,
  1127. escape = FALSE,
  1128. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  1129. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/stats_IEDsum_vs_power.tex")
  1130. # ###################################################################
  1131. # # Mixed model with both sleep stage and power explaining IED rate #
  1132. # ###################################################################
  1133. #
  1134. # # to create p-values
  1135. # detach(package:lmerTest)
  1136. # library(lmerTest)
  1137. # library(lme4)
  1138. #
  1139. # # determine reference level
  1140. # data_pow_wide$hyplabel = relevel(data_pow_wide$stage, ref="Pre")
  1141. # l1 <- lmer(IEDsum ~ stage + Delta1 + Delta2 + (1 | night) + (1 | patient), data_pow_wide)
  1142. #
  1143. # summary(l1)
  1144. # plot_model(l1)
  1145. #
  1146. # # # get mathematical description of the model and write to latex
  1147. # # eq <- equatiomatic::extract_eq(l1)
  1148. # # fileConn<-file("D:/Dropbox/Apps/Overleaf/Hspike/formula/model1.tex")
  1149. # # writeLines(c("$$",eq,"$$"), fileConn)
  1150. # # close(fileConn)
  1151. #
  1152. # # Coefficients to LaTeX table
  1153. # temp = summary(l1)
  1154. # coefs <- as.data.frame(temp$coefficients)
  1155. # coefs[,5] = ifelse(coefs[,5] > .05, paste(round(coefs[,5],digits=2),sep=""), ifelse(coefs[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(coefs[,5] < .001,"<.001\\textsuperscript{**}", ifelse(coefs[,5] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1156. # rownames(coefs) <- c("\\textit{Intercept}", "S3", "S2", "S1", "Wake", "REM", "Post", "SW", "Delta")
  1157. #
  1158. # # Post-hoc tests to LaTeX table
  1159. # temp = emmeans(l1, list(pairwise ~ stage), adjust = "tukey")
  1160. # ph1 <- as.data.frame(temp$`pairwise differences of stage`)
  1161. # ph1 <- ph1[, -4] # remove df since they are at inf
  1162. # ph1[,5] = ifelse(ph1[,5] > .05, paste(round(ph1[,5],digits=2),sep=""), ifelse(ph1[,5] < .0001, "<.0001\\textsuperscript{***}", ifelse(ph1[,5] < .001,"<.001\\textsuperscript{**}", ifelse(ph1[,5] < .01, "<.01\\textsuperscript{*}", "<.05"))))
  1163. #
  1164. # # Concatenate in one LaTeX table
  1165. # coefs <- data.frame(Predictor = row.names(coefs), coefs);
  1166. # rownames(coefs) <- NULL
  1167. # colnames(ph1) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","z", "\\textit{p}")
  1168. # colnames(coefs) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)", "df", "z","\\textit{p}")
  1169. # stats_IEDsum <- bind_rows(coefs,ph1)
  1170. #
  1171. # kbl(stats_IEDsum, "latex", booktabs = T, linesep = "", label = 'stats_IEDsum_power',
  1172. # escape = FALSE, digits = 2,
  1173. # caption = "Effect of sleepstages on IEDrate")%>%
  1174. # kable_styling(latex_options = c("HOLD_position"))%>%
  1175. # pack_rows("Sleep stages", 1, 7) %>% # latex_gap_space = "2em"
  1176. # pack_rows("Power", 8, 9) %>%
  1177. # pack_rows("Post-hoc comparisons", 10, 30) %>%
  1178. # save_kable("D:/Dropbox/Apps/Overleaf/Hspike/tables/stats_IEDsum.tex")
  1179. # Plot models
  1180. set_theme(
  1181. base = theme_article(),
  1182. # panel.bordercol = NA
  1183. )
  1184. plot_IEDrate_model <- plot_model(
  1185. lIEDrate,
  1186. title = "",
  1187. colors = "bw",
  1188. axis.labels = "",
  1189. axis.title = "",
  1190. show.values = TRUE,
  1191. show.p = TRUE,
  1192. decimals = 4,
  1193. digits = 2,
  1194. value.offset = 0.5,
  1195. value.size = 2.5) +
  1196. ylim(-3, 9) +
  1197. font_size(labels.x = 9, labels.y = 9) +
  1198. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1199. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1200. scale_y_continuous(breaks=c(-2, 0, 8))
  1201. plot_IEDrate_model$data$title = "IED rate (count/minute) model"
  1202. plot_IEDrate_model <- plot_IEDrate_model + facet_wrap(~title, scales="free_y")
  1203. plot_delta1_model <- plot_model(
  1204. lDelta1,
  1205. title = "",
  1206. colors = "bw",
  1207. axis.labels = "",
  1208. axis.title = "",
  1209. show.values = TRUE,
  1210. show.p = TRUE,
  1211. decimals = 4,
  1212. digits = 2,
  1213. value.offset = 0.5,
  1214. value.size = 2.5) +
  1215. ylim(0, 300) +
  1216. font_size(labels.x = 9, labels.y = 9) +
  1217. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1218. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1219. scale_y_continuous(expand=expansion(mult=c(0.1,0.1)), breaks=c(0, 270))
  1220. plot_delta1_model$data$title = "SWA (0.1-2.5 Hz) model"
  1221. plot_delta1_model <- plot_delta1_model + facet_wrap(~title, scales="free_y")
  1222. plot_delta2_model <- plot_model(
  1223. lDelta2,
  1224. title = "",
  1225. colors = "bw",
  1226. axis.labels = "",
  1227. axis.title = "",
  1228. show.values = TRUE,
  1229. show.p = TRUE,
  1230. decimals = 4,
  1231. digits = 2,
  1232. value.offset = 0.5,
  1233. value.size = 2.5) +
  1234. ylim(-1, 41) +
  1235. font_size(labels.x = 9, labels.y = 9) +
  1236. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1237. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1238. scale_y_continuous(breaks=c(0, 40))
  1239. plot_delta2_model$data$title = "Delta (2.5-4.0 Hz) model"
  1240. plot_delta2_model <- plot_delta2_model + facet_wrap(~title, scales="free_y")
  1241. # Boxplots together in Figure
  1242. ggarrange(plot_IED_rate, plot_IEDrate_model, plot_delta1, plot_delta1_model, plot_delta2, plot_delta2_model,
  1243. ncol = 2, nrow = 3,
  1244. vjust = 1.5, hjust = -1,
  1245. labels = c("A","B","C","D","E","F","G","H"),
  1246. legend = "right",
  1247. common.legend = TRUE,
  1248. font.label = list(size = 14, color = "black", face = "bold")) %>%
  1249. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/images/IEDrate_delta_boxplots.pdf")
  1250. ###############################
  1251. # IED amplitude & sleep stage #
  1252. ###############################
  1253. # prepare data
  1254. data_amp <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/amplitude_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  1255. data_amp <- data_amp[!data_amp$hyplabel == "NO_SCORE", ]
  1256. data_amp <- data_amp[!data_amp$hyplabel == "NO_SCORE", ]
  1257. data_amp$hyplabel[data_amp$hyplabel == "PHASE_1"] = "S1"
  1258. data_amp$hyplabel[data_amp$hyplabel == "PHASE_2"] = "S2"
  1259. data_amp$hyplabel[data_amp$hyplabel == "PHASE_3"] = "S3"
  1260. data_amp$hyplabel[data_amp$hyplabel == "AWAKE"] = "WASO"
  1261. data_amp$hyplabel[data_amp$hyplabel == "PRESLEEP"] = "Pre"
  1262. data_amp$hyplabel[data_amp$hyplabel == "POSTSLEEP"] = "Post"
  1263. data_amp$stage <- factor(data_amp$hyplabel, levels = c("Pre","S3", "S2", "S1", "Wake", "REM", "Post"))
  1264. data_amp$Patient <- factor(data_amp$patient, levels = c(8:1))
  1265. data_amp$night <- factor(data_amp$part)
  1266. data_amp$Template <- factor(data_amp$template)
  1267. # # average over patient/part/sleepstage/template for plotting
  1268. # posamp <- setNames(aggregate(data_amp$posamp, by = c(list(data_amp$patient, data_amp$night, data_amp$Template, data_amp$hyplabel)), mean), c("Patient", "part", "Template", "hyplabel", "posamp"))
  1269. # negamp <- setNames(aggregate(data_amp$negamp, by = c(list(data_amp$patient, data_amp$night, data_amp$Template, data_amp$hyplabel)), mean), c("Patient", "part", "Template", "hyplabel", "negamp"))
  1270. # data_amp_mean <- merge(posamp, negamp)
  1271. # do not separate into templates
  1272. posamp <- setNames(aggregate(data_amp$posamp, by = c(list(data_amp$patient, data_amp$night, data_amp$hyplabel)), mean), c("Patient", "night", "hyplabel", "posamp"))
  1273. negamp <- setNames(aggregate(data_amp$negamp, by = c(list(data_amp$patient, data_amp$night, data_amp$hyplabel)), mean), c("Patient", "night", "hyplabel", "negamp"))
  1274. data_amp_mean <- merge(posamp, negamp)
  1275. # # relative to pre-sleep
  1276. # temp_pos <- setNames(aggregate(data_amp$posamp, by = list(data_amp$patient, data_amp$part, data_amp$Template, data_amp$hyplabel), mean), c("Patient", "part", "Template", "hyplabel", "Pre_pos"))
  1277. # temp_neg <- setNames(aggregate(data_amp$negamp, by = list(data_amp$patient, data_amp$part, data_amp$Template, data_amp$hyplabel), mean), c("Patient", "part", "Template", "hyplabel", "Pre_neg"))
  1278. # temp_pos <- temp_pos[temp_pos$hyplabel=="Pre", ]
  1279. # temp_neg <- temp_neg[temp_neg$hyplabel=="Pre", ]
  1280. # temp_pos <- subset(temp_pos, select = -c(hyplabel))
  1281. # temp_neg <- subset(temp_neg, select = -c(hyplabel))
  1282. # data_amp_mean <- merge(data_amp_mean, temp_pos)
  1283. # data_amp_mean <- merge(data_amp_mean, temp_neg)
  1284. # data_amp_mean$Zposamp <- (data_amp_mean$posamp-data_amp_mean$Pre_pos)
  1285. # data_amp_mean$Znegamp <- (data_amp_mean$negamp-data_amp_mean$Pre_neg)
  1286. # data_amp_mean$diffamp <- data_amp_mean$Zposamp + data_amp_mean$Znegamp
  1287. # # Normalized over all trials
  1288. # y1 <- setNames(aggregate(data_amp_mean$posamp, by = c(list(data_amp_mean$Patient, data_amp_mean$Template)), mean), c("Patient", "Template", "Mposamp"))
  1289. # y1sd <- setNames(aggregate(data_amp_mean$posamp, by = c(list(data_amp_mean$Patient, data_amp_mean$Template)), sd), c("Patient", "Template", "SDposamp"))
  1290. # y2 <- setNames(aggregate(data_amp_mean$negamp, by = c(list(data_amp_mean$Patient, data_amp_mean$Template)), mean), c("Patient", "Template", "Mnegamp"))
  1291. # y2sd <- setNames(aggregate(data_amp_mean$negamp, by = c(list(data_amp_mean$Patient, data_amp_mean$Template)), sd), c("Patient", "Template", "SDnegamp"))
  1292. # do not separate into templates
  1293. y1 <- setNames(aggregate(data_amp_mean$posamp, by = c(list(data_amp_mean$Patient)), mean), c("Patient", "Mposamp"))
  1294. y1sd <- setNames(aggregate(data_amp_mean$posamp, by = c(list(data_amp_mean$Patient)), sd), c("Patient", "SDposamp"))
  1295. y2 <- setNames(aggregate(data_amp_mean$negamp, by = c(list(data_amp_mean$Patient)), mean), c("Patient", "Mnegamp"))
  1296. y2sd <- setNames(aggregate(data_amp_mean$negamp, by = c(list(data_amp_mean$Patient)), sd), c("Patient", "SDnegamp"))
  1297. data_amp_mean <- merge(data_amp_mean,y1)
  1298. data_amp_mean <- merge(data_amp_mean,y2)
  1299. data_amp_mean <- merge(data_amp_mean,y1sd)
  1300. data_amp_mean <- merge(data_amp_mean,y2sd)
  1301. data_amp_mean$Zposamp <- (data_amp_mean$posamp-data_amp_mean$Mposamp)/data_amp_mean$SDposamp
  1302. data_amp_mean$Znegamp <- (data_amp_mean$negamp-data_amp_mean$Mnegamp)/data_amp_mean$SDnegamp
  1303. data_amp_mean$diffamp <- data_amp_mean$Zposamp - data_amp_mean$Znegamp
  1304. data_amp_mean$Patient <- as.factor(data_amp_mean$Patient)
  1305. data_amp_mean$hyplabel <- factor(data_amp_mean$hyplabel, levels = c("Pre","Post", "REM", "WASO", "S1", "S2", "S3"))
  1306. data_amp_mean_sel <- data_amp_mean[!data_amp_mean$hyplabel=="Pre", ]
  1307. # plot
  1308. data_amp_mean_sel$title1 = "Standardized spike amplitude"
  1309. data_amp_mean_sel$title2 = "Standardized slow-wave amplitude"
  1310. data_amp_mean_sel$title3 = "Standardized spike vs. slow-wave amplitude"
  1311. data_amp_mean_sel$Patient <- factor(data_amp_mean_sel$Patient, levels = c(8:1))
  1312. plot_amp_pos <- ggplot(data=data_amp_mean_sel, aes(y=hyplabel, x=Zposamp)) +
  1313. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1314. geom_boxplot(outlier.shape = NA) +
  1315. geom_point(aes(group = interaction(Patient, night), col = Patient), position=position_dodge(width=0.5), size = 1) +
  1316. ylab(NULL) + xlab(NULL) +
  1317. theme_article() +
  1318. theme(legend.position="bottom") +
  1319. coord_cartesian(xlim = c(-2.5, 2.5)) +
  1320. facet_wrap(~title1)
  1321. plot_amp_neg <- ggplot(data=data_amp_mean_sel, aes(y=hyplabel, x=Znegamp)) +
  1322. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1323. geom_boxplot(outlier.shape = NA) +
  1324. geom_point(aes(group = interaction(Patient, night), col = Patient), position=position_dodge(width=0.5),size = 1) +
  1325. ylab(NULL) + xlab(NULL) +
  1326. theme_article() +
  1327. theme(legend.position="bottom") +
  1328. coord_cartesian(xlim = c(-3, 3)) +
  1329. # coord_cartesian(xlim = c(-300, 100)) +
  1330. facet_wrap(~title2)
  1331. plot_amp_diff <- ggplot(data=data_amp_mean_sel, aes(y=hyplabel, x=diffamp)) +
  1332. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1333. geom_boxplot(outlier.shape = NA) +
  1334. geom_point(aes(group = interaction(Patient, night), col = Patient), position=position_dodge(width=0.5), size = 1) +
  1335. ylab(NULL) + xlab(NULL) +
  1336. theme_article() +
  1337. theme(legend.position="bottom") +
  1338. coord_cartesian(xlim = c(-5, 5)) +
  1339. scale_x_continuous(breaks=c(-5, 0, 5)) +
  1340. facet_wrap(~title3)
  1341. # plot pos vs neg in count scatter plot
  1342. data_bin <- data_amp %>% group_by(Patient) %>% mutate(pos_bin = cut(posamp, 20))
  1343. data_bin <- data_bin %>% group_by(Patient) %>% mutate(neg_bin = cut(negamp, 20))
  1344. ggplot(data=data_bin, aes(y=pos_bin, x=neg_bin)) +
  1345. geom_count(aes(color = Patient)) +
  1346. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1347. theme(axis.text.y = element_blank()) +
  1348. theme_article() +
  1349. theme(
  1350. strip.background = element_blank(),
  1351. strip.text.x = element_blank(),
  1352. axis.text.x = element_blank(),
  1353. axis.text.y = element_blank(),
  1354. axis.ticks = element_blank()
  1355. ) +
  1356. ylab("Peak amplitude") +
  1357. xlab("Slow wave amplitude") +
  1358. # labs(size = "Proportion") +
  1359. facet_wrap(~Patient, ncol = 4, scales = "free") +
  1360. theme(aspect.ratio = 1)
  1361. ggsave("D:/Dropbox/Apps/Overleaf/Hspike/images/amp_corr.pdf", width = 7, height = 4, units = "in")
  1362. #########################
  1363. ## STATISTICS LFP peaks #
  1364. #########################
  1365. # prepare data
  1366. data_amp <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/amplitude_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  1367. data_amp <- data_amp[!data_amp$hyplabel == "NO_SCORE", ]
  1368. data_amp <- data_amp[!data_amp$hyplabel == "NO_SCORE", ]
  1369. data_amp$hyplabel[data_amp$hyplabel == "PHASE_1"] = "S1"
  1370. data_amp$hyplabel[data_amp$hyplabel == "PHASE_2"] = "S2"
  1371. data_amp$hyplabel[data_amp$hyplabel == "PHASE_3"] = "S3"
  1372. data_amp$hyplabel[data_amp$hyplabel == "AWAKE"] = "WASO"
  1373. data_amp$hyplabel[data_amp$hyplabel == "PRESLEEP"] = "Pre"
  1374. data_amp$hyplabel[data_amp$hyplabel == "POSTSLEEP"] = "Post"
  1375. data_amp$stage <- factor(data_amp$hyplabel, levels = c("Pre","S3", "S2", "S1", "WASO", "REM", "Post"))
  1376. data_amp$Patient <- factor(data_amp$patient, levels = c(8:1))
  1377. data_amp$night <- factor(data_amp$part)
  1378. data_amp$template <- factor(data_amp$template)
  1379. # Standardize data
  1380. y1 <- setNames(aggregate(data_amp$posamp, by = c(list(data_amp$patient, data_amp$night, data_amp$template)), mean), c("patient", "night", "template", "Mposamp"))
  1381. y2 <- setNames(aggregate(data_amp$negamp, by = c(list(data_amp$patient, data_amp$night, data_amp$template)), mean), c("patient", "night", "template", "Mnegamp"))
  1382. y1sd <- setNames(aggregate(data_amp$posamp, by = c(list(data_amp$patient, data_amp$night, data_amp$template)), sd), c("patient", "night", "template", "SDposamp"))
  1383. y2sd <- setNames(aggregate(data_amp$negamp, by = c(list(data_amp$patient, data_amp$night, data_amp$template)), sd), c("patient", "night", "template", "SDnegamp"))
  1384. data_amp <- merge(data_amp,y1)
  1385. data_amp <- merge(data_amp,y2)
  1386. data_amp <- merge(data_amp,y1sd)
  1387. data_amp <- merge(data_amp,y2sd)
  1388. data_amp$Zposamp <- (data_amp$posamp-data_amp$Mposamp)/data_amp$SDposamp
  1389. data_amp$Znegamp <- (data_amp$negamp-data_amp$Mnegamp)/data_amp$SDnegamp
  1390. data_amp$Zdiffamp <- data_amp$Zposamp - data_amp$Znegamp
  1391. # fit model
  1392. data_amp$stage = relevel(data_amp$stage, ref="Pre")
  1393. # to create p-values
  1394. detach(package:lmerTest)
  1395. library(lmerTest)
  1396. library(lme4)
  1397. lpos <- lmer(posamp ~ stage + (1 | patient) + (1 | night), data_amp, control = lmerControl(optimizer ='Nelder_Mead'))
  1398. lneg <- lmer(negamp ~ stage + (1 | night) + (1 | template) + (1 | patient), data_amp, control = lmerControl(optimizer ='Nelder_Mead'))
  1399. ldiff <- lmer(Zdiffamp ~ stage + (1 | night) + (1 | template) + (1 | patient), data_amp, control = lmerControl(optimizer ='Nelder_Mead'))
  1400. summary(lpos)
  1401. plot_model(lpos)
  1402. summary(lneg)
  1403. plot_model(lneg)
  1404. summary(ldiff)
  1405. plot_model(ldiff)
  1406. # Post-hoc tests
  1407. temp = emmeans(lpos, list(pairwise ~ stage), adjust = "tukey")
  1408. phpos <- as.data.frame(temp$`pairwise differences of stage`)
  1409. colnames(phpos) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  1410. phpos$df <- NA
  1411. temp = emmeans(lneg, list(pairwise ~ stage), adjust = "tukey")
  1412. phneg <- as.data.frame(temp$`pairwise differences of stage`)
  1413. colnames(phneg) <- c("Comparison","EstimateNeg","SENeg","dfNeg","Z ratioNeg","pNeg")
  1414. phneg$dfNeg <- NA
  1415. temp = emmeans(ldiff, list(pairwise ~ stage), adjust = "tukey")
  1416. phdiff <- as.data.frame(temp$`pairwise differences of stage`)
  1417. colnames(phdiff) <- c("Comparison","EstimateDiff","SEDiff","dfDiff","Z ratioDiff","pDiff")
  1418. phdiff$dfDiff <- NA
  1419. # Mathematical description of the model and write to latex
  1420. # eq <- equatiomatic::extract_eq(lpos)
  1421. # fileConn<-file("D:/Dropbox/Apps/Overleaf/Hspike/formula/model_posamp.tex")
  1422. # writeLines(c("$$",eq,"$$"), fileConn)
  1423. # close(fileConn)
  1424. #############################################
  1425. # Coefficients to LaTeX table (and reorder) #
  1426. #############################################
  1427. # Model coefficients for LaTeX table
  1428. temp = summary(lpos)
  1429. spos <- temp$coefficients
  1430. spos <- data.frame(Predictor = row.names(spos), spos);
  1431. rownames(spos) <- NULL
  1432. colnames(spos) <- c("Predictor","Estimate","SD","df","t","p")
  1433. temp = summary(lneg)
  1434. sneg <- temp$coefficients
  1435. sneg <- data.frame(Predictor = row.names(sneg), sneg)
  1436. colnames(sneg) <- c("Predictor","EstimateNeg","SDNeg","dfNeg","tNeg","pNeg")
  1437. temp = summary(lneg)
  1438. sdiff <- temp$coefficients
  1439. sdiff <- data.frame(Predictor = row.names(sdiff), sdiff)
  1440. colnames(sdiff) <- c("Predictor","EstimatePos","SDDiff","dfDiff","tDiff","pDiff")
  1441. sneg$id <- 1:nrow(sneg)
  1442. coef <- merge(spos, sneg)
  1443. coef <- merge(coef, sdiff)
  1444. coef <- coef[order(coef$id), ]
  1445. coef <- coef[, c(-1, -12)]
  1446. rownames(coef) <- NULL
  1447. coef[, 3] = round(coef[,3],digits=0)
  1448. coef[, 8] = round(coef[,8],digits=0)
  1449. coef[,13] = round(coef[,8],digits=0)
  1450. coef$Predictor <- c("\\textit{Intercept}","S3", "S2", "S1", "WASO", "Post", "REM")
  1451. coef <- coef[, c(16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)]
  1452. # Post-hoc comparisons
  1453. phneg$id <- 1:nrow(phneg)
  1454. ph <- merge(phpos,phneg)
  1455. ph <- merge(ph,phdiff)
  1456. ph <- ph[order(ph$id), ]
  1457. ph <- ph[, -12]
  1458. rownames(ph) <- NULL
  1459. # Concatenate in one LaTeX table
  1460. colnames(ph) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","df", "z", "\\textit{p}",
  1461. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}",
  1462. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}")
  1463. colnames(coef) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","df", "z", "\\textit{p}",
  1464. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}",
  1465. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}")
  1466. stats_amp <- bind_rows(coef,ph)
  1467. colnames(stats_amp) <- c("", "Coef $\\beta$","SE($\\beta$)","df", "z", "\\textit{p}",
  1468. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}",
  1469. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}")
  1470. stats_amp[,6] = ifelse(stats_amp[,6] > .05, paste(round(stats_amp[,6],digits=2),sep=""),
  1471. ifelse(stats_amp[,6] < .0001, "<.0001\\textsuperscript{***}",
  1472. ifelse(stats_amp[,6] < .001,"<.001\\textsuperscript{**}",
  1473. ifelse(stats_amp[,6] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1474. stats_amp[,11] = ifelse(stats_amp[,11] > .05, paste(round(stats_amp[,11],digits=2),sep=""),
  1475. ifelse(stats_amp[,11] < .0001, "<.0001\\textsuperscript{***}",
  1476. ifelse(stats_amp[,11] < .001,"<.001\\textsuperscript{**}",
  1477. ifelse(stats_amp[,11] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1478. stats_amp[,16] = ifelse(stats_amp[,16] > .05, paste(round(stats_amp[,16],digits=2),sep=""),
  1479. ifelse(stats_amp[,16] < .0001, "<.0001\\textsuperscript{***}",
  1480. ifelse(stats_amp[,16] < .001,"<.001\\textsuperscript{**}",
  1481. ifelse(stats_amp[,16] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1482. options(knitr.kable.NA = '')
  1483. kbl(stats_amp, "latex", booktabs = T, linesep = "", label = 'stats_amp',
  1484. escape = FALSE, digits = 2,
  1485. caption = "Effect of sleep stage on ERP peak amplitude")%>%
  1486. kable_styling(latex_options = c("HOLD_position"))%>%
  1487. pack_rows("Sleep stages", 1, 7) %>% # latex_gap_space = "2em"
  1488. pack_rows("Post-hoc comparisons", 8, 28) %>%
  1489. add_header_above(c(" ", "Spike amplitude" = 5, "Slow wave amplitude" = 5, "Difference amplitude" = 5)) %>%
  1490. kable_styling(latex_options = c("scale_down"))%>%
  1491. footnote(general_title = "",
  1492. footnote_as_chunk = TRUE,
  1493. threeparttable = TRUE,
  1494. escape = FALSE,
  1495. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  1496. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/stats_amp.tex")
  1497. #################
  1498. ## Plot models ##
  1499. #################
  1500. set_theme(
  1501. base = theme_article(),
  1502. # panel.bordercol = NA
  1503. )
  1504. plot_amp_pos_model <- plot_model(
  1505. lpos,
  1506. title = "",
  1507. colors = "bw",
  1508. axis.labels = "",
  1509. axis.title = "",
  1510. show.values = TRUE,
  1511. show.p = TRUE,
  1512. decimals = 4,
  1513. digits = 2,
  1514. value.offset = 0.5,
  1515. value.size = 2.5) +
  1516. font_size(labels.x = 9, labels.y = 9) +
  1517. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1518. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1519. scale_y_continuous(breaks=c(-20, 0, 50, 100, 150))
  1520. plot_amp_pos_model$data$title = "Model fixed effects"
  1521. plot_amp_pos_model <- plot_amp_pos_model + facet_wrap(~title, scales="free_y")
  1522. plot_amp_neg_model <- plot_model(
  1523. lneg,
  1524. title = "",
  1525. colors = "bw",
  1526. axis.labels = "",
  1527. axis.title = "",
  1528. show.values = TRUE,
  1529. show.p = TRUE,
  1530. decimals = 4,
  1531. digits = 2,
  1532. value.offset = 0.5,
  1533. value.size = 2.5) +
  1534. font_size(labels.x = 9, labels.y = 9) +
  1535. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1536. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1537. scale_y_continuous(breaks=c(0, 50, 100, 150))
  1538. plot_amp_neg_model$data$title = "Model fixed effects"
  1539. plot_amp_neg_model <- plot_amp_neg_model + facet_wrap(~title, scales="free_y")
  1540. plot_amp_diff_model <- plot_model(
  1541. ldiff,
  1542. title = "",
  1543. colors = "bw",
  1544. axis.labels = "",
  1545. axis.title = "",
  1546. show.values = TRUE,
  1547. show.p = TRUE,
  1548. decimals = 4,
  1549. digits = 2,
  1550. value.offset = 0.5,
  1551. value.size = 2.5) +
  1552. font_size(labels.x = 9, labels.y = 9) +
  1553. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1554. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1555. scale_y_continuous(breaks=c(-0.4, -0.2, 0, 0.2, 0.4))
  1556. plot_amp_diff_model$data$title = "Model fixed effects"
  1557. plot_amp_diff_model <- plot_amp_diff_model + facet_wrap(~title, scales="free_y")
  1558. ###############################
  1559. # Boxplots together in Figure #
  1560. ###############################
  1561. ggarrange(plot_amp_pos, plot_amp_pos_model, plot_amp_neg, plot_amp_neg_model, plot_amp_diff, plot_amp_diff_model,
  1562. ncol = 2, nrow = 3,
  1563. vjust = 1.5, hjust = -1,
  1564. labels = c("A","B","C","D","E","F","G","H"),
  1565. legend = "right",
  1566. common.legend = TRUE,
  1567. font.label = list(size = 14, color = "black", face = "bold")) %>%
  1568. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/images/amp_boxplots.pdf")
  1569. ######################################
  1570. # Plot normalized PSTH & sleep stage #
  1571. ######################################
  1572. # prepare data
  1573. data_psth <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/psth_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  1574. data_psth$hyplabel[data_psth$hyplabel == "Wake"] = "WASO"
  1575. data_psth$hyplabel <- factor(data_psth$hyplabel, levels = c("Pre", "Post", "REM", "WASO", "S1", "S2", "S3"))
  1576. data_psth$Patient <- factor(data_psth$Patient, levels = c(8:1))
  1577. data_psth$part <- factor(data_psth$part)
  1578. data_psth$template <- factor(data_psth$template)
  1579. data_psth$unit <- factor(data_psth$unit)
  1580. data_psth$Type <- factor(data_psth$SUA)
  1581. # data_sel <- data_psth[data_psth$hyplabel=="S1", ]
  1582. data_sel <- setNames(aggregate(data_psth$responsive, by = c(list(data_psth$Patient, data_psth$part, data_psth$unit, data_psth$Type)), mean), c("Patient", "part", "unit", "Type", "responsive"))
  1583. data_sel$responsive = as.integer(data_sel$responsive > 0)
  1584. t = data_sel %>% count(Patient, part, responsive, Type)
  1585. t2 <- pivot_wider(t, names_from = "Type", names_prefix = "SUA", values_from = "n")
  1586. t3 <- pivot_wider(t2, names_from = "responsive", names_prefix = "responsive", values_from = c("SUA1", "SUA0"))
  1587. # t4 <- pivot_wider(t, names_from = c("responsive", "Type"), values_from = c("n"))
  1588. #
  1589. # ############# USE THISFOR TABLE OF SUA/MUA reporting ###############
  1590. #
  1591. #
  1592. # test <- setNames(aggregate(data_psth$responsive, by = c(list(data_psth$Patient, data_psth$unit, data_psth$template, data_psth$Type)), mean), c("Patient", "unit", "template", "Type", "responsive"))
  1593. #
  1594. # # select responsive units
  1595. # data_psth <- data_psth[c(data_psth$responsive == 1), ]
  1596. #
  1597. # # remove unresponsive patient - already done in MATLAB
  1598. # # data_psth <- data_psth[-c(data_psth$Patient == 7), ]
  1599. #
  1600. # # select SUA
  1601. # # data_psth <- data_psth[c(data_psth$SUA == 1), ]
  1602. posrate <- setNames(aggregate(data_psth$posrate, by = c(list(data_psth$Patient, data_psth$unit, data_psth$template, data_psth$hyplabel, data_psth$Type)), mean), c("Patient", "unit", "template", "hyplabel", "Type", "posrate"))
  1603. negrate <- setNames(aggregate(data_psth$negrate, by = c(list(data_psth$Patient, data_psth$unit, data_psth$template, data_psth$hyplabel, data_psth$Type)), mean), c("Patient", "unit", "template", "hyplabel", "Type", "negrate"))
  1604. data_psth_mean <- merge(posrate, negrate)
  1605. y1 <- setNames(aggregate(data_psth_mean$posrate, by = c(list(data_psth_mean$Patient, data_psth_mean$unit, data_psth_mean$template, data_psth_mean$Type)), mean), c("Patient", "unit", "template", "Type", "Mposrate"))
  1606. y1sd <- setNames(aggregate(data_psth_mean$posrate, by = c(list(data_psth_mean$Patient, data_psth_mean$unit, data_psth_mean$template, data_psth_mean$Type)), sd), c("Patient", "unit", "template", "Type", "SDposrate"))
  1607. y2 <- setNames(aggregate(data_psth_mean$negrate, by = c(list(data_psth_mean$Patient, data_psth_mean$unit, data_psth_mean$template, data_psth_mean$Type)), mean), c("Patient", "unit", "template", "Type", "Mnegrate"))
  1608. y2sd <- setNames(aggregate(data_psth_mean$negrate, by = c(list(data_psth_mean$Patient, data_psth_mean$unit, data_psth_mean$template, data_psth_mean$Type)), sd), c("Patient", "unit", "template", "Type", "SDnegrate"))
  1609. data_psth_mean <- merge(data_psth_mean,y1)
  1610. data_psth_mean <- merge(data_psth_mean,y2)
  1611. data_psth_mean <- merge(data_psth_mean,y1sd)
  1612. data_psth_mean <- merge(data_psth_mean,y2sd)
  1613. data_psth_mean$Zposrate <- (data_psth_mean$posrate-data_psth_mean$Mposrate)/data_psth_mean$SDposrate
  1614. data_psth_mean$Znegrate <- (data_psth_mean$negrate-data_psth_mean$Mnegrate)/data_psth_mean$SDnegrate
  1615. data_psth_mean$diffrate <- data_psth_mean$Zposrate - data_psth_mean$Znegrate
  1616. # plot
  1617. data_psth_mean$title1 = "Standardized firingrate during spike"
  1618. data_psth_mean$title2 = "Standardized firingrate during slow wave"
  1619. data_psth_mean$title3 = "Relative difference"
  1620. data_psth_mean_sel <- data_psth_mean[!data_psth_mean$hyplabel=="Pre", ]
  1621. plot_cnt_pos <- ggplot(data=data_psth_mean_sel, aes(y=hyplabel, x=Zposrate)) +
  1622. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1623. geom_boxplot(outlier.shape = NA) +
  1624. geom_point(aes(group = interaction(Patient, unit), col = Patient, shape = Type), position=position_dodge(width=0.5), alpha = 0.2, size = 0.8) +
  1625. geom_point(data=data_psth_mean_sel[data_psth_mean_sel$Type == 1, ],
  1626. aes(group = interaction(Patient, unit), col = Patient, shape = Type), position=position_dodge(width=0.5), size = 0.8) +
  1627. scale_shape_discrete(label = c("MUA", "SUA"))+
  1628. ylab(NULL) + xlab(NULL) +
  1629. theme_article() +
  1630. theme(legend.position="bottom") +
  1631. coord_cartesian(xlim = c(-2.5, 2.5)) +
  1632. scale_x_continuous(breaks = c(-2.5, 0, 2.5)) +
  1633. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  1634. facet_wrap(~title1)
  1635. plot_cnt_neg <- ggplot(data=data_psth_mean_sel, aes(y=hyplabel, x=Znegrate)) +
  1636. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1637. geom_boxplot(outlier.shape = NA) +
  1638. geom_point(aes(group = interaction(Patient, unit), col = Patient, shape = Type), position=position_dodge(width=0.5), alpha = 0.2, size = 0.8) +
  1639. geom_point(data=data_psth_mean_sel[data_psth_mean_sel$Type == 1, ],
  1640. aes(group = interaction(Patient, unit), col = Patient, shape = Type), position=position_dodge(width=0.5), size = 0.8) +
  1641. scale_shape_discrete(label = c("MUA", "SUA"))+
  1642. ylab(NULL) + xlab(NULL) +
  1643. theme_article() +
  1644. theme(legend.position="bottom") +
  1645. coord_cartesian(xlim = c(-2.5, 2.5)) +
  1646. scale_x_continuous(breaks = c(-2.5, 0, 2.5)) +
  1647. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  1648. facet_wrap(~title2)
  1649. plot_cnt_diff <- ggplot(data=data_psth_mean_sel, aes(y=hyplabel, x=diffrate)) +
  1650. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1651. geom_boxplot(outlier.shape = NA) +
  1652. geom_point(aes(group = interaction(Patient, unit), col = Patient, shape = Type), position=position_dodge(width=0.5), alpha = 0.2, size = 0.8) +
  1653. geom_point(data=data_psth_mean_sel[data_psth_mean_sel$Type == 1, ],
  1654. aes(group = interaction(Patient, unit), col = Patient, shape = Type), position=position_dodge(width=0.5), size = 0.8) +
  1655. scale_shape_discrete(label = c("MUA", "SUA"))+
  1656. ylab(NULL) + xlab(NULL) +
  1657. theme_article() +
  1658. theme(legend.position="bottom") +
  1659. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  1660. coord_cartesian(xlim = c(-4, 4)) +
  1661. scale_x_continuous(breaks = c(-4, 0, 4)) +
  1662. facet_wrap(~title3)
  1663. ###################################
  1664. ## STATISTICS Positive peaks PSTH #
  1665. ###################################
  1666. # to create p-values
  1667. detach(package:lmerTest)
  1668. library(lmerTest)
  1669. library(lme4)
  1670. # prepare data
  1671. data_psth <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/psth_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  1672. data_psth$hyplabel[data_psth$hyplabel == "Wake"] = "WASO"
  1673. data_psth$hyplabel <- factor(data_psth$hyplabel, levels = c("Pre", "Post", "REM", "WASO", "S1", "S2", "S3"))
  1674. data_psth$Patient <- factor(data_psth$Patient, levels = c(8:1))
  1675. data_psth$part <- factor(data_psth$part)
  1676. data_psth$template <- factor(as.integer(data_psth$template) + as.integer(data_psth$part) * 100 + as.integer(data_psth$Patient) * 1000) # beacuse template nr. resets for each night/patient
  1677. data_psth$unit <- factor(data_psth$unit)
  1678. data_psth$responsive <- factor(data_psth$responsive)
  1679. data_psth$diffrate <- data_psth$posrate - data_psth$negrate
  1680. # select responsive units
  1681. data_psth <- data_psth[c(data_psth$responsive == 1), ]
  1682. # remove unresponsive patient
  1683. # data_psth <- data_psth[-c(data_psth$Patient == 7), ]
  1684. # remove NaN
  1685. data_psth <- data_psth[!is.nan(data_psth$posrate), ]
  1686. # Rename for plotting
  1687. data_psth$night <- factor(data_psth$part)
  1688. # Reorder for table
  1689. data_psth$stage <- factor(data_psth$hyplabel, levels = c("Pre","S3", "S2", "S1", "WASO", "REM", "Post"))
  1690. # fit model
  1691. data_psth$stage = relevel(data_psth$stage, ref="Pre")
  1692. lpos_SUA <- lmer(posrate ~ stage + (1 | Patient) + (1 | template) + (1 | unit), data_psth[data_psth$SUA == 1, ], control = lmerControl(optimizer ='Nelder_Mead'))
  1693. lneg_SUA <- lmer(negrate ~ stage + (1 | Patient) + (1 | template) + (1 | unit), data_psth[data_psth$SUA == 1, ], control = lmerControl(optimizer ='Nelder_Mead'))
  1694. ldiff_SUA <- lmer(diffrate ~ stage + (1 | Patient) + (1 | template) + (1 | unit), data_psth[data_psth$SUA == 1, ], control = lmerControl(optimizer ='Nelder_Mead'))
  1695. lpos_MUA <- lmer(posrate ~ stage + (1 | Patient) + (1 | template) + (1 | unit), data_psth[data_psth$SUA == 0, ], control = lmerControl(optimizer ='Nelder_Mead'))
  1696. lneg_MUA <- lmer(negrate ~ stage + (1 | Patient) + (1 | template) + (1 | unit), data_psth[data_psth$SUA == 0, ], control = lmerControl(optimizer ='Nelder_Mead'))
  1697. ldiff_MUA <- lmer(diffrate ~ stage + (1 | Patient) + (1 | template) + (1 | unit), data_psth[data_psth$SUA == 0, ], control = lmerControl(optimizer ='Nelder_Mead'))
  1698. lpos <- lmer(posrate ~ stage + (1 | Patient) + (1 | template) + (1 | SUA), data_psth, control = lmerControl(optimizer ='Nelder_Mead'))
  1699. lneg <- lmer(negrate ~ stage + (1 | Patient) + (1 | template) + (1 | SUA), data_psth, control = lmerControl(optimizer ='Nelder_Mead'))
  1700. ldiff <- lmer(diffrate ~ stage + (1 | Patient) + (1 | template) + (1 | SUA), data_psth, control = lmerControl(optimizer ='Nelder_Mead'))
  1701. summary(lpos_SUA)
  1702. plot_model(lpos_SUA)
  1703. summary(lneg_SUA)
  1704. plot_model(lneg_SUA)
  1705. summary(ldiff_SUA)
  1706. plot_model(ldiff_SUA)
  1707. summary(lpos_MUA)
  1708. plot_model(lpos_MUA)
  1709. summary(lneg_MUA)
  1710. plot_model(lneg_MUA)
  1711. summary(ldiff_MUA)
  1712. plot_model(ldiff_MUA)
  1713. summary(lpos)
  1714. plot_model(lpos)
  1715. summary(lneg)
  1716. plot_model(lneg)
  1717. summary(ldiff)
  1718. plot_model(ldiff)
  1719. # Post-hoc tests
  1720. temp = emmeans(lpos, list(pairwise ~ stage), adjust = "tukey")
  1721. phpos <- as.data.frame(temp$`pairwise differences of stage`)
  1722. colnames(phpos) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  1723. phpos$df <- NA
  1724. temp = emmeans(lneg, list(pairwise ~ stage), adjust = "tukey")
  1725. phneg <- as.data.frame(temp$`pairwise differences of stage`)
  1726. colnames(phneg) <- c("Comparison","EstimateNeg","SENeg","dfNeg","Z ratioNeg","pNeg")
  1727. temp = emmeans(lneg, list(pairwise ~ stage), adjust = "tukey")
  1728. phneg <- as.data.frame(temp$`pairwise differences of stage`)
  1729. colnames(phneg) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  1730. phneg$df <- NA
  1731. temp = emmeans(ldiff, list(pairwise ~ stage), adjust = "tukey")
  1732. phdiff <- as.data.frame(temp$`pairwise differences of stage`)
  1733. colnames(phdiff) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  1734. phdiff$df <- NA
  1735. #########################################
  1736. # Model coefficients to table for LaTeX #
  1737. #########################################
  1738. # Model coefficients for table
  1739. temp = summary(lpos)
  1740. spos <- temp$coefficients
  1741. spos <- data.frame(Predictor = row.names(spos), spos);
  1742. rownames(spos) <- NULL
  1743. colnames(spos) <- c("Predictor","Estimate","SD","df","t","p")
  1744. temp = summary(lneg)
  1745. sneg <- temp$coefficients
  1746. sneg <- data.frame(Predictor = row.names(sneg), sneg);
  1747. rownames(sneg) <- NULL
  1748. colnames(sneg) <- c("Predictor","Estimate","SD","df","t","p")
  1749. temp = summary(ldiff)
  1750. sdiff <- temp$coefficients
  1751. sdiff <- data.frame(Predictor = row.names(sdiff), sdiff);
  1752. rownames(sdiff) <- NULL
  1753. colnames(sdiff) <- c("Predictor","Estimate","SD","df","t","p")
  1754. # to LaTeX table (and reorder)
  1755. sneg$id <- 1:nrow(sneg)
  1756. coef <- merge(sneg, spos, by="Predictor")
  1757. coef <- merge(coef, sdiff, by="Predictor")
  1758. coef <- coef[order(coef$id), ]
  1759. coef <- coef[, c(-1, -7)]
  1760. rownames(coef) <- NULL
  1761. coef[,3] = round(coef[,3],digits=0)
  1762. coef[,8] = round(coef[,8],digits=0)
  1763. coef[,13] = round(coef[,13],digits=0)
  1764. coef$Predictor <- c("\\textit{Intercept}","S3", "S2", "S1", "WASO", "Post", "REM")
  1765. coef <- coef[, c(16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)]
  1766. # posthoc coefficients
  1767. phneg$id <- 1:nrow(phneg)
  1768. ph <- merge(phneg,phpos, by = "Comparison")
  1769. ph <- merge(ph,phdiff, by = "Comparison")
  1770. ph <- ph[order(ph$id), ]
  1771. ph <- ph[, -7]
  1772. rownames(ph) <- NULL
  1773. # Concatenate in one LaTeX table
  1774. colnames(ph) <- c("Predictor",
  1775. "Coef $\\beta$","SE($\\beta$)","df", "z", "\\textit{p}",
  1776. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}",
  1777. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}")
  1778. colnames(coef) <- c("Predictor",
  1779. "Coef $\\beta$","SE($\\beta$)","df", "z", "\\textit{p}",
  1780. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}",
  1781. "Coef $\\beta$","SE($\\beta$)","df","z", "\\textit{p}")
  1782. stats_cnt <- bind_rows(coef,ph)
  1783. colnames(stats_cnt) <- c("", "Coef $\\beta$","SE($\\beta$)","df", "z",
  1784. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  1785. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  1786. "\\textit{p}")
  1787. stats_cnt[,6] = ifelse(stats_cnt[,6] > .05, paste(round(stats_cnt[,6],digits=2),sep=""),
  1788. ifelse(stats_cnt[,6] < .0001, "<.0001\\textsuperscript{***}",
  1789. ifelse(stats_cnt[,6] < .001,"<.001\\textsuperscript{**}",
  1790. ifelse(stats_cnt[,6] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1791. stats_cnt[,11] = ifelse(stats_cnt[,11] > .05, paste(round(stats_cnt[,11],digits=2),sep=""),
  1792. ifelse(stats_cnt[,11] < .0001, "<.0001\\textsuperscript{***}",
  1793. ifelse(stats_cnt[,11] < .001,"<.001\\textsuperscript{**}",
  1794. ifelse(stats_cnt[,11] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1795. stats_cnt[,16] = ifelse(stats_cnt[,16] > .05, paste(round(stats_cnt[,16],digits=2),sep=""),
  1796. ifelse(stats_cnt[,16] < .0001, "<.0001\\textsuperscript{***}",
  1797. ifelse(stats_cnt[,16] < .001,"<.001\\textsuperscript{**}",
  1798. ifelse(stats_cnt[,16] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  1799. options(knitr.kable.NA = '')
  1800. kbl(stats_cnt, "latex", booktabs = T, linesep = "", label = 'unit_stats',
  1801. escape = FALSE, digits = 2,
  1802. caption = "Effect of sleep stage on firing rates during IED")%>%
  1803. kable_styling(latex_options = c("HOLD_position"))%>%
  1804. pack_rows("Sleep stages", 1, 7) %>% # latex_gap_space = "2em"
  1805. pack_rows("Post-hoc comparisons", 8, 28) %>%
  1806. add_header_above(c(" ", "Spike" = 5, "Wave" = 5, "Ratio" = 5)) %>%
  1807. kable_styling(latex_options = c("scale_down"))%>%
  1808. footnote(general_title = "",
  1809. footnote_as_chunk = TRUE,
  1810. threeparttable = TRUE,
  1811. escape = FALSE,
  1812. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  1813. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/unit_stats.tex")
  1814. #################
  1815. ## Plot models ##
  1816. #################
  1817. set_theme(
  1818. base = theme_article(),
  1819. # panel.bordercol = NA
  1820. )
  1821. plot_cnt_pos_model <- plot_model(
  1822. lpos,
  1823. title = "",
  1824. colors = "bw",
  1825. axis.labels = "",
  1826. axis.title = "",
  1827. show.values = TRUE,
  1828. show.p = TRUE,
  1829. decimals = 4,
  1830. digits = 2,
  1831. value.offset = 0.5,
  1832. value.size = 2.5) +
  1833. # ylim(-5, 6) +
  1834. font_size(labels.y = 9, labels.x = 9) +
  1835. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1836. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1837. scale_y_continuous(limits = c(-6, 8), breaks = c(-6, 0, 8))
  1838. plot_cnt_pos_model$data$title = "Model of spike count during LFP spike (vs. Pre-sleep)"
  1839. plot_cnt_pos_model$data$title = "Model fixed effects"
  1840. plot_cnt_pos_model <- plot_cnt_pos_model + facet_wrap(~title, scales="free_y")
  1841. plot_cnt_neg_model <- plot_model(
  1842. lneg,
  1843. title = "",
  1844. colors = "bw",
  1845. axis.labels = "",
  1846. axis.title = "",
  1847. show.values = TRUE,
  1848. show.p = TRUE,
  1849. decimals = 4,
  1850. digits = 2,
  1851. value.offset = 0.5,
  1852. value.size = 2.5) +
  1853. ylim(-3, 2) +
  1854. font_size(labels.y = 9, labels.x = 9) +
  1855. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1856. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1857. scale_y_continuous(limits = c(-3, 2), breaks = c(-3, 0, 2))
  1858. plot_cnt_neg_model$data$title = "Model of spike count during slow-wave (vs. Pre-sleep)"
  1859. plot_cnt_neg_model$data$title = "Model fixed effects"
  1860. plot_cnt_neg_model <- plot_cnt_neg_model + facet_wrap(~title, scales="free_y")
  1861. plot_cnt_diff_model <- plot_model(
  1862. ldiff,
  1863. title = "",
  1864. colors = "bw",
  1865. axis.labels = "",
  1866. axis.title = "",
  1867. show.values = TRUE,
  1868. show.p = TRUE,
  1869. decimals = 4,
  1870. digits = 2,
  1871. value.offset = 0.5,
  1872. value.size = 2.5) +
  1873. ylim(-5, 7) +
  1874. font_size(labels.y = 9, labels.x = 9) +
  1875. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  1876. labels=c("Post","REM","WASO","S1","S2","S3")) +
  1877. scale_y_continuous(limits = c(-5, 7), breaks = c(-5, 0, 7))
  1878. plot_cnt_diff_model$data$title = "Model of spike count difference between LFP spike & slow wave (vs. Pre-sleep)"
  1879. plot_cnt_diff_model$data$title = "Model fixed effects"
  1880. plot_cnt_diff_model <- plot_cnt_diff_model + facet_wrap(~title, scales="free_y")
  1881. ggarrange(plot_cnt_pos, plot_cnt_pos_model, plot_cnt_neg, plot_cnt_neg_model, plot_cnt_diff, plot_cnt_diff_model,
  1882. ncol = 2, nrow = 3,
  1883. vjust = 1.5, hjust = -1,
  1884. labels = c("A","B","C","D","E","F","G","H"),
  1885. legend = "right",
  1886. common.legend = TRUE,
  1887. font.label = list(size = 14, color = "black", face = "bold")) %>%
  1888. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/images/unit_timelocked_boxplots.pdf")
  1889. #########################################
  1890. # Plot correlation between LFP and PSTH #
  1891. #########################################
  1892. # prepare data
  1893. data_rho <- read.csv(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/data/hspike/rho_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  1894. data_rho$Patient <- factor(data_rho$Patient, levels = c(8:1))
  1895. data_rho$part <- factor(data_rho$part)
  1896. data_rho$template <- factor(data_rho$template)
  1897. data_rho$unit <- factor(data_rho$unit)
  1898. # select responsive units
  1899. # data_rho <- data_rho[c(data_rho$responsive == 1), ]
  1900. plot_rho <- ggplot(data=data_rho, aes(y=Patient, x=corr_rho)) +
  1901. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  1902. geom_boxplot(outlier.shape = NA) +
  1903. geom_point(aes(group = interaction(Patient, unit), col = Patient), position=position_dodge(width=0.3), alpha = 0.5) +
  1904. # guides(colour = "none") +
  1905. ylab(NULL) + xlab(NULL) +
  1906. theme_article() +
  1907. theme(legend.position="bottom") +
  1908. coord_cartesian(xlim = c(-0.6, 0.6))
  1909. final_plot = ggarrange(plot_rho,
  1910. nrow = 1, ncol = 1,
  1911. vjust = 1.5, hjust = -1,
  1912. legend = "bottom",
  1913. font.label = list(size = 14, color = "black", face = "bold")) %>%
  1914. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Hspike/images/rho_boxplots.pdf")
  1915. ##########
  1916. # Combine:
  1917. data_psth
  1918. data_amp
  1919. ###########################
  1920. # Unit baseline behaviour #
  1921. ###########################
  1922. data_window <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/window_spike_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  1923. data_window$hyplabel[data_window$hyplabel == "Wake"] = "WASO"
  1924. data_window$hyplabel <- factor(data_window$hyplabel, levels = c("Pre", "Post", "REM", "WASO", "S1", "S2", "S3"))
  1925. data_window$Patient <- factor(data_window$patient, levels = c(8:1))
  1926. data_window$Night <- factor(data_window$part)
  1927. data_window$Unit <- factor(data_window$unit)
  1928. data_window$responsive <- factor(data_window$responsive)
  1929. data_window$Type <- factor(data_window$Type)
  1930. levels(data_window$Type)[levels(data_window$Type)=="good"] <- "SUA"
  1931. levels(data_window$Type)[levels(data_window$Type)=="mua"] <- "MUA"
  1932. data_window$Type <- factor(ordered(data_window$Type, levels = c("MUA", "SUA")))
  1933. data_sel <- na.omit(data_window) # removing rows with missing data
  1934. data_sel <- data_sel[data_sel$BAD_cnt == 0, ] # removing rows with artefacts
  1935. data_sel <- data_sel[data_sel$IEDsum == 0, ] # removing windows with IEDs
  1936. data_CV2 <- setNames(aggregate(data_sel$CV2_trial, by = c(list(data_sel$Patient, data_sel$Unit, data_sel$Type, data_sel$hyplabel)), mean), c("Patient", "unit", "Type", "hyplabel", "CV2"))
  1937. data_CV2_burst <- setNames(aggregate(data_sel$CV2_intraburst_trial,
  1938. by = c(list(data_sel$Patient, data_sel$Unit, data_sel$Type, data_sel$hyplabel)), mean), c("Patient", "unit", "Type", "hyplabel", "CV2_burst"))
  1939. data_FR <- setNames(aggregate(data_sel$trialfreq, by = c(list(data_sel$Patient, data_sel$Unit, data_sel$Type, data_sel$hyplabel)), mean), c("Patient", "unit", "Type", "hyplabel", "FR"))
  1940. data_FRcor <- setNames(aggregate(data_sel$trialfreq_corrected, by = c(list(data_sel$Patient, data_sel$Unit, data_sel$Type, data_sel$hyplabel)), mean), c("Patient", "unit", "Type", "hyplabel", "FRcor"))
  1941. data_burst <- setNames(aggregate(data_sel$burst_trialsum, by = c(list(data_sel$Patient, data_sel$Unit, data_sel$Type, data_sel$hyplabel)), mean), c("Patient", "unit", "Type", "hyplabel", "Bursts"))
  1942. data_amp <- setNames(aggregate(data_sel$amplitude, by = c(list(data_sel$Patient, data_sel$Unit, data_sel$Type, data_sel$hyplabel)), mean), c("Patient", "unit", "Type", "hyplabel", "Amplitude"))
  1943. data_rpv <- setNames(aggregate(data_sel$RPV, by = c(list(data_sel$Patient, data_sel$Unit, data_sel$Type, data_sel$hyplabel)), mean), c("Patient", "unit", "Type", "hyplabel", "RPV"))
  1944. data_mean <- merge(data_CV2, data_FR)
  1945. data_mean <- merge(data_mean, data_FRcor)
  1946. data_mean <- merge(data_mean, data_burst)
  1947. data_mean <- merge(data_mean, data_amp)
  1948. data_mean <- merge(data_mean, data_rpv)
  1949. data_mean <- merge(data_mean, data_CV2_burst)
  1950. # relative to pre-sleep
  1951. temp <- data_CV2
  1952. names(temp)[names(temp) == "CV2"] <- "Pre_CV2"
  1953. temp <- temp[temp$hyplabel=="Pre", ]
  1954. temp <- subset(temp, select = -c(hyplabel))
  1955. data_mean <- merge(data_mean, temp)
  1956. data_mean$CV2_rel <- (data_mean$CV2-data_mean$Pre_CV2) / (data_mean$CV2+data_mean$Pre_CV2)
  1957. temp <- data_CV2_burst
  1958. names(temp)[names(temp) == "CV2_burst"] <- "Pre_CV2_burst"
  1959. temp <- temp[temp$hyplabel=="Pre", ]
  1960. temp <- subset(temp, select = -c(hyplabel))
  1961. data_mean <- merge(data_mean, temp)
  1962. data_mean$CV2_burst_rel <- (data_mean$CV2_burst-data_mean$Pre_CV2_burst) / (data_mean$CV2_burst+data_mean$Pre_CV2_burst)
  1963. temp <- data_FR
  1964. names(temp)[names(temp) == "FR"] <- "Pre_FR"
  1965. temp <- temp[temp$hyplabel=="Pre", ]
  1966. temp <- subset(temp, select = -c(hyplabel))
  1967. data_mean <- merge(data_mean, temp)
  1968. data_mean$FR_rel <- (data_mean$FR-data_mean$Pre_FR) / (data_mean$FR+data_mean$Pre_FR)
  1969. temp <- data_FRcor
  1970. names(temp)[names(temp) == "FRcor"] <- "Pre_FRcor"
  1971. temp <- temp[temp$hyplabel=="Pre", ]
  1972. temp <- subset(temp, select = -c(hyplabel))
  1973. data_mean <- merge(data_mean, temp)
  1974. data_mean$FRcor_rel <- (data_mean$FRcor-data_mean$Pre_FRcor) / (data_mean$FRcor+data_mean$Pre_FRcor)
  1975. temp <- data_amp
  1976. names(temp)[names(temp) == "Amplitude"] <- "Pre_Amplitude"
  1977. temp <- temp[temp$hyplabel=="Pre", ]
  1978. temp <- subset(temp, select = -c(hyplabel))
  1979. data_mean <- merge(data_mean, temp)
  1980. data_mean$Amplitude_rel <- (data_mean$Amplitude-data_mean$Pre_Amplitude) / (data_mean$Amplitude+data_mean$Pre_Amplitude)
  1981. temp <- data_burst
  1982. names(temp)[names(temp) == "Bursts"] <- "Pre_Bursts"
  1983. temp <- temp[temp$hyplabel=="Pre", ]
  1984. temp <- subset(temp, select = -c(hyplabel))
  1985. data_mean <- merge(data_mean, temp)
  1986. data_mean$Bursts_rel <- (data_mean$Bursts-data_mean$Pre_Bursts) / (data_mean$Bursts+data_mean$Pre_Bursts)
  1987. # Normalize per unit
  1988. # FRmean <- setNames(aggregate(data_mean_sel$FR_corrected, by = c(list(data_mean_sel$unit)), mean), c("unit", "FRmean"))
  1989. # FRsd <- setNames(aggregate(data_mean_sel$FR_corrected, by = c(list(data_mean_sel$unit)), sd), c("unit", "FRsd"))
  1990. # data_mean_sel <- merge(data_mean_sel,FRmean)
  1991. # data_mean_sel <- merge(data_mean_sel,FRsd)
  1992. # data_mean_sel$FR_standardized <- (data_mean_sel$FR_corrected-data_mean_sel$FRmean)/data_mean_sel$FRsd
  1993. #
  1994. # Ampmean <- setNames(aggregate(data_mean_sel$Amplitude, by = c(list(data_mean_sel$unit)), mean), c("unit", "Ampmean"))
  1995. # Ampsd <- setNames(aggregate(data_mean_sel$Amplitude, by = c(list(data_mean_sel$unit)), sd), c("unit", "Ampsd"))
  1996. # data_mean_sel <- merge(data_mean_sel,Ampmean)
  1997. # data_mean_sel <- merge(data_mean_sel,Ampsd)
  1998. # data_mean_sel$Amp_standardized <- (data_mean_sel$Amplitude-data_mean_sel$Ampmean)/data_mean_sel$Ampsd
  1999. # plot
  2000. data_mean_sel <- data_mean[!data_mean$hyplabel == "Pre", ] # Remove for plotting
  2001. data_mean_sel$title_CV2 = "CV2 (inter-spike intervals)"
  2002. data_mean_sel$title_CV2_burst = "CV2 (inter-burst intervals)"
  2003. data_mean_sel$title_FR = "Firing rate"
  2004. data_mean_sel$title_FRcor = "Firing rate corrected"
  2005. data_mean_sel$title_SUA_FRcor = "Standardized firing rate (SUA)"
  2006. data_mean_sel$title_MUA_FRcor = "Standardized firing rate (MUA)"
  2007. data_mean_sel$title_Amp = "Standardized amplitude"
  2008. data_mean_sel$title_Burst = "Standardized burst rate"
  2009. FR_plot <-
  2010. ggplot(data=data_mean_sel, aes(y=hyplabel, x=FR_rel )) +
  2011. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2012. geom_boxplot(outlier.shape = NA) +
  2013. geom_point(size = 0.8,
  2014. aes(group = interaction(Patient, unit), col = Patient, shape = Type, fill = Patient),
  2015. position = position_dodge(width = 0.5)) +
  2016. scale_shape_manual(name = "Unit type", labels = c("MUA", "SUA"), values = c(15, 17)) +
  2017. scale_alpha(guide = 'none') +
  2018. ylab(NULL) + xlab(NULL) +
  2019. theme_article() +
  2020. coord_cartesian(xlim = c(-1, 1)) +
  2021. scale_x_continuous(breaks = c(-1, 0, 1)) +
  2022. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  2023. facet_wrap(~title_FR)
  2024. FRcor_SUA_plot <-
  2025. ggplot(data=data_mean_sel[data_mean_sel$Type=="SUA", ], aes(y=hyplabel, x=FRcor_rel )) +
  2026. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2027. geom_boxplot(outlier.shape = NA) +
  2028. geom_point(size = 0.8,
  2029. aes(group = interaction(Patient, unit), col = Patient, fill = Patient),
  2030. position = position_dodge(width = 0.5)) +
  2031. ylab(NULL) + xlab(NULL) +
  2032. theme_article() +
  2033. coord_cartesian(xlim = c(-1, 1)) +
  2034. scale_x_continuous(breaks = c(-1, 0, 1)) +
  2035. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  2036. facet_wrap(~title_SUA_FRcor)
  2037. FRcor_MUA_plot <-
  2038. ggplot(data=data_mean_sel[data_mean_sel$Type=="MUA", ], aes(y=hyplabel, x=FRcor_rel )) +
  2039. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2040. geom_boxplot(outlier.shape = NA) +
  2041. geom_point(size = 0.8,
  2042. aes(group = interaction(Patient, unit), col = Patient, fill = Patient),
  2043. position = position_dodge(width = 0.5)) +
  2044. ylab(NULL) + xlab(NULL) +
  2045. theme_article() +
  2046. coord_cartesian(xlim = c(-1, 1)) +
  2047. scale_x_continuous(breaks = c(-1, 0, 1)) +
  2048. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  2049. facet_wrap(~title_MUA_FRcor)
  2050. Amp_plot <-
  2051. ggplot(data=data_mean_sel[data_mean_sel$Type=="SUA", ], aes(y=hyplabel, x=Amplitude_rel)) +
  2052. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2053. geom_boxplot(outlier.shape = NA) +
  2054. geom_point(size = 0.8,
  2055. aes(group = interaction(Patient, unit), col = Patient, fill = Patient),
  2056. position = position_dodge(width = 0.5)) +
  2057. ylab(NULL) + xlab(NULL) +
  2058. theme_article() +
  2059. coord_cartesian(xlim = c(-0.2, 0.2)) +
  2060. scale_x_continuous(breaks = c(-0.2, 0, 0.2)) +
  2061. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  2062. facet_wrap(~title_Amp)
  2063. CV2_plot <- # original data, not relative, since CV2 is already standardized
  2064. ggplot(data=data_mean_sel[data_mean_sel$Type == "SUA", ], aes(y=hyplabel, x=CV2)) +
  2065. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2066. geom_boxplot(outlier.shape = NA) +
  2067. geom_point(size = 0.8, # shape = 17,
  2068. aes(group = interaction(Patient, unit), col = Patient, fill = Patient),
  2069. position = position_dodge(width = 0.5)) +
  2070. ylab(NULL) + xlab(NULL) +
  2071. theme_article() +
  2072. # coord_cartesian(xlim = c(-0.1, 0.1)) +
  2073. coord_cartesian(xlim = c(0.6, 1.3)) +
  2074. # scale_x_continuous(breaks = c(-0.1, 0, 0.1)) +
  2075. scale_x_continuous(breaks = c(0.6, 1, 1.3)) +
  2076. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  2077. facet_wrap(~title_CV2)
  2078. CV2_burst_plot <- # original data, not relative, since CV2 is already standardized
  2079. ggplot(data=data_mean_sel[data_mean_sel$Type == "SUA", ], aes(y=hyplabel, x=CV2_burst)) +
  2080. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2081. geom_boxplot(outlier.shape = NA) +
  2082. geom_point(size = 0.8, # shape = 17,
  2083. aes(group = interaction(Patient, unit), col = Patient, fill = Patient),
  2084. position = position_dodge(width = 0.5)) +
  2085. ylab(NULL) + xlab(NULL) +
  2086. theme_article() +
  2087. # coord_cartesian(xlim = c(-0.6, 0.6)) +
  2088. # scale_x_continuous(breaks = c(-0.6, 0, 0.6)) +
  2089. coord_cartesian(xlim = c(0, 1)) +
  2090. scale_x_continuous(breaks = c(0, 0.5, 1)) +
  2091. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  2092. facet_wrap(~title_CV2_burst)
  2093. Burst_plot <- ggplot(data=data_mean_sel[data_mean_sel$Type == "SUA", ], aes(y=hyplabel, x=Bursts_rel)) +
  2094. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2095. geom_boxplot(outlier.shape = NA) +
  2096. geom_point(size = 0.8, # shape = 17,
  2097. aes(group = interaction(Patient, unit), col = Patient, fill = Patient),
  2098. position = position_dodge(width = 0.5)) +
  2099. # scale_shape_manual(name = "Unit type", labels = c("MUA", "SUA"), values = c(15, 17)) +
  2100. # scale_shape_discrete(label = c("MUA", "SUA")) +
  2101. ylab(NULL) + xlab(NULL) +
  2102. theme_article() +
  2103. coord_cartesian(xlim = c(-0.8, 0.8)) +
  2104. scale_x_continuous(breaks = c(-0.8, 0, 0.8)) +
  2105. scale_y_discrete(expand=expansion(mult=c(0.1,0.2))) +
  2106. facet_wrap(~title_Burst)
  2107. ################
  2108. ## STATISTICS ##
  2109. ################
  2110. # to create p-values
  2111. detach(package:lmerTest)
  2112. library(lmerTest)
  2113. library(lme4)
  2114. # load and prepare data
  2115. data_window <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/window_spike_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  2116. data_window$hyplabel[data_window$hyplabel == "Wake"] = "WASO"
  2117. data_window$hyplabel <- factor(data_window$hyplabel, levels = c("Pre", "Post", "REM", "WASO", "S1", "S2", "S3"))
  2118. data_window$Patient <- factor(data_window$patient, levels = c(8:1))
  2119. data_window$Night <- factor(data_window$part)
  2120. data_window$Unit <- factor(data_window$unit + data_window$part * 100) # add becaue template nr repeats over nights
  2121. data_window$responsive <- factor(data_window$responsive)
  2122. data_window$Type <- factor(data_window$Type)
  2123. data_window$FR <- data_window$trialfreq
  2124. data_window$FRcor <- data_window$trialfreq_corrected
  2125. levels(data_window$Type)[levels(data_window$Type)=="good"] <- "SUA"
  2126. levels(data_window$Type)[levels(data_window$Type)=="mua"] <- "MUA"
  2127. data_window$Type <- ordered(data_window$Type, levels = c("MUA", "SUA"))
  2128. data_sel <- na.omit(data_window) # remove rows with missing data
  2129. data_sel <- data_sel[data_sel$BAD_cnt == 0, ] # remove rows with artefacts
  2130. data_sel <- data_sel[data_sel$IEDsum == 0, ] # remove windows with IEDs
  2131. # Reorder for table
  2132. data_sel$stage <- factor(data_sel$hyplabel, levels = c("Pre","S3", "S2", "S1", "WASO", "REM", "Post"))
  2133. # fit model
  2134. data_sel$stage = relevel(data_sel$stage, ref="Pre")
  2135. lFR <- lmer(FR ~ stage + (1 | Patient) + (1 | Unit), data_sel[data_sel$Type=="MUA", ])
  2136. lFRcor_SUA <- lmer(FRcor ~ stage + (1 | Patient) + (1 | Unit), data_sel[data_sel$Type=="SUA", ])
  2137. lFRcor_MUA <- lmer(FRcor ~ stage + (1 | Patient) + (1 | Unit), data_sel[data_sel$Type=="MUA", ])
  2138. lAmp <- lmer(amplitude ~ stage + (1 | Patient) + (1 | Unit), data_sel)
  2139. lCV2 <- lmer(CV2_trial ~ stage + (1 | Patient) + (1 | Unit), data_sel)
  2140. lCV2_burst <- lmer(CV2_intraburst_trial ~ stage + (1 | Patient) + (1 | Unit), data_sel)
  2141. lBurst <- lmer(burst_trialsum ~ stage + (1 | Patient) + (1 | Unit), data_sel)
  2142. summary(lFR)
  2143. summary(lFRcor_SUA)
  2144. summary(lFRcor_MUA)
  2145. summary(lAmp)
  2146. summary(lCV2)
  2147. summary(lCV2_burst)
  2148. summary(lBurst)
  2149. plot_model(lFR)
  2150. plot_model(lFRcor_SUA)
  2151. plot_model(lFRcor_MUA)
  2152. plot_model(lAmp)
  2153. plot_model(lCV2)
  2154. plot_model(lCV2_burst)
  2155. plot_model(lBurst)
  2156. # Post-hoc tests
  2157. temp = emmeans(lFR, list(pairwise ~ stage), adjust = "tukey")
  2158. phFR <- as.data.frame(temp$`pairwise differences of stage`)
  2159. colnames(phFR) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2160. phFR$df <- NA
  2161. temp = emmeans(lFRcor_SUA, list(pairwise ~ stage), adjust = "tukey")
  2162. phFR_SUA <- as.data.frame(temp$`pairwise differences of stage`)
  2163. colnames(phFR_SUA) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2164. phFR_SUA$df <- NA
  2165. temp = emmeans(lFRcor_MUA, list(pairwise ~ stage), adjust = "tukey")
  2166. phFR_MUA <- as.data.frame(temp$`pairwise differences of stage`)
  2167. colnames(phFR_MUA) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2168. phFR_MUA$df <- NA
  2169. temp = emmeans(lFRcor, list(pairwise ~ stage), adjust = "tukey")
  2170. phFRcor <- as.data.frame(temp$`pairwise differences of stage`)
  2171. colnames(phFRcor) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2172. phFRcor$df <- NA
  2173. temp = emmeans(lAmp, list(pairwise ~ stage), adjust = "tukey")
  2174. phAmp <- as.data.frame(temp$`pairwise differences of stage`)
  2175. colnames(phAmp) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2176. phAmp$df <- NA
  2177. temp = emmeans(lCV2, list(pairwise ~ stage), adjust = "tukey")
  2178. phCV2 <- as.data.frame(temp$`pairwise differences of stage`)
  2179. colnames(phCV2) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2180. phCV2$df <- NA
  2181. temp = emmeans(lCV2_burst, list(pairwise ~ stage), adjust = "tukey")
  2182. phCV2_burst <- as.data.frame(temp$`pairwise differences of stage`)
  2183. colnames(phCV2_burst) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2184. phCV2_burst$df <- NA
  2185. temp = emmeans(lBurst, list(pairwise ~ stage), adjust = "tukey")
  2186. phBurst <- as.data.frame(temp$`pairwise differences of stage`)
  2187. colnames(phBurst) <- c("Comparison","Estimate","SE","df","Z ratio","p")
  2188. phBurst$df <- NA
  2189. #########################################
  2190. # Model coefficients to table for LaTeX #
  2191. #########################################
  2192. # Model coefficients for table
  2193. temp = summary(lFR)
  2194. sFR <- temp$coefficients
  2195. sFR <- data.frame(Predictor = row.names(sFR), sFR);
  2196. rownames(sFR) <- NULL
  2197. colnames(sFR) <- c("Predictor","Estimate","SD","df","t","p")
  2198. temp = summary(lFRcor_SUA)
  2199. sFRcor_SUA <- temp$coefficients
  2200. sFRcor_SUA <- data.frame(Predictor = row.names(sFRcor_SUA), sFRcor_SUA);
  2201. rownames(sFRcor_SUA) <- NULL
  2202. colnames(sFRcor_SUA) <- c("Predictor","Estimate","SD","df","t","p")
  2203. temp = summary(lFRcor_MUA)
  2204. sFRcor_MUA <- temp$coefficients
  2205. sFRcor_MUA <- data.frame(Predictor = row.names(sFRcor_MUA), sFRcor_MUA);
  2206. rownames(sFRcor_MUA) <- NULL
  2207. colnames(sFRcor_MUA) <- c("Predictor","Estimate","SD","df","t","p")
  2208. temp = summary(lAmp)
  2209. sAmp <- temp$coefficients
  2210. sAmp <- data.frame(Predictor = row.names(sAmp), sAmp);
  2211. rownames(sAmp) <- NULL
  2212. colnames(sAmp) <- c("Predictor","Estimate","SD","df","t","p")
  2213. temp = summary(lCV2)
  2214. sCV2 <- temp$coefficients
  2215. sCV2 <- data.frame(Predictor = row.names(sCV2), sCV2);
  2216. rownames(sCV2) <- NULL
  2217. colnames(sCV2) <- c("Predictor","Estimate","SD","df","t","p")
  2218. temp = summary(lCV2_burst)
  2219. sCV2_burst <- temp$coefficients
  2220. sCV2_burst <- data.frame(Predictor = row.names(sCV2_burst), sCV2_burst);
  2221. rownames(sCV2_burst) <- NULL
  2222. colnames(sCV2_burst) <- c("Predictor","Estimate","SD","df","t","p")
  2223. temp = summary(lBurst)
  2224. sBurst <- temp$coefficients
  2225. sBurst <- data.frame(Predictor = row.names(sBurst), sBurst);
  2226. rownames(sBurst) <- NULL
  2227. colnames(sBurst) <- c("Predictor","Estimate","SD","df","t","p")
  2228. # Model coefficients to LaTeX table (and reorder)
  2229. sFRcor_SUA$id <- 1:nrow(sFRcor_SUA)
  2230. coef <- merge(sFRcor_SUA, sFRcor_MUA, by="Predictor")
  2231. coef <- merge(coef, sBurst, by="Predictor")
  2232. coef <- merge(coef, sAmp, by="Predictor")
  2233. coef <- merge(coef, sCV2, by="Predictor")
  2234. coef <- merge(coef, sCV2_burst, by="Predictor")
  2235. coef <- coef[order(coef$id), ]
  2236. coef <- coef[, c(-1, -7)]
  2237. rownames(coef) <- NULL
  2238. coef[,3] = round(coef[,3],digits=0)
  2239. coef[,8] = round(coef[,8],digits=0)
  2240. coef[,13] = round(coef[,13],digits=0)
  2241. coef[,18] = round(coef[,18],digits=0)
  2242. coef[,23] = round(coef[,23],digits=0)
  2243. coef$Predictor <- c("\\textit{Intercept}","S3", "S2", "S1", "WASO", "REM", "Post")
  2244. coef <- coef[, c(31,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30)]
  2245. # posthoc coefficients
  2246. phFR_SUA$id <- 1:nrow(phFR_SUA)
  2247. ph <- merge(phFR_SUA, phFR_MUA, by="Comparison")
  2248. ph <- merge(ph,phBurst, by = "Comparison")
  2249. ph <- merge(ph,phAmp, by = "Comparison")
  2250. ph <- merge(ph,phCV2, by = "Comparison")
  2251. ph <- merge(ph,phCV2_burst, by = "Comparison")
  2252. ph <- ph[order(ph$id), ]
  2253. ph <- ph[, -7]
  2254. rownames(ph) <- NULL
  2255. # Concatenate in one LaTeX table
  2256. colnames(ph) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","df", "z",
  2257. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2258. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2259. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2260. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2261. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2262. "\\textit{p}")
  2263. colnames(coef) <- c("Predictor", "Coef $\\beta$","SE($\\beta$)","df", "z",
  2264. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2265. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2266. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2267. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2268. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2269. "\\textit{p}")
  2270. stats_window <- bind_rows(coef,ph)
  2271. colnames(stats_window) <- c("", "Coef $\\beta$","SE($\\beta$)","df", "z",
  2272. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2273. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2274. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2275. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2276. "\\textit{p}", "Coef $\\beta$","SE($\\beta$)","df","z",
  2277. "\\textit{p}")
  2278. stats_window[,6] = ifelse(stats_window[,6] > .05, paste(round(stats_window[,6], digits=2),sep=""),
  2279. ifelse(stats_window[,6] < .0001, "<.0001\\textsuperscript{***}",
  2280. ifelse(stats_window[,6] < .001, "<.001\\textsuperscript{**}",
  2281. ifelse(stats_window[,6] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  2282. stats_window[,11] = ifelse(stats_window[,11] > .05, paste(round(stats_window[,11],digits=2),sep=""),
  2283. ifelse(stats_window[,11] < .0001, "<.0001\\textsuperscript{***}",
  2284. ifelse(stats_window[,11] < .001,"<.001\\textsuperscript{**}",
  2285. ifelse(stats_window[,11] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  2286. stats_window[,16] = ifelse(stats_window[,16] > .05, paste(round(stats_window[,16],digits=2),sep=""),
  2287. ifelse(stats_window[,16] < .0001, "<.0001\\textsuperscript{***}",
  2288. ifelse(stats_window[,16] < .001,"<.001\\textsuperscript{**}",
  2289. ifelse(stats_window[,16] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  2290. stats_window[,21] = ifelse(stats_window[,21] > .05, paste(round(stats_window[,21],digits=2),sep=""),
  2291. ifelse(stats_window[,21] < .0001, "<.0001\\textsuperscript{***}",
  2292. ifelse(stats_window[,21] < .001,"<.001\\textsuperscript{**}",
  2293. ifelse(stats_window[,21] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  2294. stats_window[,26] = ifelse(stats_window[,26] > .05, paste(round(stats_window[,26],digits=2),sep=""),
  2295. ifelse(stats_window[,26] < .0001, "<.0001\\textsuperscript{***}",
  2296. ifelse(stats_window[,26] < .001,"<.001\\textsuperscript{**}",
  2297. ifelse(stats_window[,26] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  2298. stats_window[,31] = ifelse(stats_window[,31] > .05, paste(round(stats_window[,31],digits=2),sep=""),
  2299. ifelse(stats_window[,31] < .0001, "<.0001\\textsuperscript{***}",
  2300. ifelse(stats_window[,31] < .001,"<.001\\textsuperscript{**}",
  2301. ifelse(stats_window[,31] < .01, "<.01\\textsuperscript{*}", "<.05\\textsuperscript{.}"))))
  2302. options(knitr.kable.NA = '')
  2303. kbl(stats_window, "latex", booktabs = T, linesep = "", label = 'unit_window_stats',
  2304. escape = FALSE, digits = 2,
  2305. caption = "Effect of sleep stage on spontanious neuronal behaviour")%>%
  2306. kable_styling(latex_options = c("HOLD_position"))%>%
  2307. pack_rows("Sleep stages", 1, 7) %>% # latex_gap_space = "2em"
  2308. pack_rows("Post-hoc comparisons", 8, 28) %>%
  2309. add_header_above(c(" ", "Firing Rate (SUA)" = 5, "Firing Rate (MUA)" = 5, "Bursts" = 5, "Amplitude" = 5, "CV2" = 5, "CV2 (bursts)" = 5)) %>%
  2310. kable_styling(latex_options = c("scale_down"))%>%
  2311. footnote(general_title = "",
  2312. footnote_as_chunk = TRUE,
  2313. threeparttable = TRUE,
  2314. escape = FALSE,
  2315. general = c("$.=p<0.05$, $*=p<0.01$, $**=p<0.001$, $***=p<0.0001$"))%>%
  2316. save_kable("D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/tables/unit_window_stats.tex")
  2317. set_theme(
  2318. base = theme_article(),
  2319. # panel.bordercol = NA
  2320. axis.textsize = 0.9
  2321. )
  2322. FRcor_SUA_plot_model <- plot_model(
  2323. lFRcor_SUA,
  2324. title = "",
  2325. colors = "bw",
  2326. axis.title = "",
  2327. show.values = TRUE,
  2328. show.p = TRUE,
  2329. decimals = 4,
  2330. digits = 2,
  2331. value.offset = 0.5,
  2332. value.size = 2.5) +
  2333. font_size(labels.y = 9, labels.x = 9) +
  2334. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  2335. labels=c("Post","REM","WASO","S1","S2","S3")) +
  2336. scale_y_continuous(limits = c(-4.2, -1.8), breaks = c(-4, -2))
  2337. FRcor_MUA_plot_model <- plot_model(
  2338. lFRcor_MUA,
  2339. title = "",
  2340. colors = "bw",
  2341. axis.title = "",
  2342. show.values = TRUE,
  2343. show.p = TRUE,
  2344. decimals = 4,
  2345. digits = 2,
  2346. value.offset = 0.5,
  2347. value.size = 2.5) +
  2348. font_size(labels.y = 9, labels.x = 9) +
  2349. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  2350. labels=c("Post","REM","WASO","S1","S2","S3")) +
  2351. scale_y_continuous(limits = c(-7, 1), breaks = c(-7, 0, 1))
  2352. CV2_plot_model <- plot_model(
  2353. lCV2,
  2354. title = "",
  2355. colors = "bw",
  2356. axis.title = "",
  2357. show.values = TRUE,
  2358. show.p = TRUE,
  2359. decimals = 4,
  2360. digits = 2,
  2361. value.offset = 0.5,
  2362. value.size = 2.5,
  2363. axis.labels = c("REM","Post","WASO","S1","S2","S3")) +
  2364. font_size(labels.y = 9, labels.x = 9) +
  2365. scale_x_discrete(expand=expansion(mult=c(0.1, 0.2)),
  2366. labels=c("Post","REM","WASO","S1","S2","S3")) +
  2367. scale_y_continuous(limits = c(0, 0.12), breaks = c(0, 0.1))
  2368. CV2_burst_plot_model <- plot_model(
  2369. lCV2_burst,
  2370. title = "",
  2371. colors = "bw",
  2372. axis.title = "",
  2373. show.values = TRUE,
  2374. show.p = TRUE,
  2375. decimals = 4,
  2376. digits = 2,
  2377. value.offset = 0.5,
  2378. value.size = 2.5,
  2379. axis.labels = c("REM","Post","WASO","S1","S2","S3")) +
  2380. font_size(labels.y = 9, labels.x = 9) +
  2381. ylim(-0.05, 0.05) +
  2382. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  2383. labels=c("Post","REM","WASO","S1","S2","S3")) +
  2384. scale_y_continuous(limits = c(-0.04, 0.01), breaks = c(-0.04, 0, 0.01))
  2385. Amp_plot_model <- plot_model(
  2386. lAmp,
  2387. title = "",
  2388. colors = "bw",
  2389. axis.title = "",
  2390. show.values = TRUE,
  2391. show.p = TRUE,
  2392. decimals = 4,
  2393. digits = 2,
  2394. value.offset = 0.5,
  2395. value.size = 2.5,
  2396. axis.labels = c("REM","Post","WASO","S1","S2","S3")) +
  2397. font_size(labels.y = 9, labels.x = 9) +
  2398. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  2399. labels=c("Post","REM","WASO","S1","S2","S3")) +
  2400. scale_y_continuous(limits = c(-1, 2), breaks = c(-1, 0, 2))
  2401. Burst_plot_model <- plot_model(
  2402. lBurst,
  2403. title = "",
  2404. colors = "bw",
  2405. axis.title = "",
  2406. show.values = TRUE,
  2407. show.p = TRUE,
  2408. decimals = 4,
  2409. digits = 2,
  2410. value.offset = 0.5,
  2411. value.size = 2.5,
  2412. axis.labels = c("REM","Post","WASO","S1","S2","S3")) +
  2413. font_size(labels.y = 9, labels.x = 9) +
  2414. scale_x_discrete(expand=expansion(mult=c(0.1,0.2)),
  2415. labels=c("Post","REM","WASO","S1","S2","S3")) +
  2416. scale_y_continuous(limits = c(-20, 0), breaks = c(-20, 0))
  2417. Burst_plot_model$data$title = "Model fixed effects"
  2418. Burst_plot_model <- Burst_plot_model + facet_wrap(~title, scales="free_y")
  2419. # FR_plot_model$data$title = "Model fixed effects"
  2420. # FR_plot_model <- FR_plot_model + facet_wrap(~title, scales="free_y")
  2421. FRcor_SUA_plot_model$data$title = "Model fixed effects"
  2422. FRcor_SUA_plot_model <- FRcor_SUA_plot_model + facet_wrap(~title, scales="free_y")
  2423. FRcor_MUA_plot_model$data$title = "Model fixed effects"
  2424. FRcor_MUA_plot_model <- FRcor_MUA_plot_model + facet_wrap(~title, scales="free_y")
  2425. Amp_plot_model$data$title = "Model fixed effects"
  2426. Amp_plot_model <- Amp_plot_model + facet_wrap(~title, scales="free_y")
  2427. CV2_plot_model$data$title = "Model fixed effects"
  2428. CV2_plot_model <- CV2_plot_model + facet_wrap(~title, scales="free_y")
  2429. CV2_burst_plot_model$data$title = "Model fixed effects"
  2430. CV2_burst_plot_model <- CV2_burst_plot_model + facet_wrap(~title, scales="free_y")
  2431. ggarrange(FRcor_SUA_plot, FRcor_SUA_plot_model, FRcor_MUA_plot, FRcor_MUA_plot_model, Burst_plot, Burst_plot_model,
  2432. ncol = 2, nrow = 3,
  2433. vjust = 1.5, hjust = -1,
  2434. labels = c("A","B","C","D","E","F","G","H"),
  2435. legend = "right",
  2436. common.legend = TRUE,
  2437. font.label = list(size = 14, color = "black", face = "bold")) %>%
  2438. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/images/window_FR_boxplots.pdf")
  2439. ggarrange(Amp_plot, Amp_plot_model, CV2_plot, CV2_plot_model, CV2_burst_plot, CV2_burst_plot_model,
  2440. ncol = 2, nrow = 3,
  2441. vjust = 1.5, hjust = -1,
  2442. labels = c("A","B","C","D","E","F","G","H"),
  2443. legend = "right",
  2444. common.legend = TRUE,
  2445. font.label = list(size = 14, color = "black", face = "bold")) %>%
  2446. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Neuronal mechanisms underlying the modulation of interictal epileptic activity during sleep/images/window_CV2_boxplots.pdf")
  2447. ##########################################################################
  2448. ### Combine spike and power data
  2449. ##########################################################################
  2450. # load and prepare data
  2451. data_window <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/window_spike_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  2452. data_window$hyplabel <- factor(data_window$hyplabel, levels = c("NO_SCORE", "Pre", "Post", "REM", "Wake", "S1", "S2", "S3"))
  2453. data_window$Patient <- factor(data_window$patient, levels = c(8:1))
  2454. data_window$Night <- factor(data_window$part)
  2455. data_window$Unit <- factor(data_window$unit + data_window$part * 100) # add becaue template nr repeats over nights
  2456. data_window$responsive <- factor(data_window$responsive)
  2457. data_window$Type <- factor(data_window$Type)
  2458. data_window$FR <- data_window$trialfreq
  2459. data_window$FRcor <- data_window$trialfreq_corrected
  2460. levels(data_window$Type)[levels(data_window$Type)=="good"] <- "SUA"
  2461. levels(data_window$Type)[levels(data_window$Type)=="mua"] <- "MUA"
  2462. data_window$Type <- ordered(data_window$Type, levels = c("MUA", "SUA"))
  2463. # prepare data
  2464. data_power <- read.csv(file="Z:/analyses/stephen.whitmarsh/data/hspike/power_table_long.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  2465. data_power$hyplabel <- factor(data_power$hyplabel, ordered = TRUE, levels = c("NO_SCORE", "REM", "AWAKE", "PHASE_1", "PHASE_2", "PHASE_3"))
  2466. # data_power$band <- factor(data_power$band, ordered = TRUE, levels = c("delta", "theta", "alpha", "beta", "delta_div_alpha"))
  2467. data_power$band <- factor(data_power$band, ordered = TRUE, levels = c("Delta1", "Delta2"))
  2468. data_power$Patient <- factor(data_power$patient, levels = c(8:1))
  2469. data_power$part <- factor(data_power$part)
  2470. data_power$power_log <- log(data_power$power)
  2471. # data_sel <- na.omit(data_window) # remove rows with missing data
  2472. # data_sel <- data_sel[data_sel$BAD_cnt == 0, ] # remove rows with artefacts
  2473. # data_sel <- data_sel[data_sel$IEDsum == 0, ] # remove windows with IEDs
  2474. d <- merge(data_window, data_power, by = "starttime")
  2475. d <- d[d$band == "Delta2", ]
  2476. d2 <- d %>% mutate(power_bin = cut(power, breaks=seq(-1.5,10.5,1)))
  2477. levels(d2$power_bin) <- seq(1:12)-2
  2478. d$IEDsum.x[105:108] - d$IEDsum.y[105:108]
  2479. d$IEDsum.x[665:672] - d$IEDsum.y[665:672]
  2480. d$IEDsum.x
  2481. d$IEDsum.y
  2482. test <- d$IEDsum.x - d$IEDsum.y
  2483. hist(test[test != 0])
  2484. h1 <- hist(d$IEDsum.y[d$IEDsum.y != 0])
  2485. h2 <- hist(d$IEDsum.x[d$IEDsum.x != 0])
  2486. h3 <- hist(d$IEDsum.x - d$IEDsum.y, 10)
  2487. d[104:109, ]
  2488. # bin data
  2489. # prepare datastructure
  2490. d2 <- d2 %>% group_by(power_bin, IEDsum)
  2491. d2 <- d2 %>% summarise(count = n(), Patient)
  2492. d2 <- d2[order(data_pow_wide2$Patient), ]
  2493. # ggplot(data=data_pow_wide2[data_pow_wide2$IEDsum > 0, ], aes(x=Delta1_log_bin, y=IEDsum*6)) +
  2494. D2 <- ggplot(data=data_pow_wide2, aes(x=Delta_log_bin, y=IEDsum*6, color = Patient)) +
  2495. # geom_count(aes(size = after_stat(prop), group = Delta_log_bin, color = Patient)) +
  2496. geom_count() +
  2497. # scale_size_area(max_size = 3) +
  2498. # geom_smooth(data=data_pow_wide, aes(x=Delta1_log, y=IEDsum), method="lm", fullrange = FALSE, color="red") +
  2499. scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2500. theme(axis.text.y = element_blank()) +
  2501. theme_article() +
  2502. theme(
  2503. strip.background = element_blank(),
  2504. strip.text.x = element_blank()
  2505. ) +
  2506. # xlab("Delta2 power (log)")
  2507. #xlab = expression(mu "Volts" / "Hertz" ^ 2) +
  2508. # xlab = expression("Force spaces with ~" ~ mu ~ pi * sigma ~ pi) +
  2509. # ylab( units~are~(mu*g)/L )
  2510. # xlab(TeX(r'($\alpha x^\alpha$, where $\alpha \in \{1 \ldots 5\}$)')) +
  2511. # xlab(TeX(r'($log(\mu V/Hz^2$))')) +
  2512. xlab(TeX(r'($log(\mu V^2/Hz$))')) +
  2513. ylab("IEDs per minute") +
  2514. labs(size = "Observations") +
  2515. # coord_cartesian(xlim = c(2,11)) +
  2516. # coord_cartesian(ylim = c(2,11)) +
  2517. # facet_wrap(~Patient, ncol = 4, scales="free_x")
  2518. facet_wrap(~Patient, ncol = 4)
  2519. # ggsave("D:/Dropbox/Apps/Overleaf/Hspike/images/IEDrate_Delta2_count.pdf", width = 7, height = 4, units = "in")
  2520. ggarrange(D1, D2,
  2521. ncol = 1, nrow = 2,
  2522. vjust = 1, hjust = 0,
  2523. labels = c("A","B"),
  2524. legend = "right",
  2525. common.legend = TRUE,
  2526. font.label = list(size = 14, color = "black", face = "bold")) %>%
  2527. ggexport(filename = "D:/Dropbox/Apps/Overleaf/Hspike/images/IEDrate_Delta_count.pdf")
  2528. #
  2529. # ## POLAR ##
  2530. #
  2531. # library("ggplot2")
  2532. # library("dplyr")
  2533. #
  2534. # ## plot power values PER HOUR
  2535. #
  2536. # data$bin <- as.integer(cut(data$minute, seq(0, 24*60, by = 60)))
  2537. # data_binned <- setNames(aggregate(data$alpha, c(list(data$patient), list(data$bin)), mean), c("patient", "bin", "alpha"))
  2538. # data_binned <- as.data.frame(data_binned %>% group_by(patient) %>% mutate(Nalpha = alpha/max(alpha)))
  2539. #
  2540. # ggplot(data=data_binned, aes(x = bin, y = alpha, fill=patient, col=patient)) +
  2541. # scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2542. # geom_bar(stat="identity", width = 1) +
  2543. # geom_vline(xintercept = seq(0.5, 21.5, by = 3), colour = "grey90") +
  2544. # theme_bw() +
  2545. # theme(panel.border = element_blank(),
  2546. # legend.key = element_blank(),
  2547. # axis.ticks = element_blank(),
  2548. # axis.text.y = element_blank(),
  2549. # panel.grid = element_blank(),
  2550. # ) +
  2551. # scale_x_continuous(breaks=seq(0.5, 21.5, by = 3), labels = c("0" = "00:00", "3" = "03:00", "6" = "06:00", "9" = "09:00", "12" = "12:00", "15" = "15:00", "18" = "18:00", "21" = "21:00")) +
  2552. # coord_polar(theta = "x", start = 0)
  2553. #
  2554. #
  2555. # ## plot power values (use bindivision for hour divisions)
  2556. # bindivision = 1
  2557. # data$bin <- as.integer(cut(data$minute, seq(0, 24*60, by = 60/bindivision)))
  2558. # y1 <- setNames(aggregate(data$alpha, c(list(data$patient), list(data$bin)), median), c("patient", "bin", "alpha"))
  2559. # y2 <- setNames(aggregate(data$theta, c(list(data$patient), list(data$bin)), median), c("patient", "bin", "theta"))
  2560. # y3 <- setNames(aggregate(data$beta, c(list(data$patient), list(data$bin)), median), c("patient", "bin", "beta"))
  2561. # y4 <- setNames(aggregate(data$delta, c(list(data$patient), list(data$bin)), median), c("patient", "bin", "delta"))
  2562. # y1sd <- setNames(aggregate(data$alpha, c(list(data$patient), list(data$bin)), sd), c("patient", "bin", "SDalpha"))
  2563. # y2sd <- setNames(aggregate(data$theta, c(list(data$patient), list(data$bin)), sd), c("patient", "bin", "SDtheta"))
  2564. # y3sd <- setNames(aggregate(data$beta, c(list(data$patient), list(data$bin)), sd), c("patient", "bin", "SDbeta"))
  2565. # y4sd <- setNames(aggregate(data$delta, c(list(data$patient), list(data$bin)), sd), c("patient", "bin", "SDdelta"))
  2566. # data_binned <- merge(y1,y2)
  2567. # data_binned <- merge(data_binned,y3)
  2568. # data_binned <- merge(data_binned,y4)
  2569. # data_binned <- merge(data_binned,y1sd)
  2570. # data_binned <- merge(data_binned,y2sd)
  2571. # data_binned <- merge(data_binned,y3sd)
  2572. # data_binned <- merge(data_binned,y4sd)
  2573. # data_binned <- as.data.frame(data_binned %>% group_by(patient) %>% mutate(Nalpha = (alpha-min(alpha)) / max(alpha-min(alpha))))
  2574. # data_binned <- as.data.frame(data_binned %>% group_by(patient) %>% mutate(Ntheta = (theta-min(theta)) / max(theta-min(theta))))
  2575. # data_binned <- as.data.frame(data_binned %>% group_by(patient) %>% mutate(Ndelta = (delta-min(delta)) / max(delta-min(delta))))
  2576. # data_binned <- as.data.frame(data_binned %>% group_by(patient) %>% mutate(Nbeta = (beta-min(beta)) / max(beta-min(beta))))
  2577. # data_binned_melt <-melt(data_binned[c("Ndelta","Ntheta","Nalpha","Nbeta","patient","bin")], id=c("patient","bin"))
  2578. # data_binned_melt$variable <- factor(data_binned_melt$variable, labels = c("\u03B4 power (1-4Hz)","\u03B8 power (5-7Hz)","\u03B1 power (8-14Hz)","\u03B2 power (15-25Hz)"))
  2579. # data_binned_melt$patient <- factor(data_binned_melt$patient, levels = c(8:1))
  2580. #
  2581. # pdf(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/images/hspike/R/polar_power_combined.pdf")
  2582. #
  2583. # ggplot(data=data_binned_melt, aes(x = bin, y = value, fill=patient, col=patient)) +
  2584. # ggtitle("Normalized circadian LFP power") +
  2585. # scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2586. # geom_vline(xintercept = seq(0.5, 21.5 * bindivision, by = 3 * bindivision), colour = "grey90") +
  2587. # geom_hline(yintercept = seq(1, 8, by = 1), colour = "grey90") +
  2588. # geom_bar(stat="identity", width = 1) +
  2589. # theme_bw() +
  2590. # theme(panel.border = element_blank(),
  2591. # legend.key = element_blank(),
  2592. # axis.ticks = element_blank(),
  2593. # axis.text.y = element_blank(),
  2594. # panel.grid = element_blank(),
  2595. # axis.title.x = element_blank(),
  2596. # axis.title.y = element_blank(),
  2597. # strip.background = element_blank(),
  2598. # ) +
  2599. # scale_x_continuous(breaks=seq(0.5, 21.5*bindivision, by = 3 * bindivision),
  2600. # labels = c("0" = "00:00", "3" = "3:00", "6" = "6:00", "9" = "9:00",
  2601. # "12" = "12:00", "15" = "15:00", "18" = "18:00", "21" = "21:00")) +
  2602. # coord_polar(theta = "x", start = 0) +
  2603. # ylim(-1, 7) +
  2604. # facet_wrap(~variable)
  2605. #
  2606. # dev.off()
  2607. #
  2608. # library(circular)
  2609. #
  2610. # data$radian = data$minute / (24*60) * pi * 2
  2611. #
  2612. # stats_circ <- median.circular(data$radian)
  2613. #
  2614. #
  2615. # # load data: Patients x Units x time window
  2616. # data_IED <- read.csv(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/data/hspike/hypdata_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  2617. #
  2618. # # prepare data
  2619. # data_IED$patient <- factor(data_IED$patient, levels = c(8:1))
  2620. # data_IED$hour <- data_IED$minute / (60)
  2621. # data_IED$part <- factor(data_IED$part,)
  2622. #
  2623. # # load data: Patients x Units x time window
  2624. # data_seizures <- read.csv(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/data/hspike/seizuredata_table.txt", sep=',', header=TRUE, dec='.', na.strings = " ")
  2625. #
  2626. # # prepare data
  2627. # data_seizures$patient <- factor(data_seizures$patient, levels = c(8:1))
  2628. # data_seizures$hour <- data_seizures$minute / (60)
  2629. #
  2630. # # graphics.off()
  2631. #
  2632. # # display.brewer.all(colorblindFriendly = TRUE)
  2633. #
  2634. # pdf(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/images/hspike/R/polar_density_combined.pdf")
  2635. #
  2636. # ggplot(data=data_IED, aes(x=hour, fill=patient, col=patient)) +
  2637. # ggtitle("Circadian interictal density & seizure occurance") +
  2638. # scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2639. # geom_vline(xintercept = seq(0, 21, by = 3), colour = "grey90") +
  2640. # geom_hline(yintercept = seq(-0.25+0.025, -0.05, by = 0.025), colour = "grey90") +
  2641. # geom_histogram(position = 'stack', aes(y = stat(density)), binwidth=0.1, center = 0.05) + # make sure binwidth is multiple of 24/60
  2642. # coord_polar(theta = "x") +
  2643. # scale_x_continuous(breaks=seq(0, 21, by = 3), labels = c("0" = "00:00", "3" = "3:00", "6" = "6:00", "9" = "9:00", "12" = "12:00", "15" = "15:00", "18" = "18:00", "21" = "21:00")) +
  2644. # coord_polar(theta = "x", start = 0, direction = 1) +
  2645. # theme_bw() +
  2646. # theme(panel.border = element_blank(),
  2647. # legend.key = element_blank(),
  2648. # axis.ticks = element_blank(),
  2649. # axis.text.y = element_blank(),
  2650. # panel.grid = element_blank(),
  2651. # ) +
  2652. # geom_point(size=1, data = data_seizures, aes(x = hour, y = -0.05 - as.numeric(patient)*0.025+0.025, fill = patient, col = patient)) +
  2653. # ylim(-0.3, 0.85)
  2654. #
  2655. # dev.off()
  2656. #
  2657. #
  2658. #
  2659. #
  2660. #
  2661. #
  2662. #
  2663. #
  2664. # ggplot(data=data_IED, aes(x=hour, fill=patient, col=patient)) +
  2665. # ggtitle("Circadian interictal density & seizure occurance") +
  2666. # scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2667. # geom_vline(xintercept = seq(0, 21, by = 3), colour = "grey90") +
  2668. # #geom_segment(aes(x = 0, xend = 0, y = 1, yend = 0.1)) +
  2669. # geom_hline(yintercept = seq(-0.25+0.025, -0.05, by = 0.025), colour = "grey90") +
  2670. # geom_histogram(position = 'stack', aes(y = stat(density)), binwidth=0.1, center = 0.05) + # make sure binwidth is multiple of 24/60
  2671. # coord_polar(theta = "x") +
  2672. # scale_x_continuous(breaks=seq(0, 21, by = 3), labels = c("0" = "00:00", "3" = "03:00", "6" = "06:00", "9" = "09:00", "12" = "12:00", "15" = "15:00", "18" = "18:00", "21" = "21:00")) +
  2673. # coord_polar(theta = "x", start = 0, direction = 1) +
  2674. # theme_bw() +
  2675. # theme(panel.border = element_blank(),
  2676. # legend.key = element_blank(),
  2677. # axis.ticks = element_blank(),
  2678. # axis.text.y = element_blank(),
  2679. # panel.grid = element_blank(),
  2680. # ) +
  2681. # geom_point(size=0.5, data = data_seizures, aes(x = hour, y = -0.05 - as.numeric(patient)*0.025+0.025, fill = patient, col = patient)) +
  2682. # ylim(-0.3, 0.85)
  2683. #
  2684. #
  2685. #
  2686. #
  2687. #
  2688. #
  2689. #
  2690. #
  2691. #
  2692. #
  2693. #
  2694. #
  2695. #
  2696. # library(circular)
  2697. # library(units)
  2698. #
  2699. # plot.circular(data_seizures$radian, pch = 16, cex = 1, stack = TRUE,
  2700. # axes = TRUE, start.sep=0, sep = 0.025, shrink = 1,
  2701. # bins = 23, ticks = TRUE, tcl = 0.025, tcl.text = 0.125,
  2702. # col = NULL, tol = 0.04, uin = NULL,
  2703. # xlim = c(-1, 1), ylim = c(-1, 1), digits = 2, units = "rad",
  2704. # template = NULL, zero = 0.1, rotation = NULL,
  2705. # main = NULL, sub=NULL, xlab = "", ylab = "")
  2706. #
  2707. #
  2708. # plot(sin, -pi, 2*pi) # see ?plot.function
  2709. #
  2710. # pi_rad <- as_units(pi, "radians")
  2711. #
  2712. #
  2713. #
  2714. # pdf(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/images/hspike/R/polar_density_per patient.pdf")
  2715. #
  2716. # ggplot(data=data, aes(x=hour, fill=patient, col=patient)) +
  2717. # ggtitle("Circadian interictal density per patient") +
  2718. # scale_fill_brewer(palette = "Set2") + scale_color_brewer(palette = "Set2") +
  2719. # geom_histogram(position = 'stack', aes(y = stat(density)), binwidth=0.2, center = 0.1) + # make sure binwidth is multiple of 24/60
  2720. # coord_polar(theta = "x") +
  2721. # geom_vline(xintercept = seq(0, 21, by = 3), colour = "grey90") +
  2722. # scale_x_continuous(breaks=seq(0, 21, by = 3), labels = c("0" = "00:00", "3" = "03:00", "6" = "06:00", "9" = "09:00", "12" = "12:00", "15" = "15:00", "18" = "18:00", "21" = "21:00")) +
  2723. # coord_polar(theta = "x", start = 0, direction = 1) +
  2724. # theme_bw() +
  2725. #
  2726. # theme(panel.border = element_blank(),
  2727. # legend.key = element_blank(),
  2728. # axis.ticks = element_blank(),
  2729. # axis.text.y = element_blank(),
  2730. # panel.grid = element_blank(),
  2731. # strip.background = element_blank(),
  2732. # ) + facet_wrap(~patient)
  2733. # dev.off()
  2734. #
  2735. #
  2736. #
  2737. #
  2738. #
  2739. #
  2740. # # get ylim and xlim from plot
  2741. # #layer_scales(p)$y$range$range
  2742. # #layer_scales(p)$x$range$range
  2743. #
  2744. #
  2745. #
  2746. #
  2747. #
  2748. # # data$SU <- data$percRPV < 0.25
  2749. # data$SU <- factor(ifelse(data$percRPV > 0.25, "MUA", "SUA"))
  2750. # data$SU <- c("MUA","SUA","MUA","MUA","MUA","MUA","SUA","MUA","MUA","MUA","MUA","SUA","MUA","MUA","SUA","MUA","MUA","MUA","SUA","MUA","SUA","SUA","MUA","SUA","MUA")
  2751. # # data$PI <- factor(data$PI)
  2752. # data$PI <- factor(ifelse(data$template_tp < 550, "Int", "Pyr"))
  2753. # # data$PI <- revalue(data$PI, c("Int"="Interneuron", "Pyr"="Pyramidal cell"))
  2754. #
  2755. #
  2756. #
  2757. #
  2758. # data <- read.csv(file="//lexport/iss02.charpier/analyses/stephen.whitmarsh/data/aurelie/statAH.csv", sep=';', header=TRUE, dec=',', na.strings = " ")
  2759. # data$P <- data$ï..Patient
  2760. #
  2761. # # get some p-values
  2762. # detach(package:lmerTest)
  2763. # library(lmerTest)
  2764. # l1 <- lmer(EEG ~ NSE +S100 + (1 | P) + (1 | Time), data); summary(l1)
  2765. # l1 <- lmer(EEG ~ NSE + S100 + (1 | P), data); summary(l1)
  2766. #
  2767. # l1 <- lm(EEG ~ NSE + S100, data); summary(l1)

analysis.R at commit 46bf8dc, under GPL-3.0 · at the source

Overview

Authors: Stephen Whitmarsh1, Vi-Huong Nguyen-Michel2, Katia Lehongre1, Bertrand Mathon1,3, Claude Adam2, Virginie Lambrecq1,2, Valerio Frazzini1,2, Vincent Navarro1,2
  1. Sorbonne Université, Institut du Cerveau - Paris Brain Institute - ICM, Inserm, CNRS, APHP, Pitié-Salpêtrière Hospital, Paris 75013, France
  2. Epilepsy Unit and Reference Center for Rare Epilepsies, ERN EpiCARE, AP-HP, Pitié-Salpêtrière Hospital, Paris 75013, France
  3. Department of Neurosurgery, AP-HP, Pitié-Salpêtrière Hospital and Sorbonne Université, Paris 75013, France
Journal: Brain communications, volume 8, issue 3, article fcag130
Dates: received 4 March 2024; accepted 29 April 2026; published online 30 April 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1093/braincomms/fcag130 · PMID 42244910 · PMCID PMC13231451 · OpenAlex W7160118956
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: EEG (modality), extracellular electrophysiology (units, LFP) (modality), human (organism), epilepsy (population)
Methods: Spectral & time-frequency, Connectivity, Statistics, Machine learning, Single-unit activity, calcium imaging, Physiology & signal measures, fMRI & imaging
Keywords: epilepsy, multi-unit, intracranial, sleep, interictal
Topic: EEG and Brain-Computer Interfaces (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Citations: cited by 1 paper (Europe PMC); 169 references in the paper
Research resources: RRID:SCR_026138
Notices: A comment on this paper has been published (42540733, from Europe PMC)

Abstract

Epileptic seizures and interictal epileptiform discharges are strongly influenced by sleep and circadian rhythms. However, human data on the effect of sleep on neuronal behaviour during interictal activity have been lacking. We analysed EEG from eight epileptic patients implanted with macro and micro electrodes in mesial temporal structures. Sleep staging was performed on polysomnography and video-EEG. Automated detection identified thousands of interictal epileptiform discharges per patient. Both their rate and amplitude increased with deeper stages of non-rapid eye movement sleep. Single- and multi-unit firing rates were often temporally coupled with local field potentials, exhibiting increased firing during the spike and decreased activity during the following slow wave. These time-locked firing rate modulations were shown to increase during deeper stages of non-rapid eye movement sleep. Furthermore, neuronal background activity showed a decrease in firing rate, bursting and regularity with deeper stages of non-rapid eye movement sleep.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 8 matches between paragraphs and lines of code.

icm-institute/dac/EpiCode

License: GPL-3.0
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: 8897bd3fb06fc04482133af27ce4cad86167918c, 4 January 2023
Languages: MATLAB (503), C++ (49), Shell (47), C/C++ (34), R (9), C (2), Python (1), Java (1)
Size: 793 files, 646 scripts
Software Heritage: not archived
Found in: “Data availability”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: FieldTrip (293 files), Statistics and Machine Learning Toolbox (86 files), Signal Processing Toolbox (49 files), ggplot2 (8 files), ggpubr (8 files), export_fig (7 files), cowplot (6 files), lmerTest (3 files), circlize (2 files), emmeans (2 files), fdr_bh (Benjamini-Hochberg FDR) (2 files), lme4 (2 files), Parallel Computing Toolbox (2 files), reshape2 (2 files), tidyverse (2 files), SpyKING CIRCUS (1 file)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
648 files

stephenwhitmarsh/epicode

License: GPL-3.0
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: 46bf8dc29553cebb50398b76ec0832a76e655be8, 18 November 2022
Languages: MATLAB (503), C++ (49), Shell (47), C/C++ (34), R (8), C (2), Python (1), Java (1)
Size: 792 files, 645 scripts
Software Heritage: not archived
Found in: the text, “Statistics”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: FieldTrip (293 files), Statistics and Machine Learning Toolbox (86 files), Signal Processing Toolbox (49 files), export_fig (7 files), ggplot2 (7 files), ggpubr (7 files), cowplot (6 files), fdr_bh (Benjamini-Hochberg FDR) (2 files), lmerTest (2 files), Parallel Computing Toolbox (2 files), circlize (1 file), emmeans (1 file), lme4 (1 file), reshape2 (1 file), SpyKING CIRCUS (1 file), tidyverse (1 file)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
647 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 1,291 scripts, each with its path and the digest of its content;
  • 8 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability

All scripts are made available here (https://gitlab.com/icm-institute/dac/EpiCode). Anonymous electrophysiology data can be made available on reasonable request for research purposes, but cannot be publicly shared due to legal constraints.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 30 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 8 authors, 5 keywords, 138 references, 1 RRID, 1 integrity notice.

Cite

This paper

Whitmarsh, S., Nguyen-Michel, V.-H., Lehongre, K., Mathon, B., Adam, C., Lambrecq, V., Frazzini, V., & Navarro, V. (2026). Sleep increases firing rate modulation during interictal epileptiform discharges in mesial temporal structures. Brain communications, 8(3), fcag130. https://doi.org/10.1093/braincomms/fcag130

BibTeX

@article{whitmarsh2026sleep,
author = {Whitmarsh, Stephen and Nguyen-Michel, Vi-Huong and Lehongre, Katia and Mathon, Bertrand and Adam, Claude and Lambrecq, Virginie and Frazzini, Valerio and Navarro, Vincent},
title = {{Sleep increases firing rate modulation during interictal epileptiform discharges in mesial temporal structures}},
journal = {Brain communications},
year = {2026},
month = apr,
volume = {8},
number = {3},
pages = {fcag130},
publisher = {Oxford University Press},
issn = {2632-1297},
doi = {10.1093/braincomms/fcag130},
url = {https://doi.org/10.1093/braincomms/fcag130},
pmid = {42244910},
pmcid = {PMC13231451}
}

RIS

TY - JOUR
AU - Whitmarsh, Stephen
AU - Nguyen-Michel, Vi-Huong
AU - Lehongre, Katia
AU - Mathon, Bertrand
AU - Adam, Claude
AU - Lambrecq, Virginie
AU - Frazzini, Valerio
AU - Navarro, Vincent
TI - Sleep increases firing rate modulation during interictal epileptiform discharges in mesial temporal structures
T2 - Brain communications
J2 - Brain Commun
PY - 2026
DA - 2026/04/30
VL - 8
IS - 3
SP - fcag130
SN - 2632-1297
PB - Oxford University Press
DO - 10.1093/braincomms/fcag130
UR - https://doi.org/10.1093/braincomms/fcag130
LA - en
ER -

CSL-JSON

{
"id": "10.1093/braincomms/fcag130",
"type": "article-journal",
"title": "Sleep increases firing rate modulation during interictal epileptiform discharges in mesial temporal structures",
"container-title": "Brain communications",
"author": [
{
"family": "Whitmarsh",
"given": "Stephen"
},
{
"family": "Nguyen-Michel",
"given": "Vi-Huong"
},
{
"family": "Lehongre",
"given": "Katia"
},
{
"family": "Mathon",
"given": "Bertrand"
},
{
"family": "Adam",
"given": "Claude"
},
{
"family": "Lambrecq",
"given": "Virginie"
},
{
"family": "Frazzini",
"given": "Valerio"
},
{
"family": "Navarro",
"given": "Vincent"
}
],
"container-title-short": "Brain Commun",
"volume": "8",
"issue": "3",
"page": "fcag130",
"DOI": "10.1093/braincomms/fcag130",
"PMID": "42244910",
"PMCID": "PMC13231451",
"ISSN": "2632-1297",
"publisher": "Oxford University Press",
"URL": "https://doi.org/10.1093/braincomms/fcag130",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
30
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1111/psyp.70265 [code]
Neurocognitive Dynamics of Translating Information From a Spatial Map Into Action.
Journal: Psychophysiology
In common: Parallel Computing Toolbox, emmeans, lmerTest, 7 other tools, EEG, 2 references
[2] doi:10.1016/j.celrep.2026.117646 [code]
Medial entorhinal-hippocampal desynchronization parallels the emergence of memory impairment in a mouse model of Alzheimer's disease pathology.
Journal: Cell reports
In common: export_fig, FieldTrip, Parallel Computing Toolbox, 7 other tools
[3] doi:10.1038/s41467-026-74565-0 [code]
The functional neurobiology of dispositions towards negative emotions.
Journal: Nature communications
In common: fdr_bh (Benjamini-Hochberg FDR), FieldTrip, Parallel Computing Toolbox, 7 other tools
[4] doi:10.7554/elife.107088 [code]
Development of auditory and spontaneous movement responses to music over the first postnatal year.
Journal: eLife
In common: FieldTrip, emmeans, lme4, 6 other tools, EEG, 1 reference
[5] doi:10.1016/j.neuroimage.2026.122115 [code]
Midfrontal theta power relates to response speeding following frustrative nonreward.
Journal: NeuroImage
In common: emmeans, lmerTest, lme4, 6 other tools, EEG, 1 reference
[6] doi:10.1002/hbm.70605 [code]
BrainEnrich: Revealing Biological Insights for Imaging-Derived Phenotypes Through Transcriptomic Enrichment.
Journal: Human brain mapping
In common: fdr_bh (Benjamini-Hochberg FDR), emmeans, lmerTest, 6 other tools
[7] doi:10.1038/s41467-026-74753-y [code]
A human-specific microRNA controls the timing of excitatory synaptogenesis.
Journal: Nature communications
In common: circlize, emmeans, lmerTest, 6 other tools
[8] doi:10.1523/eneuro.0076-26.2026 [code]
Exogenously Driven Neural Reactivation of Spatially Matching Visual Working-Memory Contents.
Journal: eNeuro
In common: FieldTrip, emmeans, lme4, 6 other tools, EEG
[9] doi:10.1093/nc/niag011 [code]
Towards a bridge between intracerebral and surface EEG signatures of conscious report.
Journal: Neuroscience of consciousness
In common: EEG, 1 reference, 2 authors
[10] doi:10.64898/2026.05.08.26348885 [code]
Insights from nine nights of self-applied, low-density sleep EEG during sleep restriction therapy: a proof-of-concept evaluation
Journal: medRxiv (preprint)
In common: FieldTrip, emmeans, lmerTest, 6 other tools, EEG

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.