collect_kallisto_data.R 10.9 KB
Newer Older
1 2 3 4 5 6 7
#!/usr/bin/env Rscript
#+ include=FALSE

suppressMessages(require(docopt))

doc = '
Extract kallisto data and calculate confidence intervals of bootstrap data
8
Usage: collect_kallisto_data.R <ids_list> <cdna_file_name>
9 10
'

11
# commandArgs <- function(x) c("ids.txt", "/projects/bioinfo/kallisto_indices/Mus_musculus/Ensembl_v90/Mus_musculus.GRCm38.ens90.cdna.all.fa")
12
opts = docopt(doc, commandArgs(TRUE))
13
# args <- commandArgs()
14 15

#*************************************
16
#' # Kallisto data summary
17 18 19 20 21
#*************************************
# https://scilifelab.github.io/courses/rnaseq/labs/kallisto


# LOAD packages -------------------------------------------------------------------------------
22
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.47/R/core_commons.R")
23 24
# source("http://bioconductor.org/biocLite.R")
# biocLite("pachterlab/sleuth")
25 26 27 28 29 30
# source("https://bioconductor.org/biocLite.R")
# biocLite("Rsamtools")
# load_pack(kableExtra)
load_pack(knitr)
load_pack(stringr)
load_pack(fda)
31 32
load_pack(sleuth)
load_pack(Rsamtools)
33 34
load_pack(tximport)

35 36


37 38
# HANDLE input data -------------------------------------------------------------------------------
ids = read.table(opts$ids_list, header = FALSE)
39 40 41 42 43 44 45
cdna = opts$cdna_file_name %>% str_replace(., "/projects/bioinfo/kallisto_indices/", "")
# cdna = args[1] %>% str_replace(., "/projects/bioinfo/kallisto_indices/", "")

kal_dir = getwd()
sample_ids <- dirs(kal_dir)
sample_dirs <- file.path(kal_dir, sample_ids)

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68


# FUNCTIONS ------------------------------------------------------------------------------------
# also pull out raw bootstrapping data and calcualte some CI around it

calc_ci = function(df, variable, ci_interval=0.95){
    variable <- enquo(variable)

    # http://dplyr.tidyverse.org/articles/programming.html
    mean_name <- paste0( quo_name(variable), "_mean")
    ci_name <- paste0(quo_name(variable), "_ci")
    # echo(glue::glue("varname is {ci_name}"))

    df %>% summarize(
    mean=mean(!!variable),
    sd=sd(!!variable),
    N = n(),
    se=sd/sqrt(N),
    !!ci_name := qt(ci_interval/2+0.5, N-1)*se,
    !!mean_name :=mean
    ) %>% select(-c(mean, sd, N, se, mean))
}

69 70


71 72
# PREPARE -------------------------------------------------------------------------------------

73
# IDs
74 75 76 77
ids %<>%
    `colnames<-`(c("ensembl_transcript_id", "ensembl_gene_id")) %>%
    transmute(ensembl_transcript_id = str_replace_all(ensembl_transcript_id, ">", ""), ensembl_gene_id = str_replace_all(ensembl_gene_id, "gene:|[.][0-9]*$", ""))

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
# log files
log_files = list.files(sample_dirs, "kallisto.log", recursive = TRUE, full = TRUE)
log_files <- data_frame(sample = sample_ids, path = log_files)

log_data <- do.call(rbind, apply(log_files[,c("sample", "path")], 1, function(x) {

    # prepare kallisto.log output
    data <- read_tsv(x[2]) %>% `colnames<-` (c("feature")) %>%
        mutate(method = str_extract(feature, "\\[[:print:]*\\]")) %>%
        mutate(method = str_replace_all(method, "^\\[|\\]$", "")) %>%
        mutate(feature = str_replace(feature, "\\[[:print:]*\\]", ""))

    num <- data$feature[grepl("reads pseudoaligned", data$feature)] %>%
        str_match_all(., "\\d+\\,?\\d+\\,?\\d+") %>% unlist()

    # extract data
    tribble(
    ~num, ~term, ~value,
    1, "mode", data$feature[grepl("running in", data$feature)],
    2, "target_num", data$feature[grepl("number of targets:", data$feature)] %>%
        str_extract(., "\\d+\\,?\\d+\\,?\\d+") %>% noquote(),
    3, "processed", num[1],
    4, "pseudoaligned", num[2],
    5, "boot_num", length(which(data$method == "bstrp")),
    6, "sample file", data$feature[grepl("will process file", data$feature)] %>%
        str_extract(., "\\/[:print:]*$") %>%
        str_split(., "/") %>%
        unlist() %>%
        last()
    ) %>%
    mutate(sample = x[1])

}))
111 112 113 114




115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
# SUMMARIZE & VISUALIZE ---------------------------------------------------------------------------------

