modelFree_stereology_errors.Rmd 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  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(ggpubr)
  27. library(hrbrthemes)
  28. library(viridis)
  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. library(tolerance)
  42. options(digits = 10)
  43. # https://rstudio-pubs-static.s3.amazonaws.com/297778_5fce298898d64c81a4127cf811a9d486.html
  44. ################
  45. # Bootstrap PI #
  46. ################
  47. the.replication <- function(reg, s, x_Np1 = 0){
  48. # Make bootstrap residuals
  49. ep.star <- sample(s, size=length(reg$residuals),replace=TRUE)
  50. # Make bootstrap Y
  51. y.star <- fitted(reg) + ep.star
  52. # Do bootstrap regression
  53. lp <- model.frame(reg)[,2]
  54. bs.reg <- lm(y.star ~ lp - 1)
  55. # Create bootstrapped adjusted residuals
  56. bs.lev <- influence(bs.reg,do.coef = FALSE)$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 no rand noise #
  66. ##############################
  67. the.replication2 <- function(reg, s, 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. bs.reg <- lm(y.star ~ lp - 1)
  75. # Calculate draw on prediction error
  76. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  77. xb.xb <- coef(bs.reg)[1]*x_Np1
  78. return(unname(xb.xb))
  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. # Stratified random sampling #
  103. ##############################
  104. stratified <- function(df, group, size, select = NULL,
  105. replace = FALSE, bothSets = FALSE) {
  106. if (is.null(select)) {
  107. df <- df
  108. } else {
  109. if (is.null(names(select))) stop("'select' must be a named list")
  110. if (!all(names(select) %in% names(df)))
  111. stop("Please verify your 'select' argument")
  112. temp <- sapply(names(select),
  113. function(x) df[[x]] %in% select[[x]])
  114. df <- df[rowSums(temp) == length(select), ]
  115. }
  116. df.interaction <- interaction(df[group], drop = TRUE)
  117. df.table <- table(df.interaction)
  118. df.split <- split(df, df.interaction)
  119. if (length(size) > 1) {
  120. if (length(size) != length(df.split))
  121. stop("Number of groups is ", length(df.split),
  122. " but number of sizes supplied is ", length(size))
  123. if (is.null(names(size))) {
  124. n <- setNames(size, names(df.split))
  125. message(sQuote("size"), " vector entered as:\n\nsize = structure(c(",
  126. paste(n, collapse = ", "), "),\n.Names = c(",
  127. paste(shQuote(names(n)), collapse = ", "), ")) \n\n")
  128. } else {
  129. ifelse(all(names(size) %in% names(df.split)),
  130. n <- size[names(df.split)],
  131. stop("Named vector supplied with names ",
  132. paste(names(size), collapse = ", "),
  133. "\n but the names for the group levels are ",
  134. paste(names(df.split), collapse = ", ")))
  135. }
  136. } else if (size < 1) {
  137. n <- round(df.table * size, digits = 0)
  138. } else if (size >= 1) {
  139. if (all(df.table >= size) || isTRUE(replace)) {
  140. n <- setNames(rep(size, length.out = length(df.split)),
  141. names(df.split))
  142. } else {
  143. message(
  144. "Some groups\n---",
  145. paste(names(df.table[df.table < size]), collapse = ", "),
  146. "---\ncontain fewer observations",
  147. " than desired number of samples.\n",
  148. "All observations have been returned from those groups.")
  149. n <- c(sapply(df.table[df.table >= size], function(x) x = size),
  150. df.table[df.table < size])
  151. }
  152. }
  153. temp <- lapply(
  154. names(df.split),
  155. function(x) df.split[[x]][sample(df.table[x],
  156. n[x], replace = replace), ])
  157. set1 <- do.call("rbind", temp)
  158. if (isTRUE(bothSets)) {
  159. set2 <- df[!rownames(df) %in% rownames(set1), ]
  160. list(SET1 = set1, SET2 = set2)
  161. } else {
  162. set1
  163. }
  164. }
  165. ```
  166. ##Load data
  167. ```{r}
  168. # Get file paths
  169. axonNames <- list.files(paste("EstereoDataPlanos/", sep=""), full.names=T)
  170. # Load matlab file
  171. axonFiles <- lapply(axonNames, function(x) readMat(x))
  172. names(axonFiles) <- c("Type1", "Type2", "Type3", "Type4")
  173. # Extract data
  174. # errorMatrix contains 4 arrays, one per neuron type
  175. # within each array, the dimensions corresponds to step:dist:neuron
  176. # this means that each array has as many matrices as neuron of a certain type
  177. dist <- lapply(axonFiles, function(x) x$Distancias.Entre.Planos)[[1]]
  178. step <- lapply(axonFiles, function(x) x$Step.Lengths)[[1]]
  179. errorMatrix <- lapply(axonFiles, function(x) x$MATRIZ.ERROR.LENGTH)
  180. lpMatrix <- lapply(axonFiles, function(x) x$MATRIZ.ESTIMATED.AXON.LENGTH)
  181. lrVals <- lapply(axonFiles, function(x) x$AXON.REAL.LENGTH)
  182. # Get number of neurons per type
  183. numberTypes <- unlist(lapply(errorMatrix, function(x) dim(x)[3]))
  184. # Vectorizing the arrays goes as follows: neuron, dist, step
  185. errorVector <- unlist(lapply(errorMatrix, function(x) as.vector(x)))
  186. lpVector <- unlist(lapply(lpMatrix, function(x) as.vector(x)))
  187. lrVector <- unlist(lapply(lrVals, function(x) as.vector(x)))
  188. # Store in data frames
  189. allData <- data.frame(id = rep(1:sum(numberTypes), each = 90),
  190. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), times = 90*numberTypes),
  191. dist = rep(rep(dist, each = 9), sum(numberTypes)),
  192. step = rep(rep(step, 10), sum(numberTypes)),
  193. error = abs(errorVector),
  194. error2 = errorVector,
  195. LP = lpVector,
  196. LR = rep(lrVector, each = 90))
  197. allData$errorRaw <- allData$LR - allData$LP
  198. allData$distep <- allData$dist * allData$step
  199. allData$interact <- interaction(allData$dist, allData$step)
  200. ```
  201. ##Boot explanation
  202. ```{r}
  203. # OLS
  204. my.reg <- lm(LR ~ LP:neurType - 1, allData)
  205. # Predict LR for neurType axCount
  206. axCount <- 1
  207. k <- 64000
  208. y.p <- coef(my.reg)[axCount]*k
  209. # Create adjusted residuals
  210. leverage <- influence(my.reg, do.coef = FALSE)$hat
  211. my.s.resid <- residuals(my.reg)/sqrt(1-leverage)
  212. my.s.resid <- my.s.resid - mean(my.s.resid)
  213. reg <- my.reg
  214. s <- my.s.resid
  215. #####BOOTSTRAP (1 replicate)
  216. # Make bootstrap residuals
  217. ep.star <- sample(s, size=length(reg$residuals), replace=TRUE)
  218. # Make bootstrap Y
  219. y.star <- fitted(reg) + ep.star
  220. # Do bootstrap regression
  221. lp <- model.frame(reg)[,2]
  222. nt <- model.frame(reg)[,3]
  223. bs.reg <- lm(y.star ~ lp:nt - 1)
  224. # Create bootstrapped adjusted residuals
  225. bs.lev <- influence(bs.reg, do.coef = FALSE)$hat
  226. bs.s <- residuals(bs.reg)/sqrt(1-bs.lev)
  227. bs.s <- bs.s - mean(bs.s)
  228. # Calculate draw on prediction error
  229. x_Np1 <- k
  230. axType <- axCount
  231. xb.xb <- (coef(my.reg)[axType] - coef(bs.reg)[axType])*x_Np1
  232. unname(xb.xb + sample(bs.s, size=1))
  233. ```
  234. ##Descriptive
  235. ###Correlations
  236. ####Error v Dist v Step by Neuron
  237. ```{r}
  238. # # One plot per neuron type
  239. car::scatter3d(error ~ dist + step, data = allData[allData$neurType == "Type1", ],
  240. point.col = "red", surface=FALSE, ellipsoid = FALSE)
  241. rgl::open3d()
  242. car::scatter3d(error ~ dist + step, data = allData[allData$neurType == "Type2", ],
  243. point.col = "blue", surface=FALSE, ellipsoid = FALSE)
  244. rgl::open3d()
  245. car::scatter3d(error ~ dist + step, data = allData[allData$neurType == "Type3", ],
  246. point.col = "green", surface=FALSE, ellipsoid = FALSE)
  247. rgl::open3d()
  248. car::scatter3d(error ~ dist + step, data = allData[allData$neurType == "Type4", ],
  249. point.col = "purple", surface=FALSE, ellipsoid = FALSE)
  250. # All neurons in one plot
  251. # Add some jitter to step and dist in order to visualize the neuron types
  252. stepJit <- rep(c(0, 2, 4, 6), times = table(allData$neurType))
  253. distJit <- rep(c(0, 0.5, 1, 1.5), times = table(allData$neurType))
  254. allData$stepJit <- allData$step + stepJit
  255. allData$distJit <- allData$dist + distJit
  256. # Plot
  257. rgl::open3d()
  258. car::scatter3d(error ~ distJit + stepJit | neurType, data = allData,
  259. surface.col = c("red", "blue", "green", "purple"), surface=FALSE, ellipsoid = FALSE)
  260. # Plot
  261. # Duplicate data to avoid confusion
  262. data3D <- allData
  263. # Add a number identifyng every neuron-plane combination
  264. data3D$plaNum <- c(rep(1, numberTypes[1]*90), rep(2, numberTypes[2]*90), rep(3, numberTypes[3]*90), rep(4, numberTypes[4]*90))
  265. # Plot
  266. rgl::open3d()
  267. car::scatter3d(x = data3D$LP, y = data3D$LR, z = data3D$plaNum, group = data3D$neurType,
  268. surface.col = c("red", "blue", "green", "purple"), surface=FALSE, ellipsoid = FALSE)
  269. # rgl::rgl.snapshot("LR_LP_corr.png", fmt = "png")
  270. ```
  271. ####LP v Dist v Step by Neuron
  272. ```{r}
  273. # All neurons in one plot
  274. # Add some jitter to step and dist in order to visualize the neuron types
  275. stepJit <- rep(c(0, 2, 4, 6), times = table(allData$neurType))
  276. distJit <- rep(c(0, 0.5, 1, 1.5), times = table(allData$neurType))
  277. allData$stepJit <- allData$step + stepJit
  278. allData$distJit <- allData$dist + distJit
  279. # Plot
  280. rgl::open3d()
  281. car::scatter3d(LP ~ distJit + stepJit | neurType, data = allData,
  282. surface.col = c("red", "blue", "green", "purple"), surface=FALSE, ellipsoid = FALSE)
  283. ```
  284. ####LR vs LP 2d
  285. ```{r, fig.width=20, fig.height=15}
  286. # Define color and formula
  287. coul <- viridisLite::viridis(90)
  288. # coul <- viridisLite::viridis(10)
  289. formPlot <- formula("LR ~ LP")
  290. setwd("EstereoAnalysis/")
  291. png(filename=paste("scatterPerType.png", sep=""), type="cairo",
  292. units="in", width=20, height=15, pointsize=12,
  293. res=300)
  294. # Plor for every axon type
  295. par(mfcol=c(3,4))
  296. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  297. # Select data
  298. data2d <- allData[allData$neurType == i, ]
  299. data2d$combNum <- rep(1:90, length(unique(data2d$id)))
  300. # data2d$combNum <- rep(rep(1:10, each = 9), length(unique(data2d$id)))
  301. data2d$col <- coul[data2d$combNum]
  302. # Plot full data, 3.70 and 30.150; red dots are LRs
  303. plot(formPlot, data2d, pch = 21, bg = alpha(data2d$col, 0.5), col = NULL,
  304. cex = 0.8, cex.main = 2.5, cex.lab = 1.5, cex.axis = 1.5, main = i)
  305. points(data2d$LR, data2d$LR, bg="red", pch = 21, col = NULL, cex = 0.5)
  306. plot(formPlot, data2d[data2d$dist == 3 & data2d$step == 70, ],
  307. xlim = c(0, max(data2d$LP)),
  308. pch = 21, bg = alpha(data2d[data2d$dist == 3 & data2d$step == 70, "col"], 0.5),
  309. cex = 0.8, cex.main = 2.5, cex.lab = 1.5, cex.axis = 1.5, main = "3.70")
  310. points(data2d$LR, data2d$LR, bg="red", pch = 21, col = NULL, cex = 0.5)
  311. plot(formPlot, data2d[data2d$dist == 30 & data2d$step == 150, ],
  312. xlim = c(0, max(data2d$LP)),
  313. pch = 21, bg = alpha(data2d[data2d$dist == 30 & data2d$step == 150, "col"], 0.5),
  314. cex = 0.8, cex.main = 2.5, cex.lab = 1.5, cex.axis = 1.5, main = "30.150")
  315. points(data2d$LR, data2d$LR, bg="red", pch = 21, col = NULL, cex = 0.5)
  316. }
  317. dev.off()
  318. ```
  319. ####Error vs Dist.Step 2d
  320. ```{r, fig.width=20, fig.height=10}
  321. # Define color and formula
  322. coul <- viridisLite::viridis(90)
  323. # coul <- viridisLite::viridis(10)
  324. setwd("EstereoAnalysis/")
  325. png(filename=paste("scatterPerType_error.png", sep=""), type="cairo",
  326. units="in", width=20, height=10, pointsize=12,
  327. res=300)
  328. # Plor for every axon type
  329. maxErr <- max(allData$error)
  330. par(mfcol=c(2,4))
  331. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  332. # Select data
  333. data2d <- allData[allData$neurType == i, ]
  334. data2d$combNum <- rep(1:90, length(unique(data2d$id)))
  335. # data2d$combNum <- rep(rep(1:10, each = 9), length(unique(data2d$id)))
  336. data2d$col <- coul[data2d$combNum]
  337. formPlot <- formula("error ~ interact")
  338. # Plot full data, 3.70 and 30.150; red dots are LRs
  339. plot(formPlot, data2d, pch = 21, col = alpha(data2d$col, 0.5),
  340. cex = 0.8, cex.main = 2.5, cex.lab = 1.5, cex.axis = 1.5, main = i)
  341. # points(data2d$distep, data2d$error, bg="red", pch = 21, col = NULL, cex = 0.5)
  342. formPlot2 <- formula("error ~ distep")
  343. # Plot full data, 3.70 and 30.150; red dots are LRs
  344. plot(formPlot2, data2d, pch = 21, bg = alpha(data2d$col, 0.5), col = NULL,
  345. cex = 0.8, cex.main = 2.5, cex.lab = 1.5, cex.axis = 1.5, main = i)
  346. # points(data2d$distep, data2d$error, bg="red", pch = 21, col = NULL, cex = 0.5)
  347. }
  348. dev.off()
  349. ```
  350. ####Error vs Dist.Step 2d (ylim)
  351. ```{r, fig.width=20, fig.height=10}
  352. # Define color and formula
  353. coul <- viridisLite::viridis(90)
  354. # coul <- viridisLite::viridis(10)
  355. maxErr <- max(allData$error)
  356. setwd("EstereoAnalysis/")
  357. png(filename=paste("scatterPerType_errorylim.png", sep=""), type="cairo",
  358. units="in", width=20, height=10, pointsize=12,
  359. res=300)
  360. # Plor for every axon type
  361. par(mfcol=c(2,4))
  362. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  363. # Select data
  364. data2d <- allData[allData$neurType == i, ]
  365. data2d$combNum <- rep(1:90, length(unique(data2d$id)))
  366. # data2d$combNum <- rep(rep(1:10, each = 9), length(unique(data2d$id)))
  367. data2d$col <- coul[data2d$combNum]
  368. formPlot <- formula("error ~ interact")
  369. # Plot full data, 3.70 and 30.150; red dots are LRs
  370. plot(formPlot, data2d, pch = 21, col = alpha(data2d$col, 0.5),
  371. cex = 0.8, cex.main = 2.5, cex.lab = 1.5, cex.axis = 1.5, main = i, ylim = c(0, maxErr))
  372. # points(data2d$distep, data2d$error, bg="red", pch = 21, col = NULL, cex = 0.5)
  373. formPlot2 <- formula("error ~ distep")
  374. # Plot full data, 3.70 and 30.150; red dots are LRs
  375. plot(formPlot2, data2d, pch = 21, bg = alpha(data2d$col, 0.5), col = NULL,
  376. cex = 0.8, cex.main = 2.5, cex.lab = 1.5, cex.axis = 1.5, main = i, ylim = c(0, maxErr))
  377. # points(data2d$distep, data2d$error, bg="red", pch = 21, col = NULL, cex = 0.5)
  378. }
  379. dev.off()
  380. ```
  381. ##lmer
  382. ```{r}
  383. library(lme4)
  384. library(lmerTest)
  385. dataLmer <- allData[allData$neurType == "Type1", ]
  386. # dataLmer$interact <- interaction(dataLmer$dist, dataLmer$step, lex.order = T)
  387. # dataLmer$LPsca <- scale(dataLmer$LP)
  388. # dataLmer$LRsca <- scale(dataLmer$LR)
  389. # dataLmer$distsca <- scale(dataLmer$dist)
  390. # dataLmer$stepsca <- scale(dataLmer$step)
  391. # dataLmer$id2 <- factor(dataLmer$id)
  392. datagroup <- dataLmer %>% group_by(id)
  393. fit2 <- lmer(LP ~ LR + (LR|id), data=datagroup)
  394. rand(fit2)
  395. ```
  396. ```{r}
  397. library(scales)
  398. # Function to add a polygon if we have an X vector and two Y vectors of the same length.
  399. addpoly <- function(x,y1,y2,col=alpha("lightgrey",0.8),...){
  400. ii <- order(x)
  401. y1 <- y1[ii]
  402. y2 <- y2[ii]
  403. x <- x[ii]
  404. polygon(c(x,rev(x)), c(y1, rev(y2)), col=col, border=NA,...)
  405. }
  406. bb <- bootMer(fit2,
  407. FUN=function(x) predict(x, interval = "prediction"),
  408. nsim=250)
  409. ```
  410. ```{r}
  411. # Take quantiles of predictions from bootstrap replicates.
  412. # These represent the confidence interval of the mean at any value of Time.
  413. dataLmer$lci <- apply(bb$t, 2, quantile, 0.025)
  414. dataLmer$uci <- apply(bb$t, 2, quantile, 0.975)
  415. dataLmer$pred <- predict(fit2, interval = "prediction")
  416. # We will just plot one Diet for illustration
  417. dat <- subset(dataLmer, c(dist == 3 & step == 70))
  418. with(dat, {
  419. plot(LR,LP)
  420. addpoly(LR, lci, uci)
  421. lines(LR, pred)
  422. })
  423. # We will just plot one Diet for illustration
  424. dat <- subset(dataLmer, c(dist == 30 & step == 150))
  425. with(dat, {
  426. plot(LR,LP)
  427. addpoly(LR, lci, uci)
  428. lines(LR, pred)
  429. })
  430. ```
  431. ##lm
  432. ```{r, fig.width=20, fig.height=15}
  433. gList <- list()
  434. gCount <- 1
  435. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  436. dataMod <- allData[allData$neurType == i, ]
  437. lmMod <- lm(LR ~ LP - 1, dataMod)
  438. pi <- predict(lmMod, interval = "prediction")
  439. dataJoin <- cbind(dataMod, pi)
  440. gList[[gCount]] <- ggplot(dataJoin, aes(LP, LR))+
  441. geom_point() +
  442. geom_line(aes(y=lwr), color = "red", linetype = "dashed")+
  443. geom_line(aes(y=upr), color = "red", linetype = "dashed")+
  444. geom_smooth(method=lm, se=TRUE)+
  445. ggtitle(i)+
  446. theme_bw()+
  447. theme(plot.title = element_text(size = 20, face = "bold"),
  448. axis.title = element_text(size = 15, face = "bold"))
  449. gCount <- gCount + 1
  450. gList[[gCount]] <- ggplot(dataJoin[dataJoin$dist == 3 & dataJoin$step == 70, ], aes(LP, LR))+
  451. geom_point() +
  452. geom_line(aes(y=lwr), color = "red", linetype = "dashed")+
  453. geom_line(aes(y=upr), color = "red", linetype = "dashed")+
  454. geom_smooth(method=lm, se=TRUE)+
  455. ggtitle("3.70") +
  456. theme_bw()+
  457. theme(plot.title = element_text(size = 20, face = "bold"),
  458. axis.title = element_text(size = 15, face = "bold"))
  459. gCount <- gCount + 1
  460. gList[[gCount]] <- ggplot(dataJoin[dataJoin$dist == 30 & dataJoin$step == 150, ], aes(LP, LR))+
  461. geom_point() +
  462. geom_line(aes(y=lwr), color = "red", linetype = "dashed")+
  463. geom_line(aes(y=upr), color = "red", linetype = "dashed")+
  464. geom_smooth(method=lm, se=TRUE)+
  465. ggtitle("30.150")+
  466. theme_bw()+
  467. theme(plot.title = element_text(size = 20, face = "bold"),
  468. axis.title = element_text(size = 15, face = "bold"))
  469. gCount <- gCount + 1
  470. # gList[[i]] <- list(g0, g1, g2)
  471. }
  472. gList <- list(gList[[1]], gList[[4]], gList[[7]], gList[[10]],
  473. gList[[2]], gList[[5]], gList[[8]], gList[[11]],
  474. gList[[3]], gList[[6]], gList[[9]], gList[[12]])
  475. setwd("EstereoAnalysis/")
  476. png(filename=paste("confpredInt_lm.png", sep=""), type="cairo",
  477. units="in", width=20, height=15, pointsize=12,
  478. res=300)
  479. ggarrange(plotlist = gList, ncol = 4, nrow = 3)
  480. dev.off()
  481. ```
  482. ###lm train/test
  483. ```{r, fig.width=20, fig.height=15}
  484. gList <- list()
  485. gCount <- 1
  486. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  487. dataType <- allData[allData$neurType == i, ]
  488. # Stratified random training/test sets
  489. stratDat <- stratified(dataType, c("dist", "step"), 0.7, bothSets = TRUE, replace = FALSE)
  490. trainSet <- stratDat$SET1
  491. testSet <- stratDat$SET2
  492. lmMod <- lm(LR ~ LP - 1, trainSet)
  493. pi <- predict(lmMod, testSet, interval = "prediction")
  494. dataJoin <- cbind(testSet, pi)
  495. gList[[gCount]] <- ggplot(dataJoin, aes(LP, LR))+
  496. geom_point() +
  497. geom_line(aes(y=lwr), color = "red", linetype = "dashed")+
  498. geom_line(aes(y=upr), color = "red", linetype = "dashed")+
  499. geom_smooth(method=lm, se=TRUE)+
  500. ggtitle(i)+
  501. theme_bw()+
  502. theme(plot.title = element_text(size = 20, face = "bold"),
  503. axis.title = element_text(size = 15, face = "bold"))
  504. gCount <- gCount + 1
  505. gList[[gCount]] <- ggplot(dataJoin[dataJoin$dist == 3 & dataJoin$step == 70, ], aes(LP, LR))+
  506. geom_point() +
  507. geom_line(aes(y=lwr), color = "red", linetype = "dashed")+
  508. geom_line(aes(y=upr), color = "red", linetype = "dashed")+
  509. geom_smooth(method=lm, se=TRUE)+
  510. ggtitle("3.70") +
  511. theme_bw()+
  512. theme(plot.title = element_text(size = 20, face = "bold"),
  513. axis.title = element_text(size = 15, face = "bold"))
  514. gCount <- gCount + 1
  515. gList[[gCount]] <- ggplot(dataJoin[dataJoin$dist == 30 & dataJoin$step == 150, ], aes(LP, LR))+
  516. geom_point() +
  517. geom_line(aes(y=lwr), color = "red", linetype = "dashed")+
  518. geom_line(aes(y=upr), color = "red", linetype = "dashed")+
  519. geom_smooth(method=lm, se=TRUE)+
  520. ggtitle("30.150")+
  521. theme_bw()+
  522. theme(plot.title = element_text(size = 20, face = "bold"),
  523. axis.title = element_text(size = 15, face = "bold"))
  524. gCount <- gCount + 1
  525. # gList[[i]] <- list(g0, g1, g2)
  526. }
  527. gList <- list(gList[[1]], gList[[4]], gList[[7]], gList[[10]],
  528. gList[[2]], gList[[5]], gList[[8]], gList[[11]],
  529. gList[[3]], gList[[6]], gList[[9]], gList[[12]])
  530. setwd("EstereoAnalysis/")
  531. png(filename=paste("confpredInt_lm_traintest.png", sep=""), type="cairo",
  532. units="in", width=20, height=15, pointsize=12,
  533. res=300)
  534. ggarrange(plotlist = gList, ncol = 4, nrow = 3)
  535. dev.off()
  536. ```
  537. ##Bootstrap PI
  538. This code is meant to be run independently for every neurType and in parallel
  539. ```{r}
  540. # OLS
  541. my.reg <- lm(LR ~ LP:neurType - 1, allData)
  542. # summary(my.reg)
  543. # List to store distances
  544. distList <- list()
  545. # List to store random selection
  546. distRand <- list()
  547. distCount <- 1
  548. # Subset a particular neurType
  549. dataToBoot <- allData[allData$neurType == "Type1", ]
  550. axCount <- 1
  551. # Ensure reproducibility
  552. set.seed(123456)
  553. for (i in unique(allData$dist)) {
  554. # List to store steps
  555. stepList <- list()
  556. # List to store random selection
  557. stepRand <- list()
  558. stepCount <- 1
  559. for (j in unique(allData$step)) {
  560. # Subset dist and step
  561. dataGroup <- dataToBoot[dataToBoot$dist == i & dataToBoot$step == j, ]
  562. # Random sample of N=10
  563. dataSub <- sample_n(dataGroup, 10, replace = FALSE)
  564. # Store selected for later
  565. stepRand[[stepCount]] <- dataSub
  566. # List to store errors
  567. epList <- list()
  568. epCount <- 1
  569. for (k in dataSub[ , "LP"]) {
  570. # Predict LR for neurType axCount
  571. y.p <- coef(my.reg)[axCount]*k
  572. # Create adjusted residuals
  573. leverage <- influence(my.reg, do.coef = FALSE)$hat
  574. my.s.resid <- residuals(my.reg)/sqrt(1-leverage)
  575. my.s.resid <- my.s.resid - mean(my.s.resid)
  576. # Do bootstrap with 100 replications
  577. print("Enter replication")
  578. ep.draws <- replicate(n=100, the.replication.gen(reg = my.reg, s = my.s.resid, axCount, x_Np1 = k))
  579. # Store in list
  580. epList[[epCount]] <- ep.draws
  581. epCount <- epCount + 1
  582. print(epCount)
  583. }
  584. # Store in list
  585. stepList[[stepCount]] <- epList
  586. stepCount <- stepCount + 1
  587. }
  588. names(stepList) <- unique(allData$step)[1]
  589. names(stepRand) <- unique(allData$step)[1]
  590. # Store in list
  591. distList[[distCount]] <- stepList
  592. distRand[[distCount]] <- stepRand
  593. distCount <- distCount + 1
  594. }
  595. names(distList) <- unique(allData$dist)[1]
  596. names(distRand) <- unique(allData$dist)[1]
  597. # saveRDS(list(distList, distRand), paste("stereo_bootPI_full_Type", axCount, ".rds", sep = ""))
  598. ```
  599. ####Estimate porcentual errors
  600. ```{r, fig.width=8, fig.height=8}
  601. # 10 random neurons per combination of dist:step
  602. numExtract <- 20
  603. # List to store axon types
  604. axList <- list()
  605. for (m in c("Type1", "Type2", "Type3", "Type4")) {
  606. # Load object
  607. bootPI <- readRDS(paste("EstereoAnalysis/stereo_bootPI_full_", m, "_boot20.rds", sep = ""))
  608. # First list is prediction error, second is random subset
  609. typeList <- bootPI[[1]]
  610. typeRand <- bootPI[[2]]
  611. # Estimate and store in list
  612. peList <- list()
  613. peCount <- 1
  614. for (i in factor(unique(allData$dist))) {
  615. for (j in factor(unique(allData$step))) {
  616. # Extract LR values
  617. lr <- typeRand[[i]][[j]]$LR
  618. for (k in 1:length(lr)) {
  619. # Divide absolute errors by LR to get porcentual errors
  620. pe <- typeList[[i]][[j]][[k]] / lr[k]
  621. # Store in list
  622. peList[[peCount]] <- pe*100
  623. peCount <-peCount + 1
  624. }
  625. }
  626. }
  627. # Reformat as data frame
  628. peFrame <- data.frame(pe = unlist(peList),
  629. neurType = rep(m, 90*numExtract*100),
  630. dist = rep(unique(allData$dist), each = 9*numExtract*100),
  631. step = rep(rep(unique(allData$step), each = numExtract*100), 10))
  632. peFrame$interact <- interaction(peFrame$dist, peFrame$step, lex.order=T)
  633. # Store in list
  634. axList[[m]] <- list(peFrame = peFrame, typeList = typeList, typeRand = typeRand)
  635. }
  636. ```
  637. #####Plot density
  638. ```{r, fig.height=10, fig.width=20}
  639. # Plot
  640. # peGroup <- peFrame %>% group_by(interact)
  641. # peSample <- sample_n(peGroup, 100)
  642. plotList <- list()
  643. for (m in c("Type1", "Type2", "Type3", "Type4")) {
  644. plotList[[m]] <- ggplot(axList[[m]]$peFrame, aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  645. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  646. geom_density_ridges_gradient(alpha = 0.8) +
  647. theme_ridges() +
  648. theme(legend.position = "none") +
  649. xlab("% Error") +
  650. xlim(c(-40,40)) +
  651. ggtitle(m)
  652. }
  653. setwd("EstereoAnalysis/")
  654. png(filename=paste("prederrorDistributions_ols_replacementBOOT20.png", sep=""), type="cairo",
  655. units="in", width=20, height=10, pointsize=12,
  656. res=300)
  657. ggarrange(plotlist = plotList, ncol = 4, nrow = 1)
  658. dev.off()
  659. ```
  660. #####Errors vs cumul probability
  661. ```{r, fig.height=5, fig.width=20}
  662. # Inverse quantile
  663. quantInv <- function(distr, value) ecdf(distr)(value)
  664. # Function to apply to all axon types
  665. quantType <- function(peFrame, probSeq) {
  666. probList <- list()
  667. for (i in unique(peFrame$interact)) {
  668. dataProb <- peFrame[peFrame$interact == i, "pe"]
  669. probVec <- numeric()
  670. for (j in probSeq) {
  671. errProb <- quantInv(dataProb, j) - quantInv(dataProb, -j)
  672. probVec <- c(probVec, errProb)
  673. }
  674. probList[[i]] <- probVec
  675. }
  676. return(probList)
  677. }
  678. # Define errors for which to calculate probability
  679. binProb <- 0.5
  680. probSeq <- seq(binProb, 100, binProb)
  681. # Store axon types in lists
  682. axProb <- lapply(axList, function(x) quantType(x$peFrame, probSeq))
  683. # Save
  684. saveRDS(axProb, "errorProbs_bin0.5_boot20.rds")
  685. ```
  686. ######Plot heatmap
  687. ```{r, fig.height=5, fig.width=15}
  688. library(latticeExtra)
  689. # Reformat as dataframe
  690. binProb <- 0.5
  691. probSeq <- seq(binProb, 100, binProb)
  692. axProb <- readRDS("errorProbs_bin0.5_boot20_notRel.rds")
  693. probFrame <- data.frame(error = rep(probSeq, 90*4),
  694. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = length(probSeq)*90),
  695. dist = rep(rep(unique(allData$dist), each = length(probSeq)*9), 4),
  696. step = rep(rep(unique(allData$step), each = length(probSeq)), 10*4),
  697. prob = unlist(axProb))
  698. # Plot conttour plot for 5% error
  699. library(viridisLite)
  700. coul <- viridis(1000)
  701. # Store heatmaps
  702. heatList <- list()
  703. smoothList <- list()
  704. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  705. levelList1 <- list()
  706. levelList2 <- list()
  707. for (j in c(5, 10, 20)) {
  708. dataPlot <- probFrame[probFrame$neurType == i & probFrame$error == j, ]
  709. levelList1[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  710. col.regions = coul,
  711. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  712. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  713. ylim = c(155,65),
  714. colorkey = list(at = (seq(min(dataPlot$prob),
  715. max(dataPlot$prob),
  716. 0.001))),
  717. main = paste("P(%Error <=", j, ")", sep = ""))
  718. levelList2[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  719. col.regions = coul,
  720. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  721. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  722. ylim = c(150,70),
  723. xlim = c(3,30),
  724. cuts = 20,
  725. colorkey = list(at = (seq(min(dataPlot$prob),
  726. max(dataPlot$prob),
  727. 0.001))),
  728. main = paste("P(%Error <=", j, ")", sep = ""),
  729. panel = panel.levelplot.points, cex = 0) +
  730. layer_(panel.2dsmoother(..., n = 200))
  731. }
  732. heatList[[i]] <- levelList1
  733. smoothList[[i]] <- levelList2
  734. }
  735. # Plot
  736. setwd("EstereoAnalysis/")
  737. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  738. png(filename=paste("errorProbabilities_heatmap_", i, "_BOOT20.png", sep=""), type="cairo",
  739. units="in", width=15, height=10, pointsize=12,
  740. res=300)
  741. gridExtra::grid.arrange(grobs = c(heatList[[i]], smoothList[[i]]), ncol = 3, nrow = 2)
  742. dev.off()
  743. }
  744. ```
  745. #####Mean errors
  746. ```{r, fig.height=5, fig.width=20}
  747. # Function to apply to all axon types
  748. meanType <- function(peFrame) {
  749. probList <- list()
  750. for (i in unique(peFrame$interact)) {
  751. dataProb <- peFrame[peFrame$interact == i, "pe"]
  752. probList[[i]] <- mean(abs(dataProb))
  753. }
  754. return(probList)
  755. }
  756. # Store axon types in lists
  757. axMean <- lapply(axList, function(x) meanType(x$peFrame))
  758. ```
  759. ######Plot heatmap
  760. ```{r, fig.height=5, fig.width=15}
  761. library(latticeExtra)
  762. # Reformat as dataframe
  763. meanFrame <- data.frame(neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = 90),
  764. dist = rep(rep(unique(allData$dist), each = 9), 4),
  765. step = rep(unique(allData$step), 10*4),
  766. meanErr = unlist(axMean))
  767. # Contour color palette
  768. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  769. colfin <- colfunc(1000)
  770. library(viridisLite)
  771. coul <- viridis(1000)
  772. # Store heatmaps
  773. heatList <- list()
  774. smoothList <- list()
  775. for (i in c("Type1", "Type2", "Type3", "Type4")) {
  776. heatList[[i]] <- levelplot(meanErr ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  777. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  778. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  779. ylim = c(155, 65),
  780. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "meanErr"]),
  781. max(meanFrame[meanFrame$neurType == i, "meanErr"]),
  782. 0.05))),
  783. main = paste("Mean Abs Error,", i))
  784. smoothList[[i]] <- levelplot(meanErr ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  785. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  786. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  787. ylim = c(150,70),
  788. xlim = c(3,30),
  789. cuts = 20,
  790. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "meanErr"]),
  791. max(meanFrame[meanFrame$neurType == i, "meanErr"]),
  792. 0.05))),
  793. main = paste("Mean Abs Error,", i),
  794. panel = panel.levelplot.points, cex = 0) +
  795. layer_(panel.2dsmoother(..., n = 200))
  796. }
  797. # Plot
  798. setwd("EstereoAnalysis/")
  799. png(filename="meanProbabilities_heatmap_reverseBOOT20.png", type="cairo",
  800. units="in", width=20, height=10, pointsize=12,
  801. res=300)
  802. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  803. dev.off()
  804. ```
  805. ####Interval limits
  806. ```{r, fig.width=8, fig.height=8}
  807. # 10 random neurons per combination of dist:step
  808. numExtract <- 20
  809. # List to store axon types
  810. axList <- list()
  811. for (m in c("Type1", "Type2", "Type3", "Type4")) {
  812. # Load object
  813. bootPI <- readRDS(paste("EstereoAnalysis/stereo_bootPI_full_", m, "_boot20.rds", sep = ""))
  814. # First list is prediction error, second is random subset
  815. typeList <- bootPI[[1]]
  816. typeRand <- bootPI[[2]]
  817. # Estimate and store in list
  818. peList <- list()
  819. peCount <- 1
  820. for (i in factor(unique(allData$dist))) {
  821. for (j in factor(unique(allData$step))) {
  822. # Extract LR values
  823. lr <- typeRand[[i]][[j]]$LR
  824. for (k in 1:length(lr)) {
  825. # Divide absolute errors by LR to get porcentual errors
  826. pe <- typeList[[i]][[j]][[k]] / lr[k]
  827. # Store in list
  828. peList[[peCount]] <- pe*100
  829. peCount <-peCount + 1
  830. }
  831. }
  832. }
  833. # Reformat as data frame
  834. peFrame <- data.frame(pe = unlist(peList),
  835. neurType = rep(m, 90*numExtract*100),
  836. dist = rep(unique(allData$dist), each = 9*numExtract*100),
  837. step = rep(rep(unique(allData$step), each = numExtract*100), 10))
  838. peFrame$interact <- interaction(peFrame$dist, peFrame$step, lex.order=T)
  839. # Store in list
  840. axList[[m]] <- list(peFrame = peFrame, typeList = typeList, typeRand = typeRand)
  841. }
  842. ```
  843. ##Bootstrap PI (only one type)
  844. This code is meant to be run independently for every neurType and in parallel
  845. ```{r}
  846. # OLS
  847. my.reg <- lm(LR ~ LP - 1, data = allData[allData$neurType == "Type1", ])
  848. # summary(my.reg)
  849. # List to store distances
  850. distList <- list()
  851. # List to store random selection
  852. distRand <- list()
  853. distCount <- 1
  854. # Subset a particular neurType
  855. dataToBoot <- allData[allData$neurType == "Type1", ]
  856. axCount <- 1
  857. # Ensure reproducibility
  858. set.seed(123456)
  859. for (i in unique(allData$dist)) {
  860. # List to store steps
  861. stepList <- list()
  862. # List to store random selection
  863. stepRand <- list()
  864. stepCount <- 1
  865. for (j in unique(allData$step)) {
  866. # Subset dist and step
  867. dataGroup <- dataToBoot[dataToBoot$dist == i & dataToBoot$step == j, ]
  868. # Random sample of N=10
  869. # dataSub <- sample_n(dataGroup, 10, replace = FALSE)
  870. dataSub <- dataGroup
  871. # Store selected for later
  872. stepRand[[stepCount]] <- dataSub
  873. # List to store errors
  874. epList <- list()
  875. epCount <- 1
  876. for (k in dataSub[ , "LP"]) {
  877. # Predict LR for neurType axCount
  878. y.p <- coef(my.reg)[1]*k
  879. # Create adjusted residuals
  880. leverage <- influence(my.reg, do.coef = FALSE)$hat
  881. my.s.resid <- residuals(my.reg)/sqrt(1-leverage)
  882. my.s.resid <- my.s.resid - mean(my.s.resid)
  883. # Do bootstrap with 100 replications
  884. # print("Enter replication")
  885. ep.draws <- replicate(n=100, the.replication2(reg = my.reg, s = my.s.resid, x_Np1 = k))
  886. # Store in list
  887. epList[[epCount]] <- ep.draws
  888. # print(epCount)
  889. epCount <- epCount + 1
  890. }
  891. # Store in list
  892. stepList[[stepCount]] <- epList
  893. print(paste("Step", stepCount, "complete"))
  894. stepCount <- stepCount + 1
  895. }
  896. names(stepList) <- unique(allData$step)
  897. names(stepRand) <- unique(allData$step)
  898. # Store in list
  899. distList[[distCount]] <- stepList
  900. distRand[[distCount]] <- stepRand
  901. print(paste("Dist", distCount, "complete"))
  902. distCount <- distCount + 1
  903. }
  904. names(distList) <- unique(allData$dist)
  905. names(distRand) <- unique(allData$dist)
  906. saveRDS(list(distList, distRand), paste("stereo_bootPI_full_ONLYType", axCount, ".rds", sep = ""))
  907. ```
  908. ####Estimate porcentual errors
  909. ```{r, fig.width=8, fig.height=8}
  910. # 10 random neurons per combination of dist:step
  911. numExtract <- 90
  912. # List to store axon types
  913. axList <- list()
  914. for (m in c("Type1")) {
  915. # Load object
  916. bootPI <- readRDS(paste("EstereoAnalysis/stereo_bootPI_full_ONLY", m, ".rds", sep = ""))
  917. # First list is prediction error, second is random subset
  918. typeList <- bootPI[[1]]
  919. typeRand <- bootPI[[2]]
  920. # Estimate and store in list
  921. peList <- list()
  922. peCount <- 1
  923. for (i in factor(unique(allData$dist))) {
  924. for (j in factor(unique(allData$step))) {
  925. # Extract LR values
  926. lr <- typeRand[[i]][[j]]$LR
  927. for (k in 1:length(lr)) {
  928. # Divide absolute errors by LR to get porcentual errors
  929. pe <- (lr[k] - typeList[[i]][[j]][[k]]) / lr[k]
  930. # Store in list
  931. peList[[peCount]] <- pe*100
  932. peCount <-peCount + 1
  933. }
  934. }
  935. }
  936. # Reformat as data frame
  937. peFrame <- data.frame(pe = unlist(peList),
  938. neurType = rep(m, 90*numExtract*100),
  939. dist = rep(unique(allData$dist), each = 9*numExtract*100),
  940. step = rep(rep(unique(allData$step), each = numExtract*100), 10))
  941. peFrame$interact <- interaction(peFrame$dist, peFrame$step, lex.order=T)
  942. # Store in list
  943. axList[[m]] <- list(peFrame = peFrame, typeList = typeList, typeRand = typeRand)
  944. }
  945. ```
  946. #####Mean errors
  947. ```{r, fig.height=5, fig.width=20}
  948. # Function to apply to all axon types
  949. meanType <- function(peFrame) {
  950. probList <- list()
  951. for (i in unique(peFrame$interact)) {
  952. dataProb <- peFrame[peFrame$interact == i, "pe"]
  953. probList[[i]] <- mean(abs(dataProb))
  954. }
  955. return(probList)
  956. }
  957. # Store axon types in lists
  958. axMean <- lapply(axList, function(x) meanType(x$peFrame))
  959. ```
  960. ######Plot heatmap
  961. ```{r, fig.height=5, fig.width=15}
  962. library(latticeExtra)
  963. # Reformat as dataframe
  964. meanFrame <- data.frame(neurType = rep("Type1", 90),
  965. dist = rep(unique(allData$dist), each = 9),
  966. step = rep(unique(allData$step), 10),
  967. meanErr = unlist(axMean))
  968. # Contour color palette
  969. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  970. colfin <- colfunc(1000)
  971. library(viridisLite)
  972. coul <- viridis(1000)
  973. # Store heatmaps
  974. heatList <- list()
  975. smoothList <- list()
  976. for (i in c("Type1")) {
  977. heatList[[i]] <- levelplot(meanErr ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  978. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  979. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  980. ylim = c(155, 65),
  981. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "meanErr"]),
  982. max(meanFrame[meanFrame$neurType == i, "meanErr"]),
  983. 0.05))),
  984. main = paste("Mean Abs Error,", i))
  985. smoothList[[i]] <- levelplot(meanErr ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  986. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  987. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  988. ylim = c(150,70),
  989. xlim = c(3,30),
  990. cuts = 20,
  991. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "meanErr"]),
  992. max(meanFrame[meanFrame$neurType == i, "meanErr"]),
  993. 0.05))),
  994. main = paste("Mean Abs Error,", i),
  995. panel = panel.levelplot.points, cex = 0) +
  996. layer_(panel.2dsmoother(..., n = 200))
  997. }
  998. # Plot
  999. setwd("EstereoAnalysis/")
  1000. png(filename="meanProbabilities_heatmap_reverseBOOT20.png", type="cairo",
  1001. units="in", width=20, height=10, pointsize=12,
  1002. res=300)
  1003. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  1004. dev.off()
  1005. ```
  1006. ##GEE
  1007. ```{r}
  1008. # regFul <- geeglm(LR ~ LP:dist:step:neurType - 1, allData, id = id, corstr = "independence", family = "gaussian")
  1009. regFul <- lm(LR ~ LP:dist:step:neurType - 1, allData)
  1010. summary(regFul)
  1011. t1 <- allData[allData$neurType == "Type1", ]
  1012. t1$prod <- t1$LP*t1$dist*t1$step
  1013. t1$alpha <- t1$LR/t1$prod
  1014. t1$LRp <- t1$prod*coef(regFul)[1]
  1015. ```
  1016. ```{r, fig.height=5, fig.width=15}
  1017. t1 <- allData[allData$neurType == "Type1", ]
  1018. par(mfrow=c(1,3))
  1019. plot(t1$dist*t1$step, t1$error2)
  1020. plot(t1$dist, t1$error2)
  1021. plot(t1$step, t1$error2)
  1022. t1mean <- aggregate(error2 ~ step + dist, t1, mean)
  1023. par(mfrow=c(1,3))
  1024. plot(t1mean$dist*t1mean$step, t1mean$error2)
  1025. plot(t1mean$dist, t1mean$error2)
  1026. plot(t1mean$step, t1mean$error2)
  1027. t1mean$prod <- t1mean$step*t1mean$dist
  1028. summary(lm(error2 ~ step*dist, t1mean))
  1029. ```
  1030. ```{r, fig.height=5, fig.width=15}
  1031. t1 <- allData[allData$neurType == "Type1", ]
  1032. par(mfrow=c(1,3))
  1033. plot(t1$dist*t1$step, t1$error, pch = 20, cex = 0.1, ylim = c(0,5))
  1034. plot(t1$dist, t1$error)
  1035. plot(t1$step, t1$error)
  1036. t1mean <- aggregate(error ~ step + dist, t1, mean)
  1037. par(mfrow=c(1,3))
  1038. plot(t1mean$dist*t1mean$step, t1mean$error, pch = 20, cex = 0.8)
  1039. plot(t1mean$dist, t1mean$error)
  1040. plot(t1mean$step, t1mean$error)
  1041. # t1mean$prod <- t1mean$step*t1mean$dist
  1042. # summary(lm(error ~ step*dist, t1mean))
  1043. # summary(lm(error ~ step*dist, t1))
  1044. # summary(geeglm(error ~ step*dist, t1, id = id, corstr = "exchangeable", family = "gaussian"))
  1045. ```
  1046. ```{r}
  1047. my.reg <- lm(LR ~ LP - 1, allData)
  1048. cv.lm(fit, k = 5, seed = 5483, max_cores = 1)
  1049. ```