modelBased_projections_errors_5foldCV.Rmd 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. ---
  2. title: "Axonal Length"
  3. author: "Sergio D?ez Hermano"
  4. date: '`r format(Sys.Date(),"%e de %B, %Y")`'
  5. output:
  6. html_document:
  7. highlight: tango
  8. toc: yes
  9. toc_depth: 4
  10. toc_float:
  11. collapsed: no
  12. ---
  13. ```{r setup, include=FALSE}
  14. require(knitr)
  15. # include this code chunk as-is to set options
  16. opts_chunk$set(comment = NA, prompt = FALSE, fig.height=5, fig.width=5, dpi=300, fig.align = "center", echo = TRUE, message = FALSE, warning = FALSE, cache=FALSE)
  17. Sys.setlocale("LC_TIME", "C")
  18. ```
  19. ##Load libraries and functions
  20. ```{r}
  21. library(R.matlab)
  22. library(lattice)
  23. library(dplyr)
  24. library(ggplot2)
  25. library(ggridges)
  26. library(hrbrthemes)
  27. library(viridis)
  28. library(ggpubr)
  29. library(mltools)
  30. library(data.table)
  31. library(caret)
  32. library(interactions)
  33. # library(performance)
  34. library(MASS)
  35. library(geepack)
  36. library(pstools)
  37. library(MXM)
  38. library(rmcorr)
  39. library(multcomp)
  40. library(Hmisc)
  41. options(digits = 10)
  42. # https://rstudio-pubs-static.s3.amazonaws.com/297778_5fce298898d64c81a4127cf811a9d486.html
  43. ################
  44. # Bootstrap PI #
  45. ################
  46. the.replication <- function(reg, s, x_Np1 = 0){
  47. # Make bootstrap residuals
  48. ep.star <- sample(s, size=length(reg$residuals),replace=TRUE)
  49. # Make bootstrap Y
  50. y.star <- fitted(reg) + ep.star
  51. # Do bootstrap regression
  52. lp <- model.frame(reg)[,2]
  53. nt <- model.frame(reg)[,3]
  54. bs.reg <- lm(y.star ~ lp:nt - 1)
  55. # Create bootstrapped adjusted residuals
  56. bs.lev <- influence(bs.reg)$hat
  57. bs.s <- residuals(bs.reg)/sqrt(1-bs.lev)
  58. bs.s <- bs.s - mean(bs.s)
  59. # Calculate draw on prediction error
  60. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  61. xb.xb <- (coef(my.reg)[1] - coef(bs.reg)[1])*x_Np1
  62. return(unname(xb.xb + sample(bs.s, size=1)))
  63. }
  64. ############################
  65. # Bootstrap PI generalized #
  66. ############################
  67. the.replication.gen <- function(reg, s, axType, x_Np1 = 0){
  68. # Make bootstrap residuals
  69. ep.star <- sample(s, size=length(reg$residuals), replace=TRUE)
  70. # Make bootstrap Y
  71. y.star <- fitted(reg) + ep.star
  72. # Do bootstrap regression
  73. lp <- model.frame(reg)[,2]
  74. nt <- model.frame(reg)[,3]
  75. bs.reg <- lm(y.star ~ lp:nt - 1)
  76. # Create bootstrapped adjusted residuals
  77. bs.lev <- influence(bs.reg)$hat
  78. bs.s <- residuals(bs.reg)/sqrt(1-bs.lev)
  79. bs.s <- bs.s - mean(bs.s)
  80. # Calculate draw on prediction error
  81. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  82. xb.xb <- (coef(my.reg)[axType] - coef(bs.reg)[axType])*x_Np1
  83. return(unname(xb.xb + sample(bs.s, size=1)))
  84. }
  85. ##############################
  86. # Bootstrap PI per axon type #
  87. ##############################
  88. the.replication.type <- function(reg, s, x_Np1 = 0){
  89. # Make bootstrap residuals
  90. ep.star <- sample(s, size=length(reg$residuals),replace=TRUE)
  91. # Make bootstrap Y
  92. y.star <- fitted(reg) + ep.star
  93. # Do bootstrap regression
  94. lp <- model.frame(reg)[,2]
  95. bs.reg <- lm(y.star ~ lp - 1)
  96. # Create bootstrapped adjusted residuals
  97. bs.lev <- influence(bs.reg)$hat
  98. bs.s <- residuals(bs.reg)/sqrt(1-bs.lev)
  99. bs.s <- bs.s - mean(bs.s)
  100. # Calculate draw on prediction error
  101. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  102. xb.xb <- (coef(my.reg) - coef(bs.reg))*x_Np1
  103. return(unname(xb.xb + sample(bs.s, size=1)))
  104. }
  105. ##############################
  106. # Stratified random sampling #
  107. ##############################
  108. stratified <- function(df, group, size, select = NULL,
  109. replace = FALSE, bothSets = FALSE) {
  110. if (is.null(select)) {
  111. df <- df
  112. } else {
  113. if (is.null(names(select))) stop("'select' must be a named list")
  114. if (!all(names(select) %in% names(df)))
  115. stop("Please verify your 'select' argument")
  116. temp <- sapply(names(select),
  117. function(x) df[[x]] %in% select[[x]])
  118. df <- df[rowSums(temp) == length(select), ]
  119. }
  120. df.interaction <- interaction(df[group], drop = TRUE)
  121. df.table <- table(df.interaction)
  122. df.split <- split(df, df.interaction)
  123. if (length(size) > 1) {
  124. if (length(size) != length(df.split))
  125. stop("Number of groups is ", length(df.split),
  126. " but number of sizes supplied is ", length(size))
  127. if (is.null(names(size))) {
  128. n <- setNames(size, names(df.split))
  129. message(sQuote("size"), " vector entered as:\n\nsize = structure(c(",
  130. paste(n, collapse = ", "), "),\n.Names = c(",
  131. paste(shQuote(names(n)), collapse = ", "), ")) \n\n")
  132. } else {
  133. ifelse(all(names(size) %in% names(df.split)),
  134. n <- size[names(df.split)],
  135. stop("Named vector supplied with names ",
  136. paste(names(size), collapse = ", "),
  137. "\n but the names for the group levels are ",
  138. paste(names(df.split), collapse = ", ")))
  139. }
  140. } else if (size < 1) {
  141. n <- round(df.table * size, digits = 0)
  142. } else if (size >= 1) {
  143. if (all(df.table >= size) || isTRUE(replace)) {
  144. n <- setNames(rep(size, length.out = length(df.split)),
  145. names(df.split))
  146. } else {
  147. message(
  148. "Some groups\n---",
  149. paste(names(df.table[df.table < size]), collapse = ", "),
  150. "---\ncontain fewer observations",
  151. " than desired number of samples.\n",
  152. "All observations have been returned from those groups.")
  153. n <- c(sapply(df.table[df.table >= size], function(x) x = size),
  154. df.table[df.table < size])
  155. }
  156. }
  157. temp <- lapply(
  158. names(df.split),
  159. function(x) df.split[[x]][sample(df.table[x],
  160. n[x], replace = replace), ])
  161. set1 <- do.call("rbind", temp)
  162. if (isTRUE(bothSets)) {
  163. set2 <- df[!rownames(df) %in% rownames(set1), ]
  164. list(SET1 = set1, SET2 = set2)
  165. } else {
  166. set1
  167. }
  168. }
  169. ```
  170. ##Load data
  171. ```{r}
  172. # Get file paths
  173. axonNames <- list.files(paste("ProyeccionData/", sep=""), full.names=T)
  174. # Load matlab file
  175. axonFiles <- lapply(axonNames, function(x) readMat(x))
  176. names(axonFiles) <- c("Type1", "Type2", "Type3", "Type4")
  177. # VAR NAMES
  178. # REAL_LENGTH, PROYECTION_LENGTH_XY, PROYECTION_LENGTH_XZ, PROYECTION_LENGTH_YZ
  179. # Extract data
  180. realLength <- lapply(axonFiles, function(x) x$REAL.LENGTH)
  181. planeXY <- lapply(axonFiles, function(x) x$PROYECTION.LENGTH.XY)
  182. planeXZ <- lapply(axonFiles, function(x) x$PROYECTION.LENGTH.XZ)
  183. planeYZ <- lapply(axonFiles, function(x) x$PROYECTION.LENGTH.YZ)
  184. # Get number of neurons per type
  185. numberTypes <- unlist(lapply(realLength, function(x) length(x)))
  186. # Store in data frames by plane
  187. xyData <- data.frame(id = 1:length(unlist(realLength)),
  188. LR = unlist(realLength), LP = unlist(planeXY), Plane = rep("XY", sum(numberTypes)),
  189. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), numberTypes))
  190. xzData <- data.frame(id = 1:length(unlist(realLength)),
  191. LR = unlist(realLength), LP = unlist(planeXZ), Plane = rep("XZ", sum(numberTypes)),
  192. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), numberTypes))
  193. yzData <- data.frame(id = 1:length(unlist(realLength)),
  194. LR = unlist(realLength), LP = unlist(planeYZ), Plane = rep("YZ", sum(numberTypes)),
  195. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), numberTypes))
  196. # Merge into a single data frame and sort by id
  197. allData <- do.call("rbind", list(xyData, xzData, yzData))
  198. allData <- allData[order(allData$id),]
  199. # Add different number for every neuron-plane combination
  200. allData$NeurPlane <- c(rep(c(1,2,3), numberTypes[1]), rep(c(4,5,6), numberTypes[2]),
  201. rep(c(7,8,9), numberTypes[3]), rep(c(10,11,12), numberTypes[4]))
  202. allData$interact <-interaction(allData$neurType, allData$Plane, lex.order=T)
  203. allData$idR <- 1:dim(allData)[1]
  204. # Create data frame w/o Type4
  205. dataNo4 <- allData[allData$neurType != "Type4", ]; dataNo4$neurType <- factor(dataNo4$neurType)
  206. # Data in short format
  207. dataShort <- data.frame(id = 1:length(unlist(realLength)),
  208. LR = unlist(realLength), XY = unlist(planeXY), XZ = unlist(planeXZ), YZ = unlist(planeYZ),
  209. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), numberTypes))
  210. ```
  211. ##CV-Bootstrap Pred Interval
  212. RUN ONLY ONCE, AFTERWARDS LOAD THE FILE IN MEAN ERRORS CHUNK
  213. ```{r}
  214. # Ensure reproducibility
  215. set.seed(123456)
  216. axList <- list()
  217. for (h in unique(allData$neurType)) {
  218. # Subset axon type
  219. dataCV <- allData[allData$neurType == h, ]
  220. # List to store CV repetitions
  221. cvList <- list ()
  222. cvRand <- list()
  223. # Stratified random 5-fold sets
  224. setList <- list()
  225. sampSize <- 0.2*length(unique(dataCV$id))
  226. groupDat1 <- dataCV %>% group_by(Plane)
  227. set1<- sample_n(groupDat1, sampSize)
  228. groupDat2 <- groupDat1[-set1$idR, ]
  229. set2 <- sample_n(groupDat2, sampSize)
  230. groupDat3 <- groupDat2[-set2$idR, ]
  231. set3 <- sample_n(groupDat3, sampSize)
  232. groupDat4 <- groupDat3[-set3$idR, ]
  233. set4 <- sample_n(groupDat4, sampSize)
  234. groupDat5 <- groupDat4[-set4$idR, ]
  235. set5 <- sample_n(groupDat5, sampSize)
  236. # Store sets (ungrouped)
  237. setList <- lapply(list(set1, set2, set3, set4, set5), ungroup)
  238. axList[[h]]$sets <- setList
  239. # List to store CV
  240. cvList <- list()
  241. for (i in 1:5) {
  242. # Stratified random training/test sets
  243. trainSet <- do.call(rbind, setList[-i])
  244. testSet <- setList[[i]]
  245. # OLS with training set
  246. my.reg <- lm(LR ~ LP - 1, trainSet)
  247. # Create adjusted residuals
  248. leverage <- influence(my.reg)$hat
  249. my.s.resid <- residuals(my.reg)/sqrt(1-leverage)
  250. my.s.resid <- my.s.resid - mean(my.s.resid)
  251. # List to store planes
  252. planeList <- list()
  253. # Bootstrapping on test set
  254. for (j in c("XY", "XZ", "YZ")) {
  255. # Subset plane
  256. dataSub <- testSet[testSet$Plane == j, ]
  257. # List to store errors
  258. epList <- list()
  259. epCount <- 1
  260. for (k in dataSub[ , "LP"]) {
  261. # Do bootstrap with 100 replications
  262. ep.draws <- replicate(n=100, the.replication.type(reg = my.reg, s = my.s.resid, x_Np1 = k))
  263. # Store in list
  264. epList[[epCount]] <- ep.draws
  265. epCount <- epCount + 1
  266. }
  267. # Store in list
  268. planeList[[j]] <- epList
  269. print(paste("CV", i, "Plane", j, "finished"))
  270. }
  271. # Store in list
  272. cvList[[i]] <- planeList
  273. }
  274. # Store in list
  275. axList[[h]]$cv <- cvList
  276. print(paste("Axon", h, "finished"))
  277. }
  278. saveRDS(axList, paste("projection_5CV_allAxons.rds", sep = ""))
  279. ```
  280. ##Estimate porcentual errors
  281. ```{r, fig.width=8, fig.height=8}
  282. # Load 5-fold CV
  283. axList <- readRDS("ProyeccionAnalysis/projection_5CV_allAxons.rds")
  284. # Estimate and store in list
  285. peList <- list()
  286. peCount <- 1
  287. lrLength <- list()
  288. for (h in c("Type1", "Type2", "Type3", "Type4")) {
  289. for (i in 1:5) {
  290. for (j in c("XY", "XZ", "YZ")) {
  291. # Extract LR values
  292. lr <- axList[[h]]$sets[[i]]
  293. lr <- lr[lr$Plane == j, "LR"]
  294. # Extract LP values
  295. lp <- axList[[h]]$cv[[i]][[j]][[1]]
  296. for (k in 1:dim(lr)[1]) {
  297. # Divide errors by LR to get porcentual errors
  298. pe <- lp[k, ] / lr$LR[k]
  299. # Store in list
  300. peList[[peCount]] <- pe*100
  301. peCount <-peCount + 1
  302. }
  303. }
  304. }
  305. lrLength[h] <- dim(lr)[1]
  306. }
  307. # Store in data frame
  308. lrLength <- unlist(lrLength)
  309. peFrame <- data.frame(pe = unlist(peList),
  310. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), times = lrLength*5*3*100),
  311. Plane = c(rep(rep(c("XY", "XZ", "YZ"), each = lrLength[1]*100), 5),
  312. rep(rep(c("XY", "XZ", "YZ"), each = lrLength[2]*100), 5),
  313. rep(rep(c("XY", "XZ", "YZ"), each = lrLength[3]*100), 5),
  314. rep(rep(c("XY", "XZ", "YZ"), each = lrLength[4]*100), 5)))
  315. peFrame$interact <- interaction(peFrame$neurType, peFrame$Plane, lex.order=T)
  316. ```
  317. ####Plot density and histogram
  318. ```{r}
  319. # Plot
  320. # peGroup <- peFrame %>% group_by(interact)
  321. # peSample <- sample_n(peGroup, 100)
  322. setwd("ProyeccionFigures/")
  323. png(filename=paste("prederrorDistributions_5CV.png", sep=""), type="cairo",
  324. units="in", width=8, height=10, pointsize=12,
  325. res=300)
  326. (p <- ggplot(peFrame, aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  327. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  328. geom_density_ridges_gradient(alpha = 0.8) +
  329. theme_ridges() +
  330. theme(legend.position = "none") +
  331. xlab("% Error")) +
  332. xlim(c(-40,40))
  333. dev.off()
  334. png(filename=paste("prederrorHistogram_5CV.png", sep=""), type="cairo",
  335. units="in", width=8, height=10, pointsize=12,
  336. res=300)
  337. # Histogram
  338. # nint 300 bootPI
  339. # nint 500 bootPI_full
  340. # nint 400 bootPI_full_replace
  341. (h <- histogram( ~ pe | Plane + neurType, peFrame, nint = 300, type ="density", xlim = c(-50,50)))
  342. dev.off()
  343. ```
  344. #####Insets
  345. ```{r}
  346. # Find mean bandwidth
  347. bwFrame <- aggregate(pe ~ neurType + Plane, peFrame, function(x) density(x)$bw)
  348. # Named color vector
  349. colVec <- c("limegreen", "blue", "red")
  350. names(colVec) <- c("XY", "XZ", "YZ")
  351. setwd("ProyeccionFigures/")
  352. for (i in unique(peFrame$neurType)) {
  353. png(filename=paste("insetProb_", i, ".png", sep=""), type="cairo",
  354. units="in", width=5, height=5, pointsize=12,
  355. res=300)
  356. par(mfrow = c(3,2),
  357. oma = c(5,4,0,0) + 0.1,
  358. mar = c(0,0,1,1) + 0.1)
  359. for (j in unique(peFrame$Plane)) {
  360. # Estimate density
  361. dens <- density(peFrame[peFrame$neurType == i & peFrame$Plane == j, "pe"], bw = mean(bwFrame$pe))
  362. # 5%
  363. x1 <- min(which(dens$x >= -5))
  364. x2 <- max(which(dens$x < 5))
  365. plot(dens, ylim = c(0, 0.15), xlim = c(-20,20), zero.line = FALSE, main = "", ylab = "", xlab = "", axes = FALSE)
  366. with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col=colVec[[j]], border = NA))
  367. lines(dens)
  368. # Add y axis
  369. axis(side = 2, at=seq(-0.05,0.15,0.05), labels = seq(-0.05,0.15,0.05), cex.axis = 1.2)
  370. # Different x axis for bottom plot
  371. if (j == "YZ") {
  372. axis(side = 1, at=seq(-30,30,10), labels = seq(-30,30,10), cex.axis = 1.2)
  373. } else {
  374. axis(side = 1, at=seq(-30,30,10), labels = FALSE)
  375. }
  376. # 10%
  377. x1 <- min(which(dens$x >= -10))
  378. x2 <- max(which(dens$x < 10))
  379. plot(dens, ylim = c(0, 0.15), xlim = c(-20,20), zero.line = FALSE, main = "", ylab = "", xlab = "", axes = FALSE)
  380. with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col=colVec[[j]], border = NA))
  381. lines(dens)
  382. # Add y axis
  383. axis(side = 2, at=seq(-0.05,0.15,0.05), labels = FALSE)
  384. # Different x axis for bottom plot
  385. if (j == "YZ") {
  386. axis(side = 1, at=seq(-30,30,10), labels = seq(-30,30,10), cex.axis = 1.2)
  387. } else {
  388. axis(side = 1, at=seq(-30,30,10), labels = FALSE)
  389. }
  390. }
  391. title(xlab = "% Error",
  392. ylab = "Density",
  393. outer = TRUE, line = 3,
  394. cex.lab = 1.5)
  395. dev.off()
  396. }
  397. ```
  398. ####Errors vs cumul probability
  399. RUN ONLY ONCE, AFTERWARDS LOAD THE FILE IN PLOT CHUNKS
  400. ```{r, fig.height=5, fig.width=20}
  401. # Inverse quantile
  402. quantInv <- function(distr, value) ecdf(distr)(value)
  403. #ecdf plot example
  404. # plot(ecdf(peFrame[peFrame$interact == "Type1.XY", "pe"]))
  405. # lines(ecdf(peFrame[peFrame$interact == "Type1.XZ", "pe"]), col = "red")
  406. # lines(ecdf(peFrame[peFrame$interact == "Type1.YZ", "pe"]), col = "blue")
  407. probList <- list()
  408. binProb <- 0.5
  409. probSeq <- seq(binProb, 100, binProb)
  410. for (i in unique(peFrame$interact)) {
  411. dataProb <- peFrame[peFrame$interact == i, "pe"]
  412. probVec <- numeric()
  413. for (j in probSeq) {
  414. errProb <- quantInv(dataProb, j) - quantInv(dataProb, -j)
  415. probVec <- c(probVec, errProb)
  416. }
  417. probList[[i]] <- probVec
  418. }
  419. setwd("ProyeccionAnalysis/")
  420. saveRDS(probList, "cumProb_5CV.rds")
  421. ```
  422. #####Plot
  423. ```{r, fig.height=5, fig.width=20}
  424. # Plot with limited axis
  425. setwd("ProyeccionFigures/")
  426. probList <- readRDS("cumProb_5CV.rds")
  427. png(filename=paste("errorProbabilityCum_bin", binProb, "_5CV.png", sep=""), type="cairo",
  428. units="in", width=20, height=5, pointsize=12,
  429. res=300)
  430. par(mfrow = c(1,4))
  431. hlist <- list()
  432. axCount <- 1
  433. for (i in seq(1,10,3)) {
  434. # Extract height for 5% error
  435. h5 <- sapply(probList[i:(i+2)], function(x) x[5/binProb])
  436. max5 <- max(h5)
  437. # Extract height for 10% error
  438. h10 <- sapply(probList[i:(i+2)], function(x) x[10/binProb])
  439. max10 <- max(h10)
  440. # Plot cumulative curves
  441. plot(probSeq, probList[[i]], type = "l", col = "limegreen", lwd = 1.5, ylim = c(0,1), xlim = c(0.5, 40),
  442. ylab = "Cumulative probability", xlab = "% Error", main = paste("Axon Type", axCount))
  443. lines(probSeq, probList[[i + 1]], col = "red", lwd = 1.5)
  444. lines(probSeq, probList[[i + 2]], col = "blue", lwd = 1.5)
  445. # Plot vertical segments at 5% and 10%
  446. segments(5, -0.1, 5, max5, lty = "dashed", col = "gray")
  447. segments(10, -0.1, 10, max10, lty = "dashed", col = "gray")
  448. # Plot horizontal segments at cumul prob for 5% and 10%
  449. transp <- 0.8
  450. segments(-2, h5[1], 5, h5[1], lty = "dashed", col = alpha("limegreen", transp))
  451. segments(-2, h5[2], 5, h5[2], lty = "dashed", col = alpha("red", transp))
  452. segments(-2, h5[3], 5, h5[3], lty = "dashed", col = alpha("blue", transp))
  453. segments(-2, h10[1], 10, h10[1], lty = "dashed", col = alpha("limegreen", transp))
  454. segments(-2, h10[2], 10, h10[2], lty = "dashed", col = alpha("red", transp))
  455. segments(-2, h10[3], 10, h10[3], lty = "dashed", col = alpha("blue", transp))
  456. # Add legend
  457. # legend("bottomright", c("XY", "XZ", "YZ"), lwd = 1.5, col = c("limegreen", "red", "blue"))
  458. # Store to check later
  459. hlist[[paste("Type", axCount, sep="")]] <- data.frame(h5 = h5, h10 = h10)
  460. axCount <- axCount + 1
  461. }
  462. dev.off()
  463. # Plot with free axis
  464. png(filename=paste("errorProbabilityCum_bin", binProb, "_freeAxis_5CV.png", sep=""), type="cairo",
  465. units="in", width=20, height=5, pointsize=12,
  466. res=300)
  467. par(mfrow = c(1,4))
  468. hlist <- list()
  469. axCount <- 1
  470. for (i in seq(1,10,3)) {
  471. # Extract height for 5% error
  472. h5 <- sapply(probList[i:(i+2)], function(x) x[5/binProb])
  473. max5 <- max(h5)
  474. # Extract height for 10% error
  475. h10 <- sapply(probList[i:(i+2)], function(x) x[10/binProb])
  476. max10 <- max(h10)
  477. # Plot cumulative curves
  478. plot(probSeq, probList[[i]], type = "l", col = "green", lwd = 1.5,
  479. ylab = "Cumulative probability", xlab = "% Error", main = paste("Axon Type", axCount))
  480. lines(probSeq, probList[[i + 1]], col = "red", lwd = 1.5)
  481. lines(probSeq, probList[[i + 2]], col = "blue", lwd = 1.5)
  482. # Plot vertical segments at 5% and 10%
  483. segments(5, -0.1, 5, max5, lty = "dashed", col = "gray")
  484. segments(10, -0.1, 10, max10, lty = "dashed", col = "gray")
  485. # Plot horizontal segments at cumul prob for 5% and 10%
  486. segments(-2, h5[1], 5, h5[1], lty = "dashed", col = "yellowgreen")
  487. segments(-2, h5[2], 5, h5[2], lty = "dashed", col = "tomato")
  488. segments(-2, h5[3], 5, h5[3], lty = "dashed", col = "lightskyblue")
  489. segments(-2, h10[1], 10, h10[1], lty = "dashed", col = "yellowgreen")
  490. segments(-2, h10[2], 10, h10[2], lty = "dashed", col = "tomato")
  491. segments(-2, h10[3], 10, h10[3], lty = "dashed", col = "lightskyblue")
  492. # Add legend
  493. legend("bottomright", c("XY", "XZ", "YZ"), lwd = 1.5, col = c("green", "red", "blue"))
  494. # Store to check later
  495. hlist[[paste("Type", axCount, sep="")]] <- data.frame(h5 = h5, h10 = h10)
  496. axCount <- axCount + 1
  497. }
  498. dev.off()
  499. ```
  500. ##Full figure
  501. ```{r, fig.width=20}
  502. ## show the regions that have been allocated to each plot
  503. # layout.show(8)
  504. #############
  505. # Load data #
  506. #############
  507. probList <- readRDS("ProyeccionAnalysis/cumProb_5CV.rds")
  508. ##############
  509. # MAIN PLOTS #
  510. ##############
  511. setwd("ProyeccionFigures/")
  512. png(filename=paste("errorProbabilityCum_bin", binProb, "_5CV_FULL.png", sep=""), type="cairo",
  513. units="in", width=20, height=5, pointsize=12,
  514. res=300)
  515. # Graphical parameters
  516. par(oma = c(1,4,1,1),
  517. mar = c(4,0,3,0) + 0.5,
  518. cex.axis = 1.5,
  519. cex.lab = 1.5,
  520. cex.main = 2)
  521. layout(matrix(c(1,1,2,2,3,3,0,4,4,
  522. 1,5,2,7,3,9,0,4,11,
  523. 1,6,2,8,3,10,0,4,12,
  524. 1,0,2,0,3,0,0,4,0), 4, 9, byrow = TRUE),
  525. widths = c(2.5,2.5,2.5,2.5,2.5,2.5,1,3,2.5),
  526. heights = c(1.6,1.6,1.6,1.2))
  527. # layout.show(12)
  528. # Plot loop
  529. hlist <- list()
  530. axCount <- 1
  531. for (i in seq(1,10,3)) {
  532. # Extract height for 5% error
  533. h5 <- sapply(probList[i:(i+2)], function(x) x[5/binProb])
  534. # Extract height for 10% error
  535. h10 <- sapply(probList[i:(i+2)], function(x) x[10/binProb])
  536. # Plot cumulative error and Axis labels
  537. if (axCount == 1) {
  538. plot(probSeq, probList[[i]], type = "l", col = "limegreen", lwd = 1.5, ylim = c(0,1), xlim = c(0.5, 40),
  539. main = paste("Axon Type", axCount), yaxt = "n", xaxt = "n", xlab = "", ylab = "")
  540. lines(probSeq, probList[[i + 1]], col = "red", lwd = 1.5)
  541. lines(probSeq, probList[[i + 2]], col = "blue", lwd = 1.5)
  542. title(ylab = "Cumulative probability",
  543. outer = TRUE, line=3)
  544. } else if (axCount == 2) {
  545. plot(probSeq, probList[[i]], type = "l", col = "limegreen", lwd = 1.5, ylim = c(0,1), xlim = c(0.5, 40),
  546. main = paste("Axon Type", axCount), yaxt = "n", xaxt = "n", xlab = "", ylab = "")
  547. lines(probSeq, probList[[i + 1]], col = "red", lwd = 1.5)
  548. lines(probSeq, probList[[i + 2]], col = "blue", lwd = 1.5)
  549. title(xlab="% Error", line=3)
  550. } else if (axCount == 3) {
  551. plot(probSeq, probList[[i]], type = "l", col = "limegreen", lwd = 1.5, ylim = c(0,1), xlim = c(0.5, 40),
  552. main = paste("Axon Type", axCount), yaxt = "n", xaxt = "n", xlab = "", ylab = "")
  553. lines(probSeq, probList[[i + 1]], col = "red", lwd = 1.5)
  554. lines(probSeq, probList[[i + 2]], col = "blue", lwd = 1.5)
  555. } else if (axCount == 4) {
  556. par(mar = c(4,5,3,0) + 0.5)
  557. plot(probSeq, probList[[i]], type = "l", col = "limegreen", lwd = 1.5, ylim = c(0,1), xlim = c(0.5, 40),
  558. main = paste("Axon Type", axCount), yaxt = "n", xaxt = "n", xlab = "", ylab = "")
  559. lines(probSeq, probList[[i + 1]], col = "red", lwd = 1.5)
  560. lines(probSeq, probList[[i + 2]], col = "blue", lwd = 1.5)
  561. title(ylab = "Cumulative probability", xlab="% Error", line=3)
  562. }
  563. # Add x axis
  564. axis(side = 1, at=seq(-10,40,10), labels = seq(-10,40,10))
  565. # Different y axis for Type1 and Type4
  566. if (axCount == 1) {
  567. axis(side = 2, at=seq(-0.2,1,0.2), labels = seq(-0.2,1,0.2))
  568. } else if (axCount == 4) {
  569. axis(side = 1, at=seq(-10,40,10), labels = seq(-10,40,10))
  570. axis(side = 2, at=seq(-0.2,1,0.2), labels = seq(-0.2,1,0.2))
  571. }
  572. # Plot vertical segments at 5% and 10% for XY plane
  573. segments(5, -0.1, 5, h5[1], lty = "dashed", col = "darkgray")
  574. segments(10, -0.1, 10, h10[1], lty = "dashed", col = "darkgray")
  575. # Plot horizontal segments at cumul prob for 5% and 10% for XY plane
  576. transp <- 0.8
  577. segments(-2, h5[1], 5, h5[1], lty = "dashed", col = alpha("darkgray", transp))
  578. segments(-2, h10[1], 10, h10[1], lty = "dashed", col = alpha("darkgray", transp))
  579. # Store to check later
  580. hlist[[paste("Type", axCount, sep="")]] <- data.frame(h5 = h5, h10 = h10)
  581. axCount <- axCount + 1
  582. }
  583. ###############
  584. # PLOT INSETS #
  585. ###############
  586. # Find mean bandwidth
  587. bwFrame <- aggregate(pe ~ neurType + Plane, peFrame, function(x) density(x)$bw)
  588. for (i in unique(peFrame$neurType)) {
  589. # Estimate density
  590. dens <- density(peFrame[peFrame$neurType == i & peFrame$Plane == "XY", "pe"], bw = mean(bwFrame$pe))
  591. # 5%
  592. x1 <- min(which(dens$x >= -5))
  593. x2 <- max(which(dens$x < 5))
  594. par(mar = c(0.2,5,0.2,2))
  595. plot(dens, ylim = c(0, 0.15), xlim = c(-20,20), zero.line = FALSE, main = "", ylab = "", xlab = "", axes = FALSE)
  596. with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="limegreen", border = NA))
  597. lines(dens)
  598. # Add y axis
  599. axis(side = 2, at=seq(-0.05,0.15,0.05), labels = seq(-0.05,0.15,0.05), cex.axis = 1.2)
  600. # 10%
  601. x1 <- min(which(dens$x >= -10))
  602. x2 <- max(which(dens$x < 10))
  603. plot(dens, ylim = c(0, 0.15), xlim = c(-20,20), zero.line = FALSE, main = "", ylab = "", xlab = "", axes = FALSE)
  604. with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="limegreen", border = NA))
  605. lines(dens)
  606. # Add y axis
  607. axis(side = 2, at=seq(-0.05,0.15,0.05), labels = seq(-0.05,0.15,0.05), cex.axis = 1.2)
  608. # Add x axis
  609. axis(side = 1, at=seq(-30,30,10), labels = seq(-30,30,10), cex.axis = 1.2)
  610. }
  611. dev.off()
  612. ```