consistency-train.R 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env Rscript
  2. # Script to train multiple fRMA vectors in preparation for consistency
  3. # evaluation
  4. library(xlsx)
  5. library(frma)
  6. library(frmaTools)
  7. library(stringr)
  8. library(magrittr)
  9. library(plyr)
  10. library(affy)
  11. library(preprocessCore)
  12. library(ggplot2)
  13. library(proto)
  14. library(dplyr)
  15. training.data.dir <- "Training Data"
  16. datasets <- data.frame(Dataset=list.files(training.data.dir))
  17. rownames(datasets) <- datasets$Dataset
  18. datasets$Tissue <- factor(str_extract(datasets$Dataset, "\\b(PAX|BX)\\b"))
  19. tsmsg <- function(...) {
  20. message(date(), ": ", ...)
  21. }
  22. ## Some Scan Dates are marked as identical for multiple batches, which
  23. ## is bad. But the dates embedded in the file names for these batches
  24. ## are different, so we use those dates instead.
  25. parse.date.from.filename <- function(fname) {
  26. res1 <- str_match(fname, "^(\\d\\d)(\\d\\d)(\\d\\d)")[,c(4,2,3)]
  27. res2 <- str_match(fname, "^20(\\d\\d)_(\\d\\d)_(\\d\\d)")[,-1]
  28. res1[is.na(res1)] <- res2[is.na(res1)]
  29. colnames(res1) <- c("year", "month", "day")
  30. res1[,"year"] %<>% str_c("20", .)
  31. as.Date(do.call(ISOdate, data.frame(res1)))
  32. }
  33. ## This reads in the xlsx file for each of the 7 datasets and combines
  34. ## them into one big table of all samples. The Batch column contains
  35. ## the partitioning of samples into unique combinations of Dataset,
  36. ## Scan Date, and Phenotype. Finally, we split based on Tissue type to
  37. ## get one table for biopsies (BX), and one for blood (PAX).
  38. sample.tables <- ddply(datasets, .(Dataset), function(df) {
  39. df <- df[1,]
  40. rownames(df) <- NULL
  41. dset.dir <- file.path(training.data.dir, df$Dataset)
  42. x <- read.xlsx(list.files(dset.dir, pattern=glob2rx("*.xlsx"), full.names=TRUE)[1], 1) %>%
  43. setNames(c("Filename", "Phenotype", "ScanDate"))
  44. x$Filename <- as.character(x$Filename)
  45. missing.CEL <- !str_detect(x$Filename, "\\.CEL$")
  46. x$Filename[missing.CEL] <- str_c(x$Filename[missing.CEL], ".CEL")
  47. stopifnot(all(str_detect(x$Filename, "\\.CEL$")))
  48. parsed.date <- parse.date.from.filename(x$Filename)
  49. x$ScanDate[!is.na(parsed.date)] <- parsed.date[!is.na(parsed.date)]
  50. x %>% cbind(df) %>%
  51. transform(Filename=file.path(dset.dir, Filename),
  52. Batch=droplevels(Tissue:Dataset:factor(ScanDate):Phenotype)) %>%
  53. subset(! Filename %in% blacklist) %>%
  54. subset(!duplicated(Filename))
  55. }) %>%
  56. split(.$Tissue) %>%
  57. lapply(droplevels)
  58. ## fRMA requires equal-sized batches, so for each batch size from 3 to
  59. ## 15, compute how many batches have at least that many samples.
  60. x <- sapply(3:15, function(i) sapply(sample.tables, . %$% Batch %>% table %>% as.vector %>% {sum(. >= i)}))
  61. colnames(x) <- 3:15
  62. ## Based on the above and the recommendations in the frmaTools paper,
  63. ## I chose 5 as the optimal batch size. This could be optimized
  64. ## empirically, though.
  65. arrays.per.batch <- 5
  66. vectors <- lapply(names(sample.tables), function(ttype) {
  67. stab <- sample.tables[[ttype]]
  68. tsmsg("Reading full dataset for ", ttype)
  69. affy <- ReadAffy(filenames=stab$Filename, sampleNames=rownames(stab))
  70. tsmsg("Getting reference normalziation distribution from full dataset for ", ttype)
  71. normVec <- normalize.quantiles.determine.target(pm(bg.correct.rma(affy)))
  72. rm(affy); gc()
  73. ## Set the random seed for reproducibility.
  74. set.seed(1986)
  75. lapply(1:5, function(i) {
  76. on.exit(gc())
  77. tsmsg("Starting training run number ", i, " for ", ttype)
  78. tsmsg("Selecting batches for ", ttype)
  79. ## Keep only batches with enough samples
  80. big.enough <- stab$Batch %>% table %>% .[.>= arrays.per.batch] %>% names
  81. stab <- stab[stab$Batch %in% big.enough,] %>% droplevels
  82. ## Sample an equal number of arrays from each batch
  83. subtab <- ddply(stab, .(Batch), function(df) {
  84. df[sample(seq(nrow(df)), size=arrays.per.batch),]
  85. })
  86. tsmsg("Making fRMA vectors")
  87. ## Make fRMA vectors, using normVec from full dataset
  88. res <- makeVectorsAffyBatch(subtab$Filename, subtab$Batch, normVec=normVec)
  89. tsmsg("Finished training run number ", i, " for ", ttype)
  90. res
  91. }) %>% setNames(., str_c("V", seq_along(.)))
  92. }) %>% setNames(names(sample.tables))
  93. saveRDS(vectors, "consistency-vectors.RDS")
  94. save.image("consistency.rda")
  95. ## Continues in consistency-evaluate.R