5
|
1 # ---------------------- load/install packages ----------------------
|
|
2
|
|
3 if (!("gridExtra" %in% rownames(installed.packages()))) {
|
|
4 install.packages("gridExtra", repos="http://cran.xl-mirror.nl/")
|
|
5 }
|
|
6 library(gridExtra)
|
|
7 if (!("ggplot2" %in% rownames(installed.packages()))) {
|
|
8 install.packages("ggplot2", repos="http://cran.xl-mirror.nl/")
|
|
9 }
|
|
10 library(ggplot2)
|
|
11 if (!("plyr" %in% rownames(installed.packages()))) {
|
|
12 install.packages("plyr", repos="http://cran.xl-mirror.nl/")
|
|
13 }
|
|
14 library(plyr)
|
|
15
|
|
16 if (!("data.table" %in% rownames(installed.packages()))) {
|
|
17 install.packages("data.table", repos="http://cran.xl-mirror.nl/")
|
|
18 }
|
|
19 library(data.table)
|
|
20
|
|
21 if (!("reshape2" %in% rownames(installed.packages()))) {
|
|
22 install.packages("reshape2", repos="http://cran.xl-mirror.nl/")
|
|
23 }
|
|
24 library(reshape2)
|
|
25
|
|
26 if (!("lymphclon" %in% rownames(installed.packages()))) {
|
|
27 install.packages("lymphclon", repos="http://cran.xl-mirror.nl/")
|
|
28 }
|
|
29 library(lymphclon)
|
|
30
|
|
31 # ---------------------- parameters ----------------------
|
|
32
|
|
33 args <- commandArgs(trailingOnly = TRUE)
|
|
34
|
|
35 infile = args[1] #path to input file
|
|
36 outfile = args[2] #path to output file
|
|
37 outdir = args[3] #path to output folder (html/images/data)
|
|
38 clonaltype = args[4] #clonaltype definition, or 'none' for no unique filtering
|
|
39 ct = unlist(strsplit(clonaltype, ","))
|
|
40 species = args[5] #human or mouse
|
|
41 locus = args[6] # IGH, IGK, IGL, TRB, TRA, TRG or TRD
|
|
42 filterproductive = ifelse(args[7] == "yes", T, F) #should unproductive sequences be filtered out? (yes/no)
|
|
43 clonality_method = args[8]
|
|
44
|
|
45
|
|
46 # ---------------------- Data preperation ----------------------
|
|
47
|
|
48 print("Report Clonality - Data preperation")
|
|
49
|
13
|
50 inputdata = read.table(infile, sep="\t", header=TRUE, fill=T, comment.char="", stringsAsFactors=F)
|
5
|
51
|
|
52 print(paste("nrows: ", nrow(inputdata)))
|
|
53
|
|
54 setwd(outdir)
|
|
55
|
|
56 # remove weird rows
|
|
57 inputdata = inputdata[inputdata$Sample != "",]
|
|
58
|
|
59 print(paste("nrows: ", nrow(inputdata)))
|
|
60
|
|
61 #remove the allele from the V,D and J genes
|
|
62 inputdata$Top.V.Gene = gsub("[*]([0-9]+)", "", inputdata$Top.V.Gene)
|
|
63 inputdata$Top.D.Gene = gsub("[*]([0-9]+)", "", inputdata$Top.D.Gene)
|
|
64 inputdata$Top.J.Gene = gsub("[*]([0-9]+)", "", inputdata$Top.J.Gene)
|
|
65
|
|
66 print(paste("nrows: ", nrow(inputdata)))
|
|
67
|
|
68 #filter uniques
|
|
69 inputdata.removed = inputdata[NULL,]
|
|
70
|
|
71 print(paste("nrows: ", nrow(inputdata)))
|
|
72
|
|
73 inputdata$clonaltype = 1:nrow(inputdata)
|
|
74
|
|
75 #keep track of the count of sequences in samples or samples/replicates for the front page overview
|
|
76 input.sample.count = data.frame(data.table(inputdata)[, list(All=.N), by=c("Sample")])
|
|
77 input.rep.count = data.frame(data.table(inputdata)[, list(All=.N), by=c("Sample", "Replicate")])
|
|
78
|
|
79 PRODF = inputdata
|
|
80 UNPROD = inputdata
|
|
81 if(filterproductive){
|
|
82 if("Functionality" %in% colnames(inputdata)) { # "Functionality" is an IMGT column
|
|
83 #PRODF = inputdata[inputdata$Functionality == "productive" | inputdata$Functionality == "productive (see comment)", ]
|
|
84 PRODF = inputdata[inputdata$Functionality %in% c("productive (see comment)","productive"),]
|
|
85
|
|
86 PRODF.count = data.frame(data.table(PRODF)[, list(count=.N), by=c("Sample")])
|
|
87
|
|
88 UNPROD = inputdata[inputdata$Functionality %in% c("unproductive (see comment)","unproductive"), ]
|
|
89 } else {
|
|
90 PRODF = inputdata[inputdata$VDJ.Frame != "In-frame with stop codon" & inputdata$VDJ.Frame != "Out-of-frame" & inputdata$CDR3.Found.How != "NOT_FOUND" , ]
|
|
91 UNPROD = inputdata[!(inputdata$VDJ.Frame != "In-frame with stop codon" & inputdata$VDJ.Frame != "Out-of-frame" & inputdata$CDR3.Found.How != "NOT_FOUND" ), ]
|
|
92 }
|
|
93 }
|
|
94
|
13
|
95 for(i in 1:nrow(UNPROD)){
|
|
96 if(!is.numeric(UNPROD[i,"CDR3.Length"])){
|
|
97 UNPROD[i,"CDR3.Length"] = 0
|
|
98 }
|
|
99 }
|
|
100
|
5
|
101 prod.sample.count = data.frame(data.table(PRODF)[, list(Productive=.N), by=c("Sample")])
|
|
102 prod.rep.count = data.frame(data.table(PRODF)[, list(Productive=.N), by=c("Sample", "Replicate")])
|
|
103
|
|
104 unprod.sample.count = data.frame(data.table(UNPROD)[, list(Unproductive=.N), by=c("Sample")])
|
|
105 unprod.rep.count = data.frame(data.table(UNPROD)[, list(Unproductive=.N), by=c("Sample", "Replicate")])
|
|
106
|
|
107 clonalityFrame = PRODF
|
|
108
|
|
109 #remove duplicates based on the clonaltype
|
|
110 if(clonaltype != "none"){
|
|
111 clonaltype = paste(clonaltype, ",Sample", sep="") #add sample column to clonaltype, unique within samples
|
|
112 PRODF$clonaltype = do.call(paste, c(PRODF[unlist(strsplit(clonaltype, ","))], sep = ":"))
|
|
113 PRODF = PRODF[!duplicated(PRODF$clonaltype), ]
|
|
114
|
|
115 UNPROD$clonaltype = do.call(paste, c(UNPROD[unlist(strsplit(clonaltype, ","))], sep = ":"))
|
|
116 UNPROD = UNPROD[!duplicated(UNPROD$clonaltype), ]
|
|
117
|
|
118 #again for clonalityFrame but with sample+replicate
|
|
119 clonalityFrame$clonaltype = do.call(paste, c(clonalityFrame[unlist(strsplit(clonaltype, ","))], sep = ":"))
|
|
120 clonalityFrame$clonality_clonaltype = do.call(paste, c(clonalityFrame[unlist(strsplit(paste(clonaltype, ",Replicate", sep=""), ","))], sep = ":"))
|
|
121 clonalityFrame = clonalityFrame[!duplicated(clonalityFrame$clonality_clonaltype), ]
|
|
122 }
|
|
123
|
|
124 print("SAMPLE TABLE:")
|
|
125 print(table(PRODF$Sample))
|
|
126
|
|
127 prod.unique.sample.count = data.frame(data.table(PRODF)[, list(Productive_unique=.N), by=c("Sample")])
|
|
128 prod.unique.rep.count = data.frame(data.table(PRODF)[, list(Productive_unique=.N), by=c("Sample", "Replicate")])
|
|
129
|
|
130 unprod.unique.sample.count = data.frame(data.table(UNPROD)[, list(Unproductive_unique=.N), by=c("Sample")])
|
|
131 unprod.unique.rep.count = data.frame(data.table(UNPROD)[, list(Unproductive_unique=.N), by=c("Sample", "Replicate")])
|
|
132
|
|
133 PRODF$freq = 1
|
|
134
|
|
135 if(any(grepl(pattern="_", x=PRODF$ID))){ #the frequency can be stored in the ID with the pattern ".*_freq_.*"
|
|
136 PRODF$freq = gsub("^[0-9]+_", "", PRODF$ID)
|
|
137 PRODF$freq = gsub("_.*", "", PRODF$freq)
|
|
138 PRODF$freq = as.numeric(PRODF$freq)
|
|
139 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
|
|
140 PRODF$freq = 1
|
|
141 }
|
|
142 }
|
|
143
|
8
|
144 #make a names list with sample -> color
|
|
145 naive.colors = c('blue4', 'darkred', 'olivedrab3', 'red', 'gray74', 'darkviolet', 'lightblue1', 'gold', 'chartreuse2', 'pink', 'Paleturquoise3', 'Chocolate1', 'Yellow', 'Deeppink3', 'Mediumorchid1', 'Darkgreen', 'Blue', 'Gray36', 'Hotpink', 'Yellow4')
|
|
146 unique.samples = unique(PRODF$Sample)
|
|
147
|
|
148 if(length(unique.samples) <= length(naive.colors)){
|
|
149 sample.colors = naive.colors[1:length(unique.samples)]
|
|
150 } else {
|
|
151 sample.colors = rainbow(length(unique.samples))
|
|
152 }
|
|
153
|
|
154 names(sample.colors) = unique.samples
|
|
155
|
|
156 print("Sample.colors")
|
|
157 print(sample.colors)
|
5
|
158
|
|
159
|
|
160 #write the complete dataset that is left over, will be the input if 'none' for clonaltype and 'no' for filterproductive
|
|
161 write.table(PRODF, "allUnique.txt", sep="\t",quote=F,row.names=F,col.names=T)
|
|
162 write.table(PRODF, "allUnique.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
163 write.table(UNPROD, "allUnproductive.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
164
|
|
165 #write the samples to a file
|
|
166 sampleFile <- file("samples.txt")
|
|
167 un = unique(inputdata$Sample)
|
|
168 un = paste(un, sep="\n")
|
|
169 writeLines(un, sampleFile)
|
|
170 close(sampleFile)
|
|
171
|
|
172 # ---------------------- Counting the productive/unproductive and unique sequences ----------------------
|
|
173
|
|
174 print("Report Clonality - counting productive/unproductive/unique")
|
|
175
|
|
176 #create the table on the overview page with the productive/unique counts per sample/replicate
|
|
177 #first for sample
|
|
178 sample.count = merge(input.sample.count, prod.sample.count, by="Sample", all.x=T)
|
|
179 sample.count$perc_prod = round(sample.count$Productive / sample.count$All * 100)
|
|
180 sample.count = merge(sample.count, prod.unique.sample.count, by="Sample", all.x=T)
|
|
181 sample.count$perc_prod_un = round(sample.count$Productive_unique / sample.count$All * 100)
|
|
182
|
|
183 sample.count = merge(sample.count , unprod.sample.count, by="Sample", all.x=T)
|
|
184 sample.count$perc_unprod = round(sample.count$Unproductive / sample.count$All * 100)
|
|
185 sample.count = merge(sample.count, unprod.unique.sample.count, by="Sample", all.x=T)
|
|
186 sample.count$perc_unprod_un = round(sample.count$Unproductive_unique / sample.count$All * 100)
|
|
187
|
|
188 #then sample/replicate
|
|
189 rep.count = merge(input.rep.count, prod.rep.count, by=c("Sample", "Replicate"), all.x=T)
|
|
190 rep.count$perc_prod = round(rep.count$Productive / rep.count$All * 100)
|
|
191 rep.count = merge(rep.count, prod.unique.rep.count, by=c("Sample", "Replicate"), all.x=T)
|
|
192 rep.count$perc_prod_un = round(rep.count$Productive_unique / rep.count$All * 100)
|
|
193
|
|
194 rep.count = merge(rep.count, unprod.rep.count, by=c("Sample", "Replicate"), all.x=T)
|
|
195 rep.count$perc_unprod = round(rep.count$Unproductive / rep.count$All * 100)
|
|
196 rep.count = merge(rep.count, unprod.unique.rep.count, by=c("Sample", "Replicate"), all.x=T)
|
|
197 rep.count$perc_unprod_un = round(rep.count$Unproductive_unique / rep.count$All * 100)
|
|
198
|
|
199 rep.count$Sample = paste(rep.count$Sample, rep.count$Replicate, sep="_")
|
|
200 rep.count = rep.count[,names(rep.count) != "Replicate"]
|
|
201
|
|
202 count = rbind(sample.count, rep.count)
|
|
203
|
|
204
|
|
205
|
|
206 write.table(x=count, file="productive_counting.txt", sep=",",quote=F,row.names=F,col.names=F)
|
|
207
|
|
208 # ---------------------- V+J+CDR3 sequence count ----------------------
|
|
209
|
|
210 VJCDR3.count = data.frame(table(clonalityFrame$Top.V.Gene, clonalityFrame$Top.J.Gene, clonalityFrame$CDR3.Seq.DNA))
|
|
211 names(VJCDR3.count) = c("Top.V.Gene", "Top.J.Gene", "CDR3.Seq.DNA", "Count")
|
|
212
|
|
213 VJCDR3.count = VJCDR3.count[VJCDR3.count$Count > 0,]
|
|
214 VJCDR3.count = VJCDR3.count[order(-VJCDR3.count$Count),]
|
|
215
|
|
216 write.table(x=VJCDR3.count, file="VJCDR3_count.txt", sep="\t",quote=F,row.names=F,col.names=T)
|
|
217
|
|
218 # ---------------------- Frequency calculation for V, D and J ----------------------
|
|
219
|
|
220 print("Report Clonality - frequency calculation V, D and J")
|
|
221
|
|
222 PRODFV = data.frame(data.table(PRODF)[, list(Length=sum(freq)), by=c("Sample", "Top.V.Gene")])
|
|
223 Total = ddply(PRODFV, .(Sample), function(x) data.frame(Total = sum(x$Length)))
|
|
224 PRODFV = merge(PRODFV, Total, by.x='Sample', by.y='Sample', all.x=TRUE)
|
|
225 PRODFV = ddply(PRODFV, c("Sample", "Top.V.Gene"), summarise, relFreq= (Length*100 / Total))
|
|
226
|
|
227 PRODFD = data.frame(data.table(PRODF)[, list(Length=sum(freq)), by=c("Sample", "Top.D.Gene")])
|
|
228 Total = ddply(PRODFD, .(Sample), function(x) data.frame(Total = sum(x$Length)))
|
|
229 PRODFD = merge(PRODFD, Total, by.x='Sample', by.y='Sample', all.x=TRUE)
|
|
230 PRODFD = ddply(PRODFD, c("Sample", "Top.D.Gene"), summarise, relFreq= (Length*100 / Total))
|
|
231
|
|
232 PRODFJ = data.frame(data.table(PRODF)[, list(Length=sum(freq)), by=c("Sample", "Top.J.Gene")])
|
|
233 Total = ddply(PRODFJ, .(Sample), function(x) data.frame(Total = sum(x$Length)))
|
|
234 PRODFJ = merge(PRODFJ, Total, by.x='Sample', by.y='Sample', all.x=TRUE)
|
|
235 PRODFJ = ddply(PRODFJ, c("Sample", "Top.J.Gene"), summarise, relFreq= (Length*100 / Total))
|
|
236
|
|
237 # ---------------------- Setting up the gene names for the different species/loci ----------------------
|
|
238
|
|
239 print("Report Clonality - getting genes for species/loci")
|
|
240
|
|
241 Vchain = ""
|
|
242 Dchain = ""
|
|
243 Jchain = ""
|
|
244
|
|
245 if(species == "custom"){
|
|
246 print("Custom genes: ")
|
|
247 splt = unlist(strsplit(locus, ";"))
|
|
248 print(paste("V:", splt[1]))
|
|
249 print(paste("D:", splt[2]))
|
|
250 print(paste("J:", splt[3]))
|
|
251
|
|
252 Vchain = unlist(strsplit(splt[1], ","))
|
|
253 Vchain = data.frame(v.name = Vchain, chr.orderV = 1:length(Vchain))
|
|
254
|
|
255 Dchain = unlist(strsplit(splt[2], ","))
|
|
256 if(length(Dchain) > 0){
|
|
257 Dchain = data.frame(v.name = Dchain, chr.orderD = 1:length(Dchain))
|
|
258 } else {
|
|
259 Dchain = data.frame(v.name = character(0), chr.orderD = numeric(0))
|
|
260 }
|
|
261
|
|
262 Jchain = unlist(strsplit(splt[3], ","))
|
|
263 Jchain = data.frame(v.name = Jchain, chr.orderJ = 1:length(Jchain))
|
|
264
|
|
265 } else {
|
|
266 genes = read.table("genes.txt", sep="\t", header=TRUE, fill=T, comment.char="")
|
|
267
|
|
268 Vchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "V",c("IMGT.GENE.DB", "chr.order")]
|
|
269 colnames(Vchain) = c("v.name", "chr.orderV")
|
|
270 Dchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "D",c("IMGT.GENE.DB", "chr.order")]
|
|
271 colnames(Dchain) = c("v.name", "chr.orderD")
|
|
272 Jchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "J",c("IMGT.GENE.DB", "chr.order")]
|
|
273 colnames(Jchain) = c("v.name", "chr.orderJ")
|
|
274 }
|
|
275 useD = TRUE
|
|
276 if(nrow(Dchain) == 0){
|
|
277 useD = FALSE
|
|
278 cat("No D Genes in this species/locus")
|
|
279 }
|
|
280 print(paste(nrow(Vchain), "genes in V"))
|
|
281 print(paste(nrow(Dchain), "genes in D"))
|
|
282 print(paste(nrow(Jchain), "genes in J"))
|
|
283
|
|
284 # ---------------------- merge with the frequency count ----------------------
|
|
285
|
|
286 PRODFV = merge(PRODFV, Vchain, by.x='Top.V.Gene', by.y='v.name', all.x=TRUE)
|
|
287
|
|
288 PRODFD = merge(PRODFD, Dchain, by.x='Top.D.Gene', by.y='v.name', all.x=TRUE)
|
|
289
|
|
290 PRODFJ = merge(PRODFJ, Jchain, by.x='Top.J.Gene', by.y='v.name', all.x=TRUE)
|
|
291
|
|
292 # ---------------------- Create the V, D and J frequency plots and write the data.frame for every plot to a file ----------------------
|
|
293
|
|
294 print("Report Clonality - V, D and J frequency plots")
|
|
295
|
|
296 pV = ggplot(PRODFV)
|
|
297 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))
|
8
|
298 pV = pV + xlab("Summary of V gene") + ylab("Frequency") + ggtitle("Relative frequency of V gene usage") + scale_fill_manual(values=sample.colors)
|
|
299 pV = pV + theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
300 write.table(x=PRODFV, file="VFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
301
|
|
302 png("VPlot.png",width = 1280, height = 720)
|
|
303 pV
|
|
304 dev.off();
|
|
305
|
|
306 if(useD){
|
|
307 pD = ggplot(PRODFD)
|
|
308 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))
|
8
|
309 pD = pD + xlab("Summary of D gene") + ylab("Frequency") + ggtitle("Relative frequency of D gene usage") + scale_fill_manual(values=sample.colors)
|
|
310 pD = pD + theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
311 write.table(x=PRODFD, file="DFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
312
|
|
313 png("DPlot.png",width = 800, height = 600)
|
|
314 print(pD)
|
|
315 dev.off();
|
|
316 }
|
|
317
|
|
318 pJ = ggplot(PRODFJ)
|
|
319 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))
|
8
|
320 pJ = pJ + xlab("Summary of J gene") + ylab("Frequency") + ggtitle("Relative frequency of J gene usage") + scale_fill_manual(values=sample.colors)
|
|
321 pJ = pJ + theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
322 write.table(x=PRODFJ, file="JFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
323
|
|
324 png("JPlot.png",width = 800, height = 600)
|
|
325 pJ
|
|
326 dev.off();
|
|
327
|
|
328 # ---------------------- Now the frequency plots of the V, D and J families ----------------------
|
|
329
|
|
330 print("Report Clonality - V, D and J family plots")
|
|
331
|
|
332 VGenes = PRODF[,c("Sample", "Top.V.Gene")]
|
|
333 VGenes$Top.V.Gene = gsub("-.*", "", VGenes$Top.V.Gene)
|
|
334 VGenes = data.frame(data.table(VGenes)[, list(Count=.N), by=c("Sample", "Top.V.Gene")])
|
|
335 TotalPerSample = data.frame(data.table(VGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
336 VGenes = merge(VGenes, TotalPerSample, by="Sample")
|
|
337 VGenes$Frequency = VGenes$Count * 100 / VGenes$total
|
|
338 VPlot = ggplot(VGenes)
|
|
339 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)) +
|
|
340 ggtitle("Distribution of V gene families") +
|
8
|
341 ylab("Percentage of sequences") +
|
|
342 scale_fill_manual(values=sample.colors) +
|
|
343 theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
344 png("VFPlot.png")
|
|
345 VPlot
|
|
346 dev.off();
|
|
347 write.table(x=VGenes, file="VFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
348
|
|
349 if(useD){
|
|
350 DGenes = PRODF[,c("Sample", "Top.D.Gene")]
|
|
351 DGenes$Top.D.Gene = gsub("-.*", "", DGenes$Top.D.Gene)
|
|
352 DGenes = data.frame(data.table(DGenes)[, list(Count=.N), by=c("Sample", "Top.D.Gene")])
|
|
353 TotalPerSample = data.frame(data.table(DGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
354 DGenes = merge(DGenes, TotalPerSample, by="Sample")
|
|
355 DGenes$Frequency = DGenes$Count * 100 / DGenes$total
|
|
356 DPlot = ggplot(DGenes)
|
|
357 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)) +
|
|
358 ggtitle("Distribution of D gene families") +
|
8
|
359 ylab("Percentage of sequences") +
|
|
360 scale_fill_manual(values=sample.colors) +
|
|
361 theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
362 png("DFPlot.png")
|
|
363 print(DPlot)
|
|
364 dev.off();
|
|
365 write.table(x=DGenes, file="DFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
366 }
|
|
367
|
|
368 # ---------------------- Plotting the cdr3 length ----------------------
|
|
369
|
|
370 print("Report Clonality - CDR3 length plot")
|
|
371
|
9
|
372 CDR3Length = data.frame(data.table(PRODF)[, list(Count=.N), by=c("Sample", "CDR3.Length")])
|
5
|
373 TotalPerSample = data.frame(data.table(CDR3Length)[, list(total=sum(.SD$Count)), by=Sample])
|
|
374 CDR3Length = merge(CDR3Length, TotalPerSample, by="Sample")
|
|
375 CDR3Length$Frequency = CDR3Length$Count * 100 / CDR3Length$total
|
|
376 CDR3LengthPlot = ggplot(CDR3Length)
|
9
|
377 CDR3LengthPlot = CDR3LengthPlot + geom_bar(aes( x = CDR3.Length, y = Frequency, fill = Sample), stat='identity', position='dodge' ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
5
|
378 ggtitle("Length distribution of CDR3") +
|
|
379 xlab("CDR3 Length") +
|
8
|
380 ylab("Percentage of sequences") +
|
|
381 scale_fill_manual(values=sample.colors) +
|
|
382 theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
383 png("CDR3LengthPlot.png",width = 1280, height = 720)
|
|
384 CDR3LengthPlot
|
|
385 dev.off()
|
|
386 write.table(x=CDR3Length, file="CDR3LengthPlot.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
387
|
|
388 # ---------------------- Plot the heatmaps ----------------------
|
|
389
|
|
390 #get the reverse order for the V and D genes
|
|
391 revVchain = Vchain
|
|
392 revDchain = Dchain
|
|
393 revVchain$chr.orderV = rev(revVchain$chr.orderV)
|
|
394 revDchain$chr.orderD = rev(revDchain$chr.orderD)
|
|
395
|
|
396 if(useD){
|
|
397 print("Report Clonality - Heatmaps VD")
|
|
398 plotVD <- function(dat){
|
|
399 if(length(dat[,1]) == 0){
|
|
400 return()
|
|
401 }
|
|
402
|
|
403 img = ggplot() +
|
|
404 geom_tile(data=dat, aes(x=factor(reorder(Top.D.Gene, chr.orderD)), y=factor(reorder(Top.V.Gene, chr.orderV)), fill=relLength)) +
|
|
405 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
406 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
407 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
408 xlab("D genes") +
|
9
|
409 ylab("V Genes") +
|
14
|
410 theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), panel.grid.major = element_line(colour = "gainsboro"))
|
5
|
411
|
|
412 png(paste("HeatmapVD_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Dchain$v.name)), height=100+(15*length(Vchain$v.name)))
|
|
413 print(img)
|
|
414 dev.off()
|
|
415 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)
|
|
416 }
|
|
417
|
|
418 VandDCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.V.Gene", "Top.D.Gene", "Sample")])
|
|
419
|
|
420 VandDCount$l = log(VandDCount$Length)
|
|
421 maxVD = data.frame(data.table(VandDCount)[, list(max=max(l)), by=c("Sample")])
|
|
422 VandDCount = merge(VandDCount, maxVD, by.x="Sample", by.y="Sample", all.x=T)
|
|
423 VandDCount$relLength = VandDCount$l / VandDCount$max
|
6
|
424 check = is.nan(VandDCount$relLength)
|
|
425 if(any(check)){
|
|
426 VandDCount[check,"relLength"] = 0
|
|
427 }
|
5
|
428
|
|
429 cartegianProductVD = expand.grid(Top.V.Gene = Vchain$v.name, Top.D.Gene = Dchain$v.name)
|
|
430
|
|
431 completeVD = merge(VandDCount, cartegianProductVD, by.x=c("Top.V.Gene", "Top.D.Gene"), by.y=c("Top.V.Gene", "Top.D.Gene"), all=TRUE)
|
|
432
|
|
433 completeVD = merge(completeVD, revVchain, by.x="Top.V.Gene", by.y="v.name", all.x=TRUE)
|
|
434
|
|
435 completeVD = merge(completeVD, Dchain, by.x="Top.D.Gene", by.y="v.name", all.x=TRUE)
|
|
436
|
|
437 fltr = is.nan(completeVD$relLength)
|
|
438 if(all(fltr)){
|
|
439 completeVD[fltr,"relLength"] = 0
|
|
440 }
|
|
441
|
|
442 VDList = split(completeVD, f=completeVD[,"Sample"])
|
|
443 lapply(VDList, FUN=plotVD)
|
|
444 }
|
|
445
|
|
446 print("Report Clonality - Heatmaps VJ")
|
|
447
|
|
448 plotVJ <- function(dat){
|
|
449 if(length(dat[,1]) == 0){
|
|
450 return()
|
|
451 }
|
|
452 cat(paste(unique(dat[3])[1,1]))
|
|
453 img = ggplot() +
|
|
454 geom_tile(data=dat, aes(x=factor(reorder(Top.J.Gene, chr.orderJ)), y=factor(reorder(Top.V.Gene, chr.orderV)), fill=relLength)) +
|
|
455 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
456 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
457 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
458 xlab("J genes") +
|
9
|
459 ylab("V Genes") +
|
14
|
460 theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), panel.grid.major = element_line(colour = "gainsboro"))
|
5
|
461
|
|
462 png(paste("HeatmapVJ_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Jchain$v.name)), height=100+(15*length(Vchain$v.name)))
|
|
463 print(img)
|
|
464 dev.off()
|
|
465 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)
|
|
466 }
|
|
467
|
|
468 VandJCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.V.Gene", "Top.J.Gene", "Sample")])
|
|
469
|
|
470 VandJCount$l = log(VandJCount$Length)
|
|
471 maxVJ = data.frame(data.table(VandJCount)[, list(max=max(l)), by=c("Sample")])
|
|
472 VandJCount = merge(VandJCount, maxVJ, by.x="Sample", by.y="Sample", all.x=T)
|
|
473 VandJCount$relLength = VandJCount$l / VandJCount$max
|
|
474
|
6
|
475 check = is.nan(VandJCount$relLength)
|
|
476 if(any(check)){
|
|
477 VandJCount[check,"relLength"] = 0
|
|
478 }
|
|
479
|
5
|
480 cartegianProductVJ = expand.grid(Top.V.Gene = Vchain$v.name, Top.J.Gene = Jchain$v.name)
|
|
481
|
|
482 completeVJ = merge(VandJCount, cartegianProductVJ, all.y=TRUE)
|
|
483 completeVJ = merge(completeVJ, revVchain, by.x="Top.V.Gene", by.y="v.name", all.x=TRUE)
|
|
484 completeVJ = merge(completeVJ, Jchain, by.x="Top.J.Gene", by.y="v.name", all.x=TRUE)
|
|
485
|
|
486 fltr = is.nan(completeVJ$relLength)
|
|
487 if(any(fltr)){
|
|
488 completeVJ[fltr,"relLength"] = 1
|
|
489 }
|
|
490
|
|
491 VJList = split(completeVJ, f=completeVJ[,"Sample"])
|
|
492 lapply(VJList, FUN=plotVJ)
|
|
493
|
|
494
|
|
495
|
|
496 if(useD){
|
|
497 print("Report Clonality - Heatmaps DJ")
|
|
498 plotDJ <- function(dat){
|
|
499 if(length(dat[,1]) == 0){
|
|
500 return()
|
|
501 }
|
|
502 img = ggplot() +
|
|
503 geom_tile(data=dat, aes(x=factor(reorder(Top.J.Gene, chr.orderJ)), y=factor(reorder(Top.D.Gene, chr.orderD)), fill=relLength)) +
|
|
504 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
505 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
506 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
507 xlab("J genes") +
|
9
|
508 ylab("D Genes") +
|
14
|
509 theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), panel.grid.major = element_line(colour = "gainsboro"))
|
5
|
510
|
|
511 png(paste("HeatmapDJ_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Jchain$v.name)), height=100+(15*length(Dchain$v.name)))
|
|
512 print(img)
|
|
513 dev.off()
|
|
514 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)
|
|
515 }
|
|
516
|
|
517
|
|
518 DandJCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.D.Gene", "Top.J.Gene", "Sample")])
|
|
519
|
|
520 DandJCount$l = log(DandJCount$Length)
|
|
521 maxDJ = data.frame(data.table(DandJCount)[, list(max=max(l)), by=c("Sample")])
|
|
522 DandJCount = merge(DandJCount, maxDJ, by.x="Sample", by.y="Sample", all.x=T)
|
|
523 DandJCount$relLength = DandJCount$l / DandJCount$max
|
|
524
|
6
|
525 check = is.nan(DandJCount$relLength)
|
|
526 if(any(check)){
|
|
527 DandJCount[check,"relLength"] = 0
|
|
528 }
|
|
529
|
5
|
530 cartegianProductDJ = expand.grid(Top.D.Gene = Dchain$v.name, Top.J.Gene = Jchain$v.name)
|
|
531
|
|
532 completeDJ = merge(DandJCount, cartegianProductDJ, all.y=TRUE)
|
|
533 completeDJ = merge(completeDJ, revDchain, by.x="Top.D.Gene", by.y="v.name", all.x=TRUE)
|
|
534 completeDJ = merge(completeDJ, Jchain, by.x="Top.J.Gene", by.y="v.name", all.x=TRUE)
|
|
535
|
|
536 fltr = is.nan(completeDJ$relLength)
|
|
537 if(any(fltr)){
|
|
538 completeDJ[fltr, "relLength"] = 1
|
|
539 }
|
|
540
|
|
541 DJList = split(completeDJ, f=completeDJ[,"Sample"])
|
|
542 lapply(DJList, FUN=plotDJ)
|
|
543 }
|
|
544
|
|
545
|
|
546 # ---------------------- output tables for the circos plots ----------------------
|
|
547
|
|
548 print("Report Clonality - Circos data")
|
|
549
|
|
550 for(smpl in unique(PRODF$Sample)){
|
|
551 PRODF.sample = PRODF[PRODF$Sample == smpl,]
|
|
552
|
|
553 fltr = PRODF.sample$Top.V.Gene == ""
|
|
554 if(any(fltr, na.rm=T)){
|
|
555 PRODF.sample[fltr, "Top.V.Gene"] = "NA"
|
|
556 }
|
|
557
|
|
558 fltr = PRODF.sample$Top.D.Gene == ""
|
|
559 if(any(fltr, na.rm=T)){
|
|
560 PRODF.sample[fltr, "Top.D.Gene"] = "NA"
|
|
561 }
|
|
562
|
|
563 fltr = PRODF.sample$Top.J.Gene == ""
|
|
564 if(any(fltr, na.rm=T)){
|
|
565 PRODF.sample[fltr, "Top.J.Gene"] = "NA"
|
|
566 }
|
|
567
|
|
568 v.d = table(PRODF.sample$Top.V.Gene, PRODF.sample$Top.D.Gene)
|
|
569 v.j = table(PRODF.sample$Top.V.Gene, PRODF.sample$Top.J.Gene)
|
|
570 d.j = table(PRODF.sample$Top.D.Gene, PRODF.sample$Top.J.Gene)
|
|
571
|
|
572 write.table(v.d, file=paste(smpl, "_VD_circos.txt", sep=""), sep="\t", quote=F, row.names=T, col.names=NA)
|
|
573 write.table(v.j, file=paste(smpl, "_VJ_circos.txt", sep=""), sep="\t", quote=F, row.names=T, col.names=NA)
|
|
574 write.table(d.j, file=paste(smpl, "_DJ_circos.txt", sep=""), sep="\t", quote=F, row.names=T, col.names=NA)
|
|
575 }
|
|
576
|
|
577 # ---------------------- calculating the clonality score ----------------------
|
|
578
|
|
579 if("Replicate" %in% colnames(inputdata)) #can only calculate clonality score when replicate information is available
|
|
580 {
|
|
581 print("Report Clonality - Clonality")
|
|
582 write.table(clonalityFrame, "clonalityComplete.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
583 if(clonality_method == "boyd"){
|
|
584 samples = split(clonalityFrame, clonalityFrame$Sample, drop=T)
|
|
585
|
|
586 for (sample in samples){
|
|
587 res = data.frame(paste=character(0))
|
|
588 sample_id = unique(sample$Sample)[[1]]
|
|
589 for(replicate in unique(sample$Replicate)){
|
|
590 tmp = sample[sample$Replicate == replicate,]
|
|
591 clone_table = data.frame(table(tmp$clonaltype))
|
|
592 clone_col_name = paste("V", replicate, sep="")
|
|
593 colnames(clone_table) = c("paste", clone_col_name)
|
|
594 res = merge(res, clone_table, by="paste", all=T)
|
|
595 }
|
|
596
|
|
597 res[is.na(res)] = 0
|
|
598 infer.result = infer.clonality(as.matrix(res[,2:ncol(res)]))
|
|
599
|
13
|
600 #print(infer.result)
|
5
|
601
|
|
602 write.table(data.table(infer.result[[12]]), file=paste("lymphclon_clonality_", sample_id, ".csv", sep=""), sep=",",quote=F,row.names=F,col.names=F)
|
|
603
|
|
604 res$type = rowSums(res[,2:ncol(res)])
|
|
605
|
|
606 coincidence.table = data.frame(table(res$type))
|
|
607 colnames(coincidence.table) = c("Coincidence Type", "Raw Coincidence Freq")
|
|
608 write.table(coincidence.table, file=paste("lymphclon_coincidences_", sample_id, ".csv", sep=""), sep=",",quote=F,row.names=F,col.names=T)
|
|
609 }
|
|
610 } else {
|
|
611 clonalFreq = data.frame(data.table(clonalityFrame)[, list(Type=.N), by=c("Sample", "clonaltype")])
|
|
612
|
|
613 #write files for every coincidence group of >1
|
|
614 samples = unique(clonalFreq$Sample)
|
|
615 for(sample in samples){
|
|
616 clonalFreqSample = clonalFreq[clonalFreq$Sample == sample,]
|
|
617 if(max(clonalFreqSample$Type) > 1){
|
|
618 for(i in 2:max(clonalFreqSample$Type)){
|
|
619 clonalFreqSampleType = clonalFreqSample[clonalFreqSample$Type == i,]
|
|
620 clonalityFrame.sub = clonalityFrame[clonalityFrame$clonaltype %in% clonalFreqSampleType$clonaltype,]
|
|
621 clonalityFrame.sub = clonalityFrame.sub[order(clonalityFrame.sub$clonaltype),]
|
|
622 write.table(clonalityFrame.sub, file=paste("coincidences_", sample, "_", i, ".txt", sep=""), sep="\t",quote=F,row.names=F,col.names=T)
|
|
623 }
|
|
624 }
|
|
625 }
|
|
626
|
|
627 clonalFreqCount = data.frame(data.table(clonalFreq)[, list(Count=.N), by=c("Sample", "Type")])
|
|
628 clonalFreqCount$realCount = clonalFreqCount$Type * clonalFreqCount$Count
|
|
629 clonalSum = data.frame(data.table(clonalFreqCount)[, list(Reads=sum(realCount)), by=c("Sample")])
|
|
630 clonalFreqCount = merge(clonalFreqCount, clonalSum, by.x="Sample", by.y="Sample")
|
|
631
|
|
632 ct = c('Type\tWeight\n2\t1\n3\t3\n4\t6\n5\t10\n6\t15')
|
|
633 tcct = textConnection(ct)
|
|
634 CT = read.table(tcct, sep="\t", header=TRUE)
|
|
635 close(tcct)
|
|
636 clonalFreqCount = merge(clonalFreqCount, CT, by.x="Type", by.y="Type", all.x=T)
|
|
637 clonalFreqCount$WeightedCount = clonalFreqCount$Count * clonalFreqCount$Weight
|
|
638
|
|
639 ReplicateReads = data.frame(data.table(clonalityFrame)[, list(Type=.N), by=c("Sample", "Replicate", "clonaltype")])
|
|
640 ReplicateReads = data.frame(data.table(ReplicateReads)[, list(Reads=.N), by=c("Sample", "Replicate")])
|
|
641 clonalFreqCount$Reads = as.numeric(clonalFreqCount$Reads)
|
|
642 ReplicateReads$Reads = as.numeric(ReplicateReads$Reads)
|
|
643 ReplicateReads$squared = as.numeric(ReplicateReads$Reads * ReplicateReads$Reads)
|
|
644
|
|
645 ReplicatePrint <- function(dat){
|
|
646 write.table(dat[-1], paste("ReplicateReads_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
647 }
|
|
648
|
|
649 ReplicateSplit = split(ReplicateReads, f=ReplicateReads[,"Sample"])
|
|
650 lapply(ReplicateSplit, FUN=ReplicatePrint)
|
|
651
|
|
652 ReplicateReads = data.frame(data.table(ReplicateReads)[, list(ReadsSum=sum(as.numeric(Reads)), ReadsSquaredSum=sum(as.numeric(squared))), by=c("Sample")])
|
|
653 clonalFreqCount = merge(clonalFreqCount, ReplicateReads, by.x="Sample", by.y="Sample", all.x=T)
|
|
654
|
|
655 ReplicateSumPrint <- function(dat){
|
|
656 write.table(dat[-1], paste("ReplicateSumReads_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
657 }
|
|
658
|
|
659 ReplicateSumSplit = split(ReplicateReads, f=ReplicateReads[,"Sample"])
|
|
660 lapply(ReplicateSumSplit, FUN=ReplicateSumPrint)
|
|
661
|
|
662 clonalFreqCountSum = data.frame(data.table(clonalFreqCount)[, list(Numerator=sum(WeightedCount, na.rm=T)), by=c("Sample")])
|
|
663 clonalFreqCount = merge(clonalFreqCount, clonalFreqCountSum, by.x="Sample", by.y="Sample", all.x=T)
|
|
664 clonalFreqCount$ReadsSum = as.numeric(clonalFreqCount$ReadsSum) #prevent integer overflow
|
|
665 clonalFreqCount$Denominator = (((clonalFreqCount$ReadsSum * clonalFreqCount$ReadsSum) - clonalFreqCount$ReadsSquaredSum) / 2)
|
|
666 clonalFreqCount$Result = (clonalFreqCount$Numerator + 1) / (clonalFreqCount$Denominator + 1)
|
|
667
|
|
668 ClonalityScorePrint <- function(dat){
|
|
669 write.table(dat$Result, paste("ClonalityScore_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
670 }
|
|
671
|
|
672 clonalityScore = clonalFreqCount[c("Sample", "Result")]
|
|
673 clonalityScore = unique(clonalityScore)
|
|
674
|
|
675 clonalityScoreSplit = split(clonalityScore, f=clonalityScore[,"Sample"])
|
|
676 lapply(clonalityScoreSplit, FUN=ClonalityScorePrint)
|
|
677
|
|
678 clonalityOverview = clonalFreqCount[c("Sample", "Type", "Count", "Weight", "WeightedCount")]
|
|
679
|
|
680
|
|
681
|
|
682 ClonalityOverviewPrint <- function(dat){
|
|
683 dat = dat[order(dat[,2]),]
|
|
684 write.table(dat[-1], paste("ClonalityOverView_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
685 }
|
|
686
|
|
687 clonalityOverviewSplit = split(clonalityOverview, f=clonalityOverview$Sample)
|
|
688 lapply(clonalityOverviewSplit, FUN=ClonalityOverviewPrint)
|
|
689 }
|
|
690 }
|
|
691
|
|
692 bak = PRODF
|
|
693
|
|
694 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")
|
|
695 if(all(imgtcolumns %in% colnames(inputdata)))
|
|
696 {
|
|
697 print("found IMGT columns, running junction analysis")
|
|
698
|
|
699 if(locus %in% c("IGK","IGL", "TRA", "TRG")){
|
|
700 print("VJ recombination, no filtering on absent D")
|
|
701 } else {
|
|
702 print("VDJ recombination, using N column for junction analysis")
|
|
703 fltr = nchar(PRODF$Top.D.Gene) < 4
|
|
704 print(paste("Removing", sum(fltr), "sequences without a identified D"))
|
|
705 PRODF = PRODF[!fltr,]
|
|
706 }
|
|
707
|
|
708
|
|
709 #ensure certain columns are in the data (files generated with older versions of IMGT Loader)
|
|
710 col.checks = c("N.REGION.nt.nb", "N1.REGION.nt.nb", "N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb")
|
|
711 for(col.check in col.checks){
|
|
712 if(!(col.check %in% names(PRODF))){
|
|
713 print(paste(col.check, "not found adding new column"))
|
|
714 if(nrow(PRODF) > 0){ #because R is anoying...
|
|
715 PRODF[,col.check] = 0
|
|
716 } else {
|
|
717 PRODF = cbind(PRODF, data.frame(N3.REGION.nt.nb=numeric(0), N4.REGION.nt.nb=numeric(0)))
|
|
718 }
|
|
719 if(nrow(UNPROD) > 0){
|
|
720 UNPROD[,col.check] = 0
|
|
721 } else {
|
|
722 UNPROD = cbind(UNPROD, data.frame(N3.REGION.nt.nb=numeric(0), N4.REGION.nt.nb=numeric(0)))
|
|
723 }
|
|
724 }
|
|
725 }
|
|
726
|
|
727 num_median = function(x, na.rm=T) { as.numeric(median(x, na.rm=na.rm)) }
|
|
728
|
|
729 newData = data.frame(data.table(PRODF)[,list(unique=.N,
|
|
730 VH.DEL=mean(.SD$X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
731 P1=mean(.SD$P3V.nt.nb, na.rm=T),
|
|
732 N1=mean(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb"), with=F], na.rm=T)),
|
|
733 P2=mean(.SD$P5D.nt.nb, na.rm=T),
|
|
734 DEL.DH=mean(.SD$X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
735 DH.DEL=mean(.SD$X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
736 P3=mean(.SD$P3D.nt.nb, na.rm=T),
|
|
737 N2=mean(rowSums(.SD[,c("N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
738 P4=mean(.SD$P5J.nt.nb, na.rm=T),
|
|
739 DEL.JH=mean(.SD$X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
740 Total.Del=mean(rowSums(.SD[,c("X3V.REGION.trimmed.nt.nb", "X5D.REGION.trimmed.nt.nb", "X3D.REGION.trimmed.nt.nb", "X5J.REGION.trimmed.nt.nb"), with=F], na.rm=T)),
|
|
741 Total.N=mean(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb", "N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
742 Total.P=mean(rowSums(.SD[,c("P3V.nt.nb", "P5D.nt.nb", "P3D.nt.nb", "P5J.nt.nb"), with=F], na.rm=T)),
|
13
|
743 Median.CDR3.l=as.double(median(.SD$CDR3.Length))),
|
5
|
744 by=c("Sample")])
|
|
745 newData[,sapply(newData, is.numeric)] = round(newData[,sapply(newData, is.numeric)],1)
|
|
746 write.table(newData, "junctionAnalysisProd_mean.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
747
|
|
748 newData = data.frame(data.table(PRODF)[,list(unique=.N,
|
|
749 VH.DEL=num_median(.SD$X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
750 P1=num_median(.SD$P3V.nt.nb, na.rm=T),
|
|
751 N1=num_median(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb"), with=F], na.rm=T)),
|
|
752 P2=num_median(.SD$P5D.nt.nb, na.rm=T),
|
|
753 DEL.DH=num_median(.SD$X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
754 DH.DEL=num_median(.SD$X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
755 P3=num_median(.SD$P3D.nt.nb, na.rm=T),
|
|
756 N2=num_median(rowSums(.SD[,c("N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
757 P4=num_median(.SD$P5J.nt.nb, na.rm=T),
|
|
758 DEL.JH=num_median(.SD$X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
759 Total.Del=num_median(rowSums(.SD[,c("X3V.REGION.trimmed.nt.nb", "X5D.REGION.trimmed.nt.nb", "X3D.REGION.trimmed.nt.nb", "X5J.REGION.trimmed.nt.nb"), with=F], na.rm=T)),
|
|
760 Total.N=num_median(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb", "N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
761 Total.P=num_median(rowSums(.SD[,c("P3V.nt.nb", "P5D.nt.nb", "P3D.nt.nb", "P5J.nt.nb"), with=F], na.rm=T)),
|
13
|
762 Median.CDR3.l=as.double(median(.SD$CDR3.Length))),
|
5
|
763 by=c("Sample")])
|
|
764 newData[,sapply(newData, is.numeric)] = round(newData[,sapply(newData, is.numeric)],1)
|
|
765 write.table(newData, "junctionAnalysisProd_median.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
766
|
|
767 newData = data.frame(data.table(UNPROD)[,list(unique=.N,
|
|
768 VH.DEL=mean(.SD$X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
769 P1=mean(.SD$P3V.nt.nb, na.rm=T),
|
|
770 N1=mean(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb"), with=F], na.rm=T)),
|
|
771 P2=mean(.SD$P5D.nt.nb, na.rm=T),
|
|
772 DEL.DH=mean(.SD$X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
773 DH.DEL=mean(.SD$X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
774 P3=mean(.SD$P3D.nt.nb, na.rm=T),
|
|
775 N2=mean(rowSums(.SD[,c("N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
776 P4=mean(.SD$P5J.nt.nb, na.rm=T),
|
|
777 DEL.JH=mean(.SD$X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
778 Total.Del=mean(rowSums(.SD[,c("X3V.REGION.trimmed.nt.nb", "X5D.REGION.trimmed.nt.nb", "X3D.REGION.trimmed.nt.nb", "X5J.REGION.trimmed.nt.nb"), with=F], na.rm=T)),
|
|
779 Total.N=mean(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb", "N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
780 Total.P=mean(rowSums(.SD[,c("P3V.nt.nb", "P5D.nt.nb", "P3D.nt.nb", "P5J.nt.nb"), with=F], na.rm=T)),
|
13
|
781 Median.CDR3.l=as.double(median(.SD$CDR3.Length))),
|
5
|
782 by=c("Sample")])
|
|
783 newData[,sapply(newData, is.numeric)] = round(newData[,sapply(newData, is.numeric)],1)
|
|
784 write.table(newData, "junctionAnalysisUnProd_mean.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
785
|
|
786 newData = data.frame(data.table(UNPROD)[,list(unique=.N,
|
|
787 VH.DEL=num_median(.SD$X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
788 P1=num_median(.SD$P3V.nt.nb, na.rm=T),
|
|
789 N1=num_median(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb"), with=F], na.rm=T)),
|
|
790 P2=num_median(.SD$P5D.nt.nb, na.rm=T),
|
|
791 DEL.DH=num_median(.SD$X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
792 DH.DEL=num_median(.SD$X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
793 P3=num_median(.SD$P3D.nt.nb, na.rm=T),
|
|
794 N2=num_median(rowSums(.SD[,c("N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
795 P4=num_median(.SD$P5J.nt.nb, na.rm=T),
|
|
796 DEL.JH=num_median(.SD$X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
797 Total.Del=num_median(rowSums(.SD[,c("X3V.REGION.trimmed.nt.nb", "X5D.REGION.trimmed.nt.nb", "X3D.REGION.trimmed.nt.nb", "X5J.REGION.trimmed.nt.nb"), with=F], na.rm=T)),
|
|
798 Total.N=num_median(rowSums(.SD[,c("N.REGION.nt.nb", "N1.REGION.nt.nb", "N2.REGION.nt.nb", "N3.REGION.nt.nb", "N4.REGION.nt.nb"), with=F], na.rm=T)),
|
|
799 Total.P=num_median(rowSums(.SD[,c("P3V.nt.nb", "P5D.nt.nb", "P3D.nt.nb", "P5J.nt.nb"), with=F], na.rm=T)),
|
13
|
800 Median.CDR3.l=as.double(median(.SD$CDR3.Length))),
|
5
|
801 by=c("Sample")])
|
|
802
|
|
803 newData[,sapply(newData, is.numeric)] = round(newData[,sapply(newData, is.numeric)],1)
|
|
804 write.table(newData, "junctionAnalysisUnProd_median.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
805 }
|
|
806
|
|
807 PRODF = bak
|
|
808
|
|
809
|
|
810 # ---------------------- D reading frame ----------------------
|
|
811
|
8
|
812 D.REGION.reading.frame = PRODF[,c("Sample", "D.REGION.reading.frame")]
|
5
|
813
|
8
|
814 chck = is.na(D.REGION.reading.frame$D.REGION.reading.frame)
|
|
815 if(any(chck)){
|
|
816 D.REGION.reading.frame[chck,"D.REGION.reading.frame"] = "No D"
|
|
817 }
|
5
|
818
|
8
|
819 D.REGION.reading.frame = data.frame(data.table(D.REGION.reading.frame)[, list(Freq=.N), by=c("Sample", "D.REGION.reading.frame")])
|
5
|
820
|
|
821 write.table(D.REGION.reading.frame, "DReadingFrame.csv" , sep="\t",quote=F,row.names=F,col.names=T)
|
|
822
|
|
823 D.REGION.reading.frame = ggplot(D.REGION.reading.frame)
|
8
|
824 D.REGION.reading.frame = D.REGION.reading.frame + geom_bar(aes( x = D.REGION.reading.frame, y = Freq, fill=Sample), stat='identity', position='dodge' ) + ggtitle("D reading frame") + xlab("Frequency") + ylab("Frame")
|
|
825 D.REGION.reading.frame = D.REGION.reading.frame + scale_fill_manual(values=sample.colors)
|
|
826 D.REGION.reading.frame = D.REGION.reading.frame + theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
827
|
|
828 png("DReadingFrame.png")
|
|
829 D.REGION.reading.frame
|
|
830 dev.off()
|
|
831
|
|
832
|
|
833
|
|
834
|
|
835 # ---------------------- AA composition in CDR3 ----------------------
|
|
836
|
|
837 AACDR3 = PRODF[,c("Sample", "CDR3.Seq")]
|
|
838
|
|
839 TotalPerSample = data.frame(data.table(AACDR3)[, list(total=sum(nchar(as.character(.SD$CDR3.Seq)))), by=Sample])
|
|
840
|
|
841 AAfreq = list()
|
|
842
|
|
843 for(i in 1:nrow(TotalPerSample)){
|
|
844 sample = TotalPerSample$Sample[i]
|
|
845 AAfreq[[i]] = data.frame(table(unlist(strsplit(as.character(AACDR3[AACDR3$Sample == sample,c("CDR3.Seq")]), ""))))
|
|
846 AAfreq[[i]]$Sample = sample
|
|
847 }
|
|
848
|
|
849 AAfreq = ldply(AAfreq, data.frame)
|
|
850 AAfreq = merge(AAfreq, TotalPerSample, by="Sample", all.x = T)
|
|
851 AAfreq$freq_perc = as.numeric(AAfreq$Freq / AAfreq$total * 100)
|
|
852
|
|
853
|
|
854 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")
|
|
855 AAfreq = merge(AAfreq, AAorder, by.x='Var1', by.y='AA', all.x=TRUE)
|
|
856
|
|
857 AAfreq = AAfreq[!is.na(AAfreq$order.aa),]
|
|
858
|
|
859 AAfreqplot = ggplot(AAfreq)
|
|
860 AAfreqplot = AAfreqplot + geom_bar(aes( x=factor(reorder(Var1, order.aa)), y = freq_perc, fill = Sample), stat='identity', position='dodge' )
|
|
861 AAfreqplot = AAfreqplot + annotate("rect", xmin = 0.5, xmax = 2.5, ymin = 0, ymax = Inf, fill = "red", alpha = 0.2)
|
|
862 AAfreqplot = AAfreqplot + annotate("rect", xmin = 3.5, xmax = 4.5, ymin = 0, ymax = Inf, fill = "blue", alpha = 0.2)
|
|
863 AAfreqplot = AAfreqplot + annotate("rect", xmin = 5.5, xmax = 6.5, ymin = 0, ymax = Inf, fill = "blue", alpha = 0.2)
|
|
864 AAfreqplot = AAfreqplot + annotate("rect", xmin = 6.5, xmax = 7.5, ymin = 0, ymax = Inf, fill = "red", alpha = 0.2)
|
8
|
865 AAfreqplot = AAfreqplot + ggtitle("Amino Acid Composition in the CDR3") + xlab("Amino Acid, from Hydrophilic (left) to Hydrophobic (right)") + ylab("Percentage") + scale_fill_manual(values=sample.colors)
|
|
866 AAfreqplot = AAfreqplot + theme(panel.background = element_rect(fill = "white", colour="black"),text = element_text(size=15, colour="black"), axis.text.x = element_text(angle = 45, hjust = 1), panel.grid.major.y = element_line(colour = "black"), panel.grid.major.x = element_blank())
|
5
|
867
|
|
868 png("AAComposition.png",width = 1280, height = 720)
|
|
869 AAfreqplot
|
|
870 dev.off()
|
|
871 write.table(AAfreq, "AAComposition.csv" , sep=",",quote=F,na="-",row.names=F,col.names=T)
|
|
872
|
8
|
873 # ---------------------- AA median CDR3 length ----------------------
|
5
|
874
|
9
|
875 median.aa.l = data.frame(data.table(PRODF)[, list(median=as.double(median(.SD$CDR3.Length))), by=c("Sample")])
|
8
|
876 write.table(median.aa.l, "AAMedianBySample.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
877
|