-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtools.py
executable file
·2162 lines (1958 loc) · 70.4 KB
/
tools.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
import io
import csv
import glob
import os.path
import constants
import re
import sys
import itertools
import operator # for getbds4opt4start()
import subprocess, shlex
import errno # for makedir()
# check character string
def is_None_empty_whitespace(mystr):
if mystr and mystr.strip():
# mystr is not None AND mystr is not empty or whitespaces
return False
# mystr is None OR mystr is empty or whitespaces
return True
# This code makes the assumption that anything that can be iterated over will contain other elements, and should not be
# considered a leaf in the "tree". If an attempt to iterate over an object fails, then it is not a sequence, and hence
# certainly not an empty sequence (thus False is returned). Finally, this code makes use of the fact that all returns
# True if its argument is an empty sequence.
# Note: seq should not contain any character string except ''.
def isEmpty(seq):
try:
return all(map(isEmpty, seq))
except TypeError:
return False
def read_file(file):
fp = open(file, 'r')
content = fp.read()
fp.close()
return content
# Write content into file filePath
def write2file(filePath = None, content = None):
directory = os.path.dirname(filePath)
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise
with open(filePath, 'w') as fp:
fp.write(content)
# Split an multiple-sequence fasta file containing multiple fasta sequences into multiple individual fasta files
# with the file names with sequence id included.
def split_tandem_fasta(huge_fasta_file, output_path):
mfastaFileName = os.path.basename(huge_fasta_file)
fp_fasta = open("/dev/null", "r")
with open(huge_fasta_file, "r") as fp:
for line in fp:
line = line.strip()
if len(line) == 0:
continue
if line[0] == '>':
fp_fasta.close()
seqid = line[1:].split(maxsplit=1)[0]
fasta_file_name = '.'.join([mfastaFileName, seqid])
fasta_file = os.path.join(output_path, fasta_file_name)
fp_fasta= open(fasta_file, "w")
fp_fasta.write(line+'\n')
fp_fasta.close()
# This function returns a generator, using a generator comprehension. The generator returns the string sliced,
# from 0 + a multiple of the length of the chunks, to the length of the chunks + a multiple of the length of the chunks.
# example:
# s = 'CATTCGTCT', tuple(chunkstring(s, 3)) = ('CAT', 'TCG', 'TCT')
# s = 'CATTCGTC', tuple(chunkstring(s, 3)) = ('CAT', 'TCG', 'TC')
#
def chunkstring(string, length):
return (string[i : i + length] for i in range(0, len(string), length))
# Translate gene sequence into peptide sequence.
# Return: 'MKLQFP.....RPQ', peptide sequence represented by single letter
#
# gene2pepTable: (table1, ..., table11, ...)
# table11: {'starts': (initialcodon, ..., initialcondon), codon: aa, ..., codon: aa}
# codon: 'TTT' or 'TTC' or 'TTG' or ... or 'TGA' or 'GGG'
# aa: 'F' or 'L' or ... or '*' or 'G', amino acid when codon is not the initial codon
#
# geneSeq: gene sequence eg. 'CATTCGTCT', it must be the length of 3*integer
# or the last one (or two) letter will be removed.
#
def gene2pep(table='11', geneSeq=''):
if len(geneSeq) < 9:
print('Warning: mini ORF with length < 9 will not be translated', geneSeq)
return ''
pep = []
first3 = geneSeq[:3]
geneCodons = chunkstring(geneSeq[3:], 3)
# translate the first codon in gene sequence
if first3 in constants.gene2pepTable[table]['starts']:
# it is a start codon
pep.append('M')
else:
# it is not a start condon
aa = constants.gene2pepTable[table][first3]
if aa == '*':
print('hello stop codon', first3)
else:
pep.append(aa)
# stop translation if the first codon is the stop codon
#if '*' in pep:
# return '*'
# translate the left codon but stop translation if stop codon is found.
for codon in geneCodons:
# the last codon might be a single-letter string or double-letter string.
if len(codon) != 3:
continue
aa = constants.gene2pepTable[table][codon]
if aa == '*':
print('hello stop codon', codon)
# break
else:
pep.append(aa)
return ''.join(pep)
# Format sequence into FASTA format and return it with header
# header: messeage for header line in fasta format
# seq: sequence to format into FASTA with lineWidth single-letter codes per line
def fasta_format(header, seq):
header = '>' + header
fasta_seq = ''
lineWidth = constants.fastaLineWidth
#for row in chunkstring(seq, lineWidth):
# fasta_seq += row + '\n'
fasta_seq = '\n'.join(chunkstring(seq, lineWidth))
fasta = '{}\n{}\n'.format(header, fasta_seq)
#fasta = header + '\n' + fasta_seq
return fasta
# header, seq: character string
def fastaFormat(header, seq):
header = '>' + header
fasta_seq = ''
fasta_seq = '\n'.join(chunkstring(seq, constants.fastaLineWidth))
fasta = '\n'.join([header, fasta_seq])
return fasta
# get both compound identifier and content of fasta sequence
# seqs: [(id, seq), ..., (id, seq)]
# seq: character string
def getFasta(fastaFile):
fp = open(fastaFile, 'r')
seqs = []
seq = []
id = ''
for line in fp:
if line.replace('\b','').strip() == '':
continue # remove blank line
if line[0] == '>':
if len(seq) > 0:
seqs.append((id, ''.join(seq)))
id = line[1:].split(maxsplit=1)[0]
seq = []
continue
seq.append(line.strip())
if len(seq) > 0:
seqs.append((id, ''.join(seq)))
else:
print('No sequence in', fastaFile)
fp.close()
return seqs
# seqs: [(id, seq), ..., (id, seq)]
# seq: character string
def getFasta_idseq(fastaFile):
fp = open(fastaFile, 'r')
seqs = []
seq = []
id = ''
for line in fp:
if line.strip() == '':
continue # remove blank line
if line[0] == '>':
if len(seq) > 0:
seqs.append((id, ''.join(seq)))
seq = []
id = line[1:].split(maxsplit=1)[0]
continue
seq.append(line.strip())
if len(id) > 0:
seqs.append((id, ''.join(seq)))
else:
print('No sequence in', fastaFile)
fp.close()
return seqs
# get both header and content of fasta sequence
# seqs: [(header, seq), ..., (header, seq)]
# seq: character string
def getFastaFull(file):
seqs = []
with open(file, 'r') as fp:
seq = []
for line in fp:
#line = line.replace('\b', '').strip()
line = line.strip()
if line == '':
continue # remove blank line
if line[0] == '>':
if len(seq) > 0:
seqs.append((header, ''.join(seq)))
seq = []
header = line[1:] # header
continue
seq.append(line)
seqs.append((header, ''.join(seq)))
return seqs
# write IS elements in a genome into a csv file
# genome_is: list, [] or [['ISDge6', 'IS5', 'ISL2', '-', '-', '-', '-', '36785', '36563', '802', '1024', '802', 'Partial'],
# ['ISDge2', 'IS1', '.', '+', '37705', '38452', '748', '-', '-', '-', '-', '', '-'], ...]
# write a empty file if genome_is is empty
def output_csv(csvfile, genome_is):
with open(csvfile, 'w', newline='') as f:
writer = csv.writer(f, lineterminator = '\n', quoting = csv.QUOTE_MINIMAL)
writer.writerows(genome_is)
# Input
# csvfile: character string, full-path file name pointing to a csv file
# rowList: [row, ...]
# row: (item, ...) or [item, ...]
def writeCsvFile(csvfile, rowList, delimiter=','):
with open(csvfile, 'w', newline='') as fp:
spamwriter = csv.writer(fp, delimiter=delimiter, lineterminator='\n')
spamwriter.writerows(rowList)
# get isfinder genome annotation from csv files
def isfinder_IS_in_genome(isfinder_genome_file):
isfinder_genome = []
if not os.path.isfile(isfinder_genome_file):
return isfinder_genome
fp = open(isfinder_genome_file, newline='')
reader = csv.reader(fp, delimiter=',')
for row in reader:
isfinder_genome.append(row)
fp.close()
return isfinder_genome
# Group elements in a sequence by keys indexed by (i, ..., j).
# sequence: (seq1, ..., seq, ..., seqn)
# seqn: [s1, ..., sn]
# index: (i, ..., j), both i and j are integer
# keys: (key1, ..., key, ..., keyn)
# key: (seq[index_i], ..., seq[index_j])
# item_id: dictionary, {key1: [seq1, ..., seqm], ..., keyn: [seq3, ..., seqn]}
def group_by_key(sequence, index):
item_id = {}
for item in sequence:
key = []
for i in index:
key.append(item[i])
key = tuple(key)
if key not in item_id:
item_id[key] = [item]
else:
item_id[key].append(item)
return item_id
# Linearly rescale data values having observed oldMin and oldMax into a new arbitrary range newMin to newMax
# newValue = (newMax - newMin)/(oldMax - oldMin) * (value - oldMin) + newMin
# or
# newValue = a * value + b, when a = (newMax - newMin)/(oldMax - oldMin) and b = newMin - a * oldMin
def rescale(data, newMin, newMax):
oldMin, oldMax = min(data), max(data)
n = len(data)
# all values are equal
if not (oldMin < oldMax):
return (newMin,) * n
a = (newMax - newMin)/(oldMax - oldMin)
b = newMin - a * oldMin
newData = []
for value in data:
newData.append(a * value + b)
return newData
# return True if there is any digit in string
def hasNumbers(string):
return any(char.isdigit() for char in string)
# return True if there is a pair of round brackets in string
# Note: return False if ') precede ('.
def hasBrackets(s):
start = s.find('(')
if start == -1:
return False
start += 1
return ')' in s[start:]
# return string within '(' and ')'
def extract(s):
start = s.find('(')
if start == -1:
return ''
start += 1
end = s.find(')', start)
if end == -1:
return ''
else:
return s[start:end]
# Parse alignment file output by water in EMBOSS and return the alignment
# waterFile: character string, output returned by water
#
# collumns: seq1, seq2:
# 1->6 sequence number of the first residue in alignment
# 7 space character
# 8->-1 aligned sequence with gaps
# collumns: marker
# 1->6 space characters
# 7 space character
# 8->-1 character string composed of '|' (match), '.' (mismatch) and ' ' (gap)
def getAlignByWater(waterFile):
align = []
# if waterFile is file, then open it to readin
# elif waterFile is not a file, then just process it as regular character string.
if os.path.isfile(waterFile):
fp = open(waterFile)
waterFile = fp.read()
fp.close()
else:
waterFile = waterFile.decode()
scoreMarker = '# Score:'
indexScore = waterFile.find(scoreMarker) + len(scoreMarker)
score = float(waterFile[indexScore: waterFile.find('\n', indexScore)])
#print(waterFile)
#print('hello', waterFile[indexScore: waterFile.find('\n', indexScore)])
lines = [line for line in waterFile.split('\n') if line.strip() != '' and line[0] != '#']
if len(lines) > 0:
start1, end1 = int(lines[0][14:20]), int(lines[-3][-6:])
end2, start2 = int(lines[2][14:20]), int(lines[-1][-6:])
#print('hello1', lines[0][14:20], lines[-3][-6:], lines[2][14:20], lines[-1][-6:])
seq1 = marker = seq2 = ''
for tlines in zip(*[iter(lines)]*3):
seq1 += tlines[0][21:-7]
marker += tlines[1][21:]
seq2 += tlines[2][21:-7]
align = [score, (seq1, seq2, marker), (start1, end1, start2, end2)]
return align
# Given a DNA sequence strand, Return its complementary sequence strand
# mode:
# '1', seq is composed of only uppercase letters;
# '2', seq is composed of only lowercase letters;
# '3', seq can be the mixture of lower and upper case letters.
def complementDNA(seq, mode):
if mode == '1':
return seq.translate(str.maketrans(constants.na1u, constants.na2u))
elif mode == '2':
return seq.translate(str.maketrans(constants.na1l, constants.na2l))
elif mode == '3':
return seq.translate(str.maketrans(constants.na1ul, constants.na2ul))
else:
print('Error: incorrect mode in complementDNA', file=sys.stderr)
exit(0)
# Return a cleaned DNA sequence copy where non-standard bases are replaced by 'N'.
def cleanDNA(seq):
bases = []
#stdBases = 'ATCGRYN'
stdBases = 'ATCG'
for base in seq:
if base.upper() in stdBases:
bases.append(base)
else:
bases.append('N')
return ''.join(bases)
# convert cigar sting returned by SSW python interface into the pairs with one number and one character
# for example:
# Return [(4, 'M'), (2, 'I'), (8, 'M'), (1, 'D'), (10, 'M'), (6, 'S')] if cigarString == '4M2I8M1D10M6S'
def parseCigarString(cigarString):
return [(int(pair[:-1]), pair[-1]) for pair in re.findall(r'\d+[MIDNSHP=X]', cigarString)]
# print a alignment into a string
# seq1, seq2: sequences of two aligned DNA strand segment
# cigarStr: '4M2I8M1D10M6S'
# cigarPair: [(4, 'M'), (2, 'I'), (8, 'M'), (1, 'D'), (10, 'M'), (6, 'S')]
# Note: for details of cigar sting, Please check the document "The SAM Format Specification",
# http://samtools.github.io/hts-specs/SAMv1.pdf, particularly the "An example" section and
# "CIGAR: CIGAR string" section.
#
def buildAlignment(sequence1, sequence2, align, cigarStr):
begin1, end1, begin2, end2 = align.ref_begin+1, align.ref_end+1, align.query_begin+1, align.query_end+1
header = { 'conflict': False,
'score': align.score,
'begin1': begin1,
'end1': end1,
'begin2': begin2,
'end2': end2}
seq1name = 'seq1'
seq2name = 'seq2'
line1 = '{:<10} '.format(seq1name)
line2 = '{:<10} '.format(' ')
line3 = '{:<10} '.format(seq2name)
index1, index2 = 0, 0
line1 += '{:>8} '.format(begin1 + index1)
line3 += '{:>8} '.format(begin2 + index2)
line2 += '{:>8} '.format(' ')
# build alignment from the range defined by
# sequence1[align.ref_begin: align.ref_end+1] and sequence2[align.query_begin: align.query_end+1]
seq1 = sequence1[align.ref_begin: align.ref_end+1]
seq2 = sequence2[align.query_begin: align.query_end+1]
cigarPair = parseCigarString(cigarStr)
for pair in cigarPair:
if pair[1] == 'I':
line1 += '-' * pair[0]
line3 += seq2[index2: index2+pair[0]]
line2 += ' ' * pair[0]
index2 += pair[0]
elif pair[1] == 'D':
line1 += seq1[index1: index1+pair[0]]
line3 += '-' * pair[0]
line2 += ' ' * pair[0]
index1 += pair[0]
elif pair[1] == 'M':
s1 = seq1[index1: index1+pair[0]]
s2 = seq2[index2: index2+pair[0]]
line1 += s1
line3 += s2
for c1, c2 in zip(s1, s2):
if c1 == c2:
line2 += '|'
else:
line2 += '*'
index1 += pair[0]
index2 += pair[0]
elif pair[1] != 'S':
e = cigarStr + ' submittedSeq1:' + sequence1 + ' submittedSeq2:' + sequence2
raise RuntimeError(e)
#print(pair)
#print(line1)
#print(line2)
#print(line3)
line1 += ' {:<8}'.format(align.ref_begin + index1)
line3 += ' {:<8}'.format(align.query_begin + index2)
if align.ref_begin + index1 != align.ref_end+1 or align.query_begin + index2 != align.query_end+1:
header['conflict'] = True
header['end1'] = align.ref_begin + index1
header['end2'] = align.query_begin + index2
'''
fmt = 'Warning: alignment path conflicts with aligned range reported by SSW!\n'
fmt += ' seq1Begin:{} seq1Alinged:{} seq1End:{} seq2Begin:{} seq2Alinged:{} seq2End:{}\n'
fmt += ' cigarStr:{}\n alignedSeq1:{}\n alignedSeq2:{}\n submittedSeq1:{}\n submittedSeq2:{}'
w = fmt.format(
align.ref_begin+1, index1, align.ref_end+1,
align.query_begin+1, index2, align.query_end+1,
cigarStr,
seq1, seq2,
sequence1, sequence2)
print(w)
'''
return (header, line1, line2, line3)
# Build the match line between two aligned sequences.
# Return matchLine
# matchLine: character string, for example, '|*|* **|'
# seq1: character string, for example, 'TAGG--AGC'
# seq2: character string, for example, 'TGGACGGCC'
def buildMatchLine(seq1, seq2):
matchLine = ''
for c1, c2 in zip(seq1, seq2):
if c1 == c2:
matchLine += '|'
elif c1 == '-' or c2 == '-':
matchLine += ' '
else:
matchLine += '*'
return matchLine
# Shorten ir to the reasonable length
# Rules to shorten:
# Discard the aligned blocks when irId/irLen < 0.7 with irLen < constants.stringenShortestIR
# or irLen > constants.stringentLongestIR
# Discard the aligned blocks when irId/irLen < 0.6 with constants.stringentShortestIR <= irLen <= constants.stringentLongestIR
#
# ir: [] or [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
#
def shortenIR(ir):
if len(ir) == 0:
return ir
line = buildMatchLine(ir[8], ir[9])
# for example line = '||||||*| ||*||| || ||| | | |||| *| |*||*|||||||||||||||'
# blocks = [list(g) for k,g in itertools.groupby(line)]
# blocks = [ ['|', '|', '|', '|', '|', '|'],
# ['*'],
# ['|'],
# [' '],
# ['|', '|'],
# ['*'],
# ['|', '|', '|'],
# [' '],
# ['|', '|'],
# [' '],
# ['|', '|', '|'],
# [' '],
# ['|'],
# [' ', ' ', ' '],
# ['|'],
# [' '],
# ['|', '|', '|', '|'],
# [' '],
# ['*'],
# ['|'],
# [' '],
# ['|'],
# ['*'],
# ['|', '|'],
# ['*'],
# ['|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|', '|']]
# len(blocks) = 26
#ids = []
irId = 0
irLen = 0
for k,g in itertools.groupby(line):
g = list(g)
blockLen = len(g)
irLen += blockLen
if g[0] == '|':
irId += blockLen
#ids.append((irId, irLen))
#
# break loop, namely, stop growing alignment
if irId/irLen < constants.optIrIdentity:
break
elif (irLen < constants.stringentShortestIR or irLen > constants.stringentLongestIR) and irId/irLen < constants.stringentIrIdentity:
break
# ir: [] or [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
# Build shorten ir
score = irId + irLen
nGaps = line[:irLen].count(' ')
seq1 = ir[8][:irLen]
seq2 = ir[9][:irLen]
gap1 = seq1.count('-')
gap2 = seq2.count('-')
end1 = ir[4] + irLen - gap1 - 1
end2 = ir[6] + irLen - gap2 - 1
return [score, irId, irLen, nGaps, ir[4], end1, ir[6], end2, seq1, seq2]
# Filter ir by applying more stringent criteria:
# ir: [] or [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
# optIRsim, stringentIRsim: float, constants.optIrIdentity and constants.stringentIrIdentity
#
# 1) irId/irLen must be greater than stringentIrIdentity (0.7) if irLen < 5 or irLen > 55, else irId/irLen > optIrIdentity (0.6)
#
def filterIRbyCutoff(ir, optIRsim, stringentIRsim):
if len(ir) == 0:
return []
sim = ir[1]/ir[2]
if sim < optIRsim:
ir = []
elif (ir[2] < 5 or ir[2] > 55) and sim < stringentIRsim:
ir = []
return ir
# Find the number of matches in core regions which is composed of only consecutive matches.
# seq1: character string, for example, 'TAGGG--AGGC'
# seq2: character string, for example, 'TGGGACGGCGC'
# irIdCore: integer, number of matches in core regions
def getIrIdCore(seq1, seq2):
matchLine = buildMatchLine(seq1, seq2)
# search consecutive matches in matchLine
irIdCore = 0
# Option1:
# 1) core region composed of at least two consecutive matched bases
#for region in re.findall(r'\|{2,}', matchLine):
#
# Option2:
# 1) core region, composed of at least three consecutive matched bases
for region in re.findall(r'\|{3,}', matchLine):
#
irIdCore += len(region)
return irIdCore
# Return an empirical score for an ir. The greater the score is, the better the ir is.
# ir: [] or [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
#
def irScore(ir):
if len(ir) == 0:
# set a very negative value as the score of no TIR
score = -9999.9
else:
irIdCore = getIrIdCore(ir[-2], ir[-1])
# mismatch = irLen - nGaps - irId
# irIdNonCore = irId - irIdCore
# Option0:
# score = 3(irIdCore - nGaps) + irIdNonCore - mismatch
# = 2(irIdCore - nGaps) + irId - (nGaps + mismatch)
# = 2(irIdCore - nGaps) + 2*irId - iLen
# = 2(irIdCore + irId - nGaps) - irLen
score = 2 * (irIdCore + ir[1] - ir[3]) - ir[2]
# score = irIdCore - nGaps + x
# Option1: x = irIdNonCore - mismatch
# score = irIdCore - nGaps + x
# = irIdCore - nGaps + (irIdNonCore - mismatch)
# = irIdCore + irIdNonCore - (nGaps + mismatch)
# = irId - (nGaps + mismatch)
# = 2*irId - irLen
# = irId - (nGaps + mismatch)
# Here, score == 0 means irId/irLen == 50%
#score = 2 * ir[1] - ir[2]
#
# Option2: x = (irIdNonCore - mismatch) / (irIdNonCore + mismatch + 1)
# Here, irIdNonCore == mismatch means x contributes zero to final score.
#
# Pay special attention to the following cases:
# irIdCore == nGaps and/or irIdNonCore == mismatch == 0
#
# score = irIdCore - nGaps + x
# socre = irIdCore - nGaps +
# (irId - irIdCore - (irLen-nGaps-irId)) / (irLen - irIdCore - nGaps + 1)
# = irIdCore - nGaps +
# (2*irId - irIdCore - irLen + nGaps)
# / (irLen - irIdCore - nGaps + 1)
# = irIdCore - nGaps +
# (2*irId - irLen - (irIdCore - nGaps))
# / (irLen -2*nGaps - (irIdCore - nGaps) + 1)
#
# set y = irIdCore - nGaps, then
# score = y + (2*irId - irLen - y) / (irLen - 2*nGaps - y + 1)
#y = irIdCore - ir[3]
#score = y + (2*ir[1] - ir[2] - y) / (ir[2] - 2*ir[3] - y + 1)
#
# Option3: x = - (irLen - match) /irLen
# score = irIdCore -nGaps + x
# = irIdCore -nGaps - (irLen - irId)/irLen
# = irIdCore -nGaps - (1 - irId/irLen)
# = irIdCore + irId/irLen - nGaps - 1
#score = irIdCore + ir[1]/ir[2] - ir[3] - 1
#
# Option4: x = (irIdNonCore - mismatch)/2
# score = 2*(irIdCore - nGaps) + irIdNonCore - mismatch
# = 3*irIdCore - 2*nGaps - mismatch
# = 3*irIdCore - nGaps - (irLen - irId)
#score = 3*irIdCore - ir[3] - ir[2] + ir[1]
return score
# Build name of matrix file holding match and mismatch values
# Matrix file example:
# EDNAFULL.2.6.IR.water, EDNAFULL.3.4.IR.water, EDNAFULL.3.6.IR.water, EDNAFULL.5.4.IR.water
def convert2matrixFile(match, mismatch, dir2matrix):
return os.path.join(dir2matrix, 'EDNAFULL.{}.{}.IR.water'.format(match, - mismatch))
# File name, EDNAFULL.2.6.IR.water, means match and mismatch are 2 and -6 respectively.
# example:
# matrixFile: EDNAFULL.2.6.IR.water
# Return: (2, -6)
def resolveMatrixFileName(matrixFile):
fileName = os.path.basename(matrixFile)
if fileName == '':
print('Error: matrix file required', matrixFile, file=sys.stderr)
exit(0)
else:
digits = fileName.split('.',3)[1:3]
return (int(digits[0]), - int(digits[1]))
# Convert (gapopen, gapextend, matrixfile) to (gapopen, gapextend, match, mismatch)
# filters4water: [filter4water, ..., filter4water]
# filter4water: (gapopen, gapextend, matrixfile)
# Return: filters
# filters: [filter, ..., filter]
# filter: (gapopen, gapextend, match, mismatch)
def convertFilters4water(filters4water):
filters = []
for filter in filters4water:
match, mismatch = resolveMatrixFileName(filter[2])
# convert mismatch from a negative value to a positive value
filters.append((filter[0], filter[1], match, -mismatch))
return filters
# Convert (gapopen, gapextend, match, mismatch) to (gapopen, gapextend, matrixfile)
# filters: [filter, ..., filter]
# filter: (gapopen, gapextend, match, mismatch), here mismatch > 0
# dir4embossdata: directory holding the matrix files used by water program
# filters4water: [filter4water, ..., filter4water]
# filter4water: (gapopen, gapextend, matrixfile)
def convertFilters2water(filters, dir2matrix):
filters4water = []
for filter in filters:
matrixFile = convert2matrixFile(filter[2], -filter[3], dir2matrix)
filters4water.append((filter[0], filter[1], matrixFile))
return filters4water
# Return filters shared by filters4ssw and filtersFromWater
def commonFilters(filters4ssw, filtersFromWater):
filters = []
for filter1 in filters4ssw:
for filter2 in filtersFromWater:
if filter1 == filter2:
filters.append(filter1)
return filters[-1:]
# A single measure that trades off precision versus recall is the F measure,
# which is the weighted harmonic mean of precision and recall:
# Fbeta = (1 + beta**2) * recall * precision / (recall + beta**2 * precision)
# Fbeta attaches beta times as much importance to recall as precision.
# Reference:
# Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze,
# Introduction to Information Retrieval, Cambridge University Press. 2008
#
# In our practice, we use beta = 1 or 2,
# F1 = 2 * recall * precision / (recall + precision)
# F2 = 5 * recall * precision / (recall + 4*precision)
# Here, precision = 1 - fdr, recall = sensitivity, fdr(false discovery rate) = false postive hit rate = nfp/nhits
def fmeasure(recall, precision, beta):
denominator = recall + beta**2 * precision
if denominator > 0:
return (1 + beta**2) * recall * precision / denominator
else:
return 0.0
# Check if hit piece is overlapped with isfinder annotation
# 0: hit and isfinder are located on different strands
# overlap/min(b-a, d-c): overlap > 0 if it is overlap, else overlap <= 0
# Note: IS element does not depends on strand while gene depends on strand.
# So, we don't need to compare strand when examing the overlap between
# two IS elements.
#
# The is_overlap() is retained as the alternative of is_overlap_min() or is_overlap_max()
# for the code compatibility.
def is_overlap(hit_strand, hit_begin, hit_end, strand, begin, end):
#if hit_strand != strand:
# return 0.0
# Simply ignore strand
a, b, c, d = hit_begin, hit_end, begin, end
# a <=b and c <= d are satisfied
overlap = min(b, d) - max(a, c) + 1
if overlap > 0:
#return float(overlap) / (min(b-a, d-c) + 1)
return float(overlap) / (max(b-a, d-c) + 1)
#return float(overlap) / (b-a + 1)
else:
return 0.0
def is_overlap_min(hit_strand, hit_begin, hit_end, strand, begin, end):
# Simply ignore strand
a, b, c, d = hit_begin, hit_end, begin, end
# a <=b and c <= d are satisfied
overlap = min(b, d) - max(a, c) + 1
if overlap > 0:
return float(overlap) / (min(b-a, d-c) + 1)
else:
return 0.0
def is_overlap_max(hit_strand, hit_begin, hit_end, strand, begin, end):
# Simply ignore strand
a, b, c, d = hit_begin, hit_end, begin, end
# a <=b and c <= d are satisfied
overlap = min(b, d) - max(a, c) + 1
if overlap > 0:
return float(overlap) / (max(b-a, d-c) + 1)
else:
return 0.0
# Check if two ORFs (genes) are overlapped
# 0: hit and isfinder are located on different strands
# overlap/min(b-a, d-c): overlap > 0 if it is overlap, else overlap <= 0
#
def orf_overlap(orf1, orf2):
hit_strand, hit_begin, hit_end = orf1
strand, begin, end = orf2
if hit_strand != strand:
return 0.0
a, b, c, d = hit_begin, hit_end, begin, end
# a <=b and c <= d are satisfied
overlap = min(b, d) - max(a, c) + 1
if overlap > 0:
return float(overlap) / (min(b-a, d-c) + 1)
else:
return 0.0
# Check if piece1 is overlapped with piece2.
# p1: (a, b), a <= b, float or int
# p2: (c, d), c <= d, float or int
#
def overlap(p1, p2):
a, b = p1
c, d = p2
# a <=b and c <= d are satisfied
overlap = min(b, d) - max(a, c) + 1
if overlap > 0:
#return float(overlap) / (min(b-a, d-c) + 1)
return float(overlap) / (max(b-a, d-c) + 1)
#return float(overlap) / (b-a + 1)
else:
return 0.0
def overlap_min(p1, p2):
a, b = p1
c, d = p2
# a <=b and c <= d are satisfied
overlap = min(b, d) - max(a, c) + 1
if overlap > 0:
return float(overlap) / (min(b-a, d-c) + 1)
else:
return 0.0
def intersection(p1, p2):
a, b = p1
c, d = p2
# a <=b and c <= d are satisfied
overlap = min(b, d) - max(a, c) + 1
return overlap
def intergap(p1, p2):
a, b = p1
c, d = p2
# a <=b and c <= d are satisfied
gap = max(a, c) - min(b, d) - 1
return gap
# makeblastdb -dbtype nucl -in output4FragGeneScan1.19_illumina_5/NC_002754.1.fna.ffn -out blastdb/NC_002754.1.fna.ffn
def seq2blastdb(seqFile, db):
cmd = constants.makeblastdb
cmdline = [cmd, '-dbtype nucl', '-in', seqFile, '-out', db]
do_cmd = shlex.split(' '.join(cmdline))
subprocess.check_call(do_cmd, shell=False, universal_newlines=False, stdout=subprocess.DEVNULL)
# delete the file pointing by full path f.
# f: /path/to/file, a character string
def deleteFile(f):
cmd = 'rm'
cmdline = [cmd, f]
do_cmd = shlex.split(' '.join(cmdline))
subprocess.check_call(do_cmd, shell=False, universal_newlines=False, stdout=subprocess.DEVNULL)
# Search all IS elements (Tpase) ORFs against IS element (Tpase ORF) database.
# command: blastn -query /home/data/insertion_sequence/output4FragGeneScan1.19_illumina_5/NC_002754.1.fna.ffn \
# -db /home/data/insertion_sequence/blastdb/NC_002754.1.fna.ffn -out blast.6 \
# -outfmt '6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore \
# nident qlen slen' -perc_identity 90 -dust no
# Note1: There is 0 hit when querying 1471545_1471675_- against NC_011891.1.orf.fna because blastn by default
# to enable filtering query sequence with DUST to mask low complex repeat sequence in query.
# So we must disable it with '-dust no'.
# Note2: blastn-short is BLASTN program optimized for sequences shorter than 50 bases. We will use it in blastn search
# when dealing with tir sequence as tir is usually shorter than 55 bases.
def doBlastn(query, db, out, strand='both', task='megablast', perc_ident=100):
blast = constants.blastn
outfmt = shlex.quote('6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore nident qlen slen')
#perc_identity = str(constants.sim4iso * 100)
perc_identity = str(perc_ident)
if task == 'blastn-short':
wordsize = '7'
#wordsize = '5' # default value for blastn-short is 7 but we use smaller value because the length of tir is usually among 5<= length <=55.
#wordsize = '4' # wordsize must >= 4
elif task == 'megablast':
wordsize = '28' # default value for megablast
else:
wordsize = '11' # default value for blastn
cmd = [blast, '-query', query, '-db', db, '-out', out, '-outfmt', outfmt, '-perc_identity', perc_identity,
'-strand', strand, '-dust', 'no', '-task', task, '-word_size', wordsize]
do_cmd = shlex.split(' '.join(cmd))
if subprocess.call(do_cmd, shell=False, universal_newlines=False, stdout=subprocess.DEVNULL) != 0:
e = 'Fail to run {}'.format(cmd)
raise RuntimeError(e)
def blastnSearch(query, db, out, strand='both', task='megablast'):
blast = constants.blastn
outfmt = shlex.quote('6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore nident qlen slen')
#perc_identity = str(constants.sim4iso * 100)
perc_identity = str(constants.SIM4ISO)
if task == 'blastn-short':
wordsize = '7'
#wordsize = '5' # default value for blastn-short is 7 but we use smaller value because the length of tir is usually among 5<= length <=55.
#wordsize = '4' # wordsize must >= 4
elif task == 'megablast':
wordsize = '28' # default value for megablast
else:
wordsize = '11' # default value for blastn
cmd = [blast, '-query', query, '-db', db, '-out', out, '-outfmt', outfmt, '-perc_identity', perc_identity, '-strand', strand, '-dust', 'no', '-task', task, '-word_size', wordsize]
do_cmd = shlex.split(' '.join(cmd))
if subprocess.call(do_cmd, shell=False, universal_newlines=False, stdout=subprocess.DEVNULL) != 0:
e = 'Fail to run {}'.format(cmd)
raise RuntimeError(e)
# Search all IS elements (Tpase) ORFs against IS element (Tpase ORF) database.
# Return out
#
# command: blastn -db db -perc_identity 90 -strand strand -dust no -task task -word_size wordsize -num_threads nthreads \
# -outfmt '6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore nident qlen slen'
# Note1: query and outfile are stdin and stdou by default, respectively
# Note2: blastn-short is BLASTN program optimized for sequences shorter than 50 bases. We will use it in blastn search
# when dealing with tir sequence as tir is usually shorter than 55 bases.
#
def doBlastnOnStream(query, db, strand='both', task='megablast', perc_ident=100, nthreads=1):
blast = constants.blastn
outfmt = shlex.quote('6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore nident qlen slen')
perc_identity = str(perc_ident)
num_threads = str(nthreads)
if task == 'blastn-short':
wordsize = '7'
#wordsize = '5' # default value for blastn-short is 7 but we use smaller value because the length of tir is usually among 5<= length <=55.
#wordsize = '4' # wordsize must >= 4
elif task == 'megablast':
wordsize = '28' # default value for megablast
else:
wordsize = '11' # default value for blastn
cmd = [blast,
'-db', db, '-perc_identity', perc_identity, '-strand', strand, '-dust', 'no',
'-task', task, '-word_size', wordsize, '-num_threads', num_threads,
'-outfmt', outfmt
]
do_cmd = shlex.split(' '.join(cmd))
blastn = subprocess.Popen(do_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
out, err = blastn.communicate(input=query)
return (out, err)
# Search protein sequence against protein database.
# command: blastp -db db -evalue 1e-10 -task task -num_threads nthreads \
# -outfmt '6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore nident qlen slen'
# Note1: query and outfile are stdin and stdou by default, respectively
def doBlastpOnStream(query, db, task='blastp', e_value=1e-10, nthreads=1):
blast = constants.blastp
outfmt = shlex.quote('6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore nident qlen slen')
evalue = str(e_value)
num_threads = str(nthreads)
cmd = [blast,
'-db', db, '-evalue', evalue, '-task', task, '-num_threads', num_threads,
'-outfmt', outfmt
]
do_cmd = shlex.split(' '.join(cmd))
blastn = subprocess.Popen(do_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
out, err = blastn.communicate(input=query)
return (out, err)
# blastn -query query -subject subject ....
def doBlastn2seqOnStream(nthread, query, subject, strand='both', task='megablast', perc_ident=100):
blast = constants.blastn
outfmt = shlex.quote('6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore nident qlen slen')
perc_identity = str(perc_ident)
if task == 'blastn-short':
wordsize = '7'
#wordsize = '4' # wordsize must >= 4
elif task == 'megablast':
wordsize = '28' # default value for megablast
else:
wordsize = '11' # default value for blastn
num_threads = str(nthread)
cmd = [blast,
'-subject', subject, '-perc_identity', perc_identity, '-strand', strand, '-dust', 'no',
'-task', task, '-word_size', wordsize, '-outfmt', outfmt
#'-task', task, '-word_size', wordsize, '-outfmt', outfmt, '-num_threads', num_threads
# 'num_threads' is currently ignored when 'subject' is specified.
]
do_cmd = shlex.split(' '.join(cmd))
blastn = subprocess.Popen(do_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
out, err = blastn.communicate(input=query)
return (out, err)