-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtrapes.py
executable file
·1897 lines (1745 loc) · 78.6 KB
/
trapes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
import sys
import os
import random
import argparse
import subprocess
import datetime
from Bio import SeqIO
import pysam
import operator
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
#def runTCRpipe(fasta, bed, output, bam, unmapped, mapping, bases, strand, reconstruction, aaF , numIterations, thresholdScore, minOverlap,
#rsem, bowtie2, singleCell, path, subpath, sumF, lowQ, singleEnd, fastq, trimmomatic, transInd):
def runTCRpipe(genome, output, bam, unmapped, bases, strand, numIterations,thresholdScore, minOverlap, rsem, bowtie2, singleCell, path, sumF, lowQ, samtools, top, byExp, readOverlap, oneSide, Aminus, Bminus):
checkParameters(strand, singleCell, path, sumF)
if singleCell == True:
# TODO: Fix this, won't work for SE
#runSingleCell(fasta, bed, output, bam, unmapped, mapping, bases, strand, reconstruction, aaF , numIterations, thresholdScore, minOverlap,
# rsem, bowtie2, lowQ, singleEnd, fastq, trimmomatic, transInd)
sys.exit(0)
if path == './':
path = os.getcwd()
if not path.endswith('/'):
path = path + '/'
finalStatDict = dict()
tcrFout = open(sumF + '.TCRs.txt','w')
opened = False
currFolder = os.path.abspath(os.path.dirname(sys.argv[0])) + '/'
(fasta, bed, mapping, aaF) = getGenomeFiles(currFolder, genome)
for cellFolder in os.listdir(path):
fullPath = path + cellFolder + '/'
if((os.path.exists(fullPath)) & (os.path.isdir(fullPath))):
sys.stdout.write(str(datetime.datetime.now()) + " Working on: " + cellFolder + '\n')
sys.stdout.flush()
(found, nbam, nunmapped, noutput) = formatFiles(fullPath, bam, unmapped, output)
if not found:
sys.stderr.write(str(datetime.datetime.now()) + " There is not a bam or unmapped file in "
"this folder, moving to the next folder\n")
sys.stderr.flush()
else:
#reconstruction = currFolder + '/vdj.alignment'
reconstruction = currFolder + '/vdj.alignment.tcr'
runSingleCell(fasta, bed, noutput, nbam, nunmapped, mapping, bases, strand, reconstruction, aaF , numIterations, thresholdScore,
minOverlap, rsem, bowtie2, lowQ, samtools, top, byExp, readOverlap, oneSide, Aminus, Bminus, genome)
opened = addCellToTCRsum(cellFolder, noutput, opened, tcrFout)
finalStatDict = addToStatDict(noutput, cellFolder, finalStatDict)
sumFout = open(sumF + '.summary.txt','w')
sumFout.write('sample\talpha\tbeta\n')
for cell in sorted(finalStatDict):
fout = cell + '\t' + finalStatDict[cell]['alpha'] + '\t' + finalStatDict[cell]['beta'] + '\n'
sumFout.write(fout)
sumFout.close()
def getGenomeFiles(currFolder, genome):
dataFold = currFolder + 'Data/' + genome + '/'
fasta = 'NA'
bed = 'NA'
mapping = 'NA'
aaF = 'NA'
if os.path.isdir(dataFold):
for ff in os.listdir(dataFold):
if not ff.startswith('.'):
if ff.endswith('TCR.bed'):
bed = dataFold + ff
elif ff.endswith('conserved.AA.txt'):
aaF = dataFold + ff
elif ff.endswith('TCR.fa'):
fasta = dataFold + ff
elif ff.endswith('gene.id.mapping.TCR.txt'):
mapping = dataFold + ff
if (fasta == 'NA'):
sys.exit(str(datetime.datetime.now()) + " Error! TCR fasta file is missing in the Data/genome folder\n")
if (mapping == 'NA'):
sys.exit(str(datetime.datetime.now()) + " Error! TCR gene id mapping file is missing in the Data/genome folder\n")
if (bed == 'NA'):
sys.exit(str(datetime.datetime.now()) + " Error! TCR bed file is missing in the Data/genome folder\n")
if (aaF == 'NA'):
sys.exit(str(datetime.datetime.now()) + " Error! TCR conserved AA file is missing in the Data/genome folder\n")
else:
sys.exit(str(datetime.datetime.now()) + " Error! Genome parameter is invalid, no folder named: " + dataFold + '\n')
return(fasta, bed, mapping, aaF)
def addCellToTCRsum(cellFolder, noutput, opened, tcrFout):
if os.path.isfile(noutput + '.summary.txt'):
currOut = open(noutput + '.summary.txt','r')
if not opened:
opened = True
head = currOut.readline()
head = 'cell\t' + head
tcrFout.write(head)
else:
currOut.readline()
l = currOut.readline()
while l != '':
newL = cellFolder + '\t' + l
tcrFout.write(newL)
l = currOut.readline()
currOut.close()
return opened
def addToStatDict(noutput, cellFolder, finalStatDict):
if cellFolder in finalStatDict:
print "Error! %s appear more than once in final stat dictionary" % cellFolder
finalStatDict[cellFolder] = {'alpha':'Failed - found V and J segments but wasn\'t able to extend them',
'beta':'Failed - found V and J segments but wasn\'t able to extend them'}
if os.path.isfile(noutput + '.summary.txt'):
currOut = open(noutput + '.summary.txt','r')
msgA = 'None'
msgB = 'None'
currOut.readline()
l = currOut.readline()
while l != '':
lArr = l.strip('\n').split('\t')
chain = lArr[0]
stat = lArr[1]
if stat == 'Productive':
if chain == 'alpha':
msgA = 'Productive'
else:
msgB = 'Productive'
elif stat == 'Productive (no 118 PHE found)':
if chain == 'alpha':
msgA = 'Productive (no 118 PHE found)'
else:
msgB = 'Productive (no 118 PHE found)'
elif stat.startswith('Unproductive'):
if chain == 'alpha':
if msgA != 'Productive':
msgA = 'Unproductive'
else:
if msgB != 'Productive':
msgB = 'Unproductive'
elif stat.startswith('Failed reconstruction'):
if stat == 'Failed reconstruction - reached maximum number of iterations':
if chain == 'alpha':
if msgA == 'None':
msgA = 'Failed - reconstruction didn\'t converge'
else:
if msgB == 'None':
msgB = 'Failed - reconstruction didn\'t converge'
elif stat == 'Failed reconstruction - V and J segment do not overlap':
if chain == 'alpha':
if msgA == 'None':
msgA = 'Failed - V and J reconstruction don\'t overlap'
else:
if msgB == 'None':
msgB = 'Failed - V and J reconstruction don\'t overlap'
l = currOut.readline()
currOut.close()
if msgA == 'None':
alphaJunc = noutput + '.alpha.junctions.txt'
if (os.path.isfile(alphaJunc) == True):
if os.stat(alphaJunc).st_size == 0:
msgA = 'Failed - didn\'t find any V and J segments in original mapping'
else:
msgA = 'Failed - found V and J segments but wasn\'t able to extend them'
else:
msgA = 'Failed - didn\'t find any V and J segments in original mapping'
if msgB == 'None':
betaJunc = noutput + '.beta.junctions.txt'
if (os.path.isfile(betaJunc) == True):
if os.stat(betaJunc).st_size == 0:
msgB = 'Failed - didn\'t find any V and J segments in original mapping'
else:
msgB = 'Failed - found V and J segments but wasn\'t able to extend them'
else:
msgB = 'Failed - didn\'t find any V and J segments in original mapping'
else:
betaJunc = noutput + '.beta.junctions.txt'
alphaJunc = noutput + '.alpha.junctions.txt'
if os.path.isfile(betaJunc) == True:
if os.stat(betaJunc).st_size == 0:
msgB = 'Failed - didn\'t find any V and J segments in original mapping'
else:
msgB = 'Failed - didn\'t find any V and J segments in original mapping'
if (os.path.isfile(alphaJunc) == True):
if os.stat(alphaJunc).st_size == 0:
msgA = 'Failed - didn\'t find any V and J segments in original mapping'
else:
msgA = 'Failed - didn\'t find any V and J segments in original mapping'
finalStatDict[cellFolder]['alpha'] = msgA
finalStatDict[cellFolder]['beta'] = msgB
return finalStatDict
def formatFiles(fullPath, bam, unmapped, output):
found = True
nbam = fullPath + bam
if bam.startswith('/'):
nbam = fullPath + bam[1:]
elif bam.startswith('./'):
nbam = fullPath + bam[2:]
nunmapped = fullPath + unmapped
if unmapped.startswith('/'):
nunmapped = fullPath + unmapped[1:]
if unmapped.startswith('./'):
nunmapped = fullPath + unmapped[2:]
if ((os.path.isfile(nunmapped)) & (os.path.isfile(nbam))):
noutput = makeOutputDir(output, fullPath)
else:
noutput = output
found = False
return (found, nbam, nunmapped, noutput)
def makeOutputDir(output, fullPath):
noutput = output
if output.startswith('/'):
noutput = output[1:]
if output.startswith('./'):
noutput = output[2:]
if output.endswith('/'):
noutput = output[:-1]
if output.find('/') != -1:
outArr = noutput.split('/')
currPath = fullPath
for i in range(0,len(outArr)-1):
currPath = currPath + outArr[i] + '/'
if not os.path.exists(currPath):
os.makedirs(currPath)
noutput = fullPath + noutput
return noutput
def runSingleCell(fasta, bed, output, bam, unmapped, mapping, bases, strand, reconstruction, aaF , numIterations, thresholdScore, minOverlap,
rsem, bowtie2, lowQ, samtools, top, byExp, readOverlap, oneSide, Aminus, Bminus, organism):
idNameDict = makeIdNameDict(mapping)
fastaDict = makeFastaDict(fasta)
vdjDict = makeVDJBedDict(bed, idNameDict)
sys.stdout.write(str(datetime.datetime.now()) + " Pre-processing alpha chain\n")
sys.stdout.flush()
unDictAlpha = analyzeChain(fastaDict, vdjDict, output, bam, unmapped, idNameDict, bases, 'A', strand, lowQ, top, byExp, readOverlap, Aminus, Bminus, organism)
sys.stdout.write(str(datetime.datetime.now()) + " Pre-processing beta chain\n")
sys.stdout.flush()
unDictBeta = analyzeChain(fastaDict, vdjDict, output, bam, unmapped, idNameDict, bases, 'B', strand, lowQ, top, byExp, readOverlap, Aminus, Bminus, organism)
sys.stdout.write(str(datetime.datetime.now()) + " Reconstructing beta chains\n")
sys.stdout.flush()
subprocess.call([reconstruction, output + '.beta.mapped.and.unmapped.fa', output + '.beta.junctions.txt', output + '.reconstructed.junctions.beta.fa', str(numIterations), str(thresholdScore), str(minOverlap)])
sys.stdout.write(str(datetime.datetime.now()) + " Reconstructing alpha chains\n")
sys.stdout.flush()
subprocess.call([reconstruction, output + '.alpha.mapped.and.unmapped.fa', output + '.alpha.junctions.txt',
output + '.reconstructed.junctions.alpha.fa', str(numIterations), str(thresholdScore), str(minOverlap)])
sys.stdout.write(str(datetime.datetime.now()) + " Creating full TCR sequencing\n")
sys.stdout.flush()
fullTcrFileAlpha = output + '.alpha.full.TCRs.fa'
tcrF = output + '.reconstructed.junctions.alpha.fa'
(cSeq, cName, cId) = getCInfo(vdjDict['Alpha']['C'][0],idNameDict, fastaDict)
createTCRFullOutput(fastaDict, tcrF, fullTcrFileAlpha, bases, idNameDict, cSeq, cName, cId, oneSide)
fullTcrFileBeta = output + '.beta.full.TCRs.fa'
tcrF = output + '.reconstructed.junctions.beta.fa'
(cSeq, cName, cId) = getCInfo(vdjDict['Beta']['C'][0],idNameDict, fastaDict)
createTCRFullOutput(fastaDict, tcrF, fullTcrFileBeta , bases, idNameDict, cSeq, cName, cId, oneSide)
sys.stdout.write(str(datetime.datetime.now()) + " Running RSEM to quantify expression of all possible isoforms\n")
sys.stdout.flush()
outDirInd = output.rfind('/')
if outDirInd != -1:
outDir = output[:outDirInd+1]
else:
outDir = os.getcwd()
runRsem(outDir, rsem, bowtie2, fullTcrFileAlpha, fullTcrFileBeta, output, samtools)
pickFinalIsoforms(fullTcrFileAlpha, fullTcrFileBeta, output)
bestAlpha = output + '.alpha.full.TCRs.bestIso.fa'
bestBeta = output + '.beta.full.TCRs.bestIso.fa'
sys.stdout.write(str(datetime.datetime.now()) + " Finding productive CDR3\n")
sys.stdout.flush()
aaDict = makeAADict(aaF)
if os.path.isfile(bestAlpha):
fDictAlpha = findCDR3(bestAlpha, aaDict, fastaDict )
else:
fDictAlpha = dict()
if os.path.isfile(bestBeta):
fDictBeta = findCDR3(bestBeta, aaDict, fastaDict )
else:
fDictBeta = dict()
betaRsemOut = output + '.beta.rsem.out.genes.results'
alphaRsemOut = output + '.alpha.rsem.out.genes.results'
alphaBam = output + '.alpha.rsem.out.transcript.sorted.bam'
betaBam = output + '.beta.rsem.out.transcript.sorted.bam'
sys.stdout.write(str(datetime.datetime.now()) + " Writing results to summary file\n")
sys.stdout.flush()
makeSingleCellOutputFile(fDictAlpha, fDictBeta, output, betaRsemOut, alphaRsemOut, alphaBam, betaBam, fastaDict,
unDictAlpha, unDictBeta, idNameDict)
def analyzeChainSingleEnd(fastq, trimmomatic, transInd, bowtie2, idNameDict, output, fastaDict, bases):
mappedReadsDictAlpha = dict()
mappedReadsDictBeta = dict()
lenArr = [999,50,25]
for currLen in lenArr:
if currLen == 999:
steps = ['none']
else:
steps = ['left','right']
for side in steps:
if side == 'left':
crop = 'CROP:' + str(currLen)
elif side == 'right':
crop = 'HEADCROP:' + str(currLen)
else:
crop = ''
# TODO: make sure we delete those files
trimFq = fastq + '.' + str(currLen) + '.' + str(side) + '.trimmed.fq'
# TODO: use bowtie trimmer instead
# TODO: make sure about minus strand alignment
if crop == '':
subprocess.call(['java','-jar', trimmomatic, 'SE','-phred33',fastq ,trimFq, 'LEADING:15','TRAILING:15', 'MINLEN:20'])
else:
subprocess.call(['java','-jar', trimmomatic, 'SE','-phred33',fastq ,trimFq, 'LEADING:15','TRAILING:15', crop, 'MINLEN:20'])
samF = trimFq + '.sam'
if bowtie2 != '':
if bowtie2.endswith('/'):
bowtieCall = bowtie2 + 'bowtie2'
else:
bowtieCall = bowtie2 + '/bowtie2'
else:
bowtieCall = 'bowtie2'
subprocess.call([bowtieCall ,'-q --phred33 --score-min L,0,0', '-x',transInd,'-U',trimFq,'-S',samF])
if os.path.isfile(samF):
mappedReadsDictAlpha = findReadsAndSegments(samF, mappedReadsDictAlpha, idNameDict,'A')
mappedReadsDictBeta = findReadsAndSegments(samF, mappedReadsDictBeta, idNameDict,'B')
alphaOut = output + '.alpha.junctions.txt'
alphaOutReads = output + '.alpha.mapped.and.unmapped.fa'
betaOutReads = output + '.beta.mapped.and.unmapped.fa'
betaOut = output + '.beta.junctions.txt'
writeJunctionFileSE(mappedReadsDictAlpha, idNameDict, alphaOut, fastaDict, bases, 'alpha')
writeJunctionFileSE(mappedReadsDictBeta, idNameDict, betaOut, fastaDict, bases, 'beta')
writeReadsFileSE(mappedReadsDictAlpha, alphaOutReads, fastq)
writeReadsFileSE(mappedReadsDictBeta, betaOutReads, fastq)
sys.exit(1)
def writeReadsFileSE(mappedReadsDict, outReads, fastq):
if fastq.endswith('.gz'):
subprocess.call(['gunzip', fastq])
newFq = fastq.replace('.gz','')
else:
newFq = fastq
out = open(outReads, 'w')
fqF = open(newFq, 'rU')
for record in SeqIO.parse(fqF, 'fastq'):
if record.id in mappedReadsDict:
newRec = SeqRecord(record.seq, id = record.id, description = '')
SeqIO.write(newRec,out,'fasta')
out.close()
fqF.close()
if fastq.endswith('.gz'):
subprocess.call(['gzip',newFq])
def writeJunctionFileSE(mappedReadsDict,idNameDict, output, fastaDict, bases, chain):
out = open(output, 'w')
vSegs = []
jSegs = []
cSegs = []
for read in mappedReadsDict:
for seg in mappedReadsDict[read]:
if idNameDict[seg].find('V') != -1:
if seg not in vSegs:
vSegs.append(seg)
elif idNameDict[seg].find('J') != -1:
if seg not in jSegs:
jSegs.append(seg)
elif idNameDict[seg].find('C') != -1:
if seg not in cSegs:
cSegs.append(seg)
else:
print "Error! not V/J/C in fasta dict"
if len(vSegs) == 0:
print "Did not find any V segments for " + chain + " chain"
else:
if len(cSegs) == 0:
print "Did not find any C segments for " + chain + " chain"
cSegs = ['NA']
if len(jSegs) == 0:
print "Did not find any J segments for " + chain + " chain"
jSegs = ['NA']
for vSeg in vSegs:
for jSeg in jSegs:
for cSeg in cSegs:
addSegmentToJunctionFileSE(vSeg,jSeg,cSeg,out,fastaDict, bases, idNameDict)
out.close()
def addSegmentToJunctionFileSE(vSeg,jSeg,cSeg,out,fastaDict, bases, idNameDict):
vSeq = fastaDict[vSeg]
if jSeg != 'NA':
jName = idNameDict[jSeg]
jSeq = fastaDict[jSeg]
else:
jSeq = ''
jName = 'NoJ'
if cSeg != 'NA':
cName = idNameDict[cSeg]
cSeq = fastaDict[cSeg]
else:
cName = 'NoC'
cSeq = ''
jcSeq = jSeq + cSeq
lenSeg = min(len(vSeq),len(jcSeq))
if bases != -10:
if lenSeg < bases:
sys.stdout.write(str(datetime.datetime.now()) + ' Bases parameter is bigger than the length of the V or J segment, taking the length' \
'of the V/J segment instead, which is: ' + str(lenSeg) + '\n')
sys.stdout.flush()
else:
lenSeg = bases
jTrim = jcSeq[:lenSeg]
vTrim = vSeq[-1*lenSeg:]
junc = vTrim + jTrim
recordName = vSeg + '.' + jSeg + '.' + cSeg + '(' + idNameDict[vSeg] + '-' + jName + '-' + cName + ')'
record = SeqRecord(Seq(junc,IUPAC.ambiguous_dna), id = recordName, description = '')
SeqIO.write(record,out,'fasta')
def findReadsAndSegments(samF, mappedReadsDict, idNameDict,chain):
samFile = pysam.AlignmentFile(samF,'r')
readsIter = samFile.fetch(until_eof = True)
for read in readsIter:
if read.is_unmapped == False:
seg = samFile.getrname(read.reference_id)
if seg in idNameDict:
if idNameDict[seg].find(chain) != -1:
readName = read.query_name
if readName not in mappedReadsDict:
mappedReadsDict[readName] = []
if seg not in mappedReadsDict[readName]:
mappedReadsDict[readName].append(seg)
samFile.close()
return mappedReadsDict
def makeSingleCellOutputFile(alphaDict, betaDict, output, betaRsem, alphaRsem, alphaBam, betaBam, fastaDict,
unDictAlpha, unDictBeta, idNameDict):
outF = open(output + '.summary.txt', 'w')
outF.write('Chain\tStatus\tRank of TCR\tV\tJ\tC\tCDR3 NT\tCDR3 AA\t#reads in TCR\t#reads in CDR3\t#reads in V\t#reads in J\t#reads in C\t%unmapped reads used in the reconstruction\t# unmapped reads used in the reconstruction\t%unmapped reads in CDR3\t#unmapped reads in CDR3\tV ID\tJ ID\tC ID\n')
if (len(alphaDict) > 0):
writeChain(outF, 'alpha',alphaDict,alphaRsem, alphaBam, fastaDict,unDictAlpha, output, idNameDict)
if (len(betaDict) > 0):
writeChain(outF,'beta',betaDict, betaRsem, betaBam, fastaDict, unDictBeta, output, idNameDict)
outF.close()
def writeChain(outF, chain,cdrDict,rsemF, bamF, fastaDict, unDict, output, idNameDict):
writtenArr = []
if os.path.exists(rsemF):
noRsem = False
(rsemDict,unRsemDict) = makeRsemDict(rsemF, cdrDict)
else:
noRsem = True
for tcr in cdrDict:
jStart = -1
cdrInd = -1
cInd = -1
if cdrDict[tcr]['stat'] == 'Productive':
isProd = True
else:
isProd = False
fLine = chain + '\t' + cdrDict[tcr]['stat'] + '\t'
if noRsem:
rank = 'NA'
else:
rank = getRank(tcr, rsemDict, unRsemDict, isProd, noRsem)
fLine += str(rank) + '\t'
nameArr = tcr.split('.')
fLine += nameArr[0] + '\t' + nameArr[1] + '\t' + nameArr[2] + '\t'
fLine += cdrDict[tcr]['CDR3 NT'] + '\t' + cdrDict[tcr]['CDR3 AA'] + '\t'
fullSeq = cdrDict[tcr]['Full Seq'].upper()
if not noRsem:
totalCount = findCountsInRegion(bamF, 0, len(fullSeq), tcr)
fLine += str(totalCount) + '\t'
cName = nameArr[5]
while cName.endswith('_2'):
cName = cName[:-2]
cSeq = fastaDict[cName].upper()
cInd = fullSeq.find(cSeq)
if cInd == -1:
sys.stderr.write(str(datetime.datetime.now()) + 'Error! could not find C segment sequence in the full sequence\n')
sys.stderr.flush()
cCounts = 'NA'
else:
cCounts = findCountsInRegion(bamF, cInd, len(fullSeq), tcr)
if cdrDict[tcr]['CDR3 NT'] != 'NA':
cdrInd = fullSeq.find(cdrDict[tcr]['CDR3 NT'].upper())
else:
cdrInd = -1
if ((cdrInd == -1) & (cdrDict[tcr]['CDR3 NT'] != 'NA')):
sys.stderr.write(str(datetime.datetime.now()) + ' Error! Cound not find CDR3 NT sequence in the full sequence\n')
sys.stderr.flush()
if cdrInd != -1:
cdrCounts = findCountsInRegion(bamF, cdrInd, cdrInd + len(cdrDict[tcr]['CDR3 NT']), tcr)
jStart = cdrInd + len(cdrDict[tcr]['CDR3 NT'])
if cInd != -1:
jCounts = findCountsInRegion(bamF, jStart, cInd, tcr)
else:
jCounts = findCountsInRegion(bamF, jStart, jStart+50, tcr)
vCounts = findCountsInRegion(bamF, 0, cdrInd, tcr)
fLine += str(cdrCounts) + '\t' + str(vCounts) + '\t' + str(jCounts) + '\t' + str(cCounts) + '\t'
else:
fLine += 'NA\tNA\tNA\t' + str(cCounts) + '\t'
vId = nameArr[3]
jId = nameArr[4]
cId = nameArr[5]
if cdrDict[tcr]['CDR3 NT'] != 'NA':
(unDictRatioCDR, unCDRcount) = getUnDictRatio(bamF, cdrInd , cdrInd + len(cdrDict[tcr]['CDR3 NT']), tcr, unDict)
(unDictRatioALL, unAllcount) = getUnDictRatio(bamF, 0 , len(fullSeq), tcr, unDict)
fLine += str(unDictRatioALL) + '\t' + str(unAllcount) + '\t' + str(unDictRatioCDR) + '\t' + str(unCDRcount) + '\t'
else:
fLine += 'NA\tNA\tNA\tNA\t'
writtenArr.append(vId)
writtenArr.append(jId)
fLine += vId + '\t' + jId + '\t' + cId + '\n'
else:
fLine += 'NA\tNA\tNA\tNA\tNA\tNA\tNA\tNA\tNA\tNA\tNA\t' + nameArr[3] + '\t' + nameArr[4] + '\t' + nameArr[5] + '\n'
#print fLine
outF.write(str(fLine))
writeFailedReconstructions(outF, chain, writtenArr, output, idNameDict, fastaDict )
def writeFailedReconstructions(outF, chain, writtenArr, output, idNameDict, fastaDict):
recF = output + '.reconstructed.junctions.' + chain + '.fa'
if os.path.isfile(recF):
f = open(recF, 'rU')
segDict = dict()
for tcrRecord in SeqIO.parse(f, 'fasta'):
tcrSeq = str(tcrRecord.seq)
if tcrSeq.find('NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN') != -1:
status = 'Failed reconstruction - reached maximum number of iterations'
segDict = addSegmentsToDict(segDict, status, writtenArr, tcrRecord, idNameDict, fastaDict)
elif tcrSeq.find('NNNN') != -1:
status = 'Failed reconstruction - V and J segment do not overlap'
segDict = addSegmentsToDict(segDict, status, writtenArr, tcrRecord, idNameDict, fastaDict)
f.close()
if len(segDict) > 0:
writeSegDict(segDict, outF, chain)
def writeSegDict(segDict, outF, chain):
for seg in segDict:
currDict = segDict[seg]
pairs = ''
for pair in currDict['pairs']:
pairs += pair + '.'
pairs = pairs[:-1]
if currDict['len'] > 0:
fLine = chain + '\t' + currDict['status'] + '\t'
rank = findCurrRank(segDict, seg, currDict['len'])
fLine += str(rank) + '\t'
if currDict['type'] == 'V':
fLine += currDict['name'] + '\t' + 'paired with: ' + pairs + '\t'
else:
fLine += 'paired with: ' + pairs + '\t' + currDict['name'] + '\t'
fLine += 'NA\t' + currDict['seq'] + '\tNA\tNA\tNA\t'
fLine += 'NA\tNA\tNA\tNA\tNA\tNA\tNA\t'
if currDict['type'] == 'V':
fLine += seg + '\tNA\tNA\n'
else:
fLine += 'NA\t' + seg + '\tNA\n'
#print fLine
outF.write(str(fLine))
def findCurrRank(segDict, seg, currLen):
rank = 1
for s in segDict:
if s != seg:
if segDict[s]['len'] > currLen:
rank += 1
return rank
def addSegmentsToDict(segDict, status, writtenArr, tcrRecord, idNameDict, fastaDict):
head = tcrRecord.id
headArr = head.split('.')
vId = headArr[0]
jId = headArr[1].split('(')[0]
currSeqArr = tcrRecord.seq.split('N')
vSeq = currSeqArr[0]
jSeq = currSeqArr[-1]
minLen = min(len(fastaDict[vId]),len(fastaDict[jId]))
tupArr = [(vId, vSeq),(jId, jSeq)]
for i in range(0,len(tupArr)):
(id,seq) = tupArr[i]
if id not in writtenArr:
if id in segDict:
if i == 0:
if idNameDict[jId] not in segDict[id]['pairs']:
segDict[id]['pairs'].append(idNameDict[jId])
if str(segDict[id]['seq'][-20:]) != str(seq[-20:]):
sys.stderr.write(str(datetime.datetime.now()) + ' Error! reconstructed two different sequences from the same V-segment %s\n' % id)
sys.stderr.flush()
else:
if idNameDict[vId] not in segDict[id]['pairs']:
segDict[id]['pairs'].append(idNameDict[vId])
if str(segDict[id]['seq'][:20]) != str(seq[:20]):
sys.stderr.write(str(datetime.datetime.now()) + ' Error! reconstructed two different sequences from the same J-segment %s\n' % id)
sys.stderr.flush()
else:
segDict[id] = dict()
segDict[id]['status'] = status
segDict[id]['seq'] = seq
segDict[id]['len'] = len(seq) - minLen
segDict[id]['pairs'] = []
if i == 0:
segDict[id]['type'] = 'V'
segDict[id]['pairs'].append(idNameDict[jId])
else:
segDict[id]['type'] = 'J'
segDict[id]['pairs'].append(idNameDict[vId])
segDict[id]['name'] = idNameDict[id]
return segDict
def getRank(tcr, rsemDict, unRsemDict, isProd, noRsem):
if isProd:
currDict = rsemDict
else:
currDict = unRsemDict
if not noRsem:
currCount = currDict[tcr]
rank = 1
for rec in currDict:
if rec != tcr:
if unRsemDict[rec] > currCount:
rank += 1
return rank
else:
return 'NA'
def getUnDictRatio(bamF, start, end, tcr, unDict):
unMappedCount = 0
usedArr = []
mappedFile = pysam.AlignmentFile(bamF,"rb")
readsIter = mappedFile.fetch(tcr, start, end)
for read in readsIter:
if read.is_read1 :
newName = read.query_name + '_1'
else:
newName = read.query_name + '_2'
if newName not in usedArr:
usedArr.append(newName)
if newName in unDict:
unMappedCount += 1
mappedFile.close()
if len(unDict) == 0:
return(0,unMappedCount)
else:
return (float(float(unMappedCount)/len(unDict)), unMappedCount)
def findCountsInRegion(bamF, start, end, tcr):
readsArr = []
mappedFile = pysam.AlignmentFile(bamF,"rb")
readsIter = mappedFile.fetch(tcr, start, end)
for read in readsIter:
if read.is_read1 :
newName = read.query_name + '_1'
else:
newName = read.query_name + '_2'
if newName not in readsArr:
readsArr.append(newName)
mappedFile.close()
counts = len(readsArr)
return counts
def makeRsemDict(rsemF, cdrDict):
fDict = dict()
unDict = dict()
f = open(rsemF,'r')
f.readline()
l = f.readline()
while l != '':
lArr = l.strip('\n').split('\t')
name = lArr[1]
if name in cdrDict:
if cdrDict[name]['stat'] == 'Productive':
fDict[name] = float(lArr[4])
unDict[name] = float(lArr[4])
l = f.readline()
f.close()
return (fDict,unDict)
def findCDR3(fasta, aaDict, vdjFaDict):
f = open(fasta, 'rU')
fDict = dict()
for record in SeqIO.parse(f, 'fasta'):
if record.id in fDict:
sys.stderr.write(str(datetime.datetime.now()) + ' Error! same name for two fasta entries %s\n' % record.id)
sys.stderr.flush()
else:
idArr = record.id.split('.')
vSeg = idArr[0]
jSeg = idArr[1]
if ((vSeg in aaDict) & (jSeg in aaDict)):
currDict = findVandJaaMap(aaDict[vSeg],aaDict[jSeg],record.seq)
else:
if vSeg in aaDict:
newVseg = aaDict[vSeg]
else:
vId = idArr[3]
currSeq = vdjFaDict[vId]
newVseg = getBestVaa(Seq(currSeq))
if jSeg in aaDict:
newJseg = aaDict[jSeg]
else:
jId = idArr[4]
currSeq= vdjFaDict[jId]
newJseg = getBestJaa(Seq(currSeq))
currDict = findVandJaaMap(newVseg,newJseg,record.seq)
fDict[record.id] = currDict
f.close()
return fDict
def getBestJaa(currSeq):
firstSeq = getNTseq(currSeq)
secondSeq = getNTseq(currSeq[1:])
thirdSeq = getNTseq(currSeq[2:])
pos = 10
seq = ''
found = False
for s in [firstSeq, secondSeq, thirdSeq]:
tempSeq = s[:8]
indF = tempSeq.find('F')
if indF != -1:
if ((indF+3) <= len(s)):
if s[indF+3] == 'G':
found = True
if indF < pos:
pos = indF
seq = s[indF:]
indG = tempSeq.find('G')
if (indG != -1):
if found == False:
if ((indG + 2) <= len(s)):
if s[indG+2] == 'G':
if indG < pos:
found = True
seq = s[indG:]
pos = indG
if ((found == False) & (indF != -1)):
seq = s[indF:]
if seq != '':
return seq
else:
return firstSeq
def getBestVaa(currSeq):
firstSeq = getNTseq(currSeq)
secondSeq = getNTseq(currSeq[1:])
thirdSeq = getNTseq(currSeq[2:])
pos = 10
seq = ''
for s in [firstSeq, secondSeq, thirdSeq]:
#print "S: " + s
tempSeq = s[-8:]
#print "tempSeq: " + tempSeq
ind = tempSeq.find('C')
stopInd = tempSeq.find('*')
#print "Ind: " + str(ind)
if ((ind != -1) & (stopInd == -1)):
#print "inside the ind"
if ind < pos:
goodRF = isGoodRF(s)
if goodRF:
pos = ind
seq = s[:-8+ind + 1]
if seq != '':
return seq
else:
return firstSeq
def isGoodRF(s):
mInd = s.find('M')
if mInd == -1:
return False
stopInd = s.find('*')
if stopInd == -1:
return True
stopIndNext = s[stopInd+1:].find('*')
while stopIndNext != -1:
stopInd = stopIndNext + stopInd + 1
stopIndNext = s[stopInd+1:].find('*')
mInd = s[stopInd+1:].find('M')
mInd = mInd + stopInd + 1
if mInd != -1:
return True
else:
return False
def findVandJaaMap(vSeg,jSeg,fullSeq):
fDict = dict()
firstSeq = getNTseq(fullSeq)
secondSeq = getNTseq(fullSeq[1:])
thirdSeq = getNTseq(fullSeq[2:])
ntArr = [fullSeq, fullSeq[1:],fullSeq[2:]]
aaSeqsArr = [firstSeq, secondSeq, thirdSeq]
cdrArr = []
posArr = []
fPharr = []
for aaSeq in aaSeqsArr:
(cdr, pos, curPh) = getCDR3(aaSeq, vSeg,jSeg)
cdrArr.append(cdr)
posArr.append(pos)
fPharr.append(curPh)
maxLen = 0
bestCDR = ''
bestSeq = ''
hasStop = False
bestPos = -1
bestCDRnt = ''
foundGood = False
vPos = -1
jPos = -1
fPh = False
for i in range(0,3):
if posArr[i] != -1:
if ((cdrArr[i] != 'Only J') & (cdrArr[i] != 'Only V')):
if len(cdrArr[i]) > maxLen:
if cdrArr[i].find('*') == -1:
foundGood = True
bestCDR = cdrArr[i]
bestPos = posArr[i]
maxLen = len(cdrArr[i])
bestSeq = ntArr[i]
fPh = fPharr[i]
else:
if maxLen == 0:
foundGood = True
bestPos = posArr[i]
bestCDR = cdrArr[i]
maxLen = len(cdrArr[i])
bestSeq = ntArr[i]
hasStop = True
fPh = fPharr[i]
else:
if hasStop == True:
if cdrArr[i].find('*') == -1:
foundGood = True
bestPos = posArr[i]
hasStop = False
bestCDR = cdrArr[i]
maxLen = len(cdrArr[i])
bestSeq = ntArr[i]
fPh = fPharr[i]
else:
if not foundGood:
fPh = fPharr[i]
if (cdrArr[i] == 'Only J'):
jPos = posArr[i]-i
elif (cdrArr[i] == 'Only V'):
vPos = posArr[i]-i
if ((vPos != -1) & (jPos != -1) & (not foundGood)):
bestCDRnt = fullSeq[3*vPos:3*jPos]
bestCDR = 'NA'
elif bestPos != -1:
bestCDRnt = bestSeq[3*bestPos : 3*bestPos+3*len(bestCDR)]
if bestCDR.find('*') != -1:
stat = 'Unproductive - stop codon'
elif fPh:
stat = 'Productive (no 118 PHE found)'
else:
stat = 'Productive'
if maxLen == 0:
if (('Only J' in cdrArr) & ('Only V' in cdrArr)):
stat = 'Unproductive - Frame shift'
else:
if (('Only J' not in cdrArr) & ('Only V' in cdrArr)):
stat = 'Unproductive - found only V segment'
elif (('Only J' in cdrArr) & ('Only V' not in cdrArr)):
stat = 'Unproductive - found only J segment'
elif (('Only J' not in cdrArr) & ('Only V' not in cdrArr)):
stat = 'Unproductive - didn\'t find V and J segment'
else:
stat = 'Unproductive'
bestCDR = 'NA'
bestCDRnt = 'NA'
fDict['stat'] = stat
fDict['CDR3 AA'] = bestCDR
fDict['CDR3 NT'] = bestCDRnt
fDict['Full Seq'] = fullSeq
return fDict
def getCDR3(aaSeq, vSeq, jSeq):
minDist = 14
pos = -1
for i in range(0,len(aaSeq) - len(vSeq) + 1):
subAA = aaSeq[i:i+len(vSeq)]
if len(subAA) != len(vSeq):
sys.stderr.write(str(datetime.datetime.now()) + ' Error! Wrong sub length\n')
sys.stderr.flush()
dist = 0
for k in range(0,len(vSeq)):
if vSeq[k] != subAA[k]:
dist += 1
if ((dist < minDist) & (subAA.endswith('C'))):
minDist = dist
pos = i + len(vSeq)
jPos = -1
minDistJ = 4
curPh = False
for j in range(pos+1, len(aaSeq) - len(jSeq) + 1):
subAA = aaSeq[j: j + len(jSeq)]
if len(subAA) != len(jSeq):
sys.stderr.write(str(datetime.datetime.now()) + ' Error! Wrong subj length\n')
sys.stderr.flush()
dist = 0
for m in range(0,len(jSeq)):
if jSeq[m] != subAA[m]:
dist += 1
if (dist <= minDistJ):
if isLegal(subAA):
jPos = j
minDistJ = dist
curPh = False
else:
if dist < minDistJ:
curPh = True
jPos = j
minDistJ = dist
if pos == -1:
if jPos != -1:
return('Only J', jPos, curPh)
else:
return('No V/J found', -1, curPh)
else:
if jPos == -1:
return('Only V',pos, curPh)
return(aaSeq[pos:jPos], pos, curPh )
# Checks that the conserved amino acids remain
def isLegal(subAA):
if (len(subAA)<4):
return False
if (subAA[0] == 'F'):
if ((subAA[1] == 'G') | (subAA[3] == 'G')):
return True
if ((subAA[1] == 'G') & (subAA[3] == 'G')):
return True
if ((subAA[0] == 'G') & (subAA[2] == 'G')):
return True
if subAA.startswith('GR'):
return True
if subAA.startswith('SR'):
return True
return False
def getNTseq(fullSeq):
mod = len(fullSeq) % 3
if mod != 0:
fSeq = fullSeq[:-mod].translate()
else:
fSeq = fullSeq.translate()
return fSeq
def findSeqAndLengthOfAA(aaSeq):
fLen = 0
fSeq = ''
startArr = []
stopArr = []
startM = aaSeq.find('M')
while startM != -1:
startArr.append(startM)
startM = aaSeq.find('M', startM + 1)