#' ## Target information:
genome_data <- tribble(
    ~"term", ~"value",
    "file", cdna,
    "number of genes", length(unique(ids$ensembl_gene_id)),
    "number of isoforms", length(unique(ids$ensembl_transcript_id))
)

genome_data %>% kable()

#' <br>

# Number of isoforms per gene:
130 131 132 133 134 135 136 137 138 139 140
isoCounts <- ids %>%
    group_by(ensembl_gene_id) %>%
    tally()

isoCounts %>%
    filter(n < 20) %>%
    ggplot(aes(as.factor(n))) +
    geom_bar() +
    xlab("number of isoforms") +
    ggtitle("Isoforms per gene")

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

#' <br><br>

#' ## Sample information:
log_data_mod <- log_data %>%
    spread(sample, value) %>%
    select(-num)

log_data_mod %>% kable()


genome_data[sample_ids] <- genome_data$value
rbind(log_data_mod, genome_data %>% select(-value)) %>% write_tsv("mapping_info.txt")

#' <br>

plot_data <- log_data %>%
    filter(grepl("processed|pseudoaligned", term))

plot_data$value <- as.numeric(gsub(",","",plot_data$value))

plot_data %>%
    select(-num) %>%
    spread(term, value) %>%
    group_by(sample) %>%
    mutate(proportion = 100/processed * pseudoaligned) %>%
    ungroup() %>%
    ggplot(aes(sample, proportion)) +
        geom_bar(stat="identity") +
        xlab("") +
        ylab("proportion of pseudoaligned reads (%)") +
        coord_flip()


175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
# gene2tx = quote({
#     mart <- biomaRt::useMart("ENSEMBL_MART_ENSEMBL", dataset = "hsapiens_gene_ensembl", host = paste0("aug2017.archive.ensembl.org"), path = "/biomart/martservice", archive = FALSE)
#     c("ensembl_gene_id", "ensembl_transcript_id") %>% biomaRt::getBM(mart = mart)
# }) %>% cache_it() %>% tbl_df
#
# aggr_data <- gene2tx %>%
#     transmute(ensembl_gene_id, target_id = ensembl_transcript_id)
#
# # number of isoforms for each gene
# isoCounts = gene2tx %>%
#     group_by(ensembl_gene_id) %>%
#     tally()

#nrow(isoCounts)
#nrow(isoCounts[isoCounts$n >1,])



# EXTRACT count & bootstrap data & CALCULATE confidence intervals

# from https://pachterlab.github.io/sleuth_walkthroughs/trapnell/analysis.html
196
s2c <- data_frame(sample = sample_ids, path = sample_dirs) #%>%
197 198
    # left_join(design, by = "replicate") %>%
    # transmute(sample = replicate, condition, path)
199 200 201 202 203 204 205 206
s2c[] <- lapply(s2c, as.character)


# prepare sleuth object
so <- sleuth_prep(s2c, extra_bootstrap_summary = TRUE)


# retrieve data on gene level via tximport
207 208
# https://github.com/Bioconductor-mirror/tximport/blob/master/R/tximport.R#L371-L378
filesAbund = list.files(kal_dir, "abundance.tsv", recursive = TRUE, full = TRUE)
209 210 211 212 213
filesAbundNames <- basename(dirname(filesAbund))
names(filesAbund) = map(filesAbund, ~ basename(dirname(.x)))
# t <- tximport(filesAbund, type = "kallisto", txOut = TRUE)
tx <- tximport(filesAbund, type = "kallisto", tx2gene = ids)

214 215
# gene level TPMs
gene_tpm = tx$abundance %>%
216 217 218 219
    as_df %>%
    rownames_to_column("ensembl_gene_id") %>%
    gather(replicate, tpm_by_gene, - ensembl_gene_id) %>%
    tbl_df %>%
220
    write_tsv("gene_tpms.txt")
221 222 223 224 225 226 227 228


# gene level counts
gene_counts = tx$counts %>%
    as_df %>%
    rownames_to_column("ensembl_gene_id") %>%
    gather(replicate, count_by_gene, - ensembl_gene_id) %>%
    tbl_df %>%
229
    write_tsv("gene_counts.txt")
230

231 232 233

## get kallisto count results
# non-normalized counts
234 235 236 237 238 239
countData <- kallisto_table(so, use_filtered = FALSE, normalized = FALSE, include_covariates = TRUE) %>% tbl_df

## also export isoform count matrix for differential expression analysis
trim_tx_id = function(ensembl_transcript_id) str_replace_all(ensembl_transcript_id, "[.][0-9]*$", "")

# txiByLocus <- tximport(filesAbund, type = "kallisto", txOut = TRUE)
240
isoexMatrix = tximport(filesAbund, type = "kallisto", txOut = TRUE) %$% round(counts) %>% as_df %>%
241
    rownames_to_column("ensembl_transcript_id") %>%
242
    # mutate_at(vars(-ensembl_transcript_id), replaceNA, 0) %>%
243 244
    mutate_inplace(ensembl_transcript_id, trim_tx_id)

245
isoexMatrix %>% mutate_if(is.numeric, as.integer) %>% write_tsv("tx_est_count_matrix.txt")
246 247 248 249 250 251 252 253

# normalized counts
countData_norm <- kallisto_table(so, use_filtered = FALSE, normalized = TRUE, include_covariates = TRUE) %>%
    transmute(target_id, sample, norm_counts = est_counts)

countData %<>%
left_join(countData_norm, by = c("target_id", "sample")) %>%
    left_join(ids, by = c("target_id" = "ensembl_transcript_id")) %>%
254
    transmute(ensembl_gene_id, ensembl_transcript_id = str_replace_all(target_id, "[.][0-9]*$", ""), replicate = sample, est_counts, norm_counts, tpm)
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
# head(countData)


# EXTRACT bootstrap count quantiles:
### df <- get_bootstrap_summary(so, "ENST00000390353.2", "est_counts")
### obj$bs_quants[[1]]$est_counts %>% as_df %>% rownames_to_column %>% tbl_df

bsSummary = so$bs_quants %>% map_df(~ .x$est_counts %>% as_df %>% rownames_to_column %>% tbl_df,.id="replicate") %>%
    left_join(ids, by = c("rowname" = "ensembl_transcript_id")) %>%
    transmute(ensembl_gene_id, ensembl_transcript_id = str_replace_all(rowname, "[.][0-9]*$", ""), replicate, min, lower, mid, upper, max)
write_tsv(bsSummary, path="bsSummary.txt")

# PLOT bootstrap values summary
#ggplot(bsSummary_20, aes(mid)) + geom_histogram() + scale_x_log10()
#ggplot(bsSummary_50, aes(mid)) + geom_histogram() + scale_x_log10()



# CALCULATE confidence intervals
# try out single one
# kal <- read_kallisto(kal_dirs_20[1], read_bootstrap = TRUE)
# bsData = kal$bootstrap %>% map_df(~ .x) %>% tbl_df
# bsData %>% group_by(target_id) %>% calc_ci(tpm)
## read bootstaps from .h5 file
#t <- read_kallisto_h5("../alignments_human/Human_CP1/abundance.h5", read_bootstrap = TRUE, max_bootstrap = NULL)

281
bsCI = sample_dirs %>% set_names(.,basename(.))%>%
282 283 284 285 286 287 288 289 290 291
    map_df(~ read_kallisto(.x, read_bootstrap = TRUE)$bootstrap %>% map_df(~ .x) %>%
        tbl_df %>%
        group_by(target_id) %>%
        calc_ci(tpm), .id="replicate") %>%
    transmute(ensembl_transcript_id = str_replace_all(target_id, ".[0-9]*$", ""), replicate, bs_tpm_ci = tpm_ci, bs_tpm_mean = tpm_mean)

write_tsv(bsCI, "bs_tpms_mean_ci.txt")


# COMBINE all data (data per isoform):
292
kalli_tpm <- ids %>%
293 294 295
    mutate(ensembl_transcript_id = str_replace_all(ensembl_transcript_id, ".[0-9]*$", "")) %>%
    left_join(bsCI, by = "ensembl_transcript_id") %>%
    left_join(countData, by = c("ensembl_transcript_id", "ensembl_gene_id", "replicate")) %>%
296
    select(-est_counts, -norm_counts) %>%
297 298
    left_join(isoCounts, by = "ensembl_gene_id") %>%
    mutate(isoforms_num = n) %>%
299
    select(-n) %>%
300 301
    left_join(gene_tpm)
write_tsv(kalli_tpm, "kallisto_results_tpm.txt")
302

303

304 305 306 307 308 309 310 311 312 313
kalli_counts <- ids %>%
    mutate(ensembl_transcript_id = str_replace_all(ensembl_transcript_id, ".[0-9]*$", "")) %>%
    left_join(countData, by = c("ensembl_transcript_id", "ensembl_gene_id")) %>%
    left_join(isoCounts, by = "ensembl_gene_id") %>%
    mutate(isoforms_num = n) %>%
    select(-n, -tpm) %>%
    left_join(gene_counts)
write_tsv(kalli_counts, "kallisto_results_counts.txt")

# kalli_counts %>% filter(count_by_gene > 0) %>% arrange(replicate, ensembl_gene_id) %>% head()
314 315


316
#-----------------------------------------------------------------------------------------------------------------------
317
session::save.session(".collect_kallisto_data.dat")
318 319 320 321
# session::restore.session(".collect_kallisto_data.dat")