modelFree_stereology_CV_LRLP.Rmd 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  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. library(data.table)
  32. options(digits = 10)
  33. # https://rstudio-pubs-static.s3.amazonaws.com/297778_5fce298898d64c81a4127cf811a9d486.html
  34. ##############################
  35. # Bootstrap PI per axon type # STEREOLOGY VERSION, LR vs LP
  36. ##############################
  37. the.replication.type2 <- function(reg, s, disti, stepj, trainset, x_Np1 = 0){
  38. # Make bootstrap residuals
  39. ep.star <- sample(s, size=length(reg$residuals),replace=TRUE)
  40. # Make bootstrap Y
  41. y.star <- fitted(reg) + ep.star
  42. # Do bootstrap regression
  43. lp <- model.frame(reg)[,2]
  44. bs.reg <- lm(y.star ~ lp - 1)
  45. # Create bootstrapped adjusted residuals
  46. bs.lev <- influence(bs.reg, do.coef = FALSE)$hat
  47. bs.s <- residuals(bs.reg)
  48. bs.levAdd <- bs.lev[which(trainset$dist == disti & trainset$step == stepj)]
  49. bs.sAdd <- bs.s[which(trainset$dist == disti & trainset$step == stepj)]
  50. bs.Stud <- bs.sAdd/sqrt(1-bs.levAdd)
  51. bs.add <- bs.Stud - mean(bs.Stud)
  52. # Calculate draw on prediction error
  53. # xb.xb <- coef(my.reg)["(Intercept)"] - coef(bs.reg)["(Intercept)"]
  54. xb.xb <- (coef(reg) - coef(bs.reg))*x_Np1
  55. return(unname(xb.xb + sample(bs.sAdd, size=1)))
  56. }
  57. ##############################
  58. # Bootstrap PI per axon type # STEREOLOGY VERSION, LR vs LP
  59. ##############################
  60. the.replication.type3 <- function(reg, s, x_Np1 = 0){
  61. # Make bootstrap residuals
  62. ep.star <- sample(s, size=length(reg$residuals),replace=TRUE)
  63. # Make bootstrap Y
  64. y.star <- fitted(reg) + ep.star
  65. # Do bootstrap regression
  66. lp <- model.frame(reg)[,2]
  67. bs.reg <- lm(y.star ~ lp - 1)
  68. # Estimation
  69. return(unname(coef(bs.reg)*x_Np1))
  70. }
  71. ##############################
  72. # Stratified random sampling #
  73. ##############################
  74. stratified <- function(df, group, size, select = NULL,
  75. replace = FALSE, bothSets = FALSE) {
  76. if (is.null(select)) {
  77. df <- df
  78. } else {
  79. if (is.null(names(select))) stop("'select' must be a named list")
  80. if (!all(names(select) %in% names(df)))
  81. stop("Please verify your 'select' argument")
  82. temp <- sapply(names(select),
  83. function(x) df[[x]] %in% select[[x]])
  84. df <- df[rowSums(temp) == length(select), ]
  85. }
  86. df.interaction <- interaction(df[group], drop = TRUE)
  87. df.table <- table(df.interaction)
  88. df.split <- split(df, df.interaction)
  89. if (length(size) > 1) {
  90. if (length(size) != length(df.split))
  91. stop("Number of groups is ", length(df.split),
  92. " but number of sizes supplied is ", length(size))
  93. if (is.null(names(size))) {
  94. n <- setNames(size, names(df.split))
  95. message(sQuote("size"), " vector entered as:\n\nsize = structure(c(",
  96. paste(n, collapse = ", "), "),\n.Names = c(",
  97. paste(shQuote(names(n)), collapse = ", "), ")) \n\n")
  98. } else {
  99. ifelse(all(names(size) %in% names(df.split)),
  100. n <- size[names(df.split)],
  101. stop("Named vector supplied with names ",
  102. paste(names(size), collapse = ", "),
  103. "\n but the names for the group levels are ",
  104. paste(names(df.split), collapse = ", ")))
  105. }
  106. } else if (size < 1) {
  107. n <- round(df.table * size, digits = 0)
  108. } else if (size >= 1) {
  109. if (all(df.table >= size) || isTRUE(replace)) {
  110. n <- setNames(rep(size, length.out = length(df.split)),
  111. names(df.split))
  112. } else {
  113. message(
  114. "Some groups\n---",
  115. paste(names(df.table[df.table < size]), collapse = ", "),
  116. "---\ncontain fewer observations",
  117. " than desired number of samples.\n",
  118. "All observations have been returned from those groups.")
  119. n <- c(sapply(df.table[df.table >= size], function(x) x = size),
  120. df.table[df.table < size])
  121. }
  122. }
  123. temp <- lapply(
  124. names(df.split),
  125. function(x) df.split[[x]][sample(df.table[x],
  126. n[x], replace = replace), ])
  127. set1 <- do.call("rbind", temp)
  128. if (isTRUE(bothSets)) {
  129. set2 <- df[!rownames(df) %in% rownames(set1), ]
  130. list(SET1 = set1, SET2 = set2)
  131. } else {
  132. set1
  133. }
  134. }
  135. ```
  136. ##Load data
  137. ```{r}
  138. # Get file paths
  139. axonNames <- list.files(paste("EstereoDataPlanos/", sep=""), full.names=T)
  140. # Load matlab file
  141. axonFiles <- lapply(axonNames, function(x) readMat(x))
  142. names(axonFiles) <- c("Type1", "Type2", "Type3", "Type4")
  143. # Extract data
  144. # errorMatrix contains 4 arrays, one per neuron type
  145. # within each array, the dimensions corresponds to step:dist:neuron
  146. # this means that each array has as many matrices as neuron of a certain type
  147. dist <- lapply(axonFiles, function(x) x$Distancias.Entre.Planos)[[1]]
  148. step <- lapply(axonFiles, function(x) x$Step.Lengths)[[1]]
  149. errorMatrix <- lapply(axonFiles, function(x) x$MATRIZ.ERROR.LENGTH)
  150. lpMatrix <- lapply(axonFiles, function(x) x$MATRIZ.ESTIMATED.AXON.LENGTH)
  151. lrVals <- lapply(axonFiles, function(x) x$AXON.REAL.LENGTH)
  152. # Get number of neurons per type
  153. numberTypes <- unlist(lapply(errorMatrix, function(x) dim(x)[3]))
  154. # Vectorizing the arrays goes as follows: neuron, dist, step
  155. errorVector <- unlist(lapply(errorMatrix, function(x) as.vector(x)))
  156. lpVector <- unlist(lapply(lpMatrix, function(x) as.vector(x)))
  157. lrVector <- unlist(lapply(lrVals, function(x) as.vector(x)))
  158. # Store in data frames
  159. allData <- data.frame(id = rep(1:sum(numberTypes), each = 90),
  160. neurType = rep(c("Type1", "Type2", "Type3", "Type4"), times = 90*numberTypes),
  161. dist = rep(rep(dist, each = 9), sum(numberTypes)),
  162. step = rep(rep(step, 10), sum(numberTypes)),
  163. error = abs(errorVector),
  164. error2 = errorVector,
  165. LP = lpVector,
  166. LR = rep(lrVector, each = 90))
  167. allData$errorRaw <- allData$LR - allData$LP
  168. ```
  169. ##Bootstrap PI - Prediction CV - LR vs LP
  170. This code is meant to be run independently for every neurType and in parallel
  171. ```{r}
  172. # Ensure reproducibility
  173. set.seed(123456)
  174. # Subset axon type
  175. dataCV <- allData[allData$neurType == "Type1", ]
  176. # List to store CV repetitions
  177. cvList <- list ()
  178. cvRand <- list()
  179. y.cv <- list()
  180. for (h in 1:10) {
  181. # Stratified random training/test sets
  182. stratDat <- stratified(dataCV, c("dist", "step"), 0.7, bothSets = TRUE, replace = FALSE)
  183. trainSet <- stratDat$SET1
  184. testSet <- stratDat$SET2
  185. # Store train and test set
  186. cvRand[[h]] <- list(trainSet = trainSet, testSet = testSet)
  187. # OLS with training set
  188. my.reg <- lm(LR ~ LP - 1, trainSet)
  189. # Create adjusted residuals
  190. leverage <- influence(my.reg)$hat
  191. my.s.resid <- residuals(my.reg)/sqrt(1-leverage)
  192. my.s.resid <- my.s.resid - mean(my.s.resid)
  193. my.s.resid <- residuals(my.reg)
  194. # List to store errors
  195. epList <- list()
  196. # Vector to store predicted LR
  197. y.p <- numeric()
  198. # Bootstrapping on test set
  199. for (i in unique(allData$dist)) {
  200. for (j in unique(allData$step)) {
  201. # Subset data
  202. dataSub <- testSet[testSet$dist == i & testSet$step == j, ]
  203. kList <- list()
  204. kCount <- 1
  205. # Predict on unseen LP
  206. for (k in dataSub[ , "LP"]) {
  207. # Do bootstrap with 100 replications
  208. kList[[kCount]] <- replicate(n=100, the.replication.type3(reg = my.reg, s = my.s.resid, x_Np1 = k))
  209. y.p <- c(y.p, kList[[kCount]])
  210. kCount <- kCount + 1
  211. }
  212. # Store in list
  213. epList[[paste(as.character(i), as.character(j), sep = ".")]] <- kList
  214. print(paste("Step", j, "finished"))
  215. }
  216. print(paste("Dist", i, "finished"))
  217. }
  218. cvList[[h]] <- epList
  219. y.cv[[h]] <- y.p
  220. print(paste("CV", h, "finished"))
  221. }
  222. saveRDS(list(y.cv, cvList, cvRand), paste("stereo_boot10CVPI_LRLP_pred_Type1.rds", sep = ""))
  223. ```
  224. ##Bootstrap PI - CV - LR vs LP
  225. This code is meant to be run independently for every neurType and in parallel
  226. ```{r}
  227. # Ensure reproducibility
  228. set.seed(123456)
  229. # Subset axon type
  230. dataCV <- allData[allData$neurType == "Type1", ]
  231. # List to store CV repetitions
  232. cvList <- list ()
  233. cvRand <- list()
  234. y.cv <- list()
  235. for (h in 1) {
  236. # Stratified random training/test sets
  237. stratDat <- stratified(dataCV, c("dist", "step"), 0.7, bothSets = TRUE, replace = FALSE)
  238. trainSet <- stratDat$SET1
  239. testSet <- stratDat$SET2
  240. # Store train and test set
  241. cvRand[[h]] <- list(trainSet = trainSet, testSet = testSet)
  242. # OLS with training set
  243. my.reg <- lm(LR ~ LP - 1, trainSet)
  244. # Create adjusted residuals
  245. leverage <- influence(my.reg)$hat
  246. my.s.resid <- residuals(my.reg)/sqrt(1-leverage)
  247. my.s.resid <- my.s.resid - mean(my.s.resid)
  248. my.s.resid <- residuals(my.reg)
  249. # List to store errors
  250. epList <- list()
  251. # Vector to store predicted LR
  252. y.p <- numeric()
  253. # Bootstrapping on test set
  254. for (i in unique(allData$dist)) {
  255. for (j in unique(allData$step)) {
  256. # Subset data
  257. dataSub <- testSet[testSet$dist == i & testSet$step == j, ]
  258. kList <- list()
  259. kCount <- 1
  260. # Predict on unseen LP
  261. for (k in dataSub[ , "LP"]) {
  262. # Store predicted error
  263. y.p <- c(y.p, coef(my.reg)*k)
  264. # Create adjusted residuals
  265. leverage <- influence(my.reg, do.coef = FALSE)$hat
  266. my.s.resid <- residuals(my.reg)/sqrt(1-leverage)
  267. my.s.resid <- my.s.resid - mean(my.s.resid)
  268. # Do bootstrap with 100 replications
  269. kList[[kCount]] <- replicate(n=100, the.replication.type2(reg = my.reg, s = my.s.resid, disti = i, stepj = j, trainset = trainSet,
  270. x_Np1 = k))
  271. kCount <- kCount + 1
  272. }
  273. # Store in list
  274. epList[[paste(as.character(i), as.character(j), sep = ".")]] <- kList
  275. print(paste("Step", j, "finished"))
  276. }
  277. print(paste("Dist", i, "finished"))
  278. }
  279. cvList[[h]] <- epList
  280. names(y.p) <- paste(rep(unique(allData$dist), each = 9), rep(unique(allData$step), 10), sep=".")
  281. y.cv[[h]] <- y.p
  282. print(paste("CV", h, "finished"))
  283. }
  284. saveRDS(list(y.cv, cvList, cvRand), paste("stereo_boot10CVPI_LRLP_notStud_Type1.rds", sep = ""))
  285. ```
  286. ##Plotting for bsAdd
  287. ```{r}
  288. bsAdd <- readRDS("stereo_boot10CVPI_LRLP_bsAdd_Type1.rds")
  289. y.cv <- bsAdd[[1]]
  290. cvList <- bsAdd[[2]]
  291. cvRand <- bsAdd[[3]]
  292. estimList <- list()
  293. for (h in 1) {
  294. lrSet <- cvRand[[h]][["testSet"]]
  295. lrOrder <- lrSet[with(lrSet, order(dist, step)), ]
  296. errorSet <- unlist(cvList[[h]])
  297. errorFrame <- data.frame(dist = rep(lrOrder$dist, each = 100),
  298. step = rep(lrOrder$step, each = 100),
  299. LR = rep(lrOrder$LR, each = 100),
  300. error = errorSet)
  301. estimList[[h]] <- errorFrame
  302. }
  303. estimTotal <- do.call(rbind, estimList)
  304. estimTotal$pe <- (estimTotal$error/estimTotal$LR)*100
  305. estimTotal$abspe <- abs(estimTotal$pe)
  306. estimTotal$interact <- interaction(estimTotal$dist, estimTotal$step, lex.order = TRUE)
  307. estimMean <- aggregate(abspe ~ dist + step, estimTotal, mean)
  308. ```
  309. ###Mean
  310. ```{r, fig.height=10, fig.width=20}
  311. meanFrame <- estimMean
  312. meanFrame$neurType <- rep("Type1", dim(meanFrame)[1])
  313. # Library
  314. library(latticeExtra)
  315. # Contour color palette
  316. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  317. colfin <- colfunc(1000)
  318. library(viridisLite)
  319. coul <- viridis(1000)
  320. # Store heatmaps
  321. heatList <- list()
  322. smoothList <- list()
  323. for (i in c("Type1")) {
  324. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  325. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  326. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  327. ylim = c(155, 65),
  328. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  329. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  330. 0.05))),
  331. main = paste("Mean Abs Error,", i))
  332. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  333. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  334. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  335. ylim = c(150,70),
  336. xlim = c(3,30),
  337. cuts = 20,
  338. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  339. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  340. 0.05))),
  341. main = paste("Mean Abs Error,", i),
  342. panel = panel.levelplot.points, cex = 0) +
  343. layer_(panel.2dsmoother(..., n = 200))
  344. }
  345. # Plot
  346. # setwd("EstereoAnalysis/")
  347. #
  348. # png(filename="meanProbabilities_heatmap_CV.png", type="cairo",
  349. # units="in", width=20, height=10, pointsize=12,
  350. # res=300)
  351. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  352. # dev.off()
  353. ```
  354. ###Density
  355. ```{r, fig.width=5, fig.height=20}
  356. ggplot(estimTotal, aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  357. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  358. geom_density_ridges_gradient(alpha = 0.8) +
  359. theme_ridges() +
  360. theme(legend.position = "none") +
  361. xlab("% Error") +
  362. xlim(c(-40,40))
  363. ```
  364. ###Errors vs cumul probability
  365. ```{r, fig.height=5, fig.width=20}
  366. # Inverse quantile
  367. quantInv <- function(distr, value) ecdf(distr)(value)
  368. # Function to apply to all axon types
  369. quantType <- function(peFrame, probSeq) {
  370. probList <- list()
  371. for (i in unique(peFrame$interact)) {
  372. dataProb <- peFrame[peFrame$interact == i, "pe"]
  373. probVec <- numeric()
  374. for (j in probSeq) {
  375. errProb <- quantInv(dataProb, j) - quantInv(dataProb, -j)
  376. probVec <- c(probVec, errProb)
  377. }
  378. probList[[i]] <- probVec
  379. }
  380. return(probList)
  381. }
  382. # Define errors for which to calculate probability
  383. binProb <- 0.5
  384. probSeq <- seq(binProb, 100, binProb)
  385. # Store axon types in lists
  386. # axProb <- lapply(frameList, function(x) quantType(x, probSeq))
  387. axProb <- quantType(estimTotal, probSeq)
  388. # Save
  389. # saveRDS(axProb, "errorProbs_CVleaveout.rds")
  390. ```
  391. ######Plot heatmap
  392. ```{r, width=15, height=10}
  393. library(latticeExtra)
  394. # Reformat as dataframe
  395. binProb <- 0.5
  396. probSeq <- seq(binProb, 100, binProb)
  397. # axProb <- readRDS("errorProbs_CVleaveout.rds")
  398. # probFrame <- data.frame(error = rep(probSeq, 90*4),
  399. # neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = length(probSeq)*90),
  400. # dist = rep(rep(unique(allData$dist), each = length(probSeq)*9), 4),
  401. # step = rep(rep(unique(allData$step), each = length(probSeq)), 10*4),
  402. # prob = unlist(axProb))
  403. probFrame <- data.frame(error = rep(probSeq, 90),
  404. neurType = rep("Type1", length(probSeq)*90),
  405. dist = rep(unique(allData$dist), each = length(probSeq)*9),
  406. step = rep(rep(unique(allData$step), each = length(probSeq)), 10),
  407. prob = unlist(axProb))
  408. # Plot conttour plot for 5% error
  409. library(viridisLite)
  410. coul <- viridis(1000)
  411. # Store heatmaps
  412. heatList <- list()
  413. smoothList <- list()
  414. for (i in c("Type1")) {
  415. levelList1 <- list()
  416. levelList2 <- list()
  417. for (j in c(5, 10, 20)) {
  418. dataPlot <- probFrame[probFrame$neurType == i & probFrame$error == j, ]
  419. levelList1[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  420. col.regions = coul,
  421. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  422. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  423. ylim = c(155,65),
  424. colorkey = list(at = (seq(min(dataPlot$prob),
  425. max(dataPlot$prob),
  426. 0.001))),
  427. main = paste("P(%Error <=", j, ")", sep = ""))
  428. levelList2[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  429. col.regions = coul,
  430. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  431. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  432. ylim = c(150,70),
  433. xlim = c(3,30),
  434. cuts = 20,
  435. colorkey = list(at = (seq(min(dataPlot$prob),
  436. max(dataPlot$prob),
  437. 0.001))),
  438. main = paste("P(%Error <=", j, ")", sep = ""),
  439. panel = panel.levelplot.points, cex = 0) +
  440. layer_(panel.2dsmoother(..., n = 200))
  441. }
  442. heatList[[i]] <- levelList1
  443. smoothList[[i]] <- levelList2
  444. }
  445. # Plot
  446. # setwd("EstereoAnalysis/")
  447. for (i in c("Type1")) {
  448. png(filename=paste("prueba_", i, "_CVleaveout.png", sep=""), type="cairo",
  449. units="in", width=15, height=10, pointsize=12,
  450. res=300)
  451. gridExtra::grid.arrange(grobs = c(heatList[[i]], smoothList[[i]]), ncol = 3, nrow = 2)
  452. dev.off()
  453. }
  454. ```
  455. ###PI 1
  456. ```{r}
  457. jj <- allData[allData$neurType == "Type1", ]
  458. boxplot(LP ~ dist + step, jj)
  459. boxplot(LP ~ dist + step, cvRand[[1]]$trainSet)
  460. boxplot(LP ~ dist + step, cvRand[[1]]$testSet)
  461. boxplot(LR ~ dist + step, jj)
  462. boxplot(LR ~ dist + step, cvRand[[1]]$trainSet)
  463. boxplot(LR ~ dist + step, cvRand[[1]]$testSet)
  464. ```
  465. ```{r, fig.width=45, fig.height=50}
  466. piLimits <- list()
  467. cv1 <- cvList[[1]]
  468. for (i in 1:90) {
  469. piLimits[[i]] <- lapply(cv1[[i]], function(x) quantile(x, c(0.025, 0.975)))
  470. }
  471. names(piLimits) <- names(cv1)
  472. limVec <- unlist(unlist(piLimits))
  473. oddPos <- seq(1, length(limVec), 2)
  474. lowLims <- limVec[oddPos]
  475. upLims <- limVec[-oddPos]
  476. yp <- unlist(y.cv)
  477. testDat <- cvRand[[1]]$testSet
  478. testOrd <- testDat[order(testDat$dist, testDat$step), ]
  479. testOrd$interact <- interaction(testOrd$dist, testOrd$step, lex.order = T)
  480. lp <-testOrd$LP
  481. names(lp) <- testOrd$interact
  482. lr <- testOrd$LR
  483. names(lr) <- testOrd$interact
  484. # ySort <- sort(yp)
  485. # lpSort <- lp[order(yp)]
  486. # lrSort <- lr[order(yp)]
  487. # lowSort <- lowLims[order(yp)]
  488. # upSort <- upLims[order(yp)]
  489. lpSort <- sort(lp)
  490. ySort <- yp[order(lp)]
  491. lrSort <- lr[order(lp)]
  492. lowSort <- lowLims[order(lp)]
  493. upSort <- upLims[order(lp)]
  494. # plot(lpSort, ySort, type = "l")
  495. # polygon(c(lpSort, rev(lpSort)), c(ySort + lowSort, rev(ySort + upSort)), col = gray(0.5), border = NULL, lwd = 0.01)
  496. distep <- as.numeric(unlist(strsplit(jj, "[.]")))
  497. framePol <- data.frame(dist = distep[seq(1, length(distep), 2)],
  498. step = distep[-seq(1, length(distep), 2)],
  499. yp = ySort,
  500. lp = lpSort,
  501. lr = lrSort,
  502. lowLim = ySort + lowSort,
  503. upLim = ySort + upSort)
  504. par(mfcol=c(9,10))
  505. for (i in sort(unique(framePol$dist))) {
  506. for (j in sort(unique(framePol$step))) {
  507. ySort <- framePol[framePol$dist == i & framePol$step == j, "yp"]
  508. lpSort <- framePol[framePol$dist == i & framePol$step == j, "lp"]
  509. lrSort <- framePol[framePol$dist == i & framePol$step == j, "lr"]
  510. lowSort <- framePol[framePol$dist == i & framePol$step == j, "lowLim"]
  511. upSort <- framePol[framePol$dist == i & framePol$step == j, "upLim"]
  512. # ySort <- frollmean(framePol[framePol$dist == i & framePol$step == j, "yp"], 5)
  513. # lpSort <- frollmean(framePol[framePol$dist == i & framePol$step == j, "lp"], 5)
  514. # lrSort <- frollmean(framePol[framePol$dist == i & framePol$step == j, "lr"], 5)
  515. # lowSort <- frollmean(framePol[framePol$dist == i & framePol$step == j, "lowLim"], 5)
  516. # upSort <- frollmean(framePol[framePol$dist == i & framePol$step == j, "upLim"], 5)
  517. # lowesLP <- lowess(lpSort, ySort)
  518. # lowesLR <- lowess(lrSort, ySort)
  519. lowesPIlow <- lowess(lpSort, lowSort)
  520. lowesPIup <- lowess(lpSort, upSort)
  521. plot(lpSort, ySort, ylim = c(0,350000), pch = "",
  522. main = paste(i, j, sep="."), ylab = "LR", xlab = "LP", cex.main = 2.5, cex.axis = 2.5)
  523. polygon(c(lowesPIlow[[1]], rev(lowesPIup[[1]])), c(lowesPIlow[[2]], rev(lowesPIup[[2]])), col = gray(0.6), border = NULL, lwd = 0.01)
  524. # polygon(c(lpSort, rev(lpSort)), c(lowSort, rev(upSort)), col = gray(0.6), border = NULL, lwd = 0.01)
  525. lines(lpSort, ySort, type = "l")
  526. lines(lpSort, lrSort, col = "red")
  527. }
  528. }
  529. ```
  530. ###PI 2
  531. ```{r, fig.width=15, fig.height=15}
  532. piLimits <- list()
  533. cv1 <- cvList[[1]]
  534. for (i in 1:90) {
  535. piLimits[[i]] <- lapply(cv1[[i]], function(x) quantile(x, c(0.025, 0.975)))
  536. }
  537. names(piLimits) <- names(cv1)
  538. limVec <- unlist(unlist(piLimits))
  539. oddPos <- seq(1, length(limVec), 2)
  540. lowLims <- limVec[oddPos]
  541. upLims <- limVec[-oddPos]
  542. yp <- unlist(y.cv)
  543. testDat <- cvRand[[1]]$testSet
  544. testOrd <- testDat[order(testDat$dist, testDat$step), ]
  545. lp <-testOrd$LP
  546. lr <- testOrd$LR
  547. ySort <- sort(yp)
  548. lpSort <- lp[order(yp)]
  549. lrSort <- lr[order(yp)]
  550. lowSort <- lowLims[order(yp)]
  551. upSort <- upLims[order(yp)]
  552. # plot(lpSort, ySort, type = "l")
  553. # polygon(c(lpSort, rev(lpSort)), c(ySort + lowSort, rev(ySort + upSort)), col = gray(0.5), border = NULL, lwd = 0.01)
  554. distep <- as.numeric(unlist(strsplit(jj, "[.]")))
  555. framePol <- data.frame(dist = distep[seq(1, length(distep), 2)],
  556. step = distep[-seq(1, length(distep), 2)],
  557. yp = ySort,
  558. lp = lpSort,
  559. lr = lrSort,
  560. lowLim = ySort + lowSort,
  561. upLim = ySort + upSort)
  562. coul <- viridisLite::viridis(10)
  563. par(mfrow=c(3,3))
  564. for (j in sort(unique(framePol$step))) {
  565. colCount <- 1
  566. xLim <- c(min(framePol[framePol$step == j, "lp"]), max(framePol[framePol$step == j, "lp"]))
  567. for (i in sort(unique(framePol$dist))) {
  568. ySort <- framePol[framePol$dist == i & framePol$step == j, "yp"]
  569. lpSort <- framePol[framePol$dist == i & framePol$step == j, "lp"]
  570. lrSort <- framePol[framePol$dist == i & framePol$step == j, "lr"]
  571. lowSort <- framePol[framePol$dist == i & framePol$step == j, "lowLim"]
  572. upSort <- framePol[framePol$dist == i & framePol$step == j, "upLim"]
  573. lowesPIlow <- lowess(lpSort, lowSort)
  574. lowesPIup <- lowess(lpSort, upSort)
  575. if (colCount == 1) {
  576. plot(lpSort, ySort, ylim = c(0,350000), xlim = xLim, pch = "",
  577. main = j, ylab = "LR", xlab = "LP", cex.main = 2.5, cex.axis = 1.5, cex.lab = 1.5)
  578. polygon(c(lowesPIlow[[1]], rev(lowesPIup[[1]])), c(lowesPIlow[[2]], rev(lowesPIup[[2]])), col = alpha(coul[colCount], 0.5), border = NULL)
  579. lines(lpSort, ySort, type = "l")
  580. lines(lpSort, lrSort, col = "red")
  581. } else {
  582. polygon(c(lowesPIlow[[1]], rev(lowesPIup[[1]])), c(lowesPIlow[[2]], rev(lowesPIup[[2]])), col = alpha(coul[colCount], 0.5), border = NULL)
  583. lines(lpSort, ySort, type = "l")
  584. lines(lpSort, lrSort, col = "red")
  585. }
  586. abline(h = 23697.93, lty = "dashed", col ="gray")
  587. colCount <- colCount + 1
  588. }
  589. }
  590. ```
  591. ##Plotting for prueba
  592. ```{r}
  593. estimList <- list()
  594. for (h in 1:10) {
  595. lrSet <- cvRand[[h]][["testSet"]]
  596. lrOrder <- lrSet[with(lrSet, order(dist, step)), ]
  597. ySet <- y.cv[[h]]
  598. estimFrame <- data.frame(dist = lrOrder$dist, step = lrOrder$step, LR = lrOrder$LR, pred = ySet)
  599. estimList[[h]] <- estimFrame
  600. }
  601. estimTotal <- do.call(rbind, estimList)
  602. estimTotal$pe <- ((estimTotal$LR - estimTotal$pred)/estimTotal$LR)*100
  603. estimTotal$abspe <- abs(estimTotal$pe)
  604. estimTotal$interact <- interaction(estimFrame$dist, estimFrame$step, lex.order = TRUE)
  605. estimMean <- aggregate(abspe ~ dist + step, estimTotal, mean)
  606. ```
  607. ###Mean
  608. ```{r, fig.height=10, fig.width=20}
  609. meanFrame <- estimMean
  610. meanFrame$neurType <- rep("Type1", dim(meanFrame)[1])
  611. # Library
  612. library(latticeExtra)
  613. # Contour color palette
  614. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  615. colfin <- colfunc(1000)
  616. library(viridisLite)
  617. coul <- viridis(1000)
  618. # Store heatmaps
  619. heatList <- list()
  620. smoothList <- list()
  621. for (i in c("Type1")) {
  622. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  623. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  624. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  625. ylim = c(155, 65),
  626. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  627. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  628. 0.05))),
  629. main = paste("Mean Abs Error,", i))
  630. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  631. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  632. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  633. ylim = c(150,70),
  634. xlim = c(3,30),
  635. cuts = 20,
  636. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  637. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  638. 0.05))),
  639. main = paste("Mean Abs Error,", i),
  640. panel = panel.levelplot.points, cex = 0) +
  641. layer_(panel.2dsmoother(..., n = 200))
  642. }
  643. # Plot
  644. # setwd("EstereoAnalysis/")
  645. #
  646. # png(filename="meanProbabilities_heatmap_CV.png", type="cairo",
  647. # units="in", width=20, height=10, pointsize=12,
  648. # res=300)
  649. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  650. # dev.off()
  651. ```
  652. ###Density
  653. ```{r, fig.width=5, fig.height=20}
  654. ggplot(estimTotal, aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  655. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  656. geom_density_ridges_gradient(alpha = 0.8) +
  657. theme_ridges() +
  658. theme(legend.position = "none") +
  659. xlab("% Error") +
  660. xlim(c(-40,40))
  661. ```
  662. ###Errors vs cumul probability
  663. ```{r, fig.height=5, fig.width=20}
  664. # Inverse quantile
  665. quantInv <- function(distr, value) ecdf(distr)(value)
  666. # Function to apply to all axon types
  667. quantType <- function(peFrame, probSeq) {
  668. probList <- list()
  669. for (i in unique(peFrame$interact)) {
  670. dataProb <- peFrame[peFrame$interact == i, "pe"]
  671. probVec <- numeric()
  672. for (j in probSeq) {
  673. errProb <- quantInv(dataProb, j) - quantInv(dataProb, -j)
  674. probVec <- c(probVec, errProb)
  675. }
  676. probList[[i]] <- probVec
  677. }
  678. return(probList)
  679. }
  680. # Define errors for which to calculate probability
  681. binProb <- 0.5
  682. probSeq <- seq(binProb, 100, binProb)
  683. # Store axon types in lists
  684. # axProb <- lapply(frameList, function(x) quantType(x, probSeq))
  685. axProb <- quantType(estimTotal, probSeq)
  686. # Save
  687. # saveRDS(axProb, "errorProbs_CVleaveout.rds")
  688. ```
  689. ######Plot heatmap
  690. ```{r, width=15, height=10}
  691. library(latticeExtra)
  692. # Reformat as dataframe
  693. binProb <- 0.5
  694. probSeq <- seq(binProb, 100, binProb)
  695. # axProb <- readRDS("errorProbs_CVleaveout.rds")
  696. # probFrame <- data.frame(error = rep(probSeq, 90*4),
  697. # neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = length(probSeq)*90),
  698. # dist = rep(rep(unique(allData$dist), each = length(probSeq)*9), 4),
  699. # step = rep(rep(unique(allData$step), each = length(probSeq)), 10*4),
  700. # prob = unlist(axProb))
  701. probFrame <- data.frame(error = rep(probSeq, 90),
  702. neurType = rep("Type1", length(probSeq)*90),
  703. dist = rep(unique(allData$dist), each = length(probSeq)*9),
  704. step = rep(rep(unique(allData$step), each = length(probSeq)), 10),
  705. prob = unlist(axProb))
  706. # Plot conttour plot for 5% error
  707. library(viridisLite)
  708. coul <- viridis(1000)
  709. # Store heatmaps
  710. heatList <- list()
  711. smoothList <- list()
  712. for (i in c("Type1")) {
  713. levelList1 <- list()
  714. levelList2 <- list()
  715. for (j in c(5, 10, 20)) {
  716. dataPlot <- probFrame[probFrame$neurType == i & probFrame$error == j, ]
  717. levelList1[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  718. col.regions = coul,
  719. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  720. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  721. ylim = c(155,65),
  722. colorkey = list(at = (seq(min(dataPlot$prob),
  723. max(dataPlot$prob),
  724. 0.001))),
  725. main = paste("P(%Error <=", j, ")", sep = ""))
  726. levelList2[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  727. col.regions = coul,
  728. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  729. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  730. ylim = c(150,70),
  731. xlim = c(3,30),
  732. cuts = 20,
  733. colorkey = list(at = (seq(min(dataPlot$prob),
  734. max(dataPlot$prob),
  735. 0.001))),
  736. main = paste("P(%Error <=", j, ")", sep = ""),
  737. panel = panel.levelplot.points, cex = 0) +
  738. layer_(panel.2dsmoother(..., n = 200))
  739. }
  740. heatList[[i]] <- levelList1
  741. smoothList[[i]] <- levelList2
  742. }
  743. # Plot
  744. # setwd("EstereoAnalysis/")
  745. for (i in c("Type1")) {
  746. png(filename=paste("prueba_", i, "_CVleaveout.png", sep=""), type="cairo",
  747. units="in", width=15, height=10, pointsize=12,
  748. res=300)
  749. gridExtra::grid.arrange(grobs = c(heatList[[i]], smoothList[[i]]), ncol = 3, nrow = 2)
  750. dev.off()
  751. }
  752. ```
  753. ##Plotting for preds
  754. ```{r}
  755. # predsData <- readRDS("D:/Sergio/Cremoto Drive/stereo_boot10CVPI_LRLP_predReal100_Type1.rds")
  756. # jjMse <- jj %>%
  757. # group_by(dist, step) %>%
  758. # summarise(val=mltools::mse(pred, LR))
  759. testSets <- lapply(predsData, function(x) do.call(rbind, x$testSets))
  760. testJoin <- do.call(rbind, testSets)
  761. testJoin$pe <- ((testJoin$LR - testJoin$pred)/testJoin$LR)*100
  762. testJoin$abspe <- abs(testJoin$pe)
  763. testJoin$interact <- interaction(testJoin$dist, testJoin$step, lex.order = TRUE)
  764. testMean <- aggregate(abspe ~ dist + step, testJoin, mean)
  765. ```
  766. ```{r}
  767. # predsData <- readRDS("D:/Sergio/Cremoto Drive/stereo_boot10CVPI_LRLP_predReal100_Type1.rds")
  768. # jjMse <- jj %>%
  769. # group_by(dist, step) %>%
  770. # summarise(val=mltools::mse(pred, LR))
  771. testSets <- lapply(predsData, function(x) do.call(rbind, x$testSets))
  772. testPE <- lapply(testSets, function(x) x$pe <- ((x$LR - x$pred)/x$LR)*100)
  773. testJoin <- do.call(rbind, testSets)
  774. testJoin$pe <- ((testJoin$LR - testJoin$pred)/testJoin$LR)*100
  775. testJoin$abspe <- abs(testJoin$pe)
  776. testJoin$interact <- interaction(testJoin$dist, testJoin$step, lex.order = TRUE)
  777. testMean <- aggregate(abspe ~ dist + step, testJoin, mean)
  778. ```
  779. ###Mean
  780. ```{r, fig.height=10, fig.width=20}
  781. meanFrame <- testMean
  782. meanFrame$neurType <- rep("Type1", dim(meanFrame)[1])
  783. # Library
  784. library(latticeExtra)
  785. # Contour color palette
  786. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  787. colfin <- colfunc(1000)
  788. library(viridisLite)
  789. coul <- viridis(1000)
  790. # Store heatmaps
  791. heatList <- list()
  792. smoothList <- list()
  793. for (i in c("Type1")) {
  794. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  795. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  796. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  797. ylim = c(155, 65),
  798. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  799. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  800. 0.05))),
  801. main = paste("Mean Abs Error,", i))
  802. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  803. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  804. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  805. ylim = c(150,70),
  806. xlim = c(3,30),
  807. cuts = 20,
  808. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  809. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  810. 0.05))),
  811. main = paste("Mean Abs Error,", i),
  812. panel = panel.levelplot.points, cex = 0) +
  813. layer_(panel.2dsmoother(..., n = 200))
  814. }
  815. # Plot
  816. # setwd("EstereoAnalysis/")
  817. #
  818. # png(filename="meanProbabilities_heatmap_CV.png", type="cairo",
  819. # units="in", width=20, height=10, pointsize=12,
  820. # res=300)
  821. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  822. # dev.off()
  823. ```
  824. ###Density
  825. ```{r, fig.width=5, fig.height=20}
  826. ggplot(testJoin, aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  827. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  828. geom_density_ridges_gradient(alpha = 0.8) +
  829. theme_ridges() +
  830. theme(legend.position = "none") +
  831. xlab("% Error") +
  832. xlim(c(-40,40))
  833. ```
  834. ###Errors vs cumul probability
  835. ```{r, fig.height=5, fig.width=20}
  836. # Inverse quantile
  837. quantInv <- function(distr, value) ecdf(distr)(value)
  838. # Function to apply to all axon types
  839. quantType <- function(peFrame, probSeq) {
  840. probList <- list()
  841. for (i in unique(peFrame$interact)) {
  842. dataProb <- peFrame[peFrame$interact == i, "pe"]
  843. probVec <- numeric()
  844. for (j in probSeq) {
  845. errProb <- quantInv(dataProb$pe, j) - quantInv(dataProb$pe, -j)
  846. probVec <- c(probVec, errProb)
  847. }
  848. probList[[i]] <- probVec
  849. }
  850. return(probList)
  851. }
  852. # Define errors for which to calculate probability
  853. binProb <- 0.5
  854. probSeq <- seq(binProb, 100, binProb)
  855. # Store axon types in lists
  856. # axProb <- lapply(frameList, function(x) quantType(x, probSeq))
  857. axProb <- quantType(testJoin, probSeq)
  858. # Save
  859. # saveRDS(axProb, "errorProbs_CVleaveout.rds")
  860. ```
  861. ######Plot heatmap
  862. ```{r, width=15, height=10}
  863. library(latticeExtra)
  864. # Reformat as dataframe
  865. binProb <- 0.5
  866. probSeq <- seq(binProb, 100, binProb)
  867. # axProb <- readRDS("errorProbs_CVleaveout.rds")
  868. # probFrame <- data.frame(error = rep(probSeq, 90*4),
  869. # neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = length(probSeq)*90),
  870. # dist = rep(rep(unique(allData$dist), each = length(probSeq)*9), 4),
  871. # step = rep(rep(unique(allData$step), each = length(probSeq)), 10*4),
  872. # prob = unlist(axProb))
  873. probFrame <- data.frame(error = rep(probSeq, 90),
  874. neurType = rep("Type1", length(probSeq)*90),
  875. dist = rep(unique(allData$dist), each = length(probSeq)*9),
  876. step = rep(rep(unique(allData$step), each = length(probSeq)), 10),
  877. prob = unlist(axProb))
  878. # Plot conttour plot for 5% error
  879. library(viridisLite)
  880. coul <- viridis(1000)
  881. # Store heatmaps
  882. heatList <- list()
  883. smoothList <- list()
  884. for (i in c("Type1")) {
  885. levelList1 <- list()
  886. levelList2 <- list()
  887. for (j in c(5, 10, 20)) {
  888. dataPlot <- probFrame[probFrame$neurType == i & probFrame$error == j, ]
  889. levelList1[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  890. col.regions = coul,
  891. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  892. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  893. ylim = c(155,65),
  894. colorkey = list(at = (seq(min(dataPlot$prob),
  895. max(dataPlot$prob),
  896. 0.001))),
  897. main = paste("P(%Error <=", j, ")", sep = ""))
  898. levelList2[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  899. col.regions = coul,
  900. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  901. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  902. ylim = c(150,70),
  903. xlim = c(3,30),
  904. cuts = 20,
  905. colorkey = list(at = (seq(min(dataPlot$prob),
  906. max(dataPlot$prob),
  907. 0.001))),
  908. main = paste("P(%Error <=", j, ")", sep = ""),
  909. panel = panel.levelplot.points, cex = 0) +
  910. layer_(panel.2dsmoother(..., n = 200))
  911. }
  912. heatList[[i]] <- levelList1
  913. smoothList[[i]] <- levelList2
  914. }
  915. # Plot
  916. # setwd("EstereoAnalysis/")
  917. for (i in c("Type1")) {
  918. png(filename=paste("prueba_", i, "_CVleaveout.png", sep=""), type="cairo",
  919. units="in", width=15, height=10, pointsize=12,
  920. res=300)
  921. gridExtra::grid.arrange(grobs = c(heatList[[i]], smoothList[[i]]), ncol = 3, nrow = 2)
  922. dev.off()
  923. }
  924. ```
  925. ##Plotting for predMean
  926. ```{r}
  927. predsData <- readRDS("D:/Sergio/Cremoto Drive/stereo_boot10CVPI_LRLP_predRealMean_GEE_Type1.rds")
  928. # jjMse <- jj %>%
  929. # group_by(dist, step) %>%
  930. # summarise(val=mltools::mse(pred, LR))
  931. testJoin <- do.call(rbind, predsData[[1]])
  932. testJoin$interact <- interaction(testJoin$dist, testJoin$step, lex.order = TRUE)
  933. testMean <- aggregate(abspe ~ dist + step, testJoin, mean)
  934. peJoin <- do.call(rbind, predsData[[2]])
  935. peJoin$interact <- interaction(peJoin$dist, peJoin$step, lex.order = TRUE)
  936. ```
  937. ###Mean
  938. ```{r, fig.height=10, fig.width=20}
  939. meanFrame <- testMean
  940. meanFrame$neurType <- rep("Type1", dim(meanFrame)[1])
  941. # Library
  942. library(latticeExtra)
  943. # Contour color palette
  944. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  945. colfin <- colfunc(1000)
  946. library(viridisLite)
  947. coul <- viridis(1000)
  948. # Store heatmaps
  949. heatList <- list()
  950. smoothList <- list()
  951. for (i in c("Type1")) {
  952. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  953. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  954. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  955. ylim = c(155, 65),
  956. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  957. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  958. 0.05))),
  959. main = paste("Mean Abs Error,", i))
  960. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  961. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  962. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  963. ylim = c(150,70),
  964. xlim = c(3,30),
  965. cuts = 20,
  966. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  967. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  968. 0.05))),
  969. main = paste("Mean Abs Error,", i),
  970. panel = panel.levelplot.points, cex = 0) +
  971. layer_(panel.2dsmoother(..., n = 200))
  972. }
  973. # Plot
  974. # setwd("EstereoAnalysis/")
  975. #
  976. # png(filename="meanProbabilities_heatmap_CV.png", type="cairo",
  977. # units="in", width=20, height=10, pointsize=12,
  978. # res=300)
  979. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  980. # dev.off()
  981. ```
  982. ###Density
  983. ```{r, fig.width=5, fig.height=20}
  984. # https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html
  985. ggplot(peJoin, aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  986. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  987. stat_density_ridges(geom = "density_ridges_gradient") +
  988. theme_ridges() +
  989. theme(legend.position = "none") +
  990. xlab("% Error") +
  991. xlim(c(-40,40))
  992. ```
  993. ```{r, fig.width=50, fig.height=45}
  994. histogram(~ pe | factor(dist) + factor(step), data = peJoin)
  995. ```
  996. ###Errors vs cumul probability
  997. ```{r, fig.height=5, fig.width=20}
  998. # Inverse quantile
  999. quantInv <- function(distr, value) ecdf(distr)(value)
  1000. # Function to apply to all axon types
  1001. quantType <- function(peFrame, probSeq) {
  1002. probList <- list()
  1003. for (i in unique(peFrame$interact)) {
  1004. dataProb <- peFrame[peFrame$interact == i, "pe"]
  1005. probVec <- numeric()
  1006. for (j in probSeq) {
  1007. errProb <- quantInv(dataProb$pe, j) - quantInv(dataProb$pe, -j)
  1008. probVec <- c(probVec, errProb)
  1009. }
  1010. probList[[i]] <- probVec
  1011. }
  1012. return(probList)
  1013. }
  1014. # Define errors for which to calculate probability
  1015. binProb <- 0.5
  1016. probSeq <- seq(binProb, 100, binProb)
  1017. # Store axon types in lists
  1018. # axProb <- lapply(frameList, function(x) quantType(x, probSeq))
  1019. axProb <- quantType(peJoin, probSeq)
  1020. # Save
  1021. # saveRDS(axProb, "errorProbs_CVleaveout.rds")
  1022. ```
  1023. ######Plot heatmap
  1024. ```{r, width=15, height=10}
  1025. library(latticeExtra)
  1026. # Reformat as dataframe
  1027. binProb <- 0.5
  1028. probSeq <- seq(binProb, 100, binProb)
  1029. # axProb <- readRDS("errorProbs_CVleaveout.rds")
  1030. # probFrame <- data.frame(error = rep(probSeq, 90*4),
  1031. # neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = length(probSeq)*90),
  1032. # dist = rep(rep(unique(allData$dist), each = length(probSeq)*9), 4),
  1033. # step = rep(rep(unique(allData$step), each = length(probSeq)), 10*4),
  1034. # prob = unlist(axProb))
  1035. probFrame <- data.frame(error = rep(probSeq, 90),
  1036. neurType = rep("Type1", length(probSeq)*90),
  1037. dist = rep(unique(allData$dist), each = length(probSeq)*9),
  1038. step = rep(rep(unique(allData$step), each = length(probSeq)), 10),
  1039. prob = unlist(axProb))
  1040. # Plot conttour plot for 5% error
  1041. library(viridisLite)
  1042. coul <- viridis(1000)
  1043. # Store heatmaps
  1044. heatList <- list()
  1045. smoothList <- list()
  1046. for (i in c("Type1")) {
  1047. levelList1 <- list()
  1048. levelList2 <- list()
  1049. for (j in c(5, 10, 20)) {
  1050. dataPlot <- probFrame[probFrame$neurType == i & probFrame$error == j, ]
  1051. levelList1[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  1052. col.regions = coul,
  1053. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  1054. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  1055. ylim = c(155,65),
  1056. colorkey = list(at = (seq(min(dataPlot$prob),
  1057. max(dataPlot$prob),
  1058. 0.001))),
  1059. main = paste("P(%Error <=", j, ")", sep = ""))
  1060. levelList2[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  1061. col.regions = coul,
  1062. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  1063. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  1064. ylim = c(150,70),
  1065. xlim = c(3,30),
  1066. cuts = 20,
  1067. colorkey = list(at = (seq(min(dataPlot$prob),
  1068. max(dataPlot$prob),
  1069. 0.001))),
  1070. main = paste("P(%Error <=", j, ")", sep = ""),
  1071. panel = panel.levelplot.points, cex = 0) +
  1072. layer_(panel.2dsmoother(..., n = 200))
  1073. }
  1074. heatList[[i]] <- levelList1
  1075. smoothList[[i]] <- levelList2
  1076. }
  1077. # Plot
  1078. # setwd("EstereoAnalysis/")
  1079. for (i in c("Type1")) {
  1080. png(filename=paste("prueba_", i, "_CVleaveout.png", sep=""), type="cairo",
  1081. units="in", width=15, height=10, pointsize=12,
  1082. res=300)
  1083. gridExtra::grid.arrange(grobs = c(heatList[[i]], smoothList[[i]]), ncol = 3, nrow = 2)
  1084. dev.off()
  1085. }
  1086. ```
  1087. ##Plotting for CVloo
  1088. ```{r}
  1089. predsData <- readRDS("D:/Sergio/Cremoto Drive/stereo_bootCVlooPI_LRLP_predReal_Type1.rds")
  1090. # jjMse <- jj %>%
  1091. # group_by(dist, step) %>%
  1092. # summarise(val=mltools::mse(pred, LR))
  1093. testJoin <- predsData
  1094. testJoin$interact <- interaction(testJoin$dist, testJoin$step, lex.order = TRUE)
  1095. testMean <- aggregate(abspe ~ dist + step, testJoin, mean)
  1096. peJoin <- predsData
  1097. peJoin$interact <- interaction(peJoin$dist, peJoin$step, lex.order = TRUE)
  1098. ```
  1099. ###Mean
  1100. ```{r, fig.height=10, fig.width=20}
  1101. meanFrame <- testMean
  1102. meanFrame$neurType <- rep("Type1", dim(meanFrame)[1])
  1103. # Library
  1104. library(latticeExtra)
  1105. # Contour color palette
  1106. colfunc <- colorRampPalette(c("navy","royalblue","springgreen","gold","yellow"))
  1107. colfin <- colfunc(1000)
  1108. library(viridisLite)
  1109. coul <- viridis(1000)
  1110. # Store heatmaps
  1111. heatList <- list()
  1112. smoothList <- list()
  1113. for (i in c("Type1")) {
  1114. heatList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  1115. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  1116. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  1117. ylim = c(155, 65),
  1118. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  1119. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  1120. 0.05))),
  1121. main = paste("Mean Abs Error,", i))
  1122. smoothList[[i]] <- levelplot(abspe ~ dist * step, data = meanFrame[meanFrame$neurType == i, ], col.regions = coul,
  1123. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  1124. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  1125. ylim = c(150,70),
  1126. xlim = c(3,30),
  1127. cuts = 20,
  1128. colorkey = list(at = (seq(min(meanFrame[meanFrame$neurType == i, "abspe"]),
  1129. max(meanFrame[meanFrame$neurType == i, "abspe"]),
  1130. 0.05))),
  1131. main = paste("Mean Abs Error,", i),
  1132. panel = panel.levelplot.points, cex = 0) +
  1133. layer_(panel.2dsmoother(..., n = 200))
  1134. }
  1135. # Plot
  1136. # setwd("EstereoAnalysis/")
  1137. #
  1138. # png(filename="meanProbabilities_heatmap_CV.png", type="cairo",
  1139. # units="in", width=20, height=10, pointsize=12,
  1140. # res=300)
  1141. gridExtra::grid.arrange(grobs = c(heatList, smoothList), ncol = 4, nrow = 2)
  1142. # dev.off()
  1143. ```
  1144. ###Density
  1145. ```{r, fig.width=5, fig.height=20}
  1146. # https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html
  1147. print(ggplot(peJoin, aes(x = `pe`, y = `interact`, fill = ifelse(..x.. >=-5 & ..x.. <=5, ">= -5", "< 5"))) +
  1148. scale_fill_manual(values = c("gray70", "coral2"), name = NULL) +
  1149. stat_density_ridges(geom = "density_ridges_gradient") +
  1150. theme_ridges() +
  1151. theme(legend.position = "none") +
  1152. xlab("% Error") +
  1153. xlim(c(-40,40)))
  1154. ```
  1155. ```{r, fig.width=50, fig.height=45}
  1156. histogram(~ pe | factor(dist) + factor(step), data = peJoin)
  1157. ```
  1158. ###Errors vs cumul probability
  1159. ```{r, fig.height=5, fig.width=20}
  1160. # Inverse quantile
  1161. quantInv <- function(distr, value) ecdf(distr)(value)
  1162. # Function to apply to all axon types
  1163. quantType <- function(peFrame, probSeq) {
  1164. probList <- list()
  1165. for (i in unique(peFrame$interact)) {
  1166. dataProb <- peFrame[peFrame$interact == i, "pe"]
  1167. probVec <- numeric()
  1168. for (j in probSeq) {
  1169. errProb <- quantInv(dataProb$pe, j) - quantInv(dataProb$pe, -j)
  1170. probVec <- c(probVec, errProb)
  1171. }
  1172. probList[[i]] <- probVec
  1173. }
  1174. return(probList)
  1175. }
  1176. # Define errors for which to calculate probability
  1177. binProb <- 0.5
  1178. probSeq <- seq(binProb, 100, binProb)
  1179. # Store axon types in lists
  1180. # axProb <- lapply(frameList, function(x) quantType(x, probSeq))
  1181. axProb <- quantType(peJoin, probSeq)
  1182. # Save
  1183. # saveRDS(axProb, "errorProbs_CVleaveout.rds")
  1184. ```
  1185. ######Plot heatmap
  1186. ```{r, width=15, height=10}
  1187. library(latticeExtra)
  1188. # Reformat as dataframe
  1189. binProb <- 0.5
  1190. probSeq <- seq(binProb, 100, binProb)
  1191. # axProb <- readRDS("errorProbs_CVleaveout.rds")
  1192. # probFrame <- data.frame(error = rep(probSeq, 90*4),
  1193. # neurType = rep(c("Type1", "Type2", "Type3", "Type4"), each = length(probSeq)*90),
  1194. # dist = rep(rep(unique(allData$dist), each = length(probSeq)*9), 4),
  1195. # step = rep(rep(unique(allData$step), each = length(probSeq)), 10*4),
  1196. # prob = unlist(axProb))
  1197. probFrame <- data.frame(error = rep(probSeq, 90),
  1198. neurType = rep("Type1", length(probSeq)*90),
  1199. dist = rep(unique(allData$dist), each = length(probSeq)*9),
  1200. step = rep(rep(unique(allData$step), each = length(probSeq)), 10),
  1201. prob = unlist(axProb))
  1202. # Plot conttour plot for 5% error
  1203. library(viridisLite)
  1204. coul <- viridis(1000)
  1205. # Store heatmaps
  1206. heatList <- list()
  1207. smoothList <- list()
  1208. for (i in c("Type1")) {
  1209. levelList1 <- list()
  1210. levelList2 <- list()
  1211. for (j in c(5, 10, 20)) {
  1212. dataPlot <- probFrame[probFrame$neurType == i & probFrame$error == j, ]
  1213. levelList1[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  1214. col.regions = coul,
  1215. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  1216. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  1217. ylim = c(155,65),
  1218. colorkey = list(at = (seq(min(dataPlot$prob),
  1219. max(dataPlot$prob),
  1220. 0.001))),
  1221. main = paste("P(%Error <=", j, ")", sep = ""))
  1222. levelList2[[as.character(j)]] <- levelplot(prob ~ dist * step, data = dataPlot,
  1223. col.regions = coul,
  1224. scales = list(y = list(at = unique(allData$step), labels = unique(allData$step)),
  1225. x = list(at = unique(allData$dist), labels = unique(allData$dist))),
  1226. ylim = c(150,70),
  1227. xlim = c(3,30),
  1228. cuts = 20,
  1229. colorkey = list(at = (seq(min(dataPlot$prob),
  1230. max(dataPlot$prob),
  1231. 0.001))),
  1232. main = paste("P(%Error <=", j, ")", sep = ""),
  1233. panel = panel.levelplot.points, cex = 0) +
  1234. layer_(panel.2dsmoother(..., n = 200))
  1235. }
  1236. heatList[[i]] <- levelList1
  1237. smoothList[[i]] <- levelList2
  1238. }
  1239. # Plot
  1240. # setwd("EstereoAnalysis/")
  1241. for (i in c("Type1")) {
  1242. png(filename=paste("prueba_", i, "_CVleaveout.png", sep=""), type="cairo",
  1243. units="in", width=15, height=10, pointsize=12,
  1244. res=300)
  1245. gridExtra::grid.arrange(grobs = c(heatList[[i]], smoothList[[i]]), ncol = 3, nrow = 2)
  1246. dev.off()
  1247. }
  1248. ```