11
|
1 # ---------------------- load/install packages ----------------------
|
0
|
2
|
|
3 if (!("gridExtra" %in% rownames(installed.packages()))) {
|
11
|
4 install.packages("gridExtra", repos="http://cran.xl-mirror.nl/")
|
0
|
5 }
|
|
6 library(gridExtra)
|
|
7 if (!("ggplot2" %in% rownames(installed.packages()))) {
|
11
|
8 install.packages("ggplot2", repos="http://cran.xl-mirror.nl/")
|
0
|
9 }
|
11
|
10 library(ggplot2)
|
0
|
11 if (!("plyr" %in% rownames(installed.packages()))) {
|
11
|
12 install.packages("plyr", repos="http://cran.xl-mirror.nl/")
|
0
|
13 }
|
11
|
14 library(plyr)
|
0
|
15
|
|
16 if (!("data.table" %in% rownames(installed.packages()))) {
|
11
|
17 install.packages("data.table", repos="http://cran.xl-mirror.nl/")
|
0
|
18 }
|
|
19 library(data.table)
|
|
20
|
6
|
21 if (!("reshape2" %in% rownames(installed.packages()))) {
|
11
|
22 install.packages("reshape2", repos="http://cran.xl-mirror.nl/")
|
6
|
23 }
|
|
24 library(reshape2)
|
|
25
|
11
|
26 # ---------------------- parameters ----------------------
|
0
|
27
|
11
|
28 args <- commandArgs(trailingOnly = TRUE)
|
0
|
29
|
11
|
30 infile = args[1] #path to input file
|
|
31 outfile = args[2] #path to output file
|
|
32 outdir = args[3] #path to output folder (html/images/data)
|
|
33 clonaltype = args[4] #clonaltype definition, or 'none' for no unique filtering
|
21
|
34 ct = unlist(strsplit(clonaltype, ","))
|
11
|
35 species = args[5] #human or mouse
|
|
36 locus = args[6] # IGH, IGK, IGL, TRB, TRA, TRG or TRD
|
|
37 filterproductive = ifelse(args[7] == "yes", T, F) #should unproductive sequences be filtered out? (yes/no)
|
|
38
|
|
39 # ---------------------- Data preperation ----------------------
|
|
40
|
|
41 inputdata = read.table(infile, sep="\t", header=TRUE, fill=T, comment.char="")
|
0
|
42
|
11
|
43 setwd(outdir)
|
|
44
|
|
45 # remove weird rows
|
21
|
46 inputdata = inputdata[inputdata$Sample != "",]
|
0
|
47
|
11
|
48 #remove the allele from the V,D and J genes
|
|
49 inputdata$Top.V.Gene = gsub("[*]([0-9]+)", "", inputdata$Top.V.Gene)
|
|
50 inputdata$Top.D.Gene = gsub("[*]([0-9]+)", "", inputdata$Top.D.Gene)
|
|
51 inputdata$Top.J.Gene = gsub("[*]([0-9]+)", "", inputdata$Top.J.Gene)
|
21
|
52
|
11
|
53 inputdata$clonaltype = 1:nrow(inputdata)
|
21
|
54
|
11
|
55 PRODF = inputdata
|
20
|
56 UNPROD = inputdata
|
11
|
57 if(filterproductive){
|
|
58 if("Functionality" %in% colnames(inputdata)) { # "Functionality" is an IMGT column
|
|
59 PRODF = inputdata[inputdata$Functionality == "productive" | inputdata$Functionality == "productive (see comment)", ]
|
20
|
60 UNPROD = inputdata[!(inputdata$Functionality == "productive" | inputdata$Functionality == "productive (see comment)"), ]
|
11
|
61 } else {
|
|
62 PRODF = inputdata[inputdata$VDJ.Frame != "In-frame with stop codon" & inputdata$VDJ.Frame != "Out-of-frame" & inputdata$CDR3.Found.How != "NOT_FOUND" , ]
|
20
|
63 UNPROD = inputdata[!(inputdata$VDJ.Frame != "In-frame with stop codon" & inputdata$VDJ.Frame != "Out-of-frame" & inputdata$CDR3.Found.How != "NOT_FOUND" ), ]
|
11
|
64 }
|
0
|
65 }
|
|
66
|
25
|
67 clonalityFrame = PRODF
|
|
68
|
11
|
69 #remove duplicates based on the clonaltype
|
|
70 if(clonaltype != "none"){
|
21
|
71 clonaltype = paste(clonaltype, ",Sample", sep="") #add sample column to clonaltype, unique within samples
|
17
|
72 PRODF$clonaltype = do.call(paste, c(PRODF[unlist(strsplit(clonaltype, ","))], sep = ":"))
|
11
|
73 PRODF = PRODF[!duplicated(PRODF$clonaltype), ]
|
25
|
74
|
|
75 #again for clonalityFrame but with sample+replicate
|
|
76 clonalityFrame$clonaltype = do.call(paste, c(clonalityFrame[unlist(strsplit(clonaltype, ","))], sep = ":"))
|
|
77 clonalityFrame$clonality_clonaltype = do.call(paste, c(clonalityFrame[unlist(strsplit(paste(clonaltype, ",Replicate", sep=""), ","))], sep = ":"))
|
|
78 clonalityFrame = clonalityFrame[!duplicated(clonalityFrame$clonality_clonaltype), ]
|
11
|
79 }
|
0
|
80
|
11
|
81 PRODF$freq = 1
|
0
|
82
|
11
|
83 if(any(grepl(pattern="_", x=PRODF$ID))){ #the frequency can be stored in the ID with the pattern ".*_freq_.*"
|
|
84 PRODF$freq = gsub("^[0-9]+_", "", PRODF$ID)
|
|
85 PRODF$freq = gsub("_.*", "", PRODF$freq)
|
|
86 PRODF$freq = as.numeric(PRODF$freq)
|
|
87 if(any(is.na(PRODF$freq))){ #if there was an "_" in the ID, but not the frequency, go back to frequency of 1 for every sequence
|
|
88 PRODF$freq = 1
|
|
89 }
|
|
90 }
|
10
|
91
|
|
92
|
|
93
|
11
|
94 #write the complete dataset that is left over, will be the input if 'none' for clonaltype and 'no' for filterproductive
|
|
95 write.table(PRODF, "allUnique.csv", sep=",",quote=F,row.names=F,col.names=T)
|
0
|
96
|
11
|
97 #write the samples to a file
|
|
98 sampleFile <- file("samples.txt")
|
|
99 un = unique(inputdata$Sample)
|
|
100 un = paste(un, sep="\n")
|
|
101 writeLines(un, sampleFile)
|
|
102 close(sampleFile)
|
|
103
|
15
|
104 # ---------------------- Counting the productive/unproductive and unique sequences ----------------------
|
|
105
|
|
106 inputdata.dt = data.table(inputdata) #for speed
|
|
107
|
|
108 if(clonaltype == "none"){
|
21
|
109 ct = c("clonaltype")
|
15
|
110 }
|
|
111
|
|
112 inputdata.dt$samples_replicates = paste(inputdata.dt$Sample, inputdata.dt$Replicate, sep="_")
|
|
113 samples_replicates = c(unique(inputdata.dt$samples_replicates), unique(as.character(inputdata.dt$Sample)))
|
|
114 frequency_table = data.frame(ID = samples_replicates[order(samples_replicates)])
|
|
115
|
|
116
|
|
117 sample_productive_count = inputdata.dt[, list(All=.N,
|
|
118 Productive = nrow(.SD[.SD$Functionality == "productive" | .SD$Functionality == "productive (see comment)",]),
|
|
119 perc_prod = 1,
|
|
120 Productive_unique = nrow(.SD[.SD$Functionality == "productive" | .SD$Functionality == "productive (see comment)",list(count=.N),by=ct]),
|
|
121 perc_prod_un = 1,
|
|
122 Unproductive= nrow(.SD[.SD$Functionality != "productive" & .SD$Functionality != "productive (see comment)",]),
|
|
123 perc_unprod = 1,
|
|
124 Unproductive_unique =nrow(.SD[.SD$Functionality != "productive" & .SD$Functionality != "productive (see comment)",list(count=.N),by=ct]),
|
|
125 perc_unprod_un = 1),
|
|
126 by=c("Sample")]
|
|
127
|
|
128 sample_productive_count$perc_prod = round(sample_productive_count$Productive / sample_productive_count$All * 100)
|
|
129 sample_productive_count$perc_prod_un = round(sample_productive_count$Productive_unique / sample_productive_count$All * 100)
|
|
130
|
|
131 sample_productive_count$perc_unprod = round(sample_productive_count$Unproductive / sample_productive_count$All * 100)
|
|
132 sample_productive_count$perc_unprod_un = round(sample_productive_count$Unproductive_unique / sample_productive_count$All * 100)
|
|
133
|
|
134
|
|
135 sample_replicate_productive_count = inputdata.dt[, list(All=.N,
|
|
136 Productive = nrow(.SD[.SD$Functionality == "productive" | .SD$Functionality == "productive (see comment)",]),
|
|
137 perc_prod = 1,
|
|
138 Productive_unique = nrow(.SD[.SD$Functionality == "productive" | .SD$Functionality == "productive (see comment)",list(count=.N),by=ct]),
|
|
139 perc_prod_un = 1,
|
|
140 Unproductive= nrow(.SD[.SD$Functionality != "productive" & .SD$Functionality != "productive (see comment)",]),
|
|
141 perc_unprod = 1,
|
|
142 Unproductive_unique =nrow(.SD[.SD$Functionality != "productive" & .SD$Functionality != "productive (see comment)",list(count=.N),by=ct]),
|
|
143 perc_unprod_un = 1),
|
|
144 by=c("samples_replicates")]
|
|
145
|
|
146 sample_replicate_productive_count$perc_prod = round(sample_replicate_productive_count$Productive / sample_replicate_productive_count$All * 100)
|
|
147 sample_replicate_productive_count$perc_prod_un = round(sample_replicate_productive_count$Productive_unique / sample_replicate_productive_count$All * 100)
|
|
148
|
|
149 sample_replicate_productive_count$perc_unprod = round(sample_replicate_productive_count$Unproductive / sample_replicate_productive_count$All * 100)
|
|
150 sample_replicate_productive_count$perc_unprod_un = round(sample_replicate_productive_count$Unproductive_unique / sample_replicate_productive_count$All * 100)
|
|
151
|
|
152 setnames(sample_replicate_productive_count, colnames(sample_productive_count))
|
|
153
|
|
154 counts = rbind(sample_replicate_productive_count, sample_productive_count)
|
|
155 counts = counts[order(counts$Sample),]
|
|
156
|
|
157 write.table(x=counts, file="productive_counting.txt", sep=",",quote=F,row.names=F,col.names=F)
|
|
158
|
11
|
159 # ---------------------- Frequency calculation for V, D and J ----------------------
|
|
160
|
|
161 PRODFV = data.frame(data.table(PRODF)[, list(Length=sum(freq)), by=c("Sample", "Top.V.Gene")])
|
0
|
162 Total = ddply(PRODFV, .(Sample), function(x) data.frame(Total = sum(x$Length)))
|
|
163 PRODFV = merge(PRODFV, Total, by.x='Sample', by.y='Sample', all.x=TRUE)
|
|
164 PRODFV = ddply(PRODFV, c("Sample", "Top.V.Gene"), summarise, relFreq= (Length*100 / Total))
|
|
165
|
11
|
166 PRODFD = data.frame(data.table(PRODF)[, list(Length=sum(freq)), by=c("Sample", "Top.D.Gene")])
|
0
|
167 Total = ddply(PRODFD, .(Sample), function(x) data.frame(Total = sum(x$Length)))
|
|
168 PRODFD = merge(PRODFD, Total, by.x='Sample', by.y='Sample', all.x=TRUE)
|
|
169 PRODFD = ddply(PRODFD, c("Sample", "Top.D.Gene"), summarise, relFreq= (Length*100 / Total))
|
|
170
|
11
|
171 PRODFJ = data.frame(data.table(PRODF)[, list(Length=sum(freq)), by=c("Sample", "Top.J.Gene")])
|
0
|
172 Total = ddply(PRODFJ, .(Sample), function(x) data.frame(Total = sum(x$Length)))
|
|
173 PRODFJ = merge(PRODFJ, Total, by.x='Sample', by.y='Sample', all.x=TRUE)
|
|
174 PRODFJ = ddply(PRODFJ, c("Sample", "Top.J.Gene"), summarise, relFreq= (Length*100 / Total))
|
|
175
|
23
|
176 # ---------------------- Setting up the gene names for the different species/loci ----------------------
|
11
|
177
|
23
|
178 Vchain = ""
|
|
179 Dchain = ""
|
|
180 Jchain = ""
|
10
|
181
|
23
|
182 if(species == "custom"){
|
|
183 print("Custom genes: ")
|
|
184 splt = unlist(strsplit(locus, ";"))
|
|
185 print(paste("V:", splt[1]))
|
|
186 print(paste("D:", splt[2]))
|
|
187 print(paste("J:", splt[3]))
|
|
188
|
|
189 Vchain = unlist(strsplit(splt[1], ","))
|
|
190 Vchain = data.frame(v.name = Vchain, chr.orderV = 1:length(Vchain))
|
|
191
|
|
192 Dchain = unlist(strsplit(splt[2], ","))
|
|
193 if(length(Dchain) > 0){
|
|
194 Dchain = data.frame(v.name = Dchain, chr.orderD = 1:length(Dchain))
|
|
195 } else {
|
|
196 Dchain = data.frame(v.name = character(0), chr.orderD = numeric(0))
|
|
197 }
|
|
198
|
|
199 Jchain = unlist(strsplit(splt[3], ","))
|
|
200 Jchain = data.frame(v.name = Jchain, chr.orderJ = 1:length(Jchain))
|
10
|
201
|
23
|
202 } else {
|
|
203 genes = read.table("genes.txt", sep="\t", header=TRUE, fill=T, comment.char="")
|
|
204
|
|
205 Vchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "V",c("IMGT.GENE.DB", "chr.order")]
|
|
206 colnames(Vchain) = c("v.name", "chr.orderV")
|
|
207 Dchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "D",c("IMGT.GENE.DB", "chr.order")]
|
|
208 colnames(Dchain) = c("v.name", "chr.orderD")
|
|
209 Jchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "J",c("IMGT.GENE.DB", "chr.order")]
|
|
210 colnames(Jchain) = c("v.name", "chr.orderJ")
|
|
211 }
|
10
|
212 useD = TRUE
|
22
|
213 if(nrow(Dchain) == 0){
|
11
|
214 useD = FALSE
|
|
215 cat("No D Genes in this species/locus")
|
10
|
216 }
|
|
217
|
23
|
218 print(paste("useD:", useD))
|
|
219
|
22
|
220 # ---------------------- merge with the frequency count ----------------------
|
11
|
221
|
0
|
222 PRODFV = merge(PRODFV, Vchain, by.x='Top.V.Gene', by.y='v.name', all.x=TRUE)
|
|
223
|
|
224 PRODFD = merge(PRODFD, Dchain, by.x='Top.D.Gene', by.y='v.name', all.x=TRUE)
|
|
225
|
|
226 PRODFJ = merge(PRODFJ, Jchain, by.x='Top.J.Gene', by.y='v.name', all.x=TRUE)
|
|
227
|
11
|
228 # ---------------------- Create the V, D and J frequency plots and write the data.frame for every plot to a file ----------------------
|
0
|
229
|
|
230 pV = ggplot(PRODFV)
|
|
231 pV = pV + geom_bar( aes( x=factor(reorder(Top.V.Gene, chr.orderV)), y=relFreq, fill=Sample), stat='identity', position="dodge") + theme(axis.text.x = element_text(angle = 90, hjust = 1))
|
|
232 pV = pV + xlab("Summary of V gene") + ylab("Frequency") + ggtitle("Relative frequency of V gene usage")
|
6
|
233 write.table(x=PRODFV, file="VFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
0
|
234
|
|
235 png("VPlot.png",width = 1280, height = 720)
|
|
236 pV
|
|
237 dev.off();
|
|
238
|
11
|
239 if(useD){
|
|
240 pD = ggplot(PRODFD)
|
|
241 pD = pD + geom_bar( aes( x=factor(reorder(Top.D.Gene, chr.orderD)), y=relFreq, fill=Sample), stat='identity', position="dodge") + theme(axis.text.x = element_text(angle = 90, hjust = 1))
|
|
242 pD = pD + xlab("Summary of D gene") + ylab("Frequency") + ggtitle("Relative frequency of D gene usage")
|
|
243 write.table(x=PRODFD, file="DFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
244
|
|
245 png("DPlot.png",width = 800, height = 600)
|
|
246 print(pD)
|
|
247 dev.off();
|
|
248 }
|
0
|
249
|
11
|
250 pJ = ggplot(PRODFJ)
|
|
251 pJ = pJ + geom_bar( aes( x=factor(reorder(Top.J.Gene, chr.orderJ)), y=relFreq, fill=Sample), stat='identity', position="dodge") + theme(axis.text.x = element_text(angle = 90, hjust = 1))
|
|
252 pJ = pJ + xlab("Summary of J gene") + ylab("Frequency") + ggtitle("Relative frequency of J gene usage")
|
|
253 write.table(x=PRODFJ, file="JFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
254
|
|
255 png("JPlot.png",width = 800, height = 600)
|
|
256 pJ
|
0
|
257 dev.off();
|
|
258
|
|
259 pJ = ggplot(PRODFJ)
|
|
260 pJ = pJ + geom_bar( aes( x=factor(reorder(Top.J.Gene, chr.orderJ)), y=relFreq, fill=Sample), stat='identity', position="dodge") + theme(axis.text.x = element_text(angle = 90, hjust = 1))
|
|
261 pJ = pJ + xlab("Summary of J gene") + ylab("Frequency") + ggtitle("Relative frequency of J gene usage")
|
6
|
262 write.table(x=PRODFJ, file="JFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
0
|
263
|
|
264 png("JPlot.png",width = 800, height = 600)
|
|
265 pJ
|
|
266 dev.off();
|
|
267
|
11
|
268 # ---------------------- Now the frequency plots of the V, D and J families ----------------------
|
|
269
|
6
|
270 VGenes = PRODF[,c("Sample", "Top.V.Gene")]
|
|
271 VGenes$Top.V.Gene = gsub("-.*", "", VGenes$Top.V.Gene)
|
|
272 VGenes = data.frame(data.table(VGenes)[, list(Count=.N), by=c("Sample", "Top.V.Gene")])
|
|
273 TotalPerSample = data.frame(data.table(VGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
274 VGenes = merge(VGenes, TotalPerSample, by="Sample")
|
|
275 VGenes$Frequency = VGenes$Count * 100 / VGenes$total
|
|
276 VPlot = ggplot(VGenes)
|
8
|
277 VPlot = VPlot + geom_bar(aes( x = Top.V.Gene, y = Frequency, fill = Sample), stat='identity', position='dodge' ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
11
|
278 ggtitle("Distribution of V gene families") +
|
|
279 ylab("Percentage of sequences")
|
6
|
280 png("VFPlot.png")
|
|
281 VPlot
|
|
282 dev.off();
|
|
283 write.table(x=VGenes, file="VFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
284
|
11
|
285 if(useD){
|
|
286 DGenes = PRODF[,c("Sample", "Top.D.Gene")]
|
|
287 DGenes$Top.D.Gene = gsub("-.*", "", DGenes$Top.D.Gene)
|
|
288 DGenes = data.frame(data.table(DGenes)[, list(Count=.N), by=c("Sample", "Top.D.Gene")])
|
|
289 TotalPerSample = data.frame(data.table(DGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
290 DGenes = merge(DGenes, TotalPerSample, by="Sample")
|
|
291 DGenes$Frequency = DGenes$Count * 100 / DGenes$total
|
|
292 DPlot = ggplot(DGenes)
|
|
293 DPlot = DPlot + geom_bar(aes( x = Top.D.Gene, y = Frequency, fill = Sample), stat='identity', position='dodge' ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
294 ggtitle("Distribution of D gene families") +
|
|
295 ylab("Percentage of sequences")
|
|
296 png("DFPlot.png")
|
|
297 print(DPlot)
|
|
298 dev.off();
|
|
299 write.table(x=DGenes, file="DFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
300 }
|
6
|
301
|
|
302 JGenes = PRODF[,c("Sample", "Top.J.Gene")]
|
|
303 JGenes$Top.J.Gene = gsub("-.*", "", JGenes$Top.J.Gene)
|
|
304 JGenes = data.frame(data.table(JGenes)[, list(Count=.N), by=c("Sample", "Top.J.Gene")])
|
|
305 TotalPerSample = data.frame(data.table(JGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
306 JGenes = merge(JGenes, TotalPerSample, by="Sample")
|
|
307 JGenes$Frequency = JGenes$Count * 100 / JGenes$total
|
|
308 JPlot = ggplot(JGenes)
|
8
|
309 JPlot = JPlot + geom_bar(aes( x = Top.J.Gene, y = Frequency, fill = Sample), stat='identity', position='dodge' ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
11
|
310 ggtitle("Distribution of J gene families") +
|
|
311 ylab("Percentage of sequences")
|
6
|
312 png("JFPlot.png")
|
|
313 JPlot
|
|
314 dev.off();
|
|
315 write.table(x=JGenes, file="JFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
316
|
11
|
317 # ---------------------- Plotting the cdr3 length ----------------------
|
|
318
|
8
|
319 CDR3Length = data.frame(data.table(PRODF)[, list(Count=.N), by=c("Sample", "CDR3.Length.DNA")])
|
|
320 TotalPerSample = data.frame(data.table(CDR3Length)[, list(total=sum(.SD$Count)), by=Sample])
|
|
321 CDR3Length = merge(CDR3Length, TotalPerSample, by="Sample")
|
|
322 CDR3Length$Frequency = CDR3Length$Count * 100 / CDR3Length$total
|
|
323 CDR3LengthPlot = ggplot(CDR3Length)
|
|
324 CDR3LengthPlot = CDR3LengthPlot + geom_bar(aes( x = CDR3.Length.DNA, y = Frequency, fill = Sample), stat='identity', position='dodge' ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
11
|
325 ggtitle("Length distribution of CDR3") +
|
|
326 xlab("CDR3 Length") +
|
|
327 ylab("Percentage of sequences")
|
8
|
328 png("CDR3LengthPlot.png",width = 1280, height = 720)
|
|
329 CDR3LengthPlot
|
|
330 dev.off()
|
|
331 write.table(x=CDR3Length, file="CDR3LengthPlot.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
332
|
11
|
333 # ---------------------- Plot the heatmaps ----------------------
|
|
334
|
|
335
|
|
336 #get the reverse order for the V and D genes
|
0
|
337 revVchain = Vchain
|
|
338 revDchain = Dchain
|
|
339 revVchain$chr.orderV = rev(revVchain$chr.orderV)
|
|
340 revDchain$chr.orderD = rev(revDchain$chr.orderD)
|
|
341
|
11
|
342 if(useD){
|
|
343 plotVD <- function(dat){
|
|
344 if(length(dat[,1]) == 0){
|
|
345 return()
|
|
346 }
|
|
347 img = ggplot() +
|
|
348 geom_tile(data=dat, aes(x=factor(reorder(Top.D.Gene, chr.orderD)), y=factor(reorder(Top.V.Gene, chr.orderV)), fill=relLength)) +
|
|
349 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
350 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
351 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
352 xlab("D genes") +
|
|
353 ylab("V Genes")
|
|
354
|
|
355 png(paste("HeatmapVD_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Dchain$v.name)), height=100+(15*length(Vchain$v.name)))
|
|
356 print(img)
|
|
357 dev.off()
|
|
358 write.table(x=acast(dat, Top.V.Gene~Top.D.Gene, value.var="Length"), file=paste("HeatmapVD_", unique(dat[3])[1,1], ".csv", sep=""), sep=",",quote=F,row.names=T,col.names=NA)
|
|
359 }
|
|
360
|
|
361 VandDCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.V.Gene", "Top.D.Gene", "Sample")])
|
|
362
|
|
363 VandDCount$l = log(VandDCount$Length)
|
|
364 maxVD = data.frame(data.table(VandDCount)[, list(max=max(l)), by=c("Sample")])
|
|
365 VandDCount = merge(VandDCount, maxVD, by.x="Sample", by.y="Sample", all.x=T)
|
|
366 VandDCount$relLength = VandDCount$l / VandDCount$max
|
|
367
|
|
368 cartegianProductVD = expand.grid(Top.V.Gene = Vchain$v.name, Top.D.Gene = Dchain$v.name, Sample = unique(inputdata$Sample))
|
|
369
|
|
370 completeVD = merge(VandDCount, cartegianProductVD, all.y=TRUE)
|
|
371 completeVD = merge(completeVD, revVchain, by.x="Top.V.Gene", by.y="v.name", all.x=TRUE)
|
|
372 completeVD = merge(completeVD, Dchain, by.x="Top.D.Gene", by.y="v.name", all.x=TRUE)
|
|
373 VDList = split(completeVD, f=completeVD[,"Sample"])
|
|
374
|
|
375 lapply(VDList, FUN=plotVD)
|
0
|
376 }
|
|
377
|
|
378 plotVJ <- function(dat){
|
11
|
379 if(length(dat[,1]) == 0){
|
|
380 return()
|
|
381 }
|
|
382 cat(paste(unique(dat[3])[1,1]))
|
|
383 img = ggplot() +
|
|
384 geom_tile(data=dat, aes(x=factor(reorder(Top.J.Gene, chr.orderJ)), y=factor(reorder(Top.V.Gene, chr.orderV)), fill=relLength)) +
|
|
385 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
386 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
387 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
388 xlab("J genes") +
|
|
389 ylab("V Genes")
|
|
390
|
|
391 png(paste("HeatmapVJ_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Jchain$v.name)), height=100+(15*length(Vchain$v.name)))
|
|
392 print(img)
|
|
393 dev.off()
|
|
394 write.table(x=acast(dat, Top.V.Gene~Top.J.Gene, value.var="Length"), file=paste("HeatmapVJ_", unique(dat[3])[1,1], ".csv", sep=""), sep=",",quote=F,row.names=T,col.names=NA)
|
0
|
395 }
|
|
396
|
|
397 VandJCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.V.Gene", "Top.J.Gene", "Sample")])
|
|
398
|
|
399 VandJCount$l = log(VandJCount$Length)
|
|
400 maxVJ = data.frame(data.table(VandJCount)[, list(max=max(l)), by=c("Sample")])
|
|
401 VandJCount = merge(VandJCount, maxVJ, by.x="Sample", by.y="Sample", all.x=T)
|
|
402 VandJCount$relLength = VandJCount$l / VandJCount$max
|
|
403
|
11
|
404 cartegianProductVJ = expand.grid(Top.V.Gene = Vchain$v.name, Top.J.Gene = Jchain$v.name, Sample = unique(inputdata$Sample))
|
0
|
405
|
|
406 completeVJ = merge(VandJCount, cartegianProductVJ, all.y=TRUE)
|
|
407 completeVJ = merge(completeVJ, revVchain, by.x="Top.V.Gene", by.y="v.name", all.x=TRUE)
|
|
408 completeVJ = merge(completeVJ, Jchain, by.x="Top.J.Gene", by.y="v.name", all.x=TRUE)
|
|
409 VJList = split(completeVJ, f=completeVJ[,"Sample"])
|
|
410 lapply(VJList, FUN=plotVJ)
|
|
411
|
11
|
412 if(useD){
|
|
413 plotDJ <- function(dat){
|
|
414 if(length(dat[,1]) == 0){
|
|
415 return()
|
|
416 }
|
|
417 img = ggplot() +
|
|
418 geom_tile(data=dat, aes(x=factor(reorder(Top.J.Gene, chr.orderJ)), y=factor(reorder(Top.D.Gene, chr.orderD)), fill=relLength)) +
|
|
419 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
420 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
421 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
422 xlab("J genes") +
|
|
423 ylab("D Genes")
|
|
424
|
|
425 png(paste("HeatmapDJ_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Jchain$v.name)), height=100+(15*length(Dchain$v.name)))
|
|
426 print(img)
|
|
427 dev.off()
|
|
428 write.table(x=acast(dat, Top.D.Gene~Top.J.Gene, value.var="Length"), file=paste("HeatmapDJ_", unique(dat[3])[1,1], ".csv", sep=""), sep=",",quote=F,row.names=T,col.names=NA)
|
|
429 }
|
|
430
|
|
431
|
|
432 DandJCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.D.Gene", "Top.J.Gene", "Sample")])
|
|
433
|
|
434 DandJCount$l = log(DandJCount$Length)
|
|
435 maxDJ = data.frame(data.table(DandJCount)[, list(max=max(l)), by=c("Sample")])
|
|
436 DandJCount = merge(DandJCount, maxDJ, by.x="Sample", by.y="Sample", all.x=T)
|
|
437 DandJCount$relLength = DandJCount$l / DandJCount$max
|
|
438
|
|
439 cartegianProductDJ = expand.grid(Top.D.Gene = Dchain$v.name, Top.J.Gene = Jchain$v.name, Sample = unique(inputdata$Sample))
|
|
440
|
|
441 completeDJ = merge(DandJCount, cartegianProductDJ, all.y=TRUE)
|
|
442 completeDJ = merge(completeDJ, revDchain, by.x="Top.D.Gene", by.y="v.name", all.x=TRUE)
|
|
443 completeDJ = merge(completeDJ, Jchain, by.x="Top.J.Gene", by.y="v.name", all.x=TRUE)
|
|
444 DJList = split(completeDJ, f=completeDJ[,"Sample"])
|
|
445 lapply(DJList, FUN=plotDJ)
|
0
|
446 }
|
|
447
|
10
|
448
|
11
|
449 # ---------------------- calculating the clonality score ----------------------
|
0
|
450
|
11
|
451 if("Replicate" %in% colnames(inputdata)) #can only calculate clonality score when replicate information is available
|
|
452 {
|
|
453 write.table(clonalityFrame, "clonalityComplete.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
454
|
|
455 ClonalitySampleReplicatePrint <- function(dat){
|
|
456 write.table(dat, paste("clonality_", unique(inputdata$Sample) , "_", unique(dat$Replicate), ".csv", sep=""), sep=",",quote=F,row.names=F,col.names=T)
|
|
457 }
|
|
458
|
|
459 clonalityFrameSplit = split(clonalityFrame, f=clonalityFrame[,c("Sample", "Replicate")])
|
|
460 #lapply(clonalityFrameSplit, FUN=ClonalitySampleReplicatePrint)
|
|
461
|
|
462 ClonalitySamplePrint <- function(dat){
|
|
463 write.table(dat, paste("clonality_", unique(inputdata$Sample) , ".csv", sep=""), sep=",",quote=F,row.names=F,col.names=T)
|
|
464 }
|
|
465
|
|
466 clonalityFrameSplit = split(clonalityFrame, f=clonalityFrame[,"Sample"])
|
|
467 #lapply(clonalityFrameSplit, FUN=ClonalitySamplePrint)
|
|
468
|
|
469 clonalFreq = data.frame(data.table(clonalityFrame)[, list(Type=.N), by=c("Sample", "clonaltype")])
|
|
470 clonalFreqCount = data.frame(data.table(clonalFreq)[, list(Count=.N), by=c("Sample", "Type")])
|
|
471 clonalFreqCount$realCount = clonalFreqCount$Type * clonalFreqCount$Count
|
|
472 clonalSum = data.frame(data.table(clonalFreqCount)[, list(Reads=sum(realCount)), by=c("Sample")])
|
|
473 clonalFreqCount = merge(clonalFreqCount, clonalSum, by.x="Sample", by.y="Sample")
|
|
474
|
|
475 ct = c('Type\tWeight\n2\t1\n3\t3\n4\t6\n5\t10\n6\t15')
|
|
476 tcct = textConnection(ct)
|
|
477 CT = read.table(tcct, sep="\t", header=TRUE)
|
|
478 close(tcct)
|
|
479 clonalFreqCount = merge(clonalFreqCount, CT, by.x="Type", by.y="Type", all.x=T)
|
|
480 clonalFreqCount$WeightedCount = clonalFreqCount$Count * clonalFreqCount$Weight
|
|
481
|
25
|
482 ReplicateReads = data.frame(data.table(clonalityFrame)[, list(Type=.N), by=c("Sample", "Replicate", "clonality_clonaltype")])
|
11
|
483 ReplicateReads = data.frame(data.table(ReplicateReads)[, list(Reads=.N), by=c("Sample", "Replicate")])
|
|
484 clonalFreqCount$Reads = as.numeric(clonalFreqCount$Reads)
|
|
485 ReplicateReads$squared = ReplicateReads$Reads * ReplicateReads$Reads
|
|
486
|
|
487 ReplicatePrint <- function(dat){
|
|
488 write.table(dat[-1], paste("ReplicateReads_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
489 }
|
|
490
|
|
491 ReplicateSplit = split(ReplicateReads, f=ReplicateReads[,"Sample"])
|
|
492 lapply(ReplicateSplit, FUN=ReplicatePrint)
|
|
493
|
21
|
494 ReplicateReads = data.frame(data.table(ReplicateReads)[, list(ReadsSum=sum(as.numeric(Reads)), ReadsSquaredSum=sum(as.numeric(squared))), by=c("Sample")])
|
11
|
495 clonalFreqCount = merge(clonalFreqCount, ReplicateReads, by.x="Sample", by.y="Sample", all.x=T)
|
|
496
|
|
497
|
|
498 ReplicateSumPrint <- function(dat){
|
|
499 write.table(dat[-1], paste("ReplicateSumReads_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
500 }
|
|
501
|
|
502 ReplicateSumSplit = split(ReplicateReads, f=ReplicateReads[,"Sample"])
|
|
503 lapply(ReplicateSumSplit, FUN=ReplicateSumPrint)
|
|
504
|
|
505 clonalFreqCountSum = data.frame(data.table(clonalFreqCount)[, list(Numerator=sum(WeightedCount, na.rm=T)), by=c("Sample")])
|
|
506 clonalFreqCount = merge(clonalFreqCount, clonalFreqCountSum, by.x="Sample", by.y="Sample", all.x=T)
|
|
507 clonalFreqCount$ReadsSum = as.numeric(clonalFreqCount$ReadsSum) #prevent integer overflow
|
|
508 clonalFreqCount$Denominator = (((clonalFreqCount$ReadsSum * clonalFreqCount$ReadsSum) - clonalFreqCount$ReadsSquaredSum) / 2)
|
|
509 clonalFreqCount$Result = (clonalFreqCount$Numerator + 1) / (clonalFreqCount$Denominator + 1)
|
|
510
|
|
511 ClonalityScorePrint <- function(dat){
|
|
512 write.table(dat$Result, paste("ClonalityScore_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
513 }
|
|
514
|
|
515 clonalityScore = clonalFreqCount[c("Sample", "Result")]
|
|
516 clonalityScore = unique(clonalityScore)
|
|
517
|
|
518 clonalityScoreSplit = split(clonalityScore, f=clonalityScore[,"Sample"])
|
|
519 lapply(clonalityScoreSplit, FUN=ClonalityScorePrint)
|
|
520
|
|
521 clonalityOverview = clonalFreqCount[c("Sample", "Type", "Count", "Weight", "WeightedCount")]
|
|
522
|
|
523
|
|
524
|
|
525 ClonalityOverviewPrint <- function(dat){
|
|
526 write.table(dat[-1], paste("ClonalityOverView_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
527 }
|
|
528
|
|
529 clonalityOverviewSplit = split(clonalityOverview, f=clonalityOverview$Sample)
|
|
530 lapply(clonalityOverviewSplit, FUN=ClonalityOverviewPrint)
|
0
|
531 }
|
1
|
532
|
11
|
533 imgtcolumns = c("X3V.REGION.trimmed.nt.nb","P3V.nt.nb", "N1.REGION.nt.nb", "P5D.nt.nb", "X5D.REGION.trimmed.nt.nb", "X3D.REGION.trimmed.nt.nb", "P3D.nt.nb", "N2.REGION.nt.nb", "P5J.nt.nb", "X5J.REGION.trimmed.nt.nb", "X3V.REGION.trimmed.nt.nb", "X5D.REGION.trimmed.nt.nb", "X3D.REGION.trimmed.nt.nb", "X5J.REGION.trimmed.nt.nb", "N1.REGION.nt.nb", "N2.REGION.nt.nb", "P3V.nt.nb", "P5D.nt.nb", "P3D.nt.nb", "P5J.nt.nb")
|
|
534 if(all(imgtcolumns %in% colnames(inputdata)))
|
1
|
535 {
|
19
|
536 newData = data.frame(data.table(PRODF)[,list(unique=.N,
|
21
|
537 VH.DEL=mean(X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
538 P1=mean(P3V.nt.nb, na.rm=T),
|
|
539 N1=mean(N1.REGION.nt.nb, na.rm=T),
|
|
540 P2=mean(P5D.nt.nb, na.rm=T),
|
|
541 DEL.DH=mean(X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
542 DH.DEL=mean(X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
543 P3=mean(P3D.nt.nb, na.rm=T),
|
|
544 N2=mean(N2.REGION.nt.nb, na.rm=T),
|
|
545 P4=mean(P5J.nt.nb, na.rm=T),
|
|
546 DEL.JH=mean(X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
547 Total.Del=( mean(X3V.REGION.trimmed.nt.nb, na.rm=T) +
|
|
548 mean(X5D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
549 mean(X3D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
550 mean(X5J.REGION.trimmed.nt.nb, na.rm=T)),
|
|
551
|
|
552 Total.N=( mean(N1.REGION.nt.nb, na.rm=T) +
|
|
553 mean(N2.REGION.nt.nb, na.rm=T)),
|
|
554
|
|
555 Total.P=( mean(P3V.nt.nb, na.rm=T) +
|
|
556 mean(P5D.nt.nb, na.rm=T) +
|
|
557 mean(P3D.nt.nb, na.rm=T) +
|
|
558 mean(P5J.nt.nb, na.rm=T))),
|
|
559 by=c("Sample")])
|
20
|
560 write.table(newData, "junctionAnalysisProd.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
561
|
21
|
562 newData = data.frame(data.table(UNPROD)[,list(unique=.N,
|
|
563 VH.DEL=mean(X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
564 P1=mean(P3V.nt.nb, na.rm=T),
|
|
565 N1=mean(N1.REGION.nt.nb, na.rm=T),
|
|
566 P2=mean(P5D.nt.nb, na.rm=T),
|
|
567 DEL.DH=mean(X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
568 DH.DEL=mean(X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
569 P3=mean(P3D.nt.nb, na.rm=T),
|
|
570 N2=mean(N2.REGION.nt.nb, na.rm=T),
|
|
571 P4=mean(P5J.nt.nb, na.rm=T),
|
|
572 DEL.JH=mean(X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
573 Total.Del=( mean(X3V.REGION.trimmed.nt.nb, na.rm=T) +
|
|
574 mean(X5D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
575 mean(X3D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
576 mean(X5J.REGION.trimmed.nt.nb, na.rm=T)),
|
|
577
|
|
578 Total.N=( mean(N1.REGION.nt.nb, na.rm=T) +
|
|
579 mean(N2.REGION.nt.nb, na.rm=T)),
|
|
580
|
|
581 Total.P=( mean(P3V.nt.nb, na.rm=T) +
|
|
582 mean(P5D.nt.nb, na.rm=T) +
|
|
583 mean(P3D.nt.nb, na.rm=T) +
|
|
584 mean(P5J.nt.nb, na.rm=T))),
|
|
585 by=c("Sample")])
|
20
|
586 write.table(newData, "junctionAnalysisUnProd.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
5
|
587 }
|
24
|
588
|
|
589 # ---------------------- AA composition in CDR3 ----------------------
|
|
590
|
|
591 AACDR3 = PRODF[,c("Sample", "CDR3.Seq")]
|
|
592
|
|
593 TotalPerSample = data.frame(data.table(AACDR3)[, list(total=sum(nchar(as.character(.SD$CDR3.Seq)))), by=Sample])
|
|
594
|
|
595 AAfreq = list()
|
|
596
|
|
597 for(i in 1:nrow(TotalPerSample)){
|
|
598 sample = TotalPerSample$Sample[i]
|
|
599 AAfreq[[i]] = data.frame(table(unlist(strsplit(as.character(AACDR3[AACDR3$Sample == sample,c("CDR3.Seq")]), ""))))
|
|
600 AAfreq[[i]]$Sample = sample
|
|
601 }
|
|
602
|
|
603 AAfreq = ldply(AAfreq, data.frame)
|
|
604 AAfreq = merge(AAfreq, TotalPerSample, by="Sample", all.x = T)
|
|
605 AAfreq$freq_perc = as.numeric(AAfreq$Freq / AAfreq$total * 100)
|
|
606
|
|
607
|
|
608 AAorder = read.table(sep="\t", header=TRUE, text="order.aa\tAA\n1\tR\n2\tK\n3\tN\n4\tD\n5\tQ\n6\tE\n7\tH\n8\tP\n9\tY\n10\tW\n11\tS\n12\tT\n13\tG\n14\tA\n15\tM\n16\tC\n17\tF\n18\tL\n19\tV\n20\tI")
|
|
609 AAfreq = merge(AAfreq, AAorder, by.x='Var1', by.y='AA', all.x=TRUE)
|
|
610
|
|
611 AAfreq = AAfreq[!is.na(AAfreq$order.aa),]
|
|
612
|
|
613 AAfreqplot = ggplot(AAfreq)
|
|
614 AAfreqplot = AAfreqplot + geom_bar(aes( x=factor(reorder(Var1, order.aa)), y = freq_perc, fill = Sample), stat='identity', position='dodge' )
|
|
615 AAfreqplot = AAfreqplot + annotate("rect", xmin = 0.5, xmax = 2.5, ymin = 0, ymax = Inf, fill = "red", alpha = 0.2)
|
|
616 AAfreqplot = AAfreqplot + annotate("rect", xmin = 3.5, xmax = 4.5, ymin = 0, ymax = Inf, fill = "blue", alpha = 0.2)
|
|
617 AAfreqplot = AAfreqplot + annotate("rect", xmin = 5.5, xmax = 6.5, ymin = 0, ymax = Inf, fill = "blue", alpha = 0.2)
|
|
618 AAfreqplot = AAfreqplot + annotate("rect", xmin = 6.5, xmax = 7.5, ymin = 0, ymax = Inf, fill = "red", alpha = 0.2)
|
|
619 AAfreqplot = AAfreqplot + ggtitle("Amino Acid Composition in the CDR3") + xlab("Amino Acid, from Hydrophilic (left) to Hydrophobic (right)") + ylab("Percentage")
|
|
620
|
|
621 png("AAComposition.png",width = 1280, height = 720)
|
|
622 AAfreqplot
|
|
623 dev.off()
|
|
624 write.table(AAfreq, "AAComposition.csv" , sep=",",quote=F,na="-",row.names=F,col.names=T)
|
|
625
|
|
626
|