modelFree_stereology_errors_CV.Rmd 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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(ggpubr)
  26. library(ggridges)
  27. library(mltools)
  28. library(data.table)
  29. library(caret)
  30. library(interactions)
  31. options(digits = 10)
  32. # https://rstudio-pubs-static.s3.amazonaws.com/297778_5fce298898d64c81a4127cf811a9d486.html
  33. #############################
  34. # Bootstrap coefficients LM #
  35. #############################
  36. # For models with interactions
  37. bootCoefintLM <- function(mydata, modForm, nreps) {
  38. # Fit model
  39. modLM <- lm(formula(modForm), data = mydata)
  40. # Ensure reproducibility
  41. # set.seed(12345)
  42. # Set up a matrix to store the results (1 intercept + 1 predictor = 2)
  43. coefmat <- matrix(NA, nreps, length(coef(modLM)))
  44. # We need the fitted values and the residuals from the model
  45. resids <- residuals(modLM)
  46. preds <- fitted(modLM)
  47. # Repeatedly generate bootstrapped responses
  48. for(i in 1:nreps) {
  49. booty <- preds + sample(resids, rep=TRUE)
  50. modLM2 <- update(modLM, booty ~ .)
  51. coefmat[i,] <- coef(modLM2)
  52. print(i)
  53. }
  54. # Create a dataframe to store predictors values
  55. colnames(coefmat) <- names(coef(modLM2))
  56. coefmat <- data.frame(coefmat)
  57. return(coefmat)
  58. }
  59. ################
  60. # Bootstrap PI #
  61. ################
  62. the.replication <- function(reg, s, x_Np1 = 0){
  63. # Make bootstrap residuals
  64. ep.star <- sample(s, size=length(reg$residuals),replace=TRUE)
  65. # Make bootstrap Y
  66. y.star <- fitted(reg) + ep.star
  67. # Do bootstrap regression
  68. lp <- model.frame(reg)[,2]
  69. nt <- model.frame(reg)[,3]
  70. bs.reg <- lm(y.star ~ lp:nt - 1)
  71. # Create bootstrapped adjusted residuals
  72. bs.lev <- influence(bs.reg)$hat
  73. bs.s <- residuals(bs.reg)/sqrt(1-bs.lev)
  74. bs.s <- bs.s - mean(bs.s)
  75. # Calculate draw on prediction error
  76. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  77. xb.xb <- (coef(my.reg)[1] - coef(bs.reg)[1])*x_Np1
  78. return(unname(xb.xb + sample(bs.s, size=1)))
  79. }
  80. ############################
  81. # Bootstrap PI generalized #
  82. ############################
  83. the.replication.gen <- function(reg, s, axType, x_Np1 = 0){
  84. # Make bootstrap residuals
  85. ep.star <- sample(s, size=length(reg$residuals), replace=TRUE)
  86. # Make bootstrap Y
  87. y.star <- fitted(reg) + ep.star
  88. # Do bootstrap regression
  89. lp <- model.frame(reg)[,2]
  90. nt <- model.frame(reg)[,3]
  91. bs.reg <- lm(y.star ~ lp:nt - 1)
  92. # Create bootstrapped adjusted residuals
  93. bs.lev <- influence(bs.reg, do.coef = FALSE)$hat
  94. bs.s <- residuals(bs.reg)/sqrt(1-bs.lev)
  95. bs.s <- bs.s - mean(bs.s)
  96. # Calculate draw on prediction error
  97. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  98. xb.xb <- (coef(my.reg)[axType] - coef(bs.reg)[axType])*x_Np1
  99. return(unname(xb.xb + sample(bs.s, size=1)))
  100. }
  101. ##############################
  102. # Bootstrap PI per axon type # STEREOLOGY VERSION
  103. ##############################
  104. the.replication.type <- function(reg, s, x_Np1 = 0, x_Np2 = 0){
  105. # Make bootstrap residuals
  106. ep.star <- sample(s, size=length(reg$residuals),replace=TRUE)
  107. # Make bootstrap Y
  108. y.star <- fitted(reg) + ep.star
  109. # Do bootstrap regression
  110. dist <- model.frame(reg)[,2]
  111. step <- model.frame(reg)[,3]
  112. bs.reg <- lm(y.star ~ dist:step - 1)
  113. # Create bootstrapped adjusted residuals
  114. bs.lev <- influence(bs.reg, do.coef = FALSE)$hat
  115. bs.s <- residuals(bs.reg)/sqrt(1-bs.lev)
  116. bs.s <- bs.s - mean(bs.s)
  117. # Calculate draw on prediction error
  118. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  119. xb.xb <- (coef(my.reg) - coef(bs.reg))*x_Np1*x_Np2
  120. return(unname(xb.xb + sample(bs.s, size=1)))
  121. }
  122. ##############################
  123. # Stratified random sampling #
  124. ##############################
  125. stratified <- function(df, group, size, select = NULL,
  126. replace = FALSE, bothSets = FALSE) {
  127. if (is.null(select)) {
  128. df <- df
  129. } else {
  130. if (is.null(names(select))) stop("'select' must be a named list")
  131. if (!all(names(select) %in% names(df)))
  132. stop("Please verify your 'select' argument")
  133. temp <- sapply(names(select),
  134. function(x) df[[x]] %in% select[[x]])
  135. df <- df[rowSums(temp) == length(select), ]
  136. }
  137. df.interaction <- interaction(df[group], drop = TRUE)
  138. df.table <- table(df.interaction)
  139. df.split <- split(df, df.interaction)
  140. if (length(size) > 1) {
  141. if (length(size) != length(df.split))
  142. stop("Number of groups is ", length(df.split),
  143. " but number of sizes supplied is ", length(size))
  144. if (is.null(names(size))) {
  145. n <- setNames(size, names(df.split))
  146. message(sQuote("size"), " vector entered as:\n\nsize = structure(c(",
  147. paste(n, collapse = ", "), "),\n.Names = c(",
  148. paste(shQuote(names(n)), collapse = ", "), ")) \n\n")
  149. } else {
  150. ifelse(all(names(size) %in% names(df.split)),
  151. n <- size[names(df.split)],
  152. stop("Named vector supplied with names ",
  153. paste(names(size), collapse = ", "),
  154. "\n but the names for the group levels are ",
  155. paste(names(df.split), collapse = ", ")))
  156. }
  157. } else if (size < 1) {
  158. n <- round(df.table * size, digits = 0)
  159. } else if (size >= 1) {
  160. if (all(df.table >= size) || isTRUE(replace)) {
  161. n <- setNames(rep(size, length.out = length(df.split)),
  162. names(df.split))
  163. } else {
  164. message(
  165. "Some groups\n---",
  166. paste(names(df.table[df.table < size]), collapse = ", "),
  167. "---\ncontain fewer observations",
  168. " than desired number of samples.\n",
  169. "All observations have been returned from those groups.")
  170. n <- c(sapply(df.table[df.table >= size], function(x) x = size),
  171. df.table[df.table < size])
  172. }
  173. }
  174. temp <- lapply(
  175. names(df.split),
  176. function(x) df.split[[x]][sample(df.table[x],
  177. n[x], replace = replace), ])
  178. set1 <- do.call("rbind", temp)
  179. if (isTRUE(bothSets)) {
  180. set2 <- df[!rownames(df) %in% rownames(set1), ]
  181. list(SET1 = set1, SET2 = set2)
  182. } else {
  183. set1
  184. }
  185. }
  186. ```
  187. ##Load data
  188. ```{r}
  189. # Get file paths
  190. axonNames <- list.files(paste("EstereoDataPlanos/", sep=""), full.names=T)
  191. # Load matlab file
  192. axonFiles <- lapply(axonNames, function(x) readMat(x))
  193. names(axonFiles) <- c("Type1", "Type2", "Type3", "Type4")
  194. # Extract data
  195. # errorMatrix contains 4 arrays, one per neuron type
  196. # within each array, the dimensions corresponds to step:dist:neuron
  197. # this means that each array has as many matrices as neuron of a certain type
  198. dist <- lapply(axonFiles, function(x) x$Distancias.Entre.Planos)[[1]]
  199. step <- lapply(axonFiles, function(x) x$Step.Lengths)[[1]]
  200. errorMatrix <- lapply(axonFiles, function(x) x$MATRIZ.ERROR.LENGTH)
  201. lpMatrix <- lapply(axonFiles, function(x) x$MATRIZ.ESTIMATED.AXON.LENGTH)
  202. lrVals <- lapply(axonFiles, function(x) x$AXON.REAL.LENGTH)
  203. # Get number of neurons per type
  204. numberTypes <- unlist(lapply(errorMatrix, function(x) dim(x)[3]))
  205. # Vectorizing the arrays goes as follows: neuron, dist, step
  206. errorVector <- unlist(lapply(errorMatrix, function(x) as.vector(x)))
  207. lpVector <- unlist(lapply(lpMatrix, function(x) as.vector(x)))
  208. lrVector <- unlist(lapply(lrVals, function(x) as.vector(x)))
  209. # Store in data frames
  210. allData <- data.frame(id = rep(1:sum(numberTypes), each = 90),
  211. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), times = 90*numberTypes),
  212. dist = rep(rep(dist, each = 9), sum(numberTypes)),
  213. step = rep(rep(step, 10), sum(numberTypes)),
  214. error = abs(errorVector),
  215. LP = lpVector,
  216. LR = rep(lrVector, each = 90))
  217. ```
  218. ##Bootstrap PI - leave dist out
  219. ```{r}
  220. # Read data
  221. frameList <- list()
  222. for (h in c("Type1", "Type2", "Type3", "Type4")) {
  223. bootout <- readRDS(paste("EstereoAnalysis/stereo_bootPI_leaveOut_", h, ".rds", sep=""))
  224. y.p <- bootout[[1]]
  225. epList <- bootout[[2]]
  226. # Add errors to predictions
  227. epList.sum <- list()
  228. for (i in 1:90) {
  229. epList.sum[[i]] <- epList[[i]] + y.p[[i]]
  230. }
  231. names(epList.sum) <- paste(rep(unique(allData$dist), each = 9), rep(unique(allData$step), 10), sep=".")
  232. # Reformat as dataframe
  233. peFrame <- data.frame(neurType = rep(h, 90*100),
  234. dist = rep(unique(allData$dist), each = 9*100),
  235. step = rep(rep(unique(allData$step), each = 100), 10),
  236. pe = unlist(epList.sum))
  237. peFrame$interact <- interaction(peFrame$dist, peFrame$step, lex.order = TRUE)
  238. peFrame$abspe <- abs(peFrame$pe)
  239. # Store in list
  240. frameList[[h]] <- peFrame
  241. }
  242. # Join into a common data frame
  243. peFrame <- do.call(rbind, frameList)
  244. ```
  245. ###Mean error
  246. ```{r, fig.height=10, fig.width=20}
  247. meanFrame <- aggregate(abspe ~ dist + step + neurType, peFrame, mean)
  248. # Library
  249. library(latticeExtra)
  250. # Contour color palette
  251. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  252. colfin <- colfunc(1000)
  253. library(viridisLite)
  254. coul <- viridis(1000)
  255. # Store heatmaps
  256. heatList <- list()
  257. smoothList <- list()
  258. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  259. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  260. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  261. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  262. ylim = c(155, 65),
  263. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  264. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  265. 0.05))),
  266. main = paste("Mean Abs Error,", i))
  267. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  268. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  269. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  270. ylim = c(150,70),
  271. xlim = c(3,30),
  272. cuts = 20,
  273. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  274. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  275. 0.05))),
  276. main = paste("Mean Abs Error,", i),
  277. panel = panel.levelplot.points, cex = 0) +
  278. layer_(panel.2dsmoother(..., n = 200))
  279. }
  280. # Plot
  281. setwd("EstereoAnalysis/")
  282. png(filename="meanProbabilities_heatmap_CVleaveout.png", type="cairo",
  283. units="in", width=20, height=10, pointsize=12,
  284. res=300)
  285. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  286. dev.off()
  287. ```
  288. ###Plot density
  289. ```{r, fig.height=10, fig.width=20}
  290. # Plot
  291. # peGroup <- peFrame %>% group_by(interact)
  292. # peSample <- sample_n(peGroup, 100)
  293. plotList <- list()
  294. for (m in c("Type1", "Type2", "Type3", "Type4")) {
  295. plotList[[m]] <- ggplot(peFrame[peFrame$neurType == m, ], aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  296. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  297. geom_density_ridges_gradient(alpha = 0.8) +
  298. theme_ridges() +
  299. theme(legend.position = "none") +
  300. xlab("% Error") +
  301. xlim(c(-40,40)) +
  302. ggtitle(m)
  303. }
  304. setwd("EstereoAnalysis/")
  305. png(filename=paste("prederrorDistributions_ols_CVleaveout.png", sep=""), type="cairo",
  306. units="in", width=20, height=10, pointsize=12,
  307. res=300)
  308. ggarrange(plotlist = plotList, ncol = 4, nrow = 1)
  309. dev.off()
  310. ```
  311. ###Errors vs cumul probability
  312. ```{r, fig.height=5, fig.width=20}
  313. # Inverse quantile
  314. quantInv <- function(distr, value) ecdf(distr)(value)
  315. # Function to apply to all axon types
  316. quantType <- function(peFrame, probSeq) {
  317. probList <- list()
  318. for (i in unique(peFrame$interact)) {
  319. dataProb <- peFrame[peFrame$interact == i, "pe"]
  320. probVec <- numeric()
  321. for (j in probSeq) {
  322. errProb <- quantInv(dataProb, j) - quantInv(dataProb, -j)
  323. probVec <- c(probVec, errProb)
  324. }
  325. probList[[i]] <- probVec
  326. }
  327. return(probList)
  328. }
  329. # Define errors for which to calculate probability
  330. binProb <- 0.5
  331. probSeq <- seq(binProb, 100, binProb)
  332. # Store axon types in lists
  333. axProb <- lapply(frameList, function(x) quantType(x, probSeq))
  334. # Save
  335. saveRDS(axProb, "errorProbs_CVleaveout.rds")
  336. ```
  337. ######Plot heatmap
  338. ```{r, fig.height=5, fig.width=15}
  339. library(latticeExtra)
  340. # Reformat as dataframe
  341. binProb <- 0.5
  342. probSeq <- seq(binProb, 100, binProb)
  343. axProb <- readRDS("errorProbs_CVleaveout.rds")
  344. probFrame <- data.frame(error = rep(probSeq, 90*4),
  345. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = length(probSeq)*90),
  346. dist = rep(rep(unique(allData$dist), each = length(probSeq)*9), 4),
  347. step = rep(rep(unique(allData$step), each = length(probSeq)), 10*4),
  348. prob = unlist(axProb))
  349. # Plot conttour plot for 5% error
  350. library(viridisLite)
  351. coul <- viridis(1000)
  352. # Store heatmaps
  353. heatList <- list()
  354. smoothList <- list()
  355. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  356. levelList1 <- list()
  357. levelList2 <- list()
  358. for (j in c(5, 10, 20)) {
  359. dataPlot <- probFrame[probFrame$neurType == i & probFrame$error == j, ]
  360. levelList1[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  361. col.regions = coul,
  362. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  363. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  364. ylim = c(155,65),
  365. colorkey = list(at = (seq(min(dataPlot$prob),
  366. max(dataPlot$prob),
  367. 0.001))),
  368. main = paste("P(%Error <=", j, ")", sep = ""))
  369. levelList2[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  370. col.regions = coul,
  371. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  372. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  373. ylim = c(150,70),
  374. xlim = c(3,30),
  375. cuts = 20,
  376. colorkey = list(at = (seq(min(dataPlot$prob),
  377. max(dataPlot$prob),
  378. 0.001))),
  379. main = paste("P(%Error <=", j, ")", sep = ""),
  380. panel = panel.levelplot.points, cex = 0) +
  381. layer_(panel.2dsmoother(..., n = 200))
  382. }
  383. heatList[[i]] <- levelList1
  384. smoothList[[i]] <- levelList2
  385. }
  386. # Plot
  387. setwd("EstereoAnalysis/")
  388. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  389. png(filename=paste("errorProbabilities_heatmap_", i, "_CVleaveout.png", sep=""), type="cairo",
  390. units="in", width=15, height=10, pointsize=12,
  391. res=300)
  392. gridExtra::grid.arrange(grobs = c(heatList[[i]], smoothList[[i]]), ncol = 3, nrow = 2)
  393. dev.off()
  394. }
  395. ```
  396. ##Bootstrap PI - leave dist and step out
  397. ```{r}
  398. # Read data
  399. frameList <- list()
  400. for (h in c("Type1", "Type2", "Type3", "Type4")) {
  401. boot2out <- readRDS(paste("EstereoAnalysis/stereo_bootPI_leave2Out_", h, ".rds", sep=""))
  402. y.p <- boot2out[[1]]
  403. epList <- boot2out[[2]]
  404. # Add errors to predictions
  405. epList.sum <- list()
  406. for (i in 1:90) {
  407. epList.sum[[i]] <- epList[[i]] + y.p[[i]]
  408. }
  409. names(epList.sum) <- paste(rep(unique(allData$dist), each = 9), rep(unique(allData$step), 10), sep=".")
  410. # Reformat as dataframe
  411. peFrame <- data.frame(neurType = rep(h, 90*100),
  412. dist = rep(unique(allData$dist), each = 9*100),
  413. step = rep(rep(unique(allData$step), each = 100), 10),
  414. pe = unlist(epList.sum))
  415. peFrame$interact <- interaction(peFrame$dist, peFrame$step, lex.order = TRUE)
  416. peFrame$abspe <- abs(peFrame$pe)
  417. # Store in list
  418. frameList[[h]] <- peFrame
  419. }
  420. # Join into a common data frame
  421. peFrame <- do.call(rbind, frameList)
  422. ```
  423. ###Mean error
  424. ```{r, fig.height=10, fig.width=20}
  425. meanFrame <- aggregate(abspe ~ dist + step + neurType, peFrame, mean)
  426. # Library
  427. library(latticeExtra)
  428. # Contour color palette
  429. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  430. colfin <- colfunc(1000)
  431. library(viridisLite)
  432. coul <- viridis(1000)
  433. # Store heatmaps
  434. heatList <- list()
  435. smoothList <- list()
  436. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  437. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  438. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  439. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  440. ylim = c(155, 65),
  441. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  442. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  443. 0.05))),
  444. main = paste("Mean Abs Error,", i))
  445. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  446. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  447. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  448. ylim = c(150,70),
  449. xlim = c(3,30),
  450. cuts = 20,
  451. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  452. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  453. 0.05))),
  454. main = paste("Mean Abs Error,", i),
  455. panel = panel.levelplot.points, cex = 0) +
  456. layer_(panel.2dsmoother(..., n = 200))
  457. }
  458. # Plot
  459. setwd("EstereoAnalysis/")
  460. png(filename="meanProbabilities_heatmap_CVleave2out.png", type="cairo",
  461. units="in", width=20, height=10, pointsize=12,
  462. res=300)
  463. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  464. dev.off()
  465. ```
  466. ###Plot density
  467. ```{r, fig.height=10, fig.width=20}
  468. # Plot
  469. # peGroup <- peFrame %>% group_by(interact)
  470. # peSample <- sample_n(peGroup, 100)
  471. plotList <- list()
  472. for (m in c("Type1", "Type2", "Type3", "Type4")) {
  473. plotList[[m]] <- ggplot(peFrame[peFrame$neurType == m, ], aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  474. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  475. geom_density_ridges_gradient(alpha = 0.8) +
  476. theme_ridges() +
  477. theme(legend.position = "none") +
  478. xlab("% Error") +
  479. xlim(c(-40,40)) +
  480. ggtitle(m)
  481. }
  482. setwd("EstereoAnalysis/")
  483. png(filename=paste("prederrorDistributions_ols_CVleave2out.png", sep=""), type="cairo",
  484. units="in", width=20, height=10, pointsize=12,
  485. res=300)
  486. ggarrange(plotlist = plotList, ncol = 4, nrow = 1)
  487. dev.off()
  488. ```
  489. ##Bootstrap PI - CV
  490. ```{r}
  491. # Read data
  492. frameList <- list()
  493. ycvList <- list()
  494. cvTotal <- list()
  495. for (g in c("Type1", "Type2", "Type3", "Type4")) {
  496. bootCV <- readRDS(paste("EstereoAnalysis/stereo_boot10CVPI_", g, ".rds", sep=""))
  497. y.cv <- bootCV[[1]]
  498. cvList <- bootCV[[2]]
  499. epCV <- list()
  500. for (h in 1:10) {
  501. # Add errors to predictions
  502. epList.sum <- list()
  503. for (i in 1:90) {
  504. epList.sum[[i]] <- cvList[[h]][[i]] + y.cv[[h]][[i]]
  505. }
  506. names(epList.sum) <- paste(rep(unique(allData$dist), each = 9), rep(unique(allData$step), 10), sep=".")
  507. epCV[[h]] <- epList.sum
  508. }
  509. # Reformat as dataframe
  510. peFrame <- data.frame(neurType = rep(g, 90*100*10),
  511. dist = rep(rep(unique(allData$dist), each = 9*100), 10),
  512. step = rep(rep(rep(unique(allData$step), each = 100), 10), 10),
  513. pe = unlist(unlist(epCV)))
  514. peFrame$interact <- interaction(peFrame$dist, peFrame$step, lex.order = TRUE)
  515. peFrame$abspe <- abs(peFrame$pe)
  516. # Store in list
  517. frameList[[g]] <- peFrame
  518. ycvList[[g]] <- y.cv
  519. cvTotal[[g]] <- cvList
  520. }
  521. # Join into a common data frame
  522. peFrame <- do.call(rbind, frameList)
  523. ```
  524. ###Mean error
  525. ```{r, fig.height=10, fig.width=20}
  526. meanFrame <- aggregate(abspe ~ dist + step + neurType, peFrame, mean)
  527. # Library
  528. library(latticeExtra)
  529. # Contour color palette
  530. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  531. colfin <- colfunc(1000)
  532. library(viridisLite)
  533. coul <- viridis(1000)
  534. # Store heatmaps
  535. heatList <- list()
  536. smoothList <- list()
  537. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  538. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  539. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  540. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  541. ylim = c(155, 65),
  542. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  543. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  544. 0.05))),
  545. main = paste("Mean Abs Error,", i))
  546. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  547. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  548. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  549. ylim = c(150,70),
  550. xlim = c(3,30),
  551. cuts = 20,
  552. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  553. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  554. 0.05))),
  555. main = paste("Mean Abs Error,", i),
  556. panel = panel.levelplot.points, cex = 0) +
  557. layer_(panel.2dsmoother(..., n = 200))
  558. }
  559. # Plot
  560. setwd("EstereoAnalysis/")
  561. png(filename="meanProbabilities_heatmap_CV.png", type="cairo",
  562. units="in", width=20, height=10, pointsize=12,
  563. res=300)
  564. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  565. dev.off()
  566. ```
  567. ###Plot density
  568. ```{r, fig.height=10, fig.width=20}
  569. # Plot
  570. # peGroup <- peFrame %>% group_by(interact)
  571. # peSample <- sample_n(peGroup, 100)
  572. plotList <- list()
  573. for (m in c("Type1", "Type2", "Type3", "Type4")) {
  574. plotList[[m]] <- ggplot(peFrame[peFrame$neurType == m, ], aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  575. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  576. geom_density_ridges_gradient(alpha = 0.8) +
  577. theme_ridges() +
  578. theme(legend.position = "none") +
  579. xlab("% Error") +
  580. xlim(c(-40,40)) +
  581. ggtitle(m)
  582. }
  583. setwd("EstereoAnalysis/")
  584. png(filename=paste("prederrorDistributions_ols_CV.png", sep=""), type="cairo",
  585. units="in", width=20, height=10, pointsize=12,
  586. res=300)
  587. ggarrange(plotlist = plotList, ncol = 4, nrow = 1)
  588. dev.off()
  589. ```