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