-
Notifications
You must be signed in to change notification settings - Fork 20
/
annotateOffs.py
1994 lines (1771 loc) · 70.1 KB
/
annotateOffs.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
# annotate guideseq offtargets with all possible scores we have
import glob, copy, sys, math, operator, random, re, collections, tempfile, subprocess, logging, os, types
import pickle
from collections import defaultdict, Counter
from os.path import basename, join, splitext, isfile, dirname
import glob
logging.basicConfig(loglevel=logging.INFO)
try:
import svmlight # install with 'sudo pip install svmlight'
except:
logging.warn("smvlight library not found. it is only necessary for the fast way to calc chari scores. install it with 'pip install svmlight'")
# for the chari code
import time, gzip, platform
# assignment of activity datasets to genomes
# newer datasets have the genome directly in their filenames,
# e.g. doench2016_hg19
# so no need to add them to this table
datasetToGenome = {
"housden2015": "dm3",
"xu2015Train": "hg19",
"xu2015TrainMEsc": "mm10",
"eschstruth" : "danRer10",
"doench2014-Hs": "hg19",
"doench2014-Mm": "mm9",
"doench2014-CD33Exon2": "hg19",
"varshney2015": "danRer10",
"gagnon2014": "danRer10",
"xu2015": "hg19",
"ren2015": "dm3",
"farboud2015": "ce6",
"schoenig": "hg19",
"schoenigHs": "hg19",
"schoenigMm": "mm9",
"schoenigRn": "rn5",
"schoenigMm-part2": "mm9",
"concordet2-Hs": "hg19",
"concordet2-Mm": "mm9",
"concordet2-Rn": "rn5",
"concordet2": "hg19",
"morenoMateos2015": "danRer7",
"morenoMateos2015": "danRer7",
"alenaNonYuvia" : "danRer10",
"alenaOthers" : "danRer10",
"alenaPerrine" : "danRer10",
"alenaAngelo" : "danRer10",
"alenaYuvia" : "danRer10",
"chari2015Train": "hg19"
}
# the most important datasets and their descriptions
mainDataDescs = {
'varshney2015': "Varshney Zebrafish",
'varshney2015mutF1': "Varshney Zebrafish (F1)",
'varshney2015mutF0': "Varshney Zebrafish (F0)",
'ren2015': "Ren Drosophila Training",
'xu2015TrainHl60': "Wang/Xu KO Training",
'xu2015TrainMEsc': "Koike-Yusa/Xu KO Training",
'gagnon2014': "Gagnon",
'chari2015Train':"Chari Training",
'chari2015Valid_293T':"Chari Validation",
'doench2014-Hs': "Doench 2014 Human",
'doench2016_hg19': 'Doench 2016 Human',
'doench2016azd_hg19': 'Doench 2016 A375/AZD',
'doench20166tg_hg19': 'Doench 2016 A375/6TG',
'doench2016plx_hg19': 'Doench 2016 A375/PLX',
'museumIC50': "Concordet IC50",
'xu2015AAVS1': "Xu Validation AAVS1",
'xu2015FOX-AR': "Xu Validation FOX/AR",
'schoenig': u'Sch\u00F6nig LacZ',
'farboud2015' : "Farboud C.elegans Training",
'eschstruth' : "Eschstruth Zebrafish",
'morenoMateos2015' : "Moreno-Mateos Training",
'alenaAll' : "Shkumatava Dataset",
'housden2015' : "Housden Dros. Training",
'ghandi2016_ci2' : "Gandhi Ciona",
'hart2016-Hct1162lib1Avg' : "Hart Hct116-2L1",
'hart2016-HelaLib2_hg19' : "Hart Hela Lib 2",
'hart2016-HelaLib1_hg19' : "Hart Hela Lib 1",
'teboulVivo_mm9' : "Teboul In Vivo",
'concordet2' : "Concordet",
}
datasetDescs = {
"xu2015Train": "Wang/Xu",
'doench2016azd_hg19': 'Doench 2016 A375/AZD',
"xu2015TrainHl60": "Wang/Xu HL60",
"xu2015TrainKbm7": "Wang/Xu KBM7",
"xu2015TrainMEsc": "Koike-Yusa/Xu Mouse ESC",
'xu2015TrainMEsc1': "Koike-Yusa/Xu 1 Mouse ESC",
'xu2015TrainMEsc2': "Koike-Yusa/Xu 2 Mouse ESC",
"doench2016_hg19": "Doench 2016 Human",
"doench2016_mm9": "Doench 2016 Mouse EL4",
"doench2014-Hs": "Doench 2014 MOLM13/NB4/TF1",
"doench2014-Mm": "Doench 2014 Mouse EL4",
"housden2015": "Housden Dros-S2R+",
"doench2014-CD33Exon2": "Doench 2014 CD33 Exon2",
"doench2014-CD33Exon3": "Doench 2014 CD33 Exon3",
"doench2014-CD13Exon10": "Doench 2014 CD13 Exon10",
"varshney2015": "Varshney",
"varshney2015mutF1": "Varshney Zebrafish (F1)",
"varshney2015mutF0": "Varshney Zebrafish (F0)",
"gagnon2014": "Gagnon",
"xu2015": "Xu Validation",
"xu2015FOX-AR": "Xu KO Validation FOX/AR",
"xu2015AAVS1": "Xu T7 Validation AAVS1",
"ren2015": "Ren Drosophila",
"farboud2015": "Farboud C. elegans",
"morenoMateos2015": "Moreno-Mateos",
"museumT7": "Concordet Indel T7",
"museumIC50": "Concordet Indel IC50",
"schoenig": "Schoenig K562 LacZ Rank",
"eschstruth": "Eschstruth Zebrafish",
"chari2015Train": "Chari Human",
"chari2015Train293T": "Chari 293T",
"alenaAll": "Shkumatava Zebrafish",
"alenaOthers": "Shkumatava Lab: Helene/Yuvia/Antoine",
"alenaPerrine": "Shkumatava Lab: Perrine",
"alenaHelene": "Shkumatava Lab: Helene",
"alenaHAP": "Shkumatava Lab: Helene/Antoine/Perrine",
"alenaAntoine": "Shkumatava Lab: Antoine",
"alenaYuvia": "Shkumatava Lab: Yuvia",
"alenaAngelo": "Shkumatava Lab: Angelo",
"concordet2-Hs": "Concordet Human",
"concordet2-Mm": "Concordet Mouse",
"concordet2-Rn": "Concordet Rat",
"concordet2": "Concordet U2OS/MEF/C6 T7Endo",
"chari2015TrainK562": "Chari K562",
"liu2016_mm9": "Liu Neuro2A Surveyor 1/0",
"ghandi2016_ci2" : "Gandhi Ciona Electroporation",
'wang2015_hg19' : "Wang 2015",
'doench2016_hg19' : "Doench 2016 Human",
'doench2016_mm9' : "Doench 2016 Mouse",
'hart2016-HelaLib2Avg' : "Hart Hela Lib 2",
'hart2016-HelaLib1Avg' : "Hart Hela Lib 1",
'hart2016-Hct1161lib1Avg' : "Hart Hct116-1 Lib 1",
'hart2016-Rpe1Avg' : "Hart Rpe",
"chariEval" : "Chari Eval. Set (279 guides)",
"teboulVivo_mm9" : "Teboul Mouse In Vivo",
"teboulVitro_mm9" : "Teboul In Vitro"
}
# a list of all possible score names in our preferred order
allScoreNames = ['doench', 'ssc', 'crisprScan', 'wangOrig', 'chariRank', 'fusi', "drsc", 'finalGc6', 'finalGg', "wuCrispr"]
# and their colors
allScoreColors = ["blue", "red", "orange", "magenta", "orange", "grey", "orange", "black", "black", "lightblue"]
# support scoring types when reading .scores.tab files
scoreTypes = ["wang", "wangOrig", "doench", "ssc", "chariRank", "chariRaw", "crisprScan", 'drsc', "fusi", "wuCrispr"]
def getScoreTypes():
return scoreTypes
def iterTsvRows(inFile, fieldSep="\t", isGzip=False, skipLines=None, \
makeHeadersUnique=False, commentPrefix="#", headers=None):
"""
parses tab-sep file with headers as field names
yields collection.namedtuples
strips "#"-prefix from header line
"""
if isinstance(inFile, str):
if inFile.endswith(".gz") or isGzip:
fh = gzip.open(inFile, 'rb')
else:
fh = open(inFile)
else:
fh = inFile
if headers==None:
line1 = fh.readline()
line1 = line1.strip("\n").strip("#")
headers = line1.split(fieldSep)
headers = [re.sub("[^a-zA-Z0-9_]","_", h) for h in headers]
if makeHeadersUnique:
newHeaders = []
headerNum = defaultdict(int)
for h in headers:
headerNum[h]+=1
if headerNum[h]!=1:
h = h+"_"+str(headerNum[h])
newHeaders.append(h)
headers = newHeaders
if skipLines:
for i in range(0, skipLines):
fh.readline()
Record = collections.namedtuple('tsvRec', headers)
for line in fh:
if commentPrefix!=None and line.startswith(commentPrefix):
continue
line = line.rstrip("\n")
fields = line.split(fieldSep)
#fields = [x.decode(encoding) for x in fields]
try:
rec = Record(*fields)
except Exception, msg:
logging.error("Exception occured while parsing line, %s" % msg)
logging.error("Filename %s" % fh.name)
logging.error("Line was: %s" % line)
logging.error("Does number of fields match headers?")
logging.error("Headers are: %s" % headers)
raise Exception("wrong field count in line %s" % line)
# convert fields to correct data type
yield rec
def parseGuides():
" return guides as dict name -> seq "
guides = {}
guidesExt = {}
for l in open("guides.txt"):
name, seq, extSeq, pos = l.strip().split()
guides[name] = seq
guidesExt[name] = extSeq
return guides, guidesExt
hitScoreM = [0,0,0.014,0,0,0.395,0.317,0,0.389,0.079,0.445,0.508,0.613,0.851,0.732,0.828,0.615,0.804,0.685,0.583]
def calcMitGuideScore(hitSum):
""" Sguide defined on http://crispr.mit.edu/about
Input is the sum of all off-target hit scores. Returns the specificity of the guide.
"""
score = 100 / (100+hitSum)
score = int(round(score*100))
return score
def calcMitGuideScore_offs(guideSeq, otSeqs, maxMm=None, minHitScore=None, minAltHitScore=None):
" calc mit spec score given a guide and a list of off-target sequences "
if maxMm:
newOtSeqs = []
for otSeq in otSeqs:
mmCount, diffLogo = countMms(otSeq, guideSeq)
if mmCount <= maxMm:
newOtSeqs.append(otSeq)
otSeqs = newOtSeqs
# split seqs into main and alt
altOts = []
mainOts = []
for ot in otSeqs:
assert(len(ot)==23)
if ot.endswith("AG") or ot.endswith("GA"):
altOts.append(ot)
else:
assert(ot.endswith("GG"))
mainOts.append(ot)
# calc and filter hit scores
mainHitScores = [calcHitScore(guideSeq, ot) for ot in mainOts]
mainHitScores = [h for h in mainHitScores if h > minHitScore]
altHitScores = [calcHitScore(guideSeq, ot) for ot in altOts]
altHitScores = [h for h in altHitScores if h > minAltHitScore]
mainHitScores.extend(altHitScores)
scoreSum = sum(mainHitScores)
return calcMitGuideScore(scoreSum)
def calcHitScore(string1,string2, startPos=0):
"""
The MIT off-target score
see 'Scores of single hits' on http://crispr.mit.edu/about
startPos can be used to feed sequences longer than 20bp into this function
the most likely off-targets have a score of 100
>>> int(calcHitScore("GGGGGGGGGGGGGGGGGGGG","GGGGGGGGGGGGGGGGGGGG"))
100
>>> int(calcHitScore("AGGGGGGGGGGGGGGGGGGG","GGGGGGGGGGGGGGGGGGGG"))
100
>>> int(calcHitScore("GGGGGGGGGGGGGGGGGGGG","GGGGGGGGGGGGGGGGGGGA"))
41
"""
# The Patrick Hsu weighting scheme
#print string1, string2
if len(string1)==len(string2)==23:
string1 = string1[:20]
string2 = string2[:20]
assert(len(string1)==len(string2)==20)
dists = [] # distances between mismatches, for part 2
mmCount = 0 # number of mismatches, for part 3
lastMmPos = None # position of last mismatch, used to calculate distance
score1 = 1.0
for pos in range(0, len(string1)):
if string1[pos]!=string2[pos]:
mmCount+=1
if lastMmPos!=None:
dists.append(pos-lastMmPos)
score1 *= 1-hitScoreM[pos]
lastMmPos = pos
# 2nd part of the score
if mmCount<2: # special case, not shown in the paper
score2 = 1.0
else:
avgDist = sum(dists)/len(dists)
score2 = 1.0 / (((19-avgDist)/19.0) * 4 + 1)
# 3rd part of the score
if mmCount==0: # special case, not shown in the paper
score3 = 1.0
else:
score3 = 1.0 / (mmCount**2)
score = score1 * score2 * score3 * 100
return score
def parseScores(fname):
" parse a key-val tab-sep file, val is float, return as list (key, val) "
data = []
for line in open (fname):
fs = line.strip().split()
seq, score = fs
seq = seq.strip('"')
score = score.strip('"')
score = float(score)
data.append((seq, float(score)))
return data
def parseSvmOut(fname):
" parse R SVM output file, return as dict seq -> score "
data = {}
for line in open (fname):
fs = line.strip().split()
seq, score = fs
seq = seq.strip('"')
score = score.strip('"')
data[seq] = float(score)
return data
def writeDict(d, fname):
" write dict as a tab file "
ofh = open(fname, "w")
for k, v in d.iteritems():
if type(v)==types.TupleType:
ofh.write("%s\t%s\n" % (k, "\t".join([str(x) for x in v])))
else:
ofh.write("%s\t%s\n" % (k, str(v)))
ofh.close()
def readDictList(fname, isFloat=False):
" read tab-sep file into a defaultdict(list) "
if not isfile(fname):
logging.warn("%s does not exist. Returning empty dict" % fname)
return {}
logging.info("Reading %s" %fname)
data = defaultdict(list)
for line in open(fname):
if line.startswith("#"):
continue
fs = line.rstrip("\n").split("\t")
if len(fs)==2:
k, v = fs
if isFloat:
v = float(v)
else:
k = fs[0]
v = tuple(fs[1:])
if isFloat:
v = tuple([float(x) for x in v])
data[k].append(v)
return data
def readDict(fname, isFloat=False):
" read dict from a tab sep file "
if not isfile(fname):
logging.warn("%s does not exist. Returning empty dict" % fname)
return {}
logging.info("Reading %s" %fname)
data = {}
for line in open(fname):
fs = line.rstrip("\n").split("\t")
if len(fs)==2:
k, v = fs
if isFloat:
v = float(v)
else:
k = fs[0]
v = tuple(fs[1:])
if isFloat:
v = tuple([float(x) for x in v])
data[k] = v
return data
def calcSvmEffScores(seqs):
"""
returns the SVM-calculated efficiency scores from the Wang/Sabatini/Lander paper
"""
writeSvmRows(seqs, "/tmp/temp.txt")
cmd = "cd wangSabatiniSvm/; R --slave --no-save -f scorer.R --args /tmp/temp.txt /tmp/temp.out"
assert(os.system(cmd)==0)
return parseSvmOut("/tmp/temp.out")
svmScores = None
def lookupSvmScore(seq):
" retrieve svm scores from svmScores.tab "
assert(len(seq)==20)
seq = seq.upper()
global svmScores
if svmScores==None:
svmScores = readDict("svmScores.tab", isFloat=True)
return svmScores[seq]
def writeSvmRows(seqs, fname):
""" write the seqs in wang/sabatini SVM format to a file
#>>> writeSvmRows(["ATAGACCTACCTTGTTGAAG"])
"""
tmpFile = open(fname, "w")
#tmpFile = tempfile.NamedTemporaryFile(prefix="svmR")
for row in iterSvmRows(seqs):
tmpFile.write("\t".join([str(x) for x in row]))
tmpFile.write("\n")
tmpFile.close()
def iterSvmRows(seqs):
""" calculate the SVM score from the Wang/Sabatini/Lander paper
>>> list(iterSvmRows(["ATAGACCTACCTTGTTGAAG"]))
[['SEQ', 'BP1A', 'BP1C', 'BP1T', 'BP1G', 'BP2A', 'BP2C', 'BP2T', 'BP2G', 'BP3A', 'BP3C', 'BP3T', 'BP3G', 'BP4A', 'BP4C', 'BP4T', 'BP4G', 'BP5A', 'BP5C', 'BP5T', 'BP5G', 'BP6A', 'BP6C', 'BP6T', 'BP6G', 'BP7A', 'BP7C', 'BP7T', 'BP7G', 'BP8A', 'BP8C', 'BP8T', 'BP8G', 'BP9A', 'BP9C', 'BP9T', 'BP9G', 'BP10A', 'BP10C', 'BP10T', 'BP10G', 'BP11A', 'BP11C', 'BP11T', 'BP11G', 'BP12A', 'BP12C', 'BP12T', 'BP12G', 'BP13A', 'BP13C', 'BP13T', 'BP13G', 'BP14A', 'BP14C', 'BP14T', 'BP14G', 'BP15A', 'BP15C', 'BP15T', 'BP15G', 'BP16A', 'BP16C', 'BP16T', 'BP16G', 'BP17A', 'BP17C', 'BP17T', 'BP17G', 'BP18A', 'BP18C', 'BP18T', 'BP18G', 'BP19A', 'BP19C', 'BP19T', 'BP19G', 'BP20A', 'BP20C', 'BP20T', 'BP20G'], ['ATAGACCTACCTTGTTGAAG', 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]]
"""
offsets = {"A":0,"C":1,"T":2,"G":3}
# construct and write header
headers = ["SEQ"]
fields = []
for i in range(1, 21):
for n in ["A", "C", "T", "G"]:
fields.append("BP"+str(i)+n)
headers.extend(fields)
yield headers
for seq in seqs:
row = []
row.extend([0]*80)
for pos, nucl in enumerate(seq):
nuclOffset = offsets[nucl]
row[pos*4+nuclOffset] = 1
assert(len(seq)==20)
row.insert(0, seq)
yield row
def parseBeds(dirName):
" parse all beds in dir and return as baseFname -> set of (seq,score, count,guideName)"
ret = {}
for fname in glob.glob(dirName+"/*.bed"):
counts = defaultdict(int)
scores = defaultdict(int)
for line in open(fname):
fs = line.rstrip("\n").split("\t")
seq = fs[3]
score = float(fs[4])
counts[seq]+=1
scores[seq]+=score
guideName = basename(fname).split('.')[0]
seqs = set()
for seq, count in counts.iteritems():
score = scores[seq]
seqs.add( (seq, score, count, guideName) )
ret[guideName]= seqs
return ret
def parseFasta(fileObj):
" parse a fasta file, reture dict id -> seq "
seqs = {}
parts = []
seqId = None
for line in fileObj:
line = line.rstrip("\n")
if line.startswith(">"):
if seqId!=None:
seqs[seqId] = "".join(parts)
seqId = line.lstrip(">")
parts = []
else:
parts.append(line)
if len(parts)!=0:
seqs[seqId] = "".join(parts)
return seqs
def parseFastaAsList(fileObj):
" parse a fasta file, return list (id, seq) "
seqs = []
parts = []
seqId = None
for line in fileObj:
line = line.rstrip("\n")
if line.startswith(">"):
if seqId!=None:
seqs.append( (seqId, "".join(parts)) )
seqId = line.lstrip(">")
parts = []
else:
parts.append(line)
if len(parts)!=0:
seqs.append( (seqId, "".join(parts)) )
return seqs
def iterFastaSeqs(fileObj):
" parse a fasta file, yield (id, seq) "
parts = []
seqId = None
for line in fileObj:
line = line.rstrip("\n")
if line.startswith(">"):
if seqId!=None:
yield (seqId, "".join(parts))
seqId = line.lstrip(">")
parts = []
else:
parts.append(line)
if len(parts)!=0:
yield (seqId, "".join(parts))
def parseFlanks(faDir):
seqToFlank = {}
for fname in glob.glob(join(faDir, "*.fa")):
for shortSeq, seq in parseFasta(open(fname)).iteritems():
assert(shortSeq not in seqToFlank)
assert(len(seq)==100)
seqToFlank[shortSeq] = seq
return seqToFlank
def gcCont(seq):
assert(len(seq)==20)
seq = seq.upper()
return int(100*float(seq.count("C")+seq.count("G")) / len(seq))
# DOENCH SCORING
params = [
# pasted/typed table from PDF and converted to zero-based positions
(1,'G',-0.2753771),(2,'A',-0.3238875),(2,'C',0.17212887),(3,'C',-0.1006662),
(4,'C',-0.2018029),(4,'G',0.24595663),(5,'A',0.03644004),(5,'C',0.09837684),
(6,'C',-0.7411813),(6,'G',-0.3932644),(11,'A',-0.466099),(14,'A',0.08537695),
(14,'C',-0.013814),(15,'A',0.27262051),(15,'C',-0.1190226),(15,'T',-0.2859442),
(16,'A',0.09745459),(16,'G',-0.1755462),(17,'C',-0.3457955),(17,'G',-0.6780964),
(18,'A',0.22508903),(18,'C',-0.5077941),(19,'G',-0.4173736),(19,'T',-0.054307),
(20,'G',0.37989937),(20,'T',-0.0907126),(21,'C',0.05782332),(21,'T',-0.5305673),
(22,'T',-0.8770074),(23,'C',-0.8762358),(23,'G',0.27891626),(23,'T',-0.4031022),
(24,'A',-0.0773007),(24,'C',0.28793562),(24,'T',-0.2216372),(27,'G',-0.6890167),
(27,'T',0.11787758),(28,'C',-0.1604453),(29,'G',0.38634258),(1,'GT',-0.6257787),
(4,'GC',0.30004332),(5,'AA',-0.8348362),(5,'TA',0.76062777),(6,'GG',-0.4908167),
(11,'GG',-1.5169074),(11,'TA',0.7092612),(11,'TC',0.49629861),(11,'TT',-0.5868739),
(12,'GG',-0.3345637),(13,'GA',0.76384993),(13,'GC',-0.5370252),(16,'TG',-0.7981461),
(18,'GG',-0.6668087),(18,'TC',0.35318325),(19,'CC',0.74807209),(19,'TG',-0.3672668),
(20,'AC',0.56820913),(20,'CG',0.32907207),(20,'GA',-0.8364568),(20,'GG',-0.7822076),
(21,'TC',-1.029693),(22,'CG',0.85619782),(22,'CT',-0.4632077),(23,'AA',-0.5794924),
(23,'AG',0.64907554),(24,'AG',-0.0773007),(24,'CG',0.28793562),(24,'TG',-0.2216372),
(26,'GT',0.11787758),(28,'GG',-0.69774)]
intercept = 0.59763615
gcHigh = -0.1665878
gcLow = -0.2026259
binDir = "../crispor/bin/Darwin"
baseDir = "../crispor/"
def calcSscScores(seqs):
""" calc the SSC scores from the paper Xu Xiao Chen Li Meyer Brown Lui Gen Res 2015
>>> calcSscScores(["AGCAGGATAGTCCTTCCGAGTGGAGGGAGG"])
{'AGCAGGATAGTCCTTCCGAGTGGAGGGAGG': 0.182006}
"""
assert(len(seqs)!=0) # need at least one sequence
strList = []
for s in seqs:
assert(len(s)==30)
strList.append("%s 0 0 + dummy" % s)
sscIn = "\n".join(strList)
# ../../Darwin/SSC -i /dev/stdin -o /dev/stdout -l 30 -m matrix/human_mouse_CRISPR_KO_30bp.matrix
# AGCAGGATAGTCCTTCCGAGTGGAGGGAGG 187 216 - MYC_exon3_hg19
# AGCAGGATAGTCCTTCCGAGTGGAGGGAGG 0 0 - t
# AGCAGGATAGTCCTTCCGAGTGGAGGGAGG 187 216 - MYC_exon3_hg19 0.182006
sscPath = join(binDir, "SSC")
matPath = join(baseDir, "bin", "src", "SSC0.1", "matrix", "human_mouse_CRISPR_KO_30bp.matrix")
cmd = [sscPath, "-i", "/dev/stdin", "-o", "/dev/stdout", "-l", "30", "-m", matPath]
stdout, stderr = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate(sscIn)
scores = {}
i = 0
for lineIdx, line in enumerate(stdout.split("\n")):
fs = line.split()
if "Processing failed" in line:
raise Exception("SSC returned error, line %d" % lineIdx)
seq, score = fs[0], float(fs[-1])
scores[seq] = score
lineIdx += 1
if lineIdx==len(seqs):
break
return scores
def calcDoenchScore(seq):
assert(len(seq)==30)
score = intercept
guideSeq = seq[4:24]
gcCount = guideSeq.count("G") + guideSeq.count("C")
if gcCount <= 10:
gcWeight = gcLow
if gcCount > 10:
gcWeight = gcHigh
score += abs(10-gcCount)*gcWeight
for pos, modelSeq, weight in params:
subSeq = seq[pos:pos+len(modelSeq)]
if subSeq==modelSeq:
score += weight
return 1.0/(1.0+math.exp(-score))
# Microhomology score from Bae et al, Nat Biotech 2014
def calcMicroHomolScore(seq, left):
""" calculate the micro homology and out-of-frame score for a breakpoint in a 60-80mer
See http://www.nature.com/nmeth/journal/v11/n7/full/nmeth.3015.html
Source code adapted from Supp File 1
From the manuscript:
"On the basis of these observations, we developed a simple formula and a
computer program (Supplementary Fig. 3) to predict the deletion patterns
at a given nuclease target site that are associated with microhomology of
at least two bases (Fig. 1b and Supplementary Note). We assigned a pattern
score to each deletion pattern and a microhomology score (equaling the sum
of pattern scores) to each target site. We then obtained an out-of-frame
score at a given site by dividing the sum of pattern scores assigned to
frameshifting deletions by the microhomology score."
"""
assert(len(seq)>60 and len(seq)<=80)
seq = seq.upper()
length_weight=20.0
right=len(seq)-int(left)
duplRows = []
for k in reversed(range(2,left)):
for j in range(left,left+right-k+1):
for i in range(0,left-k+1):
if seq[i:i+k]==seq[j:j+k]:
length = j-i
dupSeq = seq[i:i+k]
duplRows.append( (dupSeq, i, i+k, j, j+k, length) )
if len(duplRows)==0:
return 0, 0
### After searching out all microhomology patterns, duplication should be removed!!
sum_score_3=0
sum_score_not_3=0
for i in range(len(duplRows)):
n=0
scrap, left_start, left_end, right_start, right_end, length = duplRows[i]
for j in range(i):
_, left_start_ref, left_end_ref, right_start_ref, right_end_ref, _ = duplRows[j]
if (left_start >= left_start_ref) and \
(left_end <= left_end_ref) and \
(right_start >= right_start_ref) and \
(right_end <= right_end_ref) and \
(left_start - left_start_ref) == (right_start - right_start_ref) and \
(left_end - left_end_ref) == (right_end - right_end_ref):
n+=1
if n != 0:
continue
length_factor = round(1/math.exp(length/length_weight),3)
num_GC=scrap.count("G")+scrap.count("C")
score = 100*length_factor*((len(scrap)-num_GC)+(num_GC*2))
if (length % 3)==0:
sum_score_3+=score
elif (length % 3)!=0:
sum_score_not_3+=score
mhScore = sum_score_3+sum_score_not_3
oofScore = ((sum_score_not_3)*100) / (sum_score_3+sum_score_not_3)
return int(mhScore), int(oofScore)
def parseEncode(dirName):
seqSegs = defaultdict(dict)
for fname in glob.glob(dirName+"/*.bed"):
cell = basename(fname).replace("wgEncodeAwgSegmentationCombined", "").split(".")[0]
for line in open(fname):
seq, seg = line.strip().split()
seqSegs[seq].setdefault(cell, []).append(seg)
return seqSegs
def sumReads(gSeq):
" return dict with name -> total number of reads obtained "
ret = {}
for name, beds in gSeq.iteritems():
total = 0
for bed in beds:
score = bed[1]
total+= score
ret[name] = total
return ret
def outputOldTable():
" not used anymore, was a try to use ML to predict OT count "
headers = ["offtargetSeq________", "readCount", "copyCount", "guideName", "readShare", "cutType", "hitScore", "guideSeq", "gcGuide", "flank100Gc", "ggMotifCount", "isMainPam", "isAltPam", "mhScore", "effScore", "repCount", "chromatinType"]
print "\t".join(headers)
seqToSeg = parseEncode("chromatin/annot/")
#seqToFaireSeq = parseEncode("chromatin/faireSeq/")
offtargets = parseBeds("guideSeq")
totals = sumReads(offtargets)
flanks = parseFlanks("guideSeq/flankSeq/")
guideSeqs, guideExtSeqs = parseGuides()
rowsByType = defaultdict(list)
for name, guideSeq in guideSeqs.iteritems():
totalReads = totals[name]
for off in offtargets[name]:
offSeq, readCount, seqCount, guideName = off
flankSeq = flanks[offSeq]
repCount = flankSeq.count("a")+flankSeq.count("c")+flankSeq.count("t")+flankSeq.count("g")
offSeq = offSeq.upper()
flankSeq = flankSeq.upper()
flankGc = gcCont(flankSeq)
ggCount = flankSeq[60:80].count("GG")
hitScore = calcHitScore(offSeq[:20], guideSeq[:20])
gcGuide = gcCont(guideSeq)
if gcGuide > 70:
continue
seq80 = flankSeq[10:90]
mhScore, oofScore = calcMicroHomolScore(seq80, 47) # breakpoint at -3 before NGG site (at 50)
seq30 = flankSeq[36:66]
effScore = int(100*calcDoenchScore(seq30))
isMainPam = offSeq.endswith("GG")
isAltPam = offSeq.endswith("GA") or offSeq.endswith("AG")
#isFaire = seqToFaireSeq.get(offSeq, False)
# encode annotations
encCells = seqToSeg[offSeq]
#encCellStrs = ["%s=%s" % (cell, ",".join(types)) for cell, types in encCells.items()]
#encCellStr = "|".join(encCellStrs)
counter = Counter()
for cell, types in encCells.iteritems():
if len(types)==1:
counter[types[0]]+=1
if len(counter)==0:
encType = "NoAnnot"
else:
encType, encCount = counter.most_common(1)[0]
readShare = float(readCount) / totalReads
if readShare > 0.01:
guideType = "strong"
else:
guideType = "weak"
readShare = "%.3f" % (readShare)
row = list(off)
row.extend([readShare, guideType, hitScore, flankSeq[40:60], gcGuide, flankGc, ggCount, int(isMainPam), int(isAltPam), mhScore, effScore, repCount, encType])
rowsByType[guideType].append(tuple(row))
maxCount = len(rowsByType["strong"])
for rowsByType, rows in rowsByType.iteritems():
random.shuffle(rows)
rows = rows[:maxCount]
rows.sort(key=operator.itemgetter(1), reverse=True)
for row in rows:
row = [str(x) for x in row]
print "\t".join(row)
def compSeq(str1, str2):
" return a string that marks mismatches between str1 and str2 with * "
s = []
for x, y in zip(str1, str2):
if x==y:
s.append(".")
else:
s.append("*")
return "".join(s)
def removeOneNucl(seq):
" construct 20 sequences, each one with one nucleotide deleted "
for i in range(0, 20):
yield seq[:i]+seq[i+1:]
def countMms(string1, string2):
""" count mismatches between two strings, return mmCount, diffLogo
uses only the first 20 nucleotides
>>> countMms("CCTGCCTCCGCTCTACTCACTGG", "TCTGCCTCCTTTATACTCACAGG")
(4, '*........**.*.......')
"""
if len(string1)==23:
string1 = string1[:20]
string2 = string2[:20]
mmCount = 0
string1 = string1.upper()
string2 = string2.upper()
diffLogo = []
for pos in range(0, len(string1)):
if string1[pos]!=string2[pos]:
mmCount+=1
diffLogo.append("*")
else:
diffLogo.append(".")
return mmCount, "".join(diffLogo)
def findGappedSeqs(guideSeq, offtargetSeq, minMm=9999):
""" return list of gapped versions of otSeq with lower mismatch count than mmCount
the mismatch count of the gapped sequences have to be at least lower than
minMm otherwise nothing will be returned.0
>>> findGappedSeqs("AATAGC", "AATTAG")
(1, ['AATAG(C)'], ['ATTAG'], ['.*...'])
>>> findGappedSeqs("AATAGC", "AATTAG")
(1, ['AATAG(C)'], ['ATTAG'], ['.*...'])
>>> findGappedSeqs("CGTACA", "AAGTCA")
(1, ['CGT(A)CA'], ['AGTCA'], ['*....'])
>>> findGappedSeqs("TGGATGGAGGAATGAGGAGT", "GAGGATGGGGAATGAGGAGT")
(1, ['TGGATGG(A)GGAATGAGGAGT'], ['AGGATGGGGAATGAGGAGT'], ['*..................'])
>>> findGappedSeqs("TGGATGGAGGAATGAGGAGT", "GAGGATGGGGAATGAGGAGT")
(1, ['TGGATGG(A)GGAATGAGGAGT'], ['AGGATGGGGAATGAGGAGT'], ['*..................'])
>>> findGappedSeqs("AATAGC", "AATTAG", 1)
(1, [], [], [])
"""
# AATAGC
# AATTAG
# becomes:
# AATAG
# AATAG
# and:
# CGTACA
# AAGTCA -> 4 mismatches
# **
# best gapped version is
# CGTAC
# AGTCA -> 1 mismatch
# remove either first or last bp from guide
offtarget1 = offtargetSeq[1:]
offtarget2 = offtargetSeq[:-1]
# remove one bp in turn from guideSeq
guideSeqs = defaultdict(list)
logos = defaultdict(list)
gapPos = defaultdict(list)
otSeqs = defaultdict(list)
for i, gappedGuideSeq in enumerate(removeOneNucl(guideSeq)):
for offtargetSeq in [offtarget1, offtarget2]:
mm, diffLogo = countMms(offtargetSeq, gappedGuideSeq)
if mm < minMm:
minMm = mm
gapPos[mm].append(i)
logos[mm].append(diffLogo)
guideSeqs[mm].append(guideSeq[:i]+"("+guideSeq[i]+")"+guideSeq[i+1:])
otSeqs[mm].append(offtargetSeq)
return minMm, guideSeqs[minMm], otSeqs[minMm], logos[minMm]
def countMmsAndLogo(string1, string2):
" count mismatches between two strings also return mismatch ASCII logo"
mmCount = 0
string1 = string1.upper()
string2 = string2.upper()
diffLogo = []
for pos in range(0, len(string1)):
if string1[pos]!=string2[pos]:
mmCount+=1
diffLogo.append("*")
else:
diffLogo.append(".")
return mmCount, "".join(diffLogo)
def parseOfftargets(fname, maxMismatches, onlyAlt, validPams):
""" parse the annotated validated off-target table and return as dict
guideSeq -> otSeq -> modifFreq and another dict guideName -> guideSeq
"""
otScores = defaultdict(dict)
guideSeqs = dict()
print "parsing %s" % fname
skipCount = 0
for row in iterTsvRows(fname):
#print fname, int(row.mismatches), maxMismatches
if int(row.mismatches)>maxMismatches:
#print "skip", row
skipCount += 1
continue
if validPams!=None and not row.otSeq[-2:] in validPams:
print "not using off-target %s/%s, PAM is not in %s" % (row.name, row.otSeq, validPams)
continue
guideSeqs[row.name] = row.guideSeq
if onlyAlt and not row.otSeq[-2:] in ["AG", "GA"]:
continue
otScores[row.guideSeq][row.otSeq] = float(row.readFraction)
print "Skipped %d rows with more than %d mismatches" % (skipCount, maxMismatches)
return otScores, guideSeqs
def parseRawOfftargets(inFname):
""" parse the raw list of off-targets, in the format of offtargets.tsv.
returns list of rows and a dict guideName -> guideSeq
"""
targetSeqs = {}
inRows = []
for row in iterTsvRows(inFname):
#if removeCellLine:
# by removing the prefix before /, treat Kim's two cell lines as one experiment
#study = row.name.split("_")[0].split("/")[0]
if row.type=="on-target":
targetSeqs[row.name] = row.seq
else:
inRows.append(row)
return inRows, targetSeqs
def parseOfftargetsWithNames(fname, maxMismatches, onlyAlt, validPams, useOtNames=False):
""" parse the annotated validated off-target table and return as dict
(guideSeq, guideName) -> otSeq -> modifFreq and another dict guideName -> guideSeq
"""
otScores = defaultdict(dict)
guideSeqs = dict()
print "parsing %s" % fname
skipCount = 0
for row in iterTsvRows(fname):
#print fname, int(row.mismatches), maxMismatches
if int(row.mismatches)>maxMismatches:
#print "skip", row
skipCount += 1
continue
if validPams!=None and not row.otSeq[-2:] in validPams:
print "not using off-target %s/%s, PAM is not NGG/NGA/NAG" % (row.name, row.otSeq)
continue
if onlyAlt and not row.otSeq[-2:] in ["AG", "GA"]:
continue
name = row.name
if useOtNames:
name = row.otName
otScores[(name, row.guideSeq)][row.otSeq] = float(row.readFraction)
print "Skipped %d rows with more than %d mismatches" % (skipCount, maxMismatches)
return otScores
def parseMit(dirName, guideSeqs):
" parse the MIT csv files, return a dict with guideSeq -> otSeq -> otScore "
#fnames= glob.glob(dirName+"/*.csv")
#print targetSeqs
data = defaultdict(dict)
for guideName in guideSeqs:
#"for fname in fnames:
guideNameNoCell = guideName.replace("/K562", "").replace("/Hap1","")
fname = join(dirName, guideNameNoCell+".csv")
study = guideName.split("_")[0]
#if study in ignoreStudies:
#continue
#if guideName not in targetSeqs:
#print "MIT off-target data without bench data: %s" % guideName
#continue
print "parsing %s" % fname
if not isfile(fname):
logging.error("MISSING: %s" % fname)
continue
for line in open(fname):
if line.startswith("guide"):
continue
fs = line.split(", ")
otSeq = fs[4]
score = fs[6]
if fs[7]=="True":
# ontarget
continue
guideSeq = guideSeqs[guideName]
data[guideSeq][otSeq]=float(score)
return data
def calcOtScores(predScores, scoreFunc):
#def calcOtScores(predScores, scoreFunc, notNone=False):
"""
convert a dict guideSeq -> otSeq -> otScore from the MIT otScore to another
Score. possible scoring functions are:
- calcCcTopScore from CCTop
- calcHsuSuppScore
- calcHitScore from the MIT website
- calcCfdScore from Doench et al
"""
newScores = dict()
for guideSeq, otDict in predScores.iteritems():
#print "Converting guide %s" % guideSeq
guideDict = dict()
for otSeq, otScore in otDict.iteritems():
assert("N" not in otSeq)
newScore = scoreFunc(guideSeq, otSeq)
assert(newScore is not None)
#if notNone: