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