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
|
11
|
169 # ---------------------- Setting up the gene names for the different T/B, human/mouse and locus ----------------------
|
|
170
|
22
|
171 genes = read.table("genes.txt", sep="\t", header=TRUE, fill=T, comment.char="")
|
10
|
172
|
22
|
173 Vchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "V",c("IMGT.GENE.DB", "chr.order")]
|
|
174 colnames(Vchain) = c("v.name", "chr.orderV")
|
|
175 Dchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "D",c("IMGT.GENE.DB", "chr.order")]
|
|
176 colnames(Dchain) = c("v.name", "chr.orderD")
|
|
177 Jchain = genes[grepl(species, genes$Species) & genes$locus == locus & genes$region == "J",c("IMGT.GENE.DB", "chr.order")]
|
|
178 colnames(Jchain) = c("v.name", "chr.orderJ")
|
10
|
179
|
|
180 useD = TRUE
|
22
|
181 if(nrow(Dchain) == 0){
|
11
|
182 useD = FALSE
|
|
183 cat("No D Genes in this species/locus")
|
10
|
184 }
|
|
185
|
22
|
186 # ---------------------- merge with the frequency count ----------------------
|
11
|
187
|
0
|
188 PRODFV = merge(PRODFV, Vchain, by.x='Top.V.Gene', by.y='v.name', all.x=TRUE)
|
|
189
|
|
190 PRODFD = merge(PRODFD, Dchain, by.x='Top.D.Gene', by.y='v.name', all.x=TRUE)
|
|
191
|
|
192 PRODFJ = merge(PRODFJ, Jchain, by.x='Top.J.Gene', by.y='v.name', all.x=TRUE)
|
|
193
|
11
|
194 # ---------------------- Create the V, D and J frequency plots and write the data.frame for every plot to a file ----------------------
|
0
|
195
|
|
196 pV = ggplot(PRODFV)
|
|
197 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))
|
|
198 pV = pV + xlab("Summary of V gene") + ylab("Frequency") + ggtitle("Relative frequency of V gene usage")
|
6
|
199 write.table(x=PRODFV, file="VFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
0
|
200
|
|
201 png("VPlot.png",width = 1280, height = 720)
|
|
202 pV
|
|
203 dev.off();
|
|
204
|
11
|
205 if(useD){
|
|
206 pD = ggplot(PRODFD)
|
|
207 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))
|
|
208 pD = pD + xlab("Summary of D gene") + ylab("Frequency") + ggtitle("Relative frequency of D gene usage")
|
|
209 write.table(x=PRODFD, file="DFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
210
|
|
211 png("DPlot.png",width = 800, height = 600)
|
|
212 print(pD)
|
|
213 dev.off();
|
|
214 }
|
0
|
215
|
11
|
216 pJ = ggplot(PRODFJ)
|
|
217 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))
|
|
218 pJ = pJ + xlab("Summary of J gene") + ylab("Frequency") + ggtitle("Relative frequency of J gene usage")
|
|
219 write.table(x=PRODFJ, file="JFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
220
|
|
221 png("JPlot.png",width = 800, height = 600)
|
|
222 pJ
|
0
|
223 dev.off();
|
|
224
|
|
225 pJ = ggplot(PRODFJ)
|
|
226 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))
|
|
227 pJ = pJ + xlab("Summary of J gene") + ylab("Frequency") + ggtitle("Relative frequency of J gene usage")
|
6
|
228 write.table(x=PRODFJ, file="JFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
0
|
229
|
|
230 png("JPlot.png",width = 800, height = 600)
|
|
231 pJ
|
|
232 dev.off();
|
|
233
|
11
|
234 # ---------------------- Now the frequency plots of the V, D and J families ----------------------
|
|
235
|
6
|
236 VGenes = PRODF[,c("Sample", "Top.V.Gene")]
|
|
237 VGenes$Top.V.Gene = gsub("-.*", "", VGenes$Top.V.Gene)
|
|
238 VGenes = data.frame(data.table(VGenes)[, list(Count=.N), by=c("Sample", "Top.V.Gene")])
|
|
239 TotalPerSample = data.frame(data.table(VGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
240 VGenes = merge(VGenes, TotalPerSample, by="Sample")
|
|
241 VGenes$Frequency = VGenes$Count * 100 / VGenes$total
|
|
242 VPlot = ggplot(VGenes)
|
8
|
243 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
|
244 ggtitle("Distribution of V gene families") +
|
|
245 ylab("Percentage of sequences")
|
6
|
246 png("VFPlot.png")
|
|
247 VPlot
|
|
248 dev.off();
|
|
249 write.table(x=VGenes, file="VFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
250
|
11
|
251 if(useD){
|
|
252 DGenes = PRODF[,c("Sample", "Top.D.Gene")]
|
|
253 DGenes$Top.D.Gene = gsub("-.*", "", DGenes$Top.D.Gene)
|
|
254 DGenes = data.frame(data.table(DGenes)[, list(Count=.N), by=c("Sample", "Top.D.Gene")])
|
|
255 TotalPerSample = data.frame(data.table(DGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
256 DGenes = merge(DGenes, TotalPerSample, by="Sample")
|
|
257 DGenes$Frequency = DGenes$Count * 100 / DGenes$total
|
|
258 DPlot = ggplot(DGenes)
|
|
259 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)) +
|
|
260 ggtitle("Distribution of D gene families") +
|
|
261 ylab("Percentage of sequences")
|
|
262 png("DFPlot.png")
|
|
263 print(DPlot)
|
|
264 dev.off();
|
|
265 write.table(x=DGenes, file="DFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
266 }
|
6
|
267
|
|
268 JGenes = PRODF[,c("Sample", "Top.J.Gene")]
|
|
269 JGenes$Top.J.Gene = gsub("-.*", "", JGenes$Top.J.Gene)
|
|
270 JGenes = data.frame(data.table(JGenes)[, list(Count=.N), by=c("Sample", "Top.J.Gene")])
|
|
271 TotalPerSample = data.frame(data.table(JGenes)[, list(total=sum(.SD$Count)), by=Sample])
|
|
272 JGenes = merge(JGenes, TotalPerSample, by="Sample")
|
|
273 JGenes$Frequency = JGenes$Count * 100 / JGenes$total
|
|
274 JPlot = ggplot(JGenes)
|
8
|
275 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
|
276 ggtitle("Distribution of J gene families") +
|
|
277 ylab("Percentage of sequences")
|
6
|
278 png("JFPlot.png")
|
|
279 JPlot
|
|
280 dev.off();
|
|
281 write.table(x=JGenes, file="JFFrequency.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
282
|
11
|
283 # ---------------------- Plotting the cdr3 length ----------------------
|
|
284
|
8
|
285 CDR3Length = data.frame(data.table(PRODF)[, list(Count=.N), by=c("Sample", "CDR3.Length.DNA")])
|
|
286 TotalPerSample = data.frame(data.table(CDR3Length)[, list(total=sum(.SD$Count)), by=Sample])
|
|
287 CDR3Length = merge(CDR3Length, TotalPerSample, by="Sample")
|
|
288 CDR3Length$Frequency = CDR3Length$Count * 100 / CDR3Length$total
|
|
289 CDR3LengthPlot = ggplot(CDR3Length)
|
|
290 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
|
291 ggtitle("Length distribution of CDR3") +
|
|
292 xlab("CDR3 Length") +
|
|
293 ylab("Percentage of sequences")
|
8
|
294 png("CDR3LengthPlot.png",width = 1280, height = 720)
|
|
295 CDR3LengthPlot
|
|
296 dev.off()
|
|
297 write.table(x=CDR3Length, file="CDR3LengthPlot.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
298
|
11
|
299 # ---------------------- Plot the heatmaps ----------------------
|
|
300
|
|
301
|
|
302 #get the reverse order for the V and D genes
|
0
|
303 revVchain = Vchain
|
|
304 revDchain = Dchain
|
|
305 revVchain$chr.orderV = rev(revVchain$chr.orderV)
|
|
306 revDchain$chr.orderD = rev(revDchain$chr.orderD)
|
|
307
|
11
|
308 if(useD){
|
|
309 plotVD <- function(dat){
|
|
310 if(length(dat[,1]) == 0){
|
|
311 return()
|
|
312 }
|
|
313 img = ggplot() +
|
|
314 geom_tile(data=dat, aes(x=factor(reorder(Top.D.Gene, chr.orderD)), y=factor(reorder(Top.V.Gene, chr.orderV)), fill=relLength)) +
|
|
315 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
316 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
317 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
318 xlab("D genes") +
|
|
319 ylab("V Genes")
|
|
320
|
|
321 png(paste("HeatmapVD_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Dchain$v.name)), height=100+(15*length(Vchain$v.name)))
|
|
322 print(img)
|
|
323 dev.off()
|
|
324 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)
|
|
325 }
|
|
326
|
|
327 VandDCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.V.Gene", "Top.D.Gene", "Sample")])
|
|
328
|
|
329 VandDCount$l = log(VandDCount$Length)
|
|
330 maxVD = data.frame(data.table(VandDCount)[, list(max=max(l)), by=c("Sample")])
|
|
331 VandDCount = merge(VandDCount, maxVD, by.x="Sample", by.y="Sample", all.x=T)
|
|
332 VandDCount$relLength = VandDCount$l / VandDCount$max
|
|
333
|
|
334 cartegianProductVD = expand.grid(Top.V.Gene = Vchain$v.name, Top.D.Gene = Dchain$v.name, Sample = unique(inputdata$Sample))
|
|
335
|
|
336 completeVD = merge(VandDCount, cartegianProductVD, all.y=TRUE)
|
|
337 completeVD = merge(completeVD, revVchain, by.x="Top.V.Gene", by.y="v.name", all.x=TRUE)
|
|
338 completeVD = merge(completeVD, Dchain, by.x="Top.D.Gene", by.y="v.name", all.x=TRUE)
|
|
339 VDList = split(completeVD, f=completeVD[,"Sample"])
|
|
340
|
|
341 lapply(VDList, FUN=plotVD)
|
0
|
342 }
|
|
343
|
|
344 plotVJ <- function(dat){
|
11
|
345 if(length(dat[,1]) == 0){
|
|
346 return()
|
|
347 }
|
|
348 cat(paste(unique(dat[3])[1,1]))
|
|
349 img = ggplot() +
|
|
350 geom_tile(data=dat, aes(x=factor(reorder(Top.J.Gene, chr.orderJ)), y=factor(reorder(Top.V.Gene, chr.orderV)), fill=relLength)) +
|
|
351 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
352 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
353 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
354 xlab("J genes") +
|
|
355 ylab("V Genes")
|
|
356
|
|
357 png(paste("HeatmapVJ_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Jchain$v.name)), height=100+(15*length(Vchain$v.name)))
|
|
358 print(img)
|
|
359 dev.off()
|
|
360 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
|
361 }
|
|
362
|
|
363 VandJCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.V.Gene", "Top.J.Gene", "Sample")])
|
|
364
|
|
365 VandJCount$l = log(VandJCount$Length)
|
|
366 maxVJ = data.frame(data.table(VandJCount)[, list(max=max(l)), by=c("Sample")])
|
|
367 VandJCount = merge(VandJCount, maxVJ, by.x="Sample", by.y="Sample", all.x=T)
|
|
368 VandJCount$relLength = VandJCount$l / VandJCount$max
|
|
369
|
11
|
370 cartegianProductVJ = expand.grid(Top.V.Gene = Vchain$v.name, Top.J.Gene = Jchain$v.name, Sample = unique(inputdata$Sample))
|
0
|
371
|
|
372 completeVJ = merge(VandJCount, cartegianProductVJ, all.y=TRUE)
|
|
373 completeVJ = merge(completeVJ, revVchain, by.x="Top.V.Gene", by.y="v.name", all.x=TRUE)
|
|
374 completeVJ = merge(completeVJ, Jchain, by.x="Top.J.Gene", by.y="v.name", all.x=TRUE)
|
|
375 VJList = split(completeVJ, f=completeVJ[,"Sample"])
|
|
376 lapply(VJList, FUN=plotVJ)
|
|
377
|
11
|
378 if(useD){
|
|
379 plotDJ <- function(dat){
|
|
380 if(length(dat[,1]) == 0){
|
|
381 return()
|
|
382 }
|
|
383 img = ggplot() +
|
|
384 geom_tile(data=dat, aes(x=factor(reorder(Top.J.Gene, chr.orderJ)), y=factor(reorder(Top.D.Gene, chr.orderD)), fill=relLength)) +
|
|
385 theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
|
|
386 scale_fill_gradient(low="gold", high="blue", na.value="white") +
|
|
387 ggtitle(paste(unique(dat$Sample), " (N=" , sum(dat$Length, na.rm=T) ,")", sep="")) +
|
|
388 xlab("J genes") +
|
|
389 ylab("D Genes")
|
|
390
|
|
391 png(paste("HeatmapDJ_", unique(dat[3])[1,1] , ".png", sep=""), width=150+(15*length(Jchain$v.name)), height=100+(15*length(Dchain$v.name)))
|
|
392 print(img)
|
|
393 dev.off()
|
|
394 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)
|
|
395 }
|
|
396
|
|
397
|
|
398 DandJCount = data.frame(data.table(PRODF)[, list(Length=.N), by=c("Top.D.Gene", "Top.J.Gene", "Sample")])
|
|
399
|
|
400 DandJCount$l = log(DandJCount$Length)
|
|
401 maxDJ = data.frame(data.table(DandJCount)[, list(max=max(l)), by=c("Sample")])
|
|
402 DandJCount = merge(DandJCount, maxDJ, by.x="Sample", by.y="Sample", all.x=T)
|
|
403 DandJCount$relLength = DandJCount$l / DandJCount$max
|
|
404
|
|
405 cartegianProductDJ = expand.grid(Top.D.Gene = Dchain$v.name, Top.J.Gene = Jchain$v.name, Sample = unique(inputdata$Sample))
|
|
406
|
|
407 completeDJ = merge(DandJCount, cartegianProductDJ, all.y=TRUE)
|
|
408 completeDJ = merge(completeDJ, revDchain, by.x="Top.D.Gene", by.y="v.name", all.x=TRUE)
|
|
409 completeDJ = merge(completeDJ, Jchain, by.x="Top.J.Gene", by.y="v.name", all.x=TRUE)
|
|
410 DJList = split(completeDJ, f=completeDJ[,"Sample"])
|
|
411 lapply(DJList, FUN=plotDJ)
|
0
|
412 }
|
|
413
|
10
|
414
|
11
|
415 # ---------------------- calculating the clonality score ----------------------
|
0
|
416
|
11
|
417 if("Replicate" %in% colnames(inputdata)) #can only calculate clonality score when replicate information is available
|
|
418 {
|
|
419 clonalityFrame = inputdata
|
|
420 if(clonaltype != "none"){
|
21
|
421 clonalityFrame$clonaltype = do.call(paste, c(clonalityFrame[unlist(strsplit(clonaltype, ","))], sep = ":"))
|
11
|
422 clonalityFrame$ReplicateConcat = paste(clonalityFrame$clonaltype, clonalityFrame$Sample, clonalityFrame$Replicate, sep = ":")
|
|
423 clonalityFrame = clonalityFrame[!duplicated(clonalityFrame$ReplicateConcat), ]
|
|
424 }
|
|
425 write.table(clonalityFrame, "clonalityComplete.csv", sep=",",quote=F,row.names=F,col.names=T)
|
|
426
|
|
427 ClonalitySampleReplicatePrint <- function(dat){
|
|
428 write.table(dat, paste("clonality_", unique(inputdata$Sample) , "_", unique(dat$Replicate), ".csv", sep=""), sep=",",quote=F,row.names=F,col.names=T)
|
|
429 }
|
|
430
|
|
431 clonalityFrameSplit = split(clonalityFrame, f=clonalityFrame[,c("Sample", "Replicate")])
|
|
432 #lapply(clonalityFrameSplit, FUN=ClonalitySampleReplicatePrint)
|
|
433
|
|
434 ClonalitySamplePrint <- function(dat){
|
|
435 write.table(dat, paste("clonality_", unique(inputdata$Sample) , ".csv", sep=""), sep=",",quote=F,row.names=F,col.names=T)
|
|
436 }
|
|
437
|
|
438 clonalityFrameSplit = split(clonalityFrame, f=clonalityFrame[,"Sample"])
|
|
439 #lapply(clonalityFrameSplit, FUN=ClonalitySamplePrint)
|
|
440
|
|
441 clonalFreq = data.frame(data.table(clonalityFrame)[, list(Type=.N), by=c("Sample", "clonaltype")])
|
|
442 clonalFreqCount = data.frame(data.table(clonalFreq)[, list(Count=.N), by=c("Sample", "Type")])
|
|
443 clonalFreqCount$realCount = clonalFreqCount$Type * clonalFreqCount$Count
|
|
444 clonalSum = data.frame(data.table(clonalFreqCount)[, list(Reads=sum(realCount)), by=c("Sample")])
|
|
445 clonalFreqCount = merge(clonalFreqCount, clonalSum, by.x="Sample", by.y="Sample")
|
|
446
|
|
447 ct = c('Type\tWeight\n2\t1\n3\t3\n4\t6\n5\t10\n6\t15')
|
|
448 tcct = textConnection(ct)
|
|
449 CT = read.table(tcct, sep="\t", header=TRUE)
|
|
450 close(tcct)
|
|
451 clonalFreqCount = merge(clonalFreqCount, CT, by.x="Type", by.y="Type", all.x=T)
|
|
452 clonalFreqCount$WeightedCount = clonalFreqCount$Count * clonalFreqCount$Weight
|
|
453
|
|
454 ReplicateReads = data.frame(data.table(clonalityFrame)[, list(Type=.N), by=c("Sample", "Replicate", "clonaltype")])
|
|
455 ReplicateReads = data.frame(data.table(ReplicateReads)[, list(Reads=.N), by=c("Sample", "Replicate")])
|
|
456 clonalFreqCount$Reads = as.numeric(clonalFreqCount$Reads)
|
|
457 ReplicateReads$squared = ReplicateReads$Reads * ReplicateReads$Reads
|
|
458
|
|
459 ReplicatePrint <- function(dat){
|
|
460 write.table(dat[-1], paste("ReplicateReads_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
461 }
|
|
462
|
|
463 ReplicateSplit = split(ReplicateReads, f=ReplicateReads[,"Sample"])
|
|
464 lapply(ReplicateSplit, FUN=ReplicatePrint)
|
|
465
|
21
|
466 ReplicateReads = data.frame(data.table(ReplicateReads)[, list(ReadsSum=sum(as.numeric(Reads)), ReadsSquaredSum=sum(as.numeric(squared))), by=c("Sample")])
|
11
|
467 clonalFreqCount = merge(clonalFreqCount, ReplicateReads, by.x="Sample", by.y="Sample", all.x=T)
|
|
468
|
|
469
|
|
470 ReplicateSumPrint <- function(dat){
|
|
471 write.table(dat[-1], paste("ReplicateSumReads_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
472 }
|
|
473
|
|
474 ReplicateSumSplit = split(ReplicateReads, f=ReplicateReads[,"Sample"])
|
|
475 lapply(ReplicateSumSplit, FUN=ReplicateSumPrint)
|
|
476
|
|
477 clonalFreqCountSum = data.frame(data.table(clonalFreqCount)[, list(Numerator=sum(WeightedCount, na.rm=T)), by=c("Sample")])
|
|
478 clonalFreqCount = merge(clonalFreqCount, clonalFreqCountSum, by.x="Sample", by.y="Sample", all.x=T)
|
|
479 clonalFreqCount$ReadsSum = as.numeric(clonalFreqCount$ReadsSum) #prevent integer overflow
|
|
480 clonalFreqCount$Denominator = (((clonalFreqCount$ReadsSum * clonalFreqCount$ReadsSum) - clonalFreqCount$ReadsSquaredSum) / 2)
|
|
481 clonalFreqCount$Result = (clonalFreqCount$Numerator + 1) / (clonalFreqCount$Denominator + 1)
|
|
482
|
|
483 ClonalityScorePrint <- function(dat){
|
|
484 write.table(dat$Result, paste("ClonalityScore_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
485 }
|
|
486
|
|
487 clonalityScore = clonalFreqCount[c("Sample", "Result")]
|
|
488 clonalityScore = unique(clonalityScore)
|
|
489
|
|
490 clonalityScoreSplit = split(clonalityScore, f=clonalityScore[,"Sample"])
|
|
491 lapply(clonalityScoreSplit, FUN=ClonalityScorePrint)
|
|
492
|
|
493 clonalityOverview = clonalFreqCount[c("Sample", "Type", "Count", "Weight", "WeightedCount")]
|
|
494
|
|
495
|
|
496
|
|
497 ClonalityOverviewPrint <- function(dat){
|
|
498 write.table(dat[-1], paste("ClonalityOverView_", unique(dat[1])[1,1] , ".csv", sep=""), sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
499 }
|
|
500
|
|
501 clonalityOverviewSplit = split(clonalityOverview, f=clonalityOverview$Sample)
|
|
502 lapply(clonalityOverviewSplit, FUN=ClonalityOverviewPrint)
|
0
|
503 }
|
1
|
504
|
11
|
505 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")
|
|
506 if(all(imgtcolumns %in% colnames(inputdata)))
|
1
|
507 {
|
19
|
508 newData = data.frame(data.table(PRODF)[,list(unique=.N,
|
21
|
509 VH.DEL=mean(X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
510 P1=mean(P3V.nt.nb, na.rm=T),
|
|
511 N1=mean(N1.REGION.nt.nb, na.rm=T),
|
|
512 P2=mean(P5D.nt.nb, na.rm=T),
|
|
513 DEL.DH=mean(X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
514 DH.DEL=mean(X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
515 P3=mean(P3D.nt.nb, na.rm=T),
|
|
516 N2=mean(N2.REGION.nt.nb, na.rm=T),
|
|
517 P4=mean(P5J.nt.nb, na.rm=T),
|
|
518 DEL.JH=mean(X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
519 Total.Del=( mean(X3V.REGION.trimmed.nt.nb, na.rm=T) +
|
|
520 mean(X5D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
521 mean(X3D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
522 mean(X5J.REGION.trimmed.nt.nb, na.rm=T)),
|
|
523
|
|
524 Total.N=( mean(N1.REGION.nt.nb, na.rm=T) +
|
|
525 mean(N2.REGION.nt.nb, na.rm=T)),
|
|
526
|
|
527 Total.P=( mean(P3V.nt.nb, na.rm=T) +
|
|
528 mean(P5D.nt.nb, na.rm=T) +
|
|
529 mean(P3D.nt.nb, na.rm=T) +
|
|
530 mean(P5J.nt.nb, na.rm=T))),
|
|
531 by=c("Sample")])
|
20
|
532 write.table(newData, "junctionAnalysisProd.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
|
533
|
21
|
534 newData = data.frame(data.table(UNPROD)[,list(unique=.N,
|
|
535 VH.DEL=mean(X3V.REGION.trimmed.nt.nb, na.rm=T),
|
|
536 P1=mean(P3V.nt.nb, na.rm=T),
|
|
537 N1=mean(N1.REGION.nt.nb, na.rm=T),
|
|
538 P2=mean(P5D.nt.nb, na.rm=T),
|
|
539 DEL.DH=mean(X5D.REGION.trimmed.nt.nb, na.rm=T),
|
|
540 DH.DEL=mean(X3D.REGION.trimmed.nt.nb, na.rm=T),
|
|
541 P3=mean(P3D.nt.nb, na.rm=T),
|
|
542 N2=mean(N2.REGION.nt.nb, na.rm=T),
|
|
543 P4=mean(P5J.nt.nb, na.rm=T),
|
|
544 DEL.JH=mean(X5J.REGION.trimmed.nt.nb, na.rm=T),
|
|
545 Total.Del=( mean(X3V.REGION.trimmed.nt.nb, na.rm=T) +
|
|
546 mean(X5D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
547 mean(X3D.REGION.trimmed.nt.nb, na.rm=T) +
|
|
548 mean(X5J.REGION.trimmed.nt.nb, na.rm=T)),
|
|
549
|
|
550 Total.N=( mean(N1.REGION.nt.nb, na.rm=T) +
|
|
551 mean(N2.REGION.nt.nb, na.rm=T)),
|
|
552
|
|
553 Total.P=( mean(P3V.nt.nb, na.rm=T) +
|
|
554 mean(P5D.nt.nb, na.rm=T) +
|
|
555 mean(P3D.nt.nb, na.rm=T) +
|
|
556 mean(P5J.nt.nb, na.rm=T))),
|
|
557 by=c("Sample")])
|
20
|
558 write.table(newData, "junctionAnalysisUnProd.csv" , sep=",",quote=F,na="-",row.names=F,col.names=F)
|
5
|
559 }
|