edmundmiller commited on
Commit
90f526e
1 Parent(s): 91d9093

Add Biostar Handbook code

Browse files
rnaseq/code/combine_genes.r ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Combine transcripts into genes with the tximport package.
3
+ #
4
+ # https://bioconductor.org/packages/release/bioc/html/tximport.html
5
+ #
6
+
7
+ # Load the packages
8
+ library(tximport)
9
+
10
+ # The directory where the counts for each sample are located.
11
+ data_dir <- 'salmon'
12
+
13
+ # The sample file is in CSV format and must have the headers "sample" and "condition".
14
+ design_file = "design.csv"
15
+
16
+ # What software created the mappings.
17
+ method <- "salmon"
18
+
19
+ # The ouput file name.
20
+ output_file = "counts.csv"
21
+
22
+ # The name of the file that contains transcript to gene mapping.
23
+ # See our guide on how to make a mapping file.
24
+ tx2gene_file = "tx2gene.csv"
25
+
26
+ # Inform the user.
27
+ print("# Tool: Combine genes")
28
+ print(paste("# Sample: ", design_file))
29
+ print(paste("# Data dir: ", data_dir))
30
+ print(paste("# Gene map: ", tx2gene_file))
31
+
32
+ # Read the sample file
33
+ sample_data <- read.csv(design_file, stringsAsFactors=F)
34
+
35
+ # Isolate the sample names.
36
+ sample_names <- sample_data$sample
37
+
38
+ # Generate the file names that contain the quantification data.
39
+ files <- file.path(data_dir, sample_names, "quant.sf")
40
+
41
+ # Read the transcript to gene mapping file.
42
+ tx2gene = read.csv(tx2gene_file)
43
+
44
+ # Summarize over transcripts.
45
+ tx <- tximport(files, type=method, tx2gene=tx2gene)
46
+
47
+ # Transform into a dataframe.
48
+ df <- data.frame(tx$counts)
49
+
50
+ # Set the column names
51
+ colnames(df) <- sample_names
52
+
53
+ # Add a rowname by gene id
54
+ df$ensembl_gene_id = row.names(df)
55
+
56
+ # Create a smaller data frame that connects gene to name.
57
+ id2name = tx2gene[, c("ensembl_gene_id", "external_gene_name")]
58
+
59
+ # Need to de-duplicate so the merge won't create new entries.
60
+ id2name = id2name[!duplicated(id2name),]
61
+
62
+ # Add the gene names to the list
63
+ df = merge(df, id2name, by="ensembl_gene_id", all.x = TRUE, all.y = FALSE)
64
+
65
+ # This will be the new column order.
66
+ cols <- c("ensembl_gene_id", "external_gene_name", sample_names)
67
+
68
+ # Reorganize the columns.
69
+ df <- df[, cols]
70
+
71
+ # Save the resulting summarized counts.
72
+ write.csv(df, file=output_file, row.names = FALSE, quote = FALSE)
73
+
74
+ # Inform the user.
75
+ print(paste("# Results: ", output_file))
rnaseq/code/combine_transcripts.r ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Combine transcripts with the tximport package.
3
+ #
4
+ # https://bioconductor.org/packages/release/bioc/html/tximport.html
5
+ #
6
+ # Transcript level summarization.
7
+ #
8
+
9
+ # Load the packages
10
+ library(tximport)
11
+
12
+ # The directory where the counts for each sample are located.
13
+ data_dir <- 'salmon'
14
+
15
+ # The sample file must be in CSV format and must have the headers "sample" and "condition".
16
+ desing_file = "design.csv"
17
+
18
+ # What software created the mappings.
19
+ method <- "salmon"
20
+
21
+ # The output file name.
22
+ output_file = "counts.csv"
23
+
24
+ # Inform the user.
25
+ print("# Tool: Combine transcripts")
26
+ print(paste("# Sample: ", desing_file))
27
+ print(paste("# Data dir: ", data_dir))
28
+
29
+ # Read the sample file
30
+ sample_data <- read.csv(desing_file, stringsAsFactors=F)
31
+
32
+ # Isolate the sample names.
33
+ sample_names <- sample_data$sample
34
+
35
+ # Generate the file names that contain the quantification data.
36
+ files <- file.path(data_dir, sample_names, "quant.sf")
37
+
38
+ # Summarize over transcripts.
39
+ tx <- tximport(files, type=method, txOut=TRUE)
40
+
41
+ # Transform counts into a dataframe.
42
+ df <- data.frame(tx$counts)
43
+
44
+ # Set the column names.
45
+ colnames(df) <- sample_names
46
+
47
+ # Create a new column for transcript ids.
48
+ df$ensembl_transcript_id = rownames(df)
49
+
50
+ # List the desired column order.
51
+ cols <- c("ensembl_transcript_id", sample_names)
52
+
53
+ # Reorganize the columns.
54
+ df <- df[, cols]
55
+
56
+ # Save the resulting summarized counts.
57
+ write.csv(df, file=output_file, row.names = FALSE, quote = FALSE)
58
+
59
+ # Inform the user.
60
+ print(paste("# Results: ", output_file))
rnaseq/code/compare_results.r ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Compare two RNA seq data analysis result files.
3
+ #
4
+
5
+ # The results files to be compared.
6
+ file1 = "results1.csv"
7
+ file2 = "results2.csv"
8
+
9
+ # Read the data files.
10
+ data1 <- read.csv(file1)
11
+ data2 <- read.csv(file2)
12
+
13
+ # Select the rows where the FDR is under a cutoff.
14
+ sig1 <- subset(data1, FDR <= 0.5)
15
+ sig2 <- subset(data2, FDR <= 0.5)
16
+
17
+ # Extract the gene names only
18
+ name1 = sig1$name
19
+ name2 = sig2$name
20
+
21
+ # Intersect: common elements.
22
+ isect <- intersect(name1, name2)
23
+
24
+ # Elements from both.
25
+ uni <- union(name1, name2)
26
+
27
+ # Elements in file 1 only.
28
+ only1 <- setdiff(name1, name2)
29
+
30
+ # Elements in file 2 only.
31
+ only2 <- setdiff(name2, name1)
32
+
33
+ # Report the differences
34
+ print("# Tool: compare_results.r")
35
+ print("")
36
+ print(paste("# File 1:", length(name1), file1))
37
+ print(paste("# File 2:", length(name2), file2))
38
+ print("")
39
+ print(paste("# Union:", length(uni)))
40
+ print(paste("# Intersect:", length(isect)))
41
+ print(paste("# File 1 only:", length(only1)))
42
+ print(paste("# File 2 only:", length(only2)))
43
+
44
+ print("----")
45
+
46
+ print("Only 1:")
47
+ print(paste( only1))
48
+
49
+ print("----")
50
+
51
+ print("Only 2:")
52
+ print(paste( only2))
53
+
54
+ expect = subset(data1, grepl("UP|DOWN", name))$name
rnaseq/code/create_heatmap.r ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Create heat map from a differential expression count table.
3
+ #
4
+ # Load the library.
5
+ suppressPackageStartupMessages(library(gplots))
6
+
7
+ # The name of the file that contains the counts.
8
+ count_file = "results.csv"
9
+
10
+ # The name of the output file.
11
+ output_file = "heatmap.pdf"
12
+
13
+ # Inform the user.
14
+ print("# Tool: Create Heatmap ")
15
+ print(paste("# Input: ", count_file))
16
+ print(paste("# Output: ", output_file))
17
+
18
+ # FDR cutoff.
19
+ MIN_FDR = 0.05
20
+
21
+ # Plot width
22
+ WIDTH = 12
23
+
24
+ # Plot height.
25
+ HEIGHT = 13
26
+
27
+ # Set the margins
28
+ MARGINS = c(9, 12)
29
+
30
+ # Relative heights of the rows in the plot.
31
+ LHEI = c(1, 5)
32
+
33
+ # Read normalized counts from the standard input.
34
+ data = read.csv(count_file, header=T, as.is=TRUE)
35
+
36
+ # Subset data for values under a treshold.
37
+ data = subset(data, data$FDR <= MIN_FDR)
38
+
39
+ # The heatmap row names will be taken from the first column.
40
+ row_names = data[, 1]
41
+
42
+ # The code assumes that the normalized data matrix is listed to the right of the falsePos column.
43
+ idx = which(colnames(data) == "falsePos") + 1
44
+
45
+ # The normalized counts are on the right size.
46
+ counts = data[, idx : ncol(data)]
47
+
48
+ # Load the data from the second column on.
49
+ values = as.matrix(counts)
50
+
51
+ # Adds a little noise to each element to avoid the
52
+ # clustering function failure on zero variance rows.
53
+ values = jitter(values, factor = 1, amount = 0.00001)
54
+
55
+ # Normalize each row to a z-score
56
+ zscores = NULL
57
+ for (i in 1 : nrow(values)) {
58
+ row = values[i,]
59
+ zrow = (row - mean(row)) / sd(row)
60
+ zscores = rbind(zscores, zrow)
61
+ }
62
+
63
+ # Set the row names on the zscores.
64
+ row.names(zscores) = row_names
65
+
66
+ # Turn the data into a matrix for heatmap2.
67
+ zscores = as.matrix(zscores)
68
+
69
+ # Set the color palette.
70
+ col = greenred
71
+
72
+ # Create a PDF device
73
+ pdf(output_file, width = WIDTH, height = HEIGHT)
74
+
75
+ heatmap.2(zscores, col=col, density.info="none", Colv=NULL,
76
+ dendrogram="row", trace="none", margins=MARGINS, lhei=LHEI)
77
+
78
+ #dev.off()
79
+
rnaseq/code/create_pca.r ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+ #
3
+ # This script makes a pca of all samples and a heatmap of sample distances.
4
+ #
5
+
6
+ # The inputs to the script are counts file, design file and the number of samples.
7
+ #
8
+ # How to run?
9
+ # Rscript summary_plots.r <counts_file> <design_file> <number_of_samples>
10
+ # Example: Rscript summary_plots.r counts.txt design.txt 6
11
+ # Design file example:
12
+ # Sample Condition
13
+ # MCVS450 MCVS
14
+ # MCVS515 MCVS
15
+ # MCVS520 MCVS
16
+ # MNS456 MNS
17
+ # MNS486 MNS
18
+ # MNS580 MNS
19
+
20
+
21
+ read <- function(counts_file, design_file,number_of_samples){
22
+ counts = read.table(counts_file, header=TRUE, sep="\t", row.names=1 )
23
+ idx = ncol(counts) - number_of_samples
24
+
25
+ # Cut out the valid columns.
26
+ if (idx > 0) counts = counts[-c(1:idx)] else counts=counts
27
+
28
+ numeric_idx = sapply(counts, mode) == 'numeric'
29
+ counts[numeric_idx] = round(counts[numeric_idx], 0)
30
+
31
+ colData = read.table(design_file, header=TRUE, sep="\t", row.names=1 )
32
+
33
+ # Create DESEq2 dataset.
34
+ dds = DESeqDataSetFromMatrix(countData=counts, colData=colData, design = ~1)
35
+
36
+ # Variance Stabilizing Transformation.
37
+ vsd = vst(dds)
38
+ names = colnames(counts)
39
+ groups = colnames(colData)
40
+
41
+ rlist <- list("vsd" = vsd, "names"=names, "groups" =groups)
42
+ return(rlist)
43
+
44
+ }
45
+
46
+ # Command line argument.
47
+ args = commandArgs(trailingOnly=TRUE)
48
+
49
+
50
+ if (length(args)!=3) {
51
+ stop("Counts file, Design file and the number of samples must be specified at the commandline", call.=FALSE)
52
+ }
53
+
54
+
55
+ # Load the library while suppressing verbose messages.
56
+ suppressPackageStartupMessages(library(DESeq2))
57
+ suppressPackageStartupMessages(library(ggplot2))
58
+
59
+ # Set the plot dimensions.
60
+ WIDTH = 12
61
+ HEIGHT = 8
62
+
63
+
64
+ # The first argument to the script -counts file
65
+ infile = args[1]
66
+
67
+ # The second argument to the script - design file
68
+ coldata_file = args[2]
69
+
70
+ # The third argument to the script - total number of samples.
71
+ sno = args[3]
72
+ sno= as.numeric(sno)
73
+
74
+ res = read(infile, coldata_file, sno)
75
+ vsd= res$vsd
76
+ names = res$names
77
+ groups = res$groups
78
+
79
+ # Open the drawing device.
80
+ pdf('pca.pdf', width = WIDTH, height = HEIGHT)
81
+ par(mfrow = c(2,1))
82
+ nudge <- position_nudge(y = 0.5)
83
+
84
+ z=plotPCA(vsd, intgroup=c(groups))
85
+ z+ geom_text(aes(label = names), position=nudge, size = 2.5) +ggtitle(aes("PCA"))
86
+ dev.off()
87
+
88
+ #
89
+ # Plot heatmap of sample distances
90
+ #
91
+ library(pheatmap)
92
+ library("RColorBrewer")
93
+
94
+ sampleDists = dist(t(assay(vsd)))
95
+ sampleDistMatrix = as.matrix(sampleDists)
96
+
97
+ colnames(sampleDistMatrix) = NULL
98
+
99
+ colors = colorRampPalette( rev(brewer.pal(9, "Blues")) )(255)
100
+
101
+
102
+ # Open the drawing device.
103
+
104
+ pdf('heatmap.pdf', width = 8, height = HEIGHT)
105
+
106
+ pheatmap(sampleDistMatrix,
107
+ clustering_distance_rows=sampleDists,
108
+ clustering_distance_cols=sampleDists,
109
+ col=colors) + geom_label(aes(label = names))
110
+
111
+ dev.off()
112
+
rnaseq/code/create_tx2gene.r ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Obtain gene names for transcripts with the biomaRt package.
3
+ #
4
+ # https://bioconductor.org/packages/release/bioc/html/biomaRt.html
5
+ #
6
+
7
+ # Load the biomart manager
8
+ library(biomaRt)
9
+
10
+ # The biomaRt dataset name.
11
+ dataset <- "drerio_gene_ensembl"
12
+
13
+ # The ouput file name.
14
+ output_file = "tx2gene.csv"
15
+
16
+ # Make a connection to the validated dataset.
17
+ mart <- useEnsembl(dataset = dataset, biomart = 'ensembl')
18
+
19
+ # The attributes that we want to obtain.
20
+ # The first column must match the feature id used during quantification.
21
+ attributes <- c(
22
+ "ensembl_transcript_id_version",
23
+ "ensembl_gene_id",
24
+ "ensembl_transcript_id",
25
+ "transcript_length",
26
+ "external_gene_name"
27
+ )
28
+
29
+ # Perform the query.
30
+ data <- biomaRt::getBM(attributes = attributes, mart = mart)
31
+
32
+ # Save the data into a file.
33
+ write.csv(data, file=output_file, row.names=FALSE, quote=FALSE)
34
+
35
+ # Inform the user.
36
+ print("# Tool: Create tx2gene mapping")
37
+ print(paste("# Dataset: ", dataset))
38
+ print(paste("# Output: ", output_file))
rnaseq/code/deseq2.r ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Differential expression analysis with the DESeq2 package.
3
+ #
4
+ # https://bioconductor.org/packages/release/bioc/html/DESeq2.html
5
+ #
6
+
7
+ # Load the library.
8
+ suppressPackageStartupMessages(library(DESeq2))
9
+
10
+ # The name of the file that contains the counts.
11
+ counts_file = "counts.csv"
12
+
13
+ # The sample file is in CSV format and must have the headers "sample" and "condition".
14
+ design_file = "design.csv"
15
+
16
+ # The final result file.
17
+ output_file = "results.csv"
18
+
19
+ # Read the sample file.
20
+ colData <- read.csv(design_file, stringsAsFactors=F)
21
+
22
+ # Turn conditions into factors.
23
+ colData$condition = factor(colData$condition)
24
+
25
+ # The first level should correspond to the first entry in the file!
26
+ # Required later when building a model.
27
+ colData$condition = relevel(colData$condition, toString(colData$condition[1]))
28
+
29
+ # Isolate the sample names.
30
+ sample_names <- colData$sample
31
+
32
+ # Read the data from the standard input.
33
+ df = read.csv(counts_file, header=TRUE, row.names=1 )
34
+
35
+ # Created rounded integers for the count data
36
+ countData = round(df[, sample_names])
37
+
38
+ # Other columns in the dataframe that are not sample information.
39
+ otherCols = df[!(names(df) %in% sample_names)]
40
+
41
+ #
42
+ # Running DESeq2
43
+ #
44
+
45
+ # Create DESEq2 dataset.
46
+ dds = DESeqDataSetFromMatrix(countData=countData, colData=colData, design = ~condition)
47
+
48
+ # Run deseq
49
+ dse = DESeq(dds)
50
+
51
+ # Format the results.
52
+ res = results(dse)
53
+
54
+ #
55
+ # The rest of the code is about formatting the output dataframe.
56
+ #
57
+
58
+ # Turn the DESeq2 results into a data frame.
59
+ data = cbind(otherCols, data.frame(res))
60
+
61
+ # Create the foldChange column.
62
+ data$foldChange = 2 ^ data$log2FoldChange
63
+
64
+ # Rename columns to better reflect reality.
65
+ names(data)[names(data)=="pvalue"] <-"PValue"
66
+ names(data)[names(data)=="padj"] <- "FDR"
67
+
68
+ # Create a real adjusted pvalue
69
+ data$PAdj = p.adjust(data$PValue, method="hochberg")
70
+
71
+ # Sort the data by PValue to compute false discovery counts.
72
+ data = data[with(data, order(PValue, -foldChange)), ]
73
+
74
+ # Compute the false discovery counts on the sorted table.
75
+ data$falsePos = 1:nrow(data) * data$FDR
76
+
77
+ # Create the additional columns that we wish to present.
78
+ data$baseMeanA = 1
79
+ data$baseMeanB = 1
80
+
81
+ # Get the normalized counts.
82
+ normed = counts(dse, normalized=TRUE)
83
+
84
+ # Round normalized counts to a single digit.
85
+ normed = round(normed, 1)
86
+
87
+ # Merge the two datasets by row names.
88
+ total <- merge(data, normed, by=0)
89
+
90
+ # Sort again for output.
91
+ total = total[with(total, order(PValue, -foldChange)), ]
92
+
93
+ # Sample names for condition A
94
+ col_names_A = data.frame(split(colData, colData$condition)[1])[,1]
95
+
96
+ # Sample names for condition B
97
+ col_names_B = data.frame(split(colData, colData$condition)[2])[,1]
98
+
99
+ # Create the individual baseMean columns.
100
+ total$baseMeanA = rowMeans(total[, col_names_A])
101
+ total$baseMeanB = rowMeans(total[, col_names_B])
102
+
103
+ # Bringing some sanity to numbers. Round columns to fewer digits.
104
+ total$foldChange = round(total$foldChange, 3)
105
+ total$log2FoldChange = round(total$log2FoldChange, 1)
106
+ total$baseMean = round(total$baseMean, 1)
107
+ total$baseMeanA = round(total$baseMeanA, 1)
108
+ total$baseMeanB = round(total$baseMeanB, 1)
109
+ total$lfcSE = round(total$lfcSE, 2)
110
+ total$stat = round(total$stat, 2)
111
+ total$FDR = round(total$FDR, 4)
112
+ total$falsePos = round(total$falsePos, 0)
113
+
114
+ # Reformat these columns as string.
115
+ total$PAdj = formatC(total$PAdj, format = "e", digits = 1)
116
+ total$PValue = formatC(total$PValue, format = "e", digits = 1)
117
+
118
+ # Rename the first column.
119
+ colnames(total)[1] <- "name"
120
+
121
+ # Reorganize columns names to make more sense.
122
+ new_cols = c("name", names(otherCols), "baseMean","baseMeanA","baseMeanB","foldChange",
123
+ "log2FoldChange","lfcSE","stat","PValue","PAdj", "FDR","falsePos",col_names_A, col_names_B)
124
+
125
+ # Slice the dataframe with new columns.
126
+ total = total[, new_cols]
127
+
128
+ # Write the results to the standard output.
129
+ write.csv(total, file=output_file, row.names=FALSE, quote=FALSE)
130
+
131
+ # Inform the user.
132
+ print("# Tool: DESeq2")
133
+ print(paste("# Design: ", design_file))
134
+ print(paste("# Input: ", counts_file))
135
+ print(paste("# Output: ", output_file))
136
+
137
+
rnaseq/code/edger.r ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Differential expression analysis with the edgeR package.
3
+ #
4
+ # https://bioconductor.org/packages/release/bioc/html/edgeR.html
5
+ #
6
+
7
+ # Load the library
8
+ library(edgeR)
9
+
10
+ # The name of the file that contains the counts.
11
+ counts_file = "counts.csv"
12
+
13
+ # The sample file is in CSV format and must have the headers "sample" and "condition".
14
+ design_file = "design.csv"
15
+
16
+ # The final result file.
17
+ output_file = "results.csv"
18
+
19
+ # Read the sample file.
20
+ colData <- read.csv(design_file, stringsAsFactors=F)
21
+
22
+ # Turn conditions into factors.
23
+ colData$condition = factor(colData$condition)
24
+
25
+ # The first level should correspond to the first entry in the file!
26
+ # Required when building a model.
27
+ colData$condition = relevel(colData$condition, toString(colData$condition[1]))
28
+
29
+ # Isolate the sample names.
30
+ sample_names <- colData$sample
31
+
32
+ # Read the data from the standard input.
33
+ df = read.csv(counts_file, header=TRUE, row.names=1 )
34
+
35
+ # Created rounded integers for the count data
36
+ counts = round(df[, sample_names])
37
+
38
+ # Other columns in the dataframe that are not sample information.
39
+ otherCols = df[!(names(df) %in% sample_names)]
40
+
41
+ # Using the same naming as in the library.
42
+ group <- colData$condition
43
+
44
+ # Creates a DGEList object from a table of counts and group.
45
+ dge <- DGEList(counts=counts, group=group)
46
+
47
+ # Maximizes the negative binomial conditional common likelihood to estimate a common dispersion value across all genes.
48
+ dis <- estimateCommonDisp(dge)
49
+
50
+ # Estimates tagwise dispersion values by an empirical Bayes method based on weighted conditional maximum likelihood.
51
+ tag <- estimateTagwiseDisp(dis)
52
+
53
+ # Compute genewise exact tests for differences in the means between the groups.
54
+ etx <- exactTest(tag)
55
+
56
+ # Extracts the most differentially expressed genes.
57
+ etp <- topTags(etx, n=nrow(counts))
58
+
59
+ # Get the scale of the data
60
+ scale = dge$samples$lib.size * dge$samples$norm.factors
61
+
62
+ # Get the normalized counts
63
+ normed = round(t(t(counts)/scale) * mean(scale))
64
+
65
+ # Turn the DESeq2 results into a data frame.
66
+ data = merge(otherCols, etp$table, by="row.names")
67
+
68
+ # Create column placeholders.
69
+ data$baseMean = 1
70
+ data$baseMeanA = 1
71
+ data$baseMeanB = 1
72
+ data$foldChange = 2 ^ data$logFC
73
+ data$falsePos = 1
74
+
75
+ # Rename the column.
76
+ names(data)[names(data)=="logFC"] <-"log2FoldChange"
77
+
78
+ # Compute the adjusted p-value
79
+ data$PAdj = p.adjust(data$PValue, method="hochberg")
80
+
81
+ # Rename the first columns for consistency with other methods.
82
+ colnames(data)[1] <- "name"
83
+
84
+ # Create a merged output that contains the normalized counts.
85
+ total <- merge(data, normed, by.x='name', by.y="row.names")
86
+
87
+ # Sort the data for the output.
88
+ total = total[with(total, order(PValue, -foldChange)), ]
89
+
90
+ # Compute the false discovery counts on the sorted table.
91
+ data$falsePos = 1:nrow(data) * data$FDR
92
+
93
+ # Sample names for condition A
94
+ col_names_A = data.frame(split(colData, colData$condition)[1])[,1]
95
+
96
+ # Sample names for condition B
97
+ col_names_B = data.frame(split(colData, colData$condition)[2])[,1]
98
+
99
+ # Create the individual baseMean columns.
100
+ total$baseMeanA = rowMeans(total[, col_names_A])
101
+ total$baseMeanB = rowMeans(total[, col_names_B])
102
+ total$baseMean = total$baseMeanA + total$baseMeanB
103
+
104
+ # Round the numbers
105
+ total$foldChange = round(total$foldChange, 3)
106
+ total$FDR = round(total$FDR, 4)
107
+ total$PAdj = round(total$PAdj, 4)
108
+ total$logCPM = round(total$logCPM, 1)
109
+ total$log2FoldChange = round(total$log2FoldChange, 1)
110
+ total$baseMean = round(total$baseMean, 1)
111
+ total$baseMeanA = round(total$baseMeanA, 1)
112
+ total$baseMeanB = round(total$baseMeanB, 1)
113
+ total$falsePos = round(total$falsePos, 0)
114
+
115
+ # Reformat these columns as string.
116
+ total$PAdj = formatC(total$PAdj, format = "e", digits = 1)
117
+ total$PValue = formatC(total$PValue, format = "e", digits = 1)
118
+
119
+ # Reorganize columns names to make more sense.
120
+ new_cols = c("name", names(otherCols), "baseMean","baseMeanA","baseMeanB","foldChange",
121
+ "log2FoldChange","logCPM","PValue","PAdj", "FDR","falsePos",col_names_A, col_names_B)
122
+
123
+ # Slice the dataframe with new columns.
124
+ total = total[, new_cols]
125
+
126
+ # Write the result to the standard output.
127
+ write.csv(total, file=output_file, row.names=FALSE, quote=FALSE)
128
+
129
+ # Inform the user.
130
+ print("# Tool: edgeR")
131
+ print(paste("# Design: ", design_file))
132
+ print(paste("# Input: ", counts_file))
133
+ print(paste("# Output: ", output_file))
134
+
rnaseq/code/filter_counts.r ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Filter a count table to remove entries with low expression.
3
+ #
4
+
5
+ # The sample file is in CSV format and must have the headers "sample" and "condition".
6
+ sample_file = "samples.csv"
7
+
8
+ # The count file that contains the summarized counts.
9
+ counts_file = "combined_genes.csv"
10
+
11
+ # The result file name.
12
+ output_file = "filtered_counts.csv"
13
+
14
+ # Inform the user.
15
+ print("# Tool: Filter counts")
16
+ print(paste("# Sample: ", sample_file))
17
+ print(paste("# Counts: ", counts_file))
18
+
19
+ # Read the sample file
20
+ sd <- read.csv(sample_file, stringsAsFactors=F)
21
+
22
+ # Isolate the sample names.
23
+ sn <- sd$sample
24
+
25
+ # Read the count file.
26
+ df = read.csv(counts_file, stringsAsFactors = FALSE)
27
+
28
+ # Create a matrix from the sample names
29
+ dm = as.matrix(df[,sn])
30
+
31
+ #
32
+ # The filtering condition below selects for at least 10 reads across all conditions.
33
+ #
34
+ min_count = 10
35
+
36
+ # Apply the filter on the row sums.
37
+ keep <- (rowSums(dm) >= min_count)
38
+
39
+ # Compute reporting counts.
40
+ count_total = length(keep)
41
+ count_good = sum(keep)
42
+ count_removed = count_total - count_good
43
+
44
+ # Notify the user on filtering.
45
+ print (paste("# Minimum:", min_count, "Total:", count_total, "Kept:", count_good, "Removed:", count_removed))
46
+
47
+ # Slice the input dataframe with the boolean vector.
48
+ df = df[keep,]
49
+
50
+ # Save the resulting filtered counts.
51
+ write.csv(df, file=output_file, row.names = FALSE, quote = FALSE)
52
+
53
+ # Inform the user.
54
+ print(paste("# Results:", output_file))
55
+
rnaseq/code/mission-impossible.mk ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This Makefile perform the Mission Impossible RNA-seq analysis.
3
+ #
4
+ #
5
+ # More info in the Biostar Handbook volume RNA-Seq by Example
6
+ #
7
+
8
+ # The reference genome.
9
+ REF = refs/genome.fa
10
+
11
+ # The file containing transcripts.
12
+ TRX = refs/transcripts.fa
13
+
14
+ # The name of the HISAT2 index.
15
+ HISAT2_INDEX = idx/genome
16
+
17
+ # The name of the salmon index
18
+ SALMON_INDEX = idx/transcripts.salmon
19
+
20
+ # The design file.
21
+ DESIGN = design.csv
22
+
23
+ # These targets are not files.
24
+ .PHONY: data align results
25
+
26
+ # Tell the user to read the source of this Makefile to understand it.
27
+ usage:
28
+ @echo "#"
29
+ @echo "# Use the the source, Luke!"
30
+ @echo "#"
31
+
32
+ # Create the design file and ids.txt file.
33
+ ${DESIGN}:
34
+
35
+ # The design file
36
+ @echo "sample,condition" > design.csv
37
+ @echo "BORED_1,bored" >> design.csv
38
+ @echo "BORED_2,bored" >> design.csv
39
+ @echo "BORED_3,bored" >> design.csv
40
+ @echo "EXCITED_1,excited" >> design.csv
41
+ @echo "EXCITED_2,excited" >> design.csv
42
+ @echo "EXCITED_3,excited" >> design.csv
43
+
44
+ # Create the ids.txt file (first column only, delete first line)
45
+ cat design.csv | cut -f1 -d , | sed 1d > ids.txt
46
+
47
+ # Download the data for the analysis.
48
+ data:
49
+ # Download the reference genome.
50
+ wget -nc http://data.biostarhandbook.com/books/rnaseq/data/golden.genome.tar.gz
51
+
52
+ # Unpack the reference genome.
53
+ tar xzvf golden.genome.tar.gz
54
+
55
+ # Download the sequencing reads.
56
+ wget -nc http://data.biostarhandbook.com/books/rnaseq/data/golden.reads.tar.gz
57
+
58
+ # Unpack the sequencing reads.
59
+ tar zxvf golden.reads.tar.gz
60
+
61
+ # Build the HISAT2 and salmon index for the reference genomes
62
+ index: ${REF}
63
+ mkdir -p idx
64
+ hisat2-build ${REF} ${HISAT2_INDEX}
65
+ salmon index -t ${TRX} -i ${SALMON_INDEX}
66
+
67
+ # Runs a HISAT2 alignment.
68
+ align: ${DESIGN} ${HISAT2_INDEX_FILE}
69
+ mkdir -p bam
70
+ cat ids.txt | parallel --progress --verbose "hisat2 -x ${HISAT2_INDEX} -1 reads/{}_R1.fq -2 reads/{}_R2.fq | samtools sort > bam/{}.bam"
71
+ cat ids.txt | parallel -j 1 echo "bam/{}.bam" | \
72
+ xargs featureCounts -p -a refs/features.gff -o counts.txt
73
+ RScript code/parse_featurecounts.r
74
+
75
+ # Run a SALMON classification.
76
+ classify: ${DESIGN} ${SALMON_INDEX}
77
+ mkdir -p salmon
78
+ cat ids.txt | parallel --progress --verbose "salmon quant -i ${SALMON_INDEX} -l A --validateMappings -1 reads/{}_R1.fq -2 reads/{}_R2.fq -o salmon/{}"
79
+ RScript code/combine_transcripts.r
80
+
81
+ # Runs an analysis on the aligned data.
82
+ results:
83
+ mkdir -p res
84
+ RScript code/deseq2.r
85
+ RScript code/create_heatmap.r
86
+
87
+ # Required software
88
+ install:
89
+ @echo ""
90
+ @echo mamba install wget parallel samtools subread hisat2 salmon bioconductor-tximport bioconductor-edger bioconductor-biomart bioconductor-deseq2 r-gplots
91
+ @echo ""
92
+
rnaseq/code/parse_featurecounts.r ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Transform feature counts output to simple counts.
3
+ #
4
+
5
+ # The results files to be compared.
6
+
7
+ # Count file produced by featurecounts.
8
+ counts_file <- "counts.txt"
9
+
10
+ # The sample file must be in CSV format and must have the headers "sample" and "condition".
11
+ design_file = "design.csv"
12
+
13
+ # The name of the output file.
14
+ output_file = "counts.csv"
15
+
16
+ # Inform the user.
17
+ print("# Tool: Parse featurecounts")
18
+ print(paste("# Design: ", design_file))
19
+ print(paste("# Input: ", counts_file))
20
+
21
+ # Read the sample file.
22
+ sample_data <- read.csv(design_file, stringsAsFactors=F)
23
+
24
+ # Turn conditions into factors.
25
+ sample_data$condition <- factor(sample_data$condition)
26
+
27
+ # The first level should correspond to the first entry in the file!
28
+ # Required when building a model.
29
+ sample_data$condition <- relevel(sample_data$condition, toString(sample_data$condition[1]))
30
+
31
+ # Read the featurecounts output.
32
+ df <- read.table(counts_file, header=TRUE)
33
+
34
+ #
35
+ # It is absolutely essential that the order of the featurecounts headers is the same
36
+ # as the order of the sample names in the file! The code below will overwrite the headers!
37
+ #
38
+
39
+ # Subset the dataframe to the columns of interest.
40
+ counts <- df[ ,c(1, 7:length(names(df)))]
41
+
42
+ # Rename the columns
43
+ names(counts) <- c("name", sample_data$sample)
44
+
45
+ # Write the result to the standard output.
46
+ write.csv(counts, file=output_file, row.names=FALSE, quote=FALSE)
47
+
48
+ # Inform the user.
49
+ print(paste("# Output: ", output_file))