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