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