-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtagdigger_fun.py
1924 lines (1827 loc) · 91.6 KB
/
tagdigger_fun.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
# Functions and restriction enzyme data for the Python program TagDigger,
# created by Lindsay V. Clark.
import gzip
import csv
import hashlib
import os
import sys
import bisect
import re
# confirm that Python 3 is being used.
if sys.version_info.major < 3 or (sys.version_info.major == 3 and sys.version_info.minor < 3):
print("Python 3.3 or higher required. You appear to be using an older version of Python.")
raise Exception("Python 3 required.")
# dictionary of restriction enzyme cut sites, including only what will show
# up after the barcode.
enzymes = {'ApeKI': 'CWGC', 'EcoT22I': 'TGCAT', 'NcoI': 'CATGG',
'NsiI': 'TGCAT', 'PstI': 'TGCAG', 'SbfI': 'TGCAGG', 'None': ''}
# dictionary of possible adapter sequences to find.
# Restriction site listed first, with ^ indicating the end of genomic
# sequence that we would expect to find. Then top strand adapter sequence,
# not including the restriction site overhang. [barcode] indicates where the
# reverse complement of the barcode should be located.
adapters = {'PstI-MspI-Hall': [('CCG^G', # Sacks lab, designed by Megan Hall (I think)
'CTCAGGCATCACTCGATTCCTCCGTCGTATGCCGTCTTCTGCTTG'),
('CTGCA^G',
'[barcode]AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT')],
'NsiI-MspI-Hall': [('CCG^G', # Sacks lab, NsiI, with above adapters
'CTCAGGCATCACTCGATTCCTCCGTCGTATGCCGTCTTCTGCTTG'),
('ATGCA^T',
'[barcode]AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT')],
'PstI-MspI-Clark': [('CCG^G', # Sacks lab, altered for full P7 sequence
'CTCAGGCATCACTCGATTCCTATCTCGTATGCCGTCTTCTGCTTG'),
('CTGCA^G',
'[barcode]AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT')],
'NsiI-MspI-Clark': [('CCG^G', # Sacks lab, NsiI, with above adapters for full P7 sequence
'CTCAGGCATCACTCGATTCCTATCTCGTATGCCGTCTTCTGCTTG'),
('ATGCA^T',
'[barcode]AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT')],
'PstI-MspI-Poland': [('CCG^G', # DOI: 10.1371/journal.pone.0032253
'AGATCGGAAGAGCGGTTCAGCAGGAATGCCGAGACCGATCTCGTATGCCGTCTTCTGCTTG'),
('CTGCA^G',
'[barcode]AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT')]
}
# codes for ambiguous nucleotides
IUPAC_codes = {frozenset('AG'): 'R', frozenset('CT'): 'Y',
frozenset('GT'): 'K', frozenset('AC'): 'M',
frozenset('CG'): 'S', frozenset('AT'): 'W',
frozenset('CGT'): 'B', frozenset('AGT'): 'D',
frozenset('ACT'): 'H', frozenset('ACG'): 'V',
frozenset('ACGT'): 'N',
frozenset('A'): 'A', frozenset('C'): 'C',
frozenset('G'): 'G', frozenset('T'): 'T'}
# Function definitions.
def combine_barcode_and_cutsite(barcodes, cutsite):
'''Add restriction cut sites to the end of each barcode in a list,
to make searching for barcode + cutsite more efficient. Convert
to upper case.'''
assert all([set(barcode.upper()) <= set('ACGT') for
barcode in barcodes]), "Non-ACGT barcode."
assert set(cutsite.upper()) <= set('ACGT'), "Invalid cut site."
# Note that cut sites have already been enumerated and therefore should not
# have ambiguous letters at this point.
return [(barcode + cutsite).upper() for barcode in barcodes]
def tree_one_level(num_seq):
'''Take a set of sequences, sort them by the first letter, return
a set of lists. num_seq is a list of lists, where each list has
the sequence and its index number.'''
# if we have gotten to the end of a sequence
if len(num_seq[0][0]) == 0:
return num_seq[0]
# if we need to split sequences up by the first letter
else:
mysubtree = [['A',[]],['C',[]],['G',[]],['T',[]]]
for s in num_seq:
assert len(s[0]) > 0, "Problematic sequence: {}. Likely due to overlapping tags.".format(s[1])
myind = "ACGT".find(s[0][0])
s[0] = s[0][1:]
mysubtree[myind][1].append(s)
return mysubtree
def tree_recursive(num_seq):
'''Build tree recursively for indexing sequences (either barcodes or
tags) rapidly.'''
mysubtree = tree_one_level(num_seq)
if len(mysubtree[0]) > 0:
for i in range(4):
if len(mysubtree[i][1]) > 0:
mysubtree[i][1] = tree_recursive(mysubtree[i][1])
return mysubtree
def build_sequence_tree(sequences, numseq):
'''Give each sequence a number to use for indexing, then build tree.
numseq is maximum number to use for indexing, which is len(sequences)
unless there are multiple cutsites (like with ApeKI).'''
myindex = 0
seqlist = []
for s in sequences:
seqlist.append([s, myindex])
myindex += 1
if myindex == numseq:
myindex = 0
if(numseq == 1 and sequences == ['']):
result = [['A', ['', 0]], ['C', ['', 0]], ['G', ['', 0]], ['T', ['', 0]]]
else:
result = tree_recursive(seqlist)
return(result)
def sequence_index_lookup(sequence, seqtree):
'''Lookup a sequence in an index tree, and get the index. Return -1 if
the sequence is not in the index tree.'''
# If we are out of sequence
if len(sequence) == 0:
return -1
# If we get an N or something else not in ACGT:
if sequence[0] not in {'A', 'C', 'G', 'T'}:
return -1
# If we do have a normal nucleotide, get its index for the tree
myind = "ACGT".find(sequence[0])
# If we have gotten to the point where we can tell the sequence
# does not exist in this set:
if len(seqtree[myind][1]) == 0:
return -1
# If we have gotten to the end of the sequence and can retrieve the index:
if len(seqtree[myind][1][0]) == 0:
return seqtree[myind][1][1]
# otherwise go to the next nucleotide
return sequence_index_lookup(sequence[1:], seqtree[myind][1])
def enumerate_cut_sites(cutsite):
'''Given an ambiguous cut site written in IUPAC codes, generate all
possible cut sites.'''
cutsites = [cutsite]
while cutsites[0].find('R') > -1:
newcutsites = [x.replace('R', 'A', 1) for x in cutsites]
newcutsites += [x.replace('R', 'G', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('Y') > -1:
newcutsites = [x.replace('Y', 'C', 1) for x in cutsites]
newcutsites += [x.replace('Y', 'T', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('K') > -1:
newcutsites = [x.replace('K', 'G', 1) for x in cutsites]
newcutsites += [x.replace('K', 'T', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('M') > -1:
newcutsites = [x.replace('M', 'A', 1) for x in cutsites]
newcutsites += [x.replace('M', 'C', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('S') > -1:
newcutsites = [x.replace('S', 'C', 1) for x in cutsites]
newcutsites += [x.replace('S', 'G', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('W') > -1:
newcutsites = [x.replace('W', 'A', 1) for x in cutsites]
newcutsites += [x.replace('W', 'T', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('B') > -1:
newcutsites = [x.replace('B', 'C', 1) for x in cutsites]
newcutsites += [x.replace('B', 'G', 1) for x in cutsites]
newcutsites += [x.replace('B', 'T', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('D') > -1:
newcutsites = [x.replace('D', 'A', 1) for x in cutsites]
newcutsites += [x.replace('D', 'G', 1) for x in cutsites]
newcutsites += [x.replace('D', 'T', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('H') > -1:
newcutsites = [x.replace('H', 'A', 1) for x in cutsites]
newcutsites += [x.replace('H', 'C', 1) for x in cutsites]
newcutsites += [x.replace('H', 'T', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('V') > -1:
newcutsites = [x.replace('V', 'A', 1) for x in cutsites]
newcutsites += [x.replace('V', 'C', 1) for x in cutsites]
newcutsites += [x.replace('V', 'G', 1) for x in cutsites]
cutsites = newcutsites
while cutsites[0].find('N') > -1:
newcutsites = [x.replace('N', 'A', 1) for x in cutsites]
newcutsites += [x.replace('N', 'C', 1) for x in cutsites]
newcutsites += [x.replace('N', 'G', 1) for x in cutsites]
newcutsites += [x.replace('N', 'T', 1) for x in cutsites]
cutsites = newcutsites
return cutsites
def find_tags_fastq(fqfile, barcodes, tags, cutsite="TGCAG",
maxreads=5e9, tassel_tagcount = False):
'''Make indexing trees for barcodes, cut sites, and tags, then go
through a FASTQ file and count up instances of barcode*tag combos.'''
# asserts
assert all([set(barcode.upper()) <= set('ACGT') for
barcode in barcodes]), "Non-ACGT barcode."
cutsite = cutsite.upper()
assert set(cutsite) <= set('ACGTNRYKMSWBDHV'), "Invalid cut site."
tags = [tag.upper() for tag in tags]
assert all([set(tag) <= set('ACGT') for tag in tags]), \
"Non-ACGT tag."
# Get cut site length
cutlen = len(cutsite)
# Get lengths of all barcodes + cut site
barcutlen = [len(x) + cutlen for x in barcodes]
# Get number of barcodes
barnum = len(barcodes)
# Make multiple cut sites if there are any ambiguous bases.
cutsites = enumerate_cut_sites(cutsite)
# Combine barcodes with cut sites.
barcut = []
for cut in cutsites:
barcut += combine_barcode_and_cutsite(barcodes, cut)
# Make indexing tree for barcodes + cut sites.
barcuttree = build_sequence_tree(barcut, barnum)
# If we see every tag starting with a cut site:
if set([x[:cutlen] for x in tags]).issubset(set(cutsites)):
# If there is only one possible cut site, remove it from tags since
# we already checked for it when checking for barcodes.
if(len(cutsites) == 1):
tags = [x[cutlen:] for x in tags]
else:
# If there are multiple cutsites, we need to keep them as part of the
# tags (they may contain a relevant SNP) and adjust the starting
# position for where we will read tags in the FASTQ sequences.
barcutlen = [x - cutlen for x in barcutlen]
# Make indexing tree for tags.
tagtree = build_sequence_tree(tags, len(tags))
# Set up matrix to contain tag counts. First index is barcode and second
# index is tag.
mycounts = [[0 for x in range(len(tags))] for x in range(barnum)]
# Open connection to FASTQ file.
if fqfile[-2:].lower() == 'gz':
fqcon = gzip.open(fqfile, 'rt')
else:
fqcon = open(fqfile, 'r')
# Loop through sequence reads and search for tags.
try:
readscount = 0
barcutcount = 0
tagcount = 0
lineindex = 0
for line in fqcon:
if lineindex % 4 == 0 and tassel_tagcount:
# extract counts if the file is converted from a TASSEL tagCount file
thesecounts = int(line[line.find("count=")+6:].strip())
if lineindex % 4 == 1: # lines with sequence
readscount += 1
line1 = line.strip().upper()
barindex = sequence_index_lookup(line1, barcuttree)
if barindex > -1: # if barcode and cut site have a match
barcutcount += 1
tagindex = sequence_index_lookup(line1[barcutlen[barindex]:],
tagtree)
if tagindex > -1: # if the sequence matches an expected tag
tagcount += 1
if tassel_tagcount:
mycounts[barindex][tagindex] += thesecounts
else:
mycounts[barindex][tagindex] += 1
if readscount % 1000000 == 0:
print(fqfile)
if readscount % 50000 == 0:
print("Reads: {0} With barcode and cut site: {1} With tag: {2}".format(readscount, barcutcount, tagcount))
if readscount >= maxreads: # stop loop if we get to max reads
break
lineindex += 1
finally:
fqcon.close()
return mycounts
def isFastq(filename):
'''Check the first four lines of a file, return 1 if is it an unzipped
FASTQ file, 2 if it is gzipped FASTQ file, and 0 if it is neither or
if it can't be opened.'''
try:
# determine whether to open as zipped or not
if filename[-2:].lower() == 'gz':
mycon = gzip.open(filename, 'rt')
myresult = 2
else:
mycon = open(filename, 'r')
myresult = 1
except IOError:
myresult = 0
else:
try:
thisline = mycon.readline() # first line is comment
if thisline[0] != '@':
myresult = 0
thisline = mycon.readline() # second line is sequence
if not set(thisline.strip()) <= {'A', 'C', 'G', 'T', 'N',
'a', 'c', 'g', 't', 'n'}:
myresult = 0
thisline = mycon.readline() # third line is comment
if thisline[0] != '+':
myresult = 0
finally:
mycon.close()
return myresult
def readBarcodeKeyfile(filename, forSplitter=False):
'''Read in a csv file containing file names, barcodes, and sample names,
and output a dictionary containing this information.
forSplitter: indicates whether this is for the barcode splitter, as
opposed to the tag counter.'''
try:
with open(filename, 'r', newline='') as mycon:
mycsv = csv.reader(mycon)
rowcount = 0
result = dict()
for row in mycsv:
if rowcount == 0:
# read header row
if forSplitter:
fi = row.index("Input File")
bi = row.index("Barcode")
si = row.index("Output File")
else:
fi = row.index("File")
bi = row.index("Barcode")
si = row.index("Sample")
else:
f = row[fi].strip() # file name
b = row[bi].strip().upper() # barcode
s = row[si].strip() # sample
# skip blank lines
if f == "" and b == "" and s == "":
continue
# check row contents
if f == "":
raise Exception("Blank cell found where file name should be in row {}.".format(rowcount + 1))
if s == "":
raise Exception("Blank cell found where sample name should be in row {}.".format(rowcount + 1))
if not set(b) <= {'A', 'C', 'G', 'T'}:
raise Exception("{0} in row {1} is not a valid barcode.".format(b, rowcount + 1))
# check whether this file is already in dict, add if necessary
if f not in result.keys():
result[f] = [[], []] # first list for barcodes, second for samples
if b in result[f][0]:
raise Exception("Each barcode can only be present once for each file.")
# add the barcode and sample
result[f][0].append(b)
result[f][1].append(s)
rowcount += 1
# check that no output file names are duplicated
if forSplitter:
alloutfile = set() # all unique output files
totout = 0 # total number of output files
for k in result.keys():
alloutfile.update(result[k][1])
totout += len(result[k][1])
if len(alloutfile) < totout:
raise Exception("All output files must have unique names for barcode splitter.")
except IOError:
print("Could not read file {}.".format(filename))
result = None
except ValueError:
if forSplitter:
print("File header needed containing 'Input File', 'Barcode', and 'Output File'.")
else:
print("File header needed containing 'File', 'Barcode', and 'Sample'.")
result = None
except Exception as err:
print(err.args[0])
result = None
return result
def compareTags(taglist, trim = True):
'''Find SNP alleles within a set of sequence tags representing the
same locus.'''
assert type(taglist) is list, "taglist must be list."
assert all([set(t) <= set('ATCG') for t in taglist]), \
"taglist must be a list of ACGT strings."
# make sure all tags are same length
if len(set([len(t) for t in taglist])) > 1:
if trim: # trim down to minimum length
minlen = min([len(t) for t in taglist])
taglist = [tag[:minlen] for tag in taglist]
else: # pad out to maximum length
maxlen = max([len(t) for t in taglist])
taglist = [tag.ljust(maxlen, 'N') for tag in taglist]
# get index(es) and nucleotides for variable sites
result =[(i, [t[i] for t in taglist]) for i in range(len(taglist[0])) \
if len(set([t[i] for t in taglist if t[i] != 'N'])) > 1]
return result
def readTags_UNEAK_FASTA(filename, toKeep = None):
'''Read in pairs of tags from a FASTA file output by the TASSEL UNEAK
pipeline. filename is FASTA file, and toKeep is a list of tag names
to retain.'''
linecount = 0
namelist = [] # for storing tag names
seqlist = [] # for storing tag sequences
try:
with open(filename, mode='r') as mycon:
for line in mycon:
if linecount % 4 == 0: # lines with first tag name
if line[:3] != ">TP":
raise Exception("Line {0} of {1} does not start with '>TP'.".format(linecount+1, filename))
tagname1 = line[1:line.rfind("_")]
# get length of real tag (some are padded with A's at the end)
taglength1 = int(line[line.rfind("_")+1:].strip())
if linecount % 4 == 1: # lines with first tag sequence
seq1 = line.strip().upper()
seq1 = seq1[:taglength1]
if not set(seq1) <= set('ACGT'):
raise Exception("Line {0} is not ACGT sequence.".format(linecount+1))
if seq1 in seqlist:
raise Exception("Non-unique sequence found: line {0}.".format(linecount+1))
if linecount % 4 == 2: # lines with second tag name
if line[:3] != ">TP":
raise Exception("Line {0} of {1} does not start with '>TP'.".format(linecount+1, filename))
tagname2 = line[1:line.rfind("_")]
if tagname1[:tagname1.find("_")] != tagname2[:tagname2.find("_")]:
raise Exception("Tag name in line {0} does not match tag name in line {1}.".format(linecount+1, linecount - 1))
# if taglength != int(line[line.rfind("_")+1:].strip()):
# raise Exception("Tag length in line {0} does not match tag length in line {1}.".format(linecount+1, linecount - 1))
## Note: some tag pairs output by UNEAK do have different lengths. Polymorphism in second cut site?
taglength2 = int(line[line.rfind("_")+1:].strip())
if linecount % 4 == 3: # lines with second tag sequence
seq2 = line.strip().upper()
seq2 = seq2[:taglength2]
if not set(seq2) <= set('ACGT'):
raise Exception("Line {0} is not ACGT sequence.".format(linecount+1))
if seq2 in seqlist:
raise Exception("Non-unique sequence found: line {0}.".format(linecount+1))
# determine whether to skip this one if just doing a subset
if toKeep != None and tagname1[:tagname1.find("_")] not in toKeep:
linecount +=1
continue
# if tags are different lengths, make sure that they can be distinguished
minlen = min(taglength1, taglength2)
if taglength1 != taglength2 and seq1[:minlen] == seq2[:minlen]:
print("{} skipped because tags cannot be distinguished.".format(tagname1[:tagname1.find("_")]))
linecount += 1
continue
# determine differences between sequences
diff = compareTags([seq1, seq2])
# add nucleotide to tag name
tagname1 += "_"
tagname1 += diff[0][1][0]
tagname2 += "_"
tagname2 += diff[0][1][1]
# determine which should be the first and second allele, using
# alphabetical order to match hapMap2numeric.
if diff[0][1][0] < diff[0][1][1]:
tagname1 += "_0"
tagname2 += "_1"
else:
tagname1 += "_1"
tagname2 += "_0"
# add names and sequences to lists
namelist.extend([tagname1, tagname2])
seqlist.extend([seq1[:minlen], seq2[:minlen]])
linecount += 1
result = [namelist, seqlist]
except IOError:
print("File {} not readable.".format(filename))
result = None
except Exception as err:
# print("Line {}".format(linecount +1))
print(err.args[0])
result = None
return result
def readTags_Rows(filename, toKeep = None):
'''Read a CSV of sequence tags, where each row has a marker name, an
allele name, and a tag sequence.'''
rowcount = 0
namelist = []
seqlist = []
try:
with open(filename, mode='r') as mycon:
mycsv = csv.reader(mycon)
for row in mycsv:
if rowcount == 0: # header row
if not {"Marker name", "Allele name", "Tag sequence"} <= set(row):
raise Exception("Need 'Marker name', 'Allele name', and 'Tag sequence' in header row.")
mi = row.index("Marker name")
ai = row.index("Allele name")
ti = row.index("Tag sequence")
else: # rows after header row
mname = row[mi].strip() # marker name
if '_' in mname:
raise Exception("Marker {}: marker names cannot contain underscores.".format(mname))
if toKeep != None and mname not in toKeep:
rowcount += 1
continue # skip this marker if it is not in the list of ones we want.
allele = row[ai].strip() # allele name
tag = row[ti].upper().strip() # tag sequence
if not set(tag) <= set('ACGT'):
raise Exception("Tag sequence not formatted as ACGT in row {}.".format(rowcount+1))
if tag in seqlist:
raise Exception("Non-unique sequence found: line {0}.".format(rowcount+1))
namelist.append(mname + '_' + allele)
seqlist.append(tag)
rowcount += 1
result = [namelist, seqlist]
except IOError:
print("File {} not readable.".format(filename))
result = None
except Exception as err:
print(err.args[0])
result = None
return result
def readTags_Columns(filename, toKeep = None):
'''Read a CSV of sequence tags, where each row has a marker name and
two tag sequences representing two alleles.'''
rowcount = 0
namelist = []
seqlist = []
try:
with open(filename, mode='r') as mycon:
mycsv = csv.reader(mycon)
for row in mycsv:
if rowcount == 0:
if not {"Marker name", "Tag sequence 0", "Tag sequence 1"} <= set(row):
raise Exception("Need 'Marker name', 'Tag sequence 0', and 'Tag sequence 1' in header row.")
mi = row.index("Marker name")
ti0 = row.index("Tag sequence 0")
ti1 = row.index("Tag sequence 1")
else: # all rows after header row
mname = row[mi].strip() # marker name
if '_' in mname:
raise Exception("Marker {}: marker names cannot contain underscores.".format(mname))
if toKeep != None and mname not in toKeep:
rowcount +=1
continue # skip this marker if it is not in the list of ones we want.
tag0 = row[ti0].upper().strip() # get tag sequences
tag1 = row[ti1].upper().strip()
if not set(tag0 + tag1) <= set('ACGT'):
raise Exception("Tag sequence not formatted as ACGT in row {}.".format(rowcount+1))
if (tag0 in seqlist) or (tag1 in seqlist):
raise Exception("Non-unique sequence found: line {0}.".format(rowcount+1))
seqlist.append(tag0)
seqlist.append(tag1)
# make allele names
diff = compareTags([tag0, tag1])
t0SNP = ''.join([s[1][0] for s in diff])
t1SNP = ''.join([s[1][1] for s in diff])
namelist.append(mname + '_' + t0SNP + '_0')
namelist.append(mname + '_' + t1SNP + '_1')
rowcount += 1
result = [namelist, seqlist]
except IOError:
print("File {} not readable.".format(filename))
result = None
except Exception as err:
print(err.args[0])
result = None
return result
def readTags_Merged(filename, toKeep = None, allowDuplicates=False):
'''Read a CSV of sequence tags, where each row has a marker name and a
tag sequence with polymorphic nucleotides in square brackets separated
by a forward slash. Because this is the format for the SNP database
produced by the tag manager, and that database might have multiple
markers that share alleles, this function differs from the other
readTags functions in how it handles duplicate tags.'''
rowcount = 0
namelist = []
seqlist = []
try:
with open(filename, mode='r') as mycon:
mycsv = csv.reader(mycon)
for row in mycsv:
if rowcount == 0:
if not {"Marker name", "Tag sequence"} <= set(row):
raise Exception("Need 'Marker name' and 'Tag sequence' in header row.")
mi = row.index("Marker name")
ti = row.index("Tag sequence")
else:
if not set('[/]') < set(row[ti]):
raise Exception("Characters '[/]' not found in row {}.".format(rowcount+1))
mname = row[mi].strip() # marker name
if '_' in mname:
raise Exception("Marker {}: marker names cannot contain underscores.".format(row[mi]))
if toKeep != None and mname not in toKeep:
rowcount += 1
continue # skip this marker if it is not in the list of ones we want.
# find delimiting characters within sequence
p1 = row[ti].find('[')
#p2 = row[ti].find('/')
p3 = row[ti].find(']')
# recreate the tag sequences
subtags = row[ti][p1+1:p3].split('/') # list of versions of the variable region
subtags = [x.strip().upper() for x in subtags]
tags = [(row[ti][:p1] + x + row[ti][p3+1:]).upper().strip().replace('-','') for x in subtags]
if not allowDuplicates and any([x in seqlist for x in tags]):
print("Non-unique sequence found: line {0}.".format(rowcount+1))
print("Marker {} skipped.".format(mname))
rowcount += 1
continue
seqlist.extend(tags)
if not all([set(x) <= set('ACGT') for x in tags]):
raise Exception("Tag sequence not formatted correctly in row {}.".format(rowcount+1))
# generate the allele names
namelist.extend(["{}_{}_{}".format(mname, subtags[i], i) for i in range(len(tags))])
rowcount += 1
result = [namelist, seqlist]
except IOError:
print("File {} not readable.".format(filename))
result = None
except Exception as err:
print(err.args[0])
result = None
return result
def readTags_Stacks(tagsfile, snpsfile, allelesfile, toKeep = None, binaryOnly = False, version = 1):
'''Read tags from the catalog format produced by Stacks.'''
# column numbers for different versions
locusID_tagfile = 2 if version == 1 else 1
sequence_tagfile = 9 if version == 1 else 5
locusID_allelesfile = 2 if version == 1 else 1
haplotype_allelesfile = 3 if version == 1 else 2
locusID_snpsfile = 2 if version == 1 else 1
position_snpsfile = 3 if version == 1 else 2
# read files
try:
alltags = dict() # keys are locus numbers, values are sequences
with gzip.open(tagsfile, mode = 'rt') if tagsfile.endswith('.gz') else open(tagsfile, mode = 'r') as mycon:
tr = csv.reader(mycon, delimiter='\t')
for row in tr:
if row[0].startswith("#"):
continue # skip comment line
if toKeep == None or row[locusID_tagfile] in toKeep:
alltags[row[locusID_tagfile]] = row[sequence_tagfile]
alleles = list() # tuples, where first item is locus number and second is haplotype
with gzip.open(allelesfile, mode = 'rt') if allelesfile.endswith('.gz') else open(allelesfile, mode = 'r') as mycon:
ar = csv.reader(mycon, delimiter='\t')
for row in ar:
if row[0].startswith("#"):
continue
if toKeep == None or row[locusID_allelesfile] in toKeep:
alleles.append((row[locusID_allelesfile], row[haplotype_allelesfile]))
positions = dict() # keys are locus numbers, values are lists of variant positions
with gzip.open(snpsfile, mode = 'rt') if snpsfile.endswith('.gz') else open(snpsfile, mode = 'r') as mycon:
sr = csv.reader(mycon, delimiter='\t')
for row in sr:
if row[0].startswith("#"):
continue
if toKeep == None or row[locusID_snpsfile] in toKeep:
if row[locusID_snpsfile] in positions.keys():
positions[row[locusID_snpsfile]].append(int(row[position_snpsfile]))
else:
positions[row[locusID_snpsfile]] = [int(row[position_snpsfile])]
namelist = []
seqlist = []
# generate tag sequences
for a in alleles:
thislocus = a[0]
consensusseq = alltags[thislocus]
if len(a[1]) == 0: # non-variable tags
outseq = consensusseq
else:
thesepos = positions[thislocus]
outseq = consensusseq[:thesepos[0]] # first non-variable portion
for i in range(len(a[1])):
outseq = outseq + a[1][i]
if i+1 == len(a[1]):
outseq = outseq + consensusseq[thesepos[i]+1:]
else:
outseq = outseq + consensusseq[thesepos[i]+1:thesepos[i+1]]
outseq = outseq.upper()
if not set(outseq) <= set('ACGT'):
print("{}_{} skipped for having non-ACGT nucleotides.".format(a[0], a[1]))
else:
namelist.append(a[0] + '_' + a[1]) # name by locus number and haplotype
seqlist.append(outseq)
# cleanup
if binaryOnly:
markers = extractMarkers(namelist)
newnamelist = []
newseqlist = []
for i in range(len(markers[0])):
if len(markers[1][i][0]) != 2:
continue
index1 = markers[1][i][1][0]
index2 = markers[1][i][1][1]
# give 0 or 1 designation based on alphabetical order
if markers[1][i][0][0] < markers[1][i][0][1]:
newname1 = namelist[index1] + '_0'
newname2 = namelist[index2] + '_1'
else:
newname1 = namelist[index1] + '_1'
newname2 = namelist[index2] + '_0'
newnamelist.extend([newname1, newname2])
newseqlist.extend([seqlist[index1], seqlist[index2]])
namelist = newnamelist
seqlist = newseqlist
return [namelist, seqlist]
except IOError:
print("Files not readable.")
return None
except IndexError:
print("Files in wrong format.")
return None
except ValueError:
print("Files in wrong format.")
return None
except KeyError:
print("Locus names not matching properly.")
return None
except Exception as err:
print(err.args[0])
return None
def readTags_TASSELSAM(filename, toKeep = None, binaryOnly = False, noMonomorphic = False,
writeMarkerKey = False, keyfilename = None):
'''Read tag sequences from a SAM file and match marker names using the
same conventions as TASSEL-GBSv2.
toKeep: an optional list of marker names to keep, in TASSEL-GBSv2 format.
binaryOnly: boolean indicating whether to only keep markers with two tags.
writeMarkerKey: boolean indicating whether to write a key of TASSEL SNP names vs.
tagDigger marker names.
keyfilename: name for marker key file.'''
assert (not writeMarkerKey) or keyfilename != None, "keyfilename needed."
namelist = []
seqlist = []
tempseq = dict() # keys are marker names, values are lists of tags
numdig = 0 # number of digits for indicating alignment position
markerkey = [] # each item will be a tuple containing the TASSEL name for the SNP followed by
# the tagdigger name for the marker.
try:
with open(filename, mode='r') as mycon:
for line in mycon:
if line[0:3] == '@SQ':
# length of number indicating chromosome size
chrsize = len(line.split()[2][3:])
if chrsize > numdig:
numdig = chrsize
continue
elif line[0] == '@':
continue
mycolumns = line.split()
myflags = int(mycolumns[1])
# skip if no alignment (4 flag)
if myflags - 4 in {0, 1, 2, 8, 16, 32, 64, 128}:
continue
# chromosome name
chrom = mycolumns[2] #.upper()
# eliminate underscores in chromosome names
chrom = chrom.replace('_', '*')
# position
pos = int(mycolumns[3])
# strand
if myflags - 16 in {0, 1, 2, 8, 32, 64, 128}:
strand = "bot"
else:
strand = "top"
# sequence
sequence = mycolumns[9]
if strand == 'bot':
sequence = reverseComplement(sequence)
# adjust position to begin at cut site
cigar = mycolumns[5]
deletions = sum([int(x[:-1]) for x in re.findall('\d+D', cigar)])
insertions = sum([int(x[:-1]) for x in re.findall('\d+I', cigar)])
pos = pos + len(sequence) - insertions + deletions - 1
# make marker name and add to dictionary
marker ="{}-{:0>{width}}-{}".format(chrom, pos, strand, width=numdig)
if marker in tempseq.keys():
# check that an overlapping version of this sequence isn't already there (keep shorter version).
# can happen rarely with restriction site polymorphism.
addthisseq = True
tempseq[marker] = [ts for ts in tempseq[marker] if not ts.startswith(sequence)]
for exstseq in tempseq[marker]:
if sequence.startswith(exstseq):
addthisseq = False # this one is longer, don't add it
if addthisseq:
tempseq[marker].append(sequence)
else:
tempseq[marker] = [sequence]
allMarkers = sorted(tempseq.keys())
for m in allMarkers:
thesetags = tempseq[m]
ntags = len(thesetags)
if binaryOnly and ntags != 2:
continue
if noMonomorphic and ntags == 1:
continue
diff = compareTags(thesetags, trim = False)
if toKeep != None or writeMarkerKey: # check if marker is in list to be retained
markerinfo = m.split('-')
chrom = markerinfo[0].upper()
if chrom.startswith("CHROMOSOME"):
chrom = chrom[10:]
if chrom.startswith("CHR"):
chrom = chrom[3:]
# put S at the beginning of chromosome number ## is this always right?
chrom = 'S' + chrom
pos = int(markerinfo[1]) # position of leftmost nucleotide
if markerinfo[2] == 'top':
snppos = [pos + d[0] for d in diff]
else:
snppos = [pos - d[0] for d in diff]
# generate SNP names in TASSEL format
possiblenames = ['{}_{}'.format(chrom, p) for p in snppos]
# skip if none of these SNP names were in the list to keep
if toKeep != None and all([p not in toKeep for p in possiblenames]):
continue
if writeMarkerKey:
# add names to list of markers to write.
for p in possiblenames:
markerkey.append((p, m))
allelenames = [''.join([d[1][i] for d in diff]) for i in range(ntags)]
thesetagnames = [m + '_' + a for a in allelenames]
if binaryOnly and allelenames[0] < allelenames[1]:
thesetagnames[0] += '_0'
thesetagnames[1] += '_1'
if binaryOnly and allelenames[1] < allelenames[0]:
thesetagnames[1] += '_0'
thesetagnames[0] += '_1'
namelist.extend(thesetagnames)
seqlist.extend(thesetags)
if len(namelist) == 0:
raise Exception("No markers output; is list of markers to keep in right format (e.g. S03_350622)?")
except IOError:
print("Could not read file {}.".format(filename))
return None
except Exception as err:
print(err.args[0])
return None
else:
if writeMarkerKey:
try:
with open(keyfilename, mode='w', newline='') as outcon:
cw = csv.writer(outcon)
cw.writerow(["TASSEL-GBSv2 marker name", "TagDigger marker name"])
for mk in markerkey:
cw.writerow(mk)
except IOError:
print("Could not write file {}.".format(keyfilename))
return None
return [namelist, seqlist]
def readTags_pyRAD(filename, toKeep = None, binaryOnly = False):
'''Read the .alleles output from pyRAD and import tags.'''
namelist = [] # for storing tag names
seqlist = [] # for storing tag sequences
theseseq = set() # set of sequences for the first marker
allowedchars = {'A', 'C', 'G', 'T', '-', 'N'}
linenum = 0
def seqformarker(seq, m):
'''Process a group of sequences for one marker.'''
# trim sequences to the length of the shortest one
seqlen = min([len(s) for s in seq])
seq = [s[:seqlen] for s in seq]
while any([s[-1] == '-' for s in seq]):
seq = [s[:-1] for s in seq]
seqlen -= 1
# remove sequences with N's
seq = [s for s in seq if 'N' not in s]
seq = sorted(set(seq)) # sort alphabetically
nseq = len(seq)
nl = [] # to add to namelist
sl = [] # to add to seqlist
if (nseq != 0 and not binaryOnly) or nseq == 2:
# remove gaps from sequences
sl = [s.replace('-','') for s in seq]
# find variable sites for generating tag names
alleles = [[s[i] for s in seq] for i in range(seqlen) if len(set([s[i] for s in seq])) > 1]
alstr = [''.join([a[i] for a in alleles]) for i in range(nseq)]
# make tag names
nl = ['{}_{}_{}'.format(m, alstr[i], i) for i in range(nseq)]
return [nl, sl]
try: # Read file.
with open(filename, mode = 'r') as mycon:
for line in mycon:
if line[0] == '>': # line with sequence data
thisseq = line.split()[1]
if not set(thisseq) <= allowedchars:
raise Exception("Character other than ACGTN- detected in sequence.")
theseseq.add(thisseq) # add the sequence from this line to the set for this marker
elif line[0] == '/': # line with marker number
mrkrnum = line.split()[-1][1:-1] # number for this marker
mrkrnum = mrkrnum.replace("|", "")
mrkrnum = mrkrnum.replace("*", "")
mrkrnum = mrkrnum.replace("-", "")
if toKeep == None or mrkrnum in toKeep:
x = seqformarker(theseseq, mrkrnum)
namelist.extend(x[0]) # add tag names to master list
seqlist.extend(x[1]) # add sequences to master list
theseseq = set() # reset sequences for next marker
else:
raise Exception("File not in pyRAD format.")
linenum += 1 # increment count of which line we are on
result = [namelist, seqlist]
except IOError:
print("File {} not readable.".format(filename))
result = None
except Exception as err:
print("Line {}:".format(linenum))
print(err.args[0])
result = None
return result
def readMarkerNames(filename):
'''Read in a simple list of marker names, and use for selecting markers
to keep from a larger list of tags.'''
try:
with open(filename, mode='r') as mycon:
mylines = mycon.readlines()
except IOError:
print("File {} not readable.".format(filename))
result = None
else:
# clear out commas, whitespace, and empty lines
result = [x.replace(",", "").strip() for x in mylines if \
x.replace(",", "").strip() != ""]
return result
def readTags_interactive():
'''Interactively read in sequence tags. To be used by tagdigger and
tag manager.'''
# read in optional file of marker names
toKeep = None
print('''
Do you wish to supply a list of marker names? If provided, this list
will be used to subset the list of markers in the tag file.''')
thischoice = ""
while thischoice.upper() not in {'Y', 'N'}:
thischoice = input("Y/N: ").strip()
print("")
if thischoice.upper() == 'Y':
while toKeep == None:
toKeep = readMarkerNames(input("File name: ").strip())
# summarize file of marker names
print('''
File contains {} marker names.'''.format(len(toKeep)))
for i in range(min(10, len(toKeep))):
print(toKeep[i])
if len(toKeep) > 10:
print('...')
# list tag file formats:
print('''
Available tag file formats are:
1: UNEAK FASTA
2: Merged tags
3: Tags in columns
4: Tags in rows
5: Stacks catalog
6: SAM file for TASSEL-GBSv2 pipeline
7: pyRAD .alleles output
''')
tagfunctions = {'1': readTags_UNEAK_FASTA,
'2': readTags_Merged,
'3': readTags_Columns,
'4': readTags_Rows,
'5': readTags_Stacks,
'6': readTags_TASSELSAM,
'7': readTags_pyRAD }
# choose format and read tag file
tags = None
while tags == None:
thischoice = '0'
while thischoice not in {'1', '2', '3', '4', '5', '6', '7'}:
thischoice = input("Enter the number of the format of your tag file: ").strip()
if thischoice == '5':
tagsfile = input("Enter the name of the *.catalog.tags.tsv file: ").strip()
snpsfile = input("Enter the name of the *.catalog.snps.tsv file: ").strip()
allelesfile = input("Enter the name of the *.catalog.alleles.tsv file: ").strip()
stksversion = ""
while stksversion not in {"1", "2"}:
stksversion = input("Enter Stacks version (1 or 2): ").strip()[0]
binchoice = ""
while binchoice not in {'Y', 'N'}:
binchoice = input("Only retain binary markers? y/n: ").strip().upper()
tags = readTags_Stacks(tagsfile, snpsfile, allelesfile, toKeep = toKeep,
binaryOnly = binchoice == 'Y', version = int(stksversion))
elif thischoice == '6':
tagfile = input("Enter the file name: ").strip()
binchoice = ""
while binchoice not in {'Y', 'N'}:
binchoice = input("Only retain binary markers? y/n: ").strip().upper()