-
Notifications
You must be signed in to change notification settings - Fork 6
/
microsatellite.py
1271 lines (1043 loc) · 48.7 KB
/
microsatellite.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Snoop thru a fasta file looking for microsatellite repeats of given periods
Output format: length_of_repeat left_flank_length right_flank_length repeat_motif hamming_distance read_name read_sequence read_quality (additional columns)
If --r option turned on, output format will have additional columns behind:
read_name read_chr pre_s pre_e tr_s tr_e suf_s suf_e tr_len tr_ref_seq
pre_s where the read start
pre_e the last position before microsatellite
tr_s where microsatellite start
tr_e where microsatellite end
suf_s first base after microsatellite
tr_ref_seq reference sequence corresponding to microsatellite
* output positions are 0 based
:Author: Chen Sun (cxs1031@cse.psu.edu); Bob Harris (rsharris@bx.psu.edu)
modifing log:
09/27/2013
replace function dense_intervals with function non_negative_intervals, which do not need to import such file.
10/18/2013
modify function find_repeat_element to get a quick speed, under the condition that hamming_distance = 0, which means do not allowed any mutation/indel
02/25/2014
add function that can deal with mapped reads
with additional output
02/28/2014
modify the 0-based end point, as in 0-base area, it is half-open [ )
so the 0-based site, should always be added by 1
03/05/2014
deal with multi-fasta
"""
from sys import argv,stdin,stderr,exit
from string import maketrans
from md5 import new as md5_new
import re
#from pyfracluster import dense_intervals
def usage(s=None):
message = """
usage: microsat_snoop [fasta_file] [options]
<fasta_file> Name of file to read sequences from; if absent,
sequences are read from stdin
--fasta Input file is in fasta format
(this is the default)
--fastq Input file is in fastq format
(default is fasta unless filename is .fastq)
--fastq:noquals Input file is in fastq format, but discard quals
--sam Input file is SAM file
--r Indicate additional output information, if indicated,
--ref option is mendatory
--ref=<filepath> Reference file (absolute) path
--period=<length> (mandatory,cumulative) repeat length(s) to be
searched for
<length> is expected to be small, less than 10
<length> can also be a comma-separated list, or
a range <low>..<high>
--rate=<fraction> control the candidate repeat interval detector;
it will consider intervals with at least
<fraction> of matches when shifted by the period;
<fraction> is between 0 and 1 and can be either a
real number or <n>/<d>
(default is 6/7)
--minlength=<length> minimum length of intervals reported, in bp
(default is 20)
--progress=<count> how often to report the sequence we're searching
(default is no progress report)
--allowduplicates process all input sequences
(this is the default)
--noduplicates ignore any input sequence that's the same as an
earlier sequence
--nonearduplicates ignore any input sequence that has the same first
100 bp as an earlier sequence
--nonearduplicate=<length> ignore any input sequence that has the same first
<length> bp as an earlier sequence
--hamming=<count> Don't report candidate repeat intervals that have
more than <count> mismatches
(default is to do no such filtering)
--prefix=<length> Don't report candidate repeat intervals that
start within <length> of the sequence start
(default is to do no such filtering)
--suffix=<length> Don't report candidate repeat intervals that
end within <length> of the sequence end
(default is to do no such filtering)
--subsample=<k>/<n> Process only the <k>th sequence of every group of
<n> sequences; <k> ranges from 1 to <n>
--multipleruns Consider all candidate intervals in a sequence
(default is to consider only the longest)
--partialmotifs Consider microatelites with a partial motif
(default is to consider only whole motifs)
--splitbyvalidity Preprocess sequences, splitting at Ns; this
prevents candidates from including Ns
(default is not to split)
--noflankdisplay Show entire sequence as flanking regions
(this is the default)
--flankdisplay=<length> Limit length of flanking regions shown
--readnamesuffix=<string> Root of suffix to append to read names; e.g. 1
for forward, 2 for reverse; this triggers other
info to be included in the suffix
(default is "1" for fastq; no suffix for fasta)
--head=<number> limit the number of sequences processed
--markend Write a marker line upon completion
(default is not to write a marker)
--help=details Describe the process, and quit"""
if (s == None): exit (message)
else: exit ("%s\n%s" % (s,message))
detailedDescription = """In broad terms, the process works as follows:
(1) Identify intervals that are highly correlated with the interval shifted by
P (the repeat period). These intervals are called "runs" or "candidates".
The level of correlation required is controlled by rateThreshold.
Depending on whether we want to look for more than one microsat, we either
find the longest such run (simple algorithm) or many runs (more complicated
algorithm). The following steps are then performed on each run.
(2) Find the most likely repeat motif in the run. This is done by counting
all kmers (of length P) and choosing the most frequent. If that kmer is
itself covered by a sub-repeat we discard this run. The idea is that we
can ignore a 6-mer like ACGACG because we will find it when we are looking
for 3-mers.
(3) Once we identify the most likely repeat motif, we then modify the
interval, adjusting start and end to find the interval that has the fewest
mismatches vs. a sequence of the motif repeated (hamming distance). Only
whole copies of the motif are considered.
(4) At this point we have a valid microsat interval (in the eyes of the
program). It is subjected to some filtering stages (hamming distance or too
close to an end), and if it satisfies those conditions, it's reported to
the user."""
def main():
global debug
#=== parse the command line ===
inputFilename = None
referenceFileName = None #add by Chen Sun on 02/25
inputFormat = None
repeatPeriods = []
rateThreshold = 6 / 7.0
lengthThreshold = 20
reportProgress = None
discardDuplicates = False
discardNearDuplicates = False
nearDuplicatePrefix = 100
hammingThreshold = 0
prefixThreshold = None
suffixThreshold = None
subsampleK = None
subsampleN = None
reportMultipleRuns = False
allowPartialMotifs = False
splitByValidity = False
flankDisplayLimit = None
readNameSuffix = None
headLimit = None
markEndOfFile = False
additionalInfo = False
debug = []
for arg in argv[1:]:
if (arg == "--fasta"):
inputFormat = "fasta"
elif (arg == "--fastq"):
inputFormat = "fastq"
elif (arg == "--fastq:noquals"):
inputFormat = "fastq:noquals"
elif (arg == "--sam"):
inputFormat = "sam"
elif (arg == "--r"):
additionalInfo = True
elif (arg.startswith("--ref=")):
referenceFileName = arg.split("=",1)[1]
elif (arg.startswith("--period=")):
val = arg.split("=",1)[1]
for period in val.split(","):
if (".." in period):
(lowPeriod,highPeriod) = period.split("..",1)
lowPeriod = int(lowPeriod)
highPeriod = int(highPeriod)
for period in xrange(lowPeriod,highPeriod+1):
repeatPeriods += [period]
else:
repeatPeriods += [int(period)]
elif (arg.startswith("--rate=")):
val = arg.split("=",1)[1]
rateThreshold = float_or_fraction(val)
assert (0.0 < rateThreshold <= 1.0), "%s not a valid rate" % val
elif (arg.startswith("--minlength=")):
val = arg.split("=",1)[1]
lengthThreshold = int(val)
assert (lengthThreshold >= 0)
elif (arg.startswith("--progress=")):
val = arg.split("=",1)[1]
reportProgress = int(val)
elif (arg == "--allowduplicates"):
discardDuplicates = False
discardNearDuplicates = False
elif (arg == "--noduplicates"):
discardDuplicates = True
discardNearDuplicates = False
elif (arg == "--nonearduplicates"):
discardDuplicates = False
discardNearDuplicates = True
elif (arg.startswith("--nonearduplicate=")):
val = arg.split("=",1)[1]
discardDuplicates = False
discardNearDuplicates = True
nearDuplicatePrefix = int(val)
assert (nearDuplicatePrefix > 0)
elif (arg.startswith("--hamming=")):
val = arg.split("=",1)[1]
hammingThreshold = int(val)
assert (hammingThreshold >= 0)
elif (arg.startswith("--prefix=")):
val = arg.split("=",1)[1]
prefixThreshold = int(val)
assert (prefixThreshold >= 0)
elif (arg.startswith("--suffix=")):
val = arg.split("=",1)[1]
suffixThreshold = int(val)
assert (suffixThreshold >= 0)
elif (arg.startswith("--subsample=")):
val = arg.split("=",1)[1]
(k,n) = val.split("/",2)
subsampleK = int(k)
subsampleN = int(n)
assert (0 < subsampleK <= subsampleN)
elif (arg == "--multipleruns"):
reportMultipleRuns = True
elif (arg == "--partialmotifs"):
allowPartialMotifs = True
elif (arg == "--splitbyvalidity"):
splitByValidity = True
elif (arg == "--noflankdisplay"):
flankDisplayLimit = None
elif (arg.startswith("--flankdisplay=")):
val = arg.split("=",1)[1]
flankDisplayLimit = int(val)
assert (flankDisplayLimit >= 0)
elif (arg.startswith("--readnamesuffix")):
readNameSuffix = arg.split("=",1)[1]
elif (arg.startswith("--head=")):
headLimit = int_with_unit(arg.split("=",1)[1])
elif (arg == "--markend"):
markEndOfFile = True
elif (arg == "--help=details"):
exit (detailedDescription)
elif (arg.startswith("--debug=")):
debug += (arg.split("=",1)[1]).split(",")
elif (arg.startswith("--")):
usage("unrecognized option: %s" % arg)
elif (inputFilename == None):
inputFilename = arg
else:
usage("unrecognized option: %s" % arg)
#=== determine periods of interest ===
if (repeatPeriods == []):
usage("you gotta give me a repeat period")
if (additionalInfo == True):
if (referenceFileName == None):
usage("reference file path needed. use --ref=<reference> to indicate")
periodSeed = {}
for period in repeatPeriods:
if (period < 1): usage("period %d is not valid" % period)
periodSeed[period] = True
repeatPeriods = [period for period in periodSeed]
repeatPeriods.sort()
#=== determine input format ===
if (inputFormat == "fasta"): sequence_reader = fasta_sequences
elif (inputFormat == "fastq"): sequence_reader = fastq_sequences
elif (inputFormat == "fastq:noquals"): sequence_reader = fastq_sequences
elif (inputFormat == "sam"): sequence_reader = sam_sequences
elif (inputFilename == None): sequence_reader = fasta_sequences
elif (inputFilename.endswith(".fastq")): sequence_reader = fastq_sequences
elif (inputFilename.endswith(".fq")): sequence_reader = fastq_sequences
elif (inputFilename.endswith(".sam")): sequence_reader = sam_sequences
else: sequence_reader = fasta_sequences
if (inputFilename != None): inputF = file(inputFilename,"rt")
else: inputF = stdin
if (readNameSuffix == None) \
and (sequence_reader == fastq_sequences) \
and (inputFormat != "fastq:noquals"):
readNameSuffix = "1"
#=== process the sequences ===
refSequence = {}
rightName = ""
sequence = ""
if additionalInfo:
firstFasta = True
originalRefF = open(referenceFileName)
for line in originalRefF.readlines():
line = line.replace('\r','')
line = line.replace('\n','')
if line.startswith(">"):
if firstFasta:
firstFasta = False
else:
refSequence[rightName] = sequence
rightName = line[1:]
sequence = ""
continue
sequence += line
originalRefF.close()
refSequence[rightName] = sequence
sequenceSeen = {}
numSequences = 0
for seqInfo in sequence_reader(inputF):
numSequences += 1
if (headLimit != None) and (numSequences > headLimit):
print >>stderr, "limit of %d sequences reached" % headLimit
break
if (sequence_reader == sam_sequences):
#seqName,"".join(seqNucs).upper().translate(nonDnaMap), refName, pre_s, cigar
(name, sequence, refName, pre_s, cigar) = seqInfo
quals = None
elif (sequence_reader == fastq_sequences):
(name,sequence,quals) = seqInfo
if (inputFormat == "fastq:noquals"): quals = None
else:
(name,sequence) = seqInfo
quals = None
if (reportProgress != None) and (numSequences % reportProgress == 0):
print >>stderr, "%s %d" % (name,numSequences)
# if we're subsampling and not interested in this sequence, skip it
if (subsampleN != None):
if ((numSequences-1) % subsampleN != (subsampleK-1)):
continue
# if this sequence is shorter than the length of interest, skip it
seqLen = len(sequence)
if (seqLen < period) or (seqLen < lengthThreshold): continue
# if we're not interested in duplicates and this is one, skip it;
# note that we assume no hash collisions occur, i.e. that all hash
# matches are truly sequence matches
if (discardDuplicates):
h = hash108(sequence)
if (h in sequenceSeen): continue
sequenceSeen[h] = True
elif (discardNearDuplicates):
h = hash108(sequence[:nearDuplicatePrefix])
if (h in sequenceSeen): continue
sequenceSeen[h] = True
# split the sequence into chunks of valid nucleotides
if (splitByValidity):
chunks = [(start,end) for (start,end) in nucleotide_runs(sequence)]
else:
chunks = [(0,len(sequence))]
# evaluate for each period of interest
for period in repeatPeriods:
# operate on each chunk
for (chunkStart,chunkEnd) in chunks:
chunkLen = chunkEnd - chunkStart
if (chunkLen < period) or (chunkLen < lengthThreshold): continue
if ("validity" in debug) or ("correlation" in debug) or ("runs" in debug):
print >>stderr, ">%s_%d_%d" % (name,chunkStart,chunkEnd)
# compute correlation sequence
corr = correlation_sequence(sequence,period,chunkStart,chunkEnd)
if ("correlation" in debug) or ("runs" in debug):
print >>stderr, sequence[chunkStart:chunkEnd]
print >>stderr, corr
# find runs (candidates for being a microsat)
if (reportMultipleRuns):
runs = all_suitable_runs(corr,lengthThreshold-period,rateThreshold, hammingThreshold)
else:
runs = longest_suitable_run(corr,lengthThreshold,rateThreshold)
if (runs == []): continue
if ("runs" in debug):
for (start,end) in runs:
run = [" "] * seqLen
for ix in xrange(start-period,end):
run[ix] = "*"
print >>stderr, "".join(run)
if ("candidates" in debug):
for (start,end) in runs:
print >>stderr, "%s %d %d" % (name,start,end)
# process runs and report those that pass muster
runCount = 0
for (start,end) in runs:
runCount += 1
start = chunkStart + start - period
end = chunkStart + end
(kmer,d,start,end) = find_repeat_element(hammingThreshold, period,sequence,start,end,allowPartials=allowPartialMotifs)
if (kmer == None): continue # (no useful repeat kmer was found)
rptExtent = end - start
prefixLen = start
suffixLen = seqLen - end
if (rptExtent <= period): continue
if (hammingThreshold != None) and (d > hammingThreshold): continue
if (prefixThreshold != None) and (prefixLen < prefixThreshold): continue
if (suffixThreshold != None) and (suffixLen < suffixThreshold): continue
if (flankDisplayLimit == None):
seq = sequence[:start] \
+ sequence[start:end].lower() \
+ sequence[end:]
else:
seq = sequence[max(chunkStart,start-flankDisplayLimit):start] \
+ sequence[start:end].lower() \
+ sequence[end:min(chunkEnd,end+flankDisplayLimit)]
reportName = name
if (readNameSuffix != None):
reportName += "_"+readNameSuffix+"_per"+str(period)+"_"+str(runCount)
if (quals == None or quals == "." or quals == "\t."): quals = "\t."
else: quals = "\t" + quals
if not additionalInfo:
print "%d\t%d\t%d\t%s\t%d\t%s\t%s%s" \
% (rptExtent,prefixLen,suffixLen,kmer,d,reportName,seq,quals)
else:
#pre_e = pre_s + prefixLen - 1
refPoint = pre_s
donorPoint = 0
donorBeforeStart = prefixLen - 1 #pre_e
donorMicroStart = prefixLen #tr_s
donorMicroEnd = donorMicroStart + rptExtent - 1 #tr_e
donorAfterMicro = donorMicroEnd + 1 #suf_s
donorEnd = len(seq) - 1 #suf_e
set_pre_e = False
set_tr_s = False
set_tr_e = False
set_suf_s = False
set_suf_e = False
pre_e = 0
tr_s = 0
tr_e = 0
suf_s = 0
suf_e = 0
matchList = re.findall('(\d+)([IDM])', cigar)
unCognitiveCigar = False
for matchN, matchType in matchList:
matchNum = int(matchN)
if matchType == "M":
donorPoint = donorPoint + matchNum
refPoint = refPoint + matchNum
elif matchType == "D":
refPoint = refPoint + matchNum
continue
elif matchType == "I":
donorPoint = donorPoint + matchNum
else:
unCognitiveCigar = True
break
if not set_pre_e:
if donorPoint >= donorBeforeStart:
pre_e = refPoint - (donorPoint - donorBeforeStart)
set_pre_e = True
else:
continue
if not set_tr_s:
if donorPoint >= donorMicroStart:
tr_s = refPoint - (donorPoint - donorMicroStart)
set_tr_s = True
else:
continue
if not set_tr_e:
if donorPoint >= donorMicroEnd:
tr_e = refPoint - (donorPoint - donorMicroEnd)
set_tr_e = True
else:
continue
if not set_suf_s:
if donorPoint >= donorAfterMicro:
suf_s = refPoint - (donorPoint - donorAfterMicro)
set_suf_s = True
else:
continue
if not set_suf_e:
if donorPoint >= donorEnd:
suf_e = refPoint - (donorPoint - donorEnd)
set_suf_e = True
else:
continue
if unCognitiveCigar:
break
tr_len = tr_e - tr_s + 1
if refName not in refSequence:
tr_ref_seq = "."
else:
if refSequence[refName] == "":
tr_ref_seq = "."
elif len(refSequence[refName]) <= tr_e:
tr_ref_seq = "."
else:
tr_ref_seq = refSequence[refName][tr_s:tr_e+1]
pre_e += 1
tr_e += 1
suf_e += 1
print "%d\t%d\t%d\t%s\t%d\t%s\t%s%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%s" \
% (rptExtent,prefixLen,suffixLen,kmer,d,reportName,seq,quals,reportName,refName,pre_s,pre_e,tr_s,tr_e,suf_s,suf_e,tr_len,tr_ref_seq)
if (markEndOfFile):
print "# microsat_snoop end-of-file"
if (inputF != stdin):
inputF.close()
# non_negative_intervals
# find intervals with exactly + and no -
# from string like this : +++++++++---+++++++++
def non_negative_intervals(seq, minLength=None):
start = -1
end = -1
firstPlus = 1
#print seq
for ix in range(len(seq)): # for every char in seq
ch = seq[ix]
if(ch == "+"):
if(firstPlus):
firstPlus = 0
start = ix
else:
continue
elif(ch == "-"):
if(start >= 0):
end = ix-1
if((end - start + 1) >= minLength):
yield (start,end+1)
start = -1
firstPlus = 1
if(start > 0):
if((ix - start + 1) >= minLength):
yield (start, ix+1)
###################################################################
# modified by Chen Sun on 7/11/2014
# We do not want other modules, so parse these functions inside
#
###################################################################
# parse a string of the form {positives}/{positives_and_neutrals}
def parse_spec(s):
if ("/" not in s): raise ValueError
(n,d) = s.split("/",1)
if (not n.startswith("{")) or (not n.endswith("}")): raise ValueError
if (not d.startswith("{")) or (not d.endswith("}")): raise ValueError
positives = n[1:-1]
d = d[1:-1]
for ch in positives:
if (ch not in d): raise ValueError
neutrals = [ch for ch in d if (ch not in positives)]
return (positives,neutrals)
# convert a string to a number, allowing fractions
def float_or_fraction(s):
if ("/" in s):
(numer,denom) = s.split("/",1)
return float(numer)/float(denom)
else:
return float(s)
# dense_intervals--
# Find all non-overlapping runs with a good enough rate (of positives), and
# which meet our length threshold.
#
# The algorithm used is adapted from Zhang, Berman, Miller, "Post-processing
# long pairwise alignments", Bioinformatics Vol. 15 no. 12 1999.
#
# $$$ we use the denominator as the threshold, but we really should use the
# $$$ .. numerator, comparing it to minLength*rate
def dense_intervals(seq,rate,positives,neutrals,blockers="",minLength=None):
if (blockers == None):
blockers = "".join([chr(n) for n in range(1,256)
if (chr(n) not in positives)
and (chr(n) not in neutrals)])
stackLeft = [None] # stack with each entry containing five
stackRight = [None] # .. elements; note that entry zero is not
stackLeftScore = [None] # .. used
stackRightScore = [None]
stackLower = [None]
top = 0
score = 0
for ix in range(len(seq)):
ch = seq[ix]
if (ch in blockers):
# emit intervals
for sp in range(1,top+1):
left = stackLeft [sp] + 1
right = stackRight[sp]
while (left < right) and (seq[left] not in positives): left += 1
while (right > left) and (seq[right] not in positives): right -= 1
right += 1
if (minLength == None) or (right - left >= minLength):
yield (left,right)
#empty stack
stackLeft = [None]
stackRight = [None]
stackLeftScore = [None]
stackRightScore = [None]
stackLower = [None]
top = 0
score = 0
continue
if (ch in positives): weight = 1-rate
elif (ch in neutrals): weight = -rate
else: raise ValueError
score += weight
#if ("algorithm" in debug):
# print >>sys.stderr, "%3d: %c %5.2f" % (ix, ch, score),
if (weight < 0):
#if ("algorithm" in debug):
# print >>sys.stderr
continue
if (top > 0) and (stackRight[top] == ix-1):
# add this site to the interval on top of the stack
stackRight [top] = ix
stackRightScore[top] = score
#if ("algorithm" in debug):
# print >>sys.stderr, \
# " extending [%d] %d-%d %4.1f %4.1f" \
# % (top,
# stackLeft [top], stackRight [top],
# stackLeftScore[top], stackRightScore[top]),
else:
# create a one site interval
top += 1
if (top >= len(stackLeft)):
stackLeft += [None]
stackRight += [None]
stackLeftScore += [None]
stackRightScore += [None]
stackLower += [None]
stackLeft [top] = ix - 1
stackLeftScore [top] = score - weight
stackRight [top] = ix
stackRightScore[top] = score
stackLower [top] = top - 1
while (stackLower[top] > 0) \
and (stackLeftScore[stackLower[top]] > stackLeftScore[top]):
stackLower[top] = stackLower[stackLower[top]]
#if ("algorithm" in debug):
# print >>sys.stderr, \
# " creating [%d] %d-%d %4.1f %4.1f -> %d" \
# % (top,
# stackLeft [top], stackRight [top],
# stackLeftScore[top], stackRightScore[top],
# stackLower [top]),
# merge intervals; if there is a previous interval with a no-higher
# left score and no-higher right score, merge this interval (and all
# intervening ones) into that one
while (top > 1) \
and (stackLower[top] > 0) \
and (stackRightScore[stackLower[top]] <= stackRightScore[top]):
stackRight [stackLower[top]] = stackRight [top]
stackRightScore[stackLower[top]] = stackRightScore[top]
top = stackLower[top]
#if ("algorithm" in debug):
# print >>sys.stderr, \
# "\n%*s merging [%d] %d-%d %4.1f %4.1f" \
# % (13, "", top,
# stackLeft[top], stackRight [top],
# stackLeftScore[top], stackRightScore[top]),
#if ("algorithm" in debug):
# print >>sys.stderr
# emit intervals
for sp in range(1,top+1):
left = stackLeft [sp] + 1
right = stackRight[sp]
while (left < right) and (seq[left] not in positives): left += 1
while (right > left) and (seq[right] not in positives): right -= 1
right += 1
if (minLength == None) or (right - left >= minLength):
yield (left,right)
###################################################################
# modified by Chen Sun on 7/11/2014
#
###################################################################
# correlation_sequence--
# Compute the correlation sequence for a given period. This is a sequence
# of + and - indicating whether the base at a given position matches the one
# P positions earlier (where P is the period). The first P positions are
# blank. Positions with single character runs longer than the period are
# considered as non-matches, unless the period is 1.
def correlation_sequence(sequence,period,start=None,end=None):
if (start == None): start = 0
if (end == None): end = len(sequence)
prevCh = sequence[start]
run = 1
for ix in xrange(start+1,start+period):
ch = sequence[ix]
if (ch != prevCh): run = 1
else: run += 1
prevCh = ch
corr = [" "] * period
for ix in xrange(start+period,end):
rptCh = sequence[ix-period]
ch = sequence[ix]
if (ch != prevCh): run = 1
else: run += 1
if (ch in "ACGT") \
and (ch == rptCh) \
and ((period == 1) or (run < period)):
corr += ["+"]
else:
corr += ["-"]
prevCh = ch
return "".join(corr)
# longest_suitable_run--
# Find longest run with a good enough rate (of positives).
#
# We score a "+" as 1-r and anything else as -r. This is based on the fol-
# lowing derivation (p is the number of "+"s, n is the number of non-"+"s):
# p/(p+n) >= r
# ==> p >= rp + rn
# ==> (1-r)p - rn >= 0
#
# We adapt an algorithm from "Programming Pearls", pg. 81 (2000 printing).
#
# $$$ we use the denominator as the threshold, but we really should use the
# $$$ .. numerator, comparing it to minLength*rate
#
# $$$ this needs to account for $$$ this situation:
# $$$ sequence: ACGACGACGACGTTATTATTATTA
# $$$ matches: +++++++++---+++++++++
# $$$ this is currently considered to be one interval (if rate <= 6/7), but it
# $$$ ought to be two; we can't just post-process, though, because some other
# $$$ interval might be longer than the longest half of this; maybe what we
# $$$ need to do is consider matches at distances -P and -2P, or if we match
# $$$ -P but that itself was a mismatch, we should carry the mismatch forward
def longest_suitable_run(seq,minLength,rate):
maxEndingHere = 0
maxSoFar = 0
start = None
for ix in xrange(len(seq)):
if (seq[ix] == "+"): s = 1-rate
else: s = -rate
if (maxEndingHere+s < 0):
maxEndingHere = 0
block = ix
else:
maxEndingHere += s
if (maxEndingHere >= maxSoFar):
maxSoFar = maxEndingHere
start = block + 1
end = ix + 1
if (start == None) or (end - start < minLength):
return []
else:
return [(start,end)]
# all_suitable_runs--
# Find all non-overlapping runs with a good enough rate (of positives), and
# which meet our length threshold.
# $$$ this needs to post-process the intervals, splitting them to account for
# $$$ this situation:
# $$$ sequence: ACGACGACGACGTTATTATTATTA
# $$$ matches: +++++++++---+++++++++
# $$$ this is currently reported as one interval (if rate <= 6/7), but it
# $$$ ought to be two
def all_suitable_runs(seq,minCorrLength,rate, hammingThreshold):
################################################################
# modified by Chen Sun on 07/11/2014
#
################################################################
if hammingThreshold > 0:
return [(start,end) for (start,end) in dense_intervals(seq,rate,"+","-",blockers=None,minLength=minCorrLength)]
elif hammingThreshold == 0:
return [(start,end) for (start,end) in non_negative_intervals(seq, minLength=minCorrLength)]
# find_repeat_element--
# Find the most plausible repeat element for a run, and nudge the ends of
# the run if needed. Note that we will not consider kmers that represent
# shorter repeats. For example, we won't report ACTACT as a 6-mer since we
# consider this to have a shorter period than 6.
def find_repeat_element(hammingThreshold, period,seq,start,end,allowPartials=False):
if hammingThreshold > 0:
(kmer,bestD,bestStart,bestEnd) = find_hamming_repeat_element(period,seq,start,end,allowPartials)
return (kmer,bestD,bestStart,bestEnd)
# count the number of occurences of each k-mer; note that we can't
# reject kmers containing smaller repeats yet, since for a sequence like
# ACACACACACAAACACACACACACACACAC we must first discover ACACAC as the best
# 6-mer, and THEN reject it; if we reject ACACAC while counting, we'd end
# up reporting something like ACACAA as the best motif
if ("element" in debug):
print >>stderr, "find_repeat_element(%d,%d,%d)" % (period,start,end)
if ("partial" in debug):
print period, seq, start, end, allowPartials;
print seq[start:end]
kmerToCount = {}
kmerToFirst = {}
for ix in xrange(start,end-(period-1)):
kmer = seq[ix:ix+period]
if ("N" in kmer): continue
if (kmer not in kmerToCount):
kmerToCount[kmer] = 1
kmerToFirst[kmer] = ix
else:
kmerToCount[kmer] += 1
#if ("element" in debug):
# print >>stderr, " %d: %s" % (ix,kmer)
# choose the best k-mer; this is simply the most frequently occurring one,
# with ties broken by whichever one came first
kmers = [(-kmerToCount[kmer],kmerToFirst[kmer],kmer) for kmer in kmerToCount]
if (kmers == []): return (None,None,start,end)
kmers.sort()
if ("element" in debug):
for (count,first,kmer) in kmers:
print >>stderr, " %s: %d" % (kmer,-count)
(count,first,kmer) = kmers[0]
if (contains_repeat(kmer)): return (None,None,start,end)
# determine the hamming distance between the run and a simple repeat, for
# each "plausible" start and end; we compute the distance for each such
# interval, and choose the one with the lowest hamming distance; ties are
# broken in a deterministic-but-unspecified manner
bestD = bestStart = bestEnd = None
###################################################################################
# modified by Chen Sun(cxs1031@cse.psu.edu) on 10/18/2013
# since we do not allow hamming_distance > 0, which means we do not allow mutation,
# we do not need this section to produce bestStart and End
###################################################################################
#for (s,e) in plausible_intervals(start,end,period,len(seq),allowPartials=allowPartials):
# d = hamming_distance(seq,s,e,kmer)
# if (d == None): continue
# if (bestD == None) or (d <= bestD):
# (bestD,bestStart,bestEnd) = (d,s,e)
bestStart = start
if(allowPartials):
bestEnd = end
elif(not allowPartials):
bestEnd = start
pattern = seq[start:start+period]
if ("partial" in debug):
print "kmer:", kmer
if(pattern != kmer):
print "pattern:", pattern
while(bestEnd <= end-period):
bestEnd += period
# bestD will always be 0, as we do not allow mutation
bestD = 0
if ("partial" in debug):
print bestD, bestStart, bestEnd
###################################################################################
# modified by Chen Sun(cxs1031@cse.psu.edu) on 10/10
#
###################################################################################
return (kmer,bestD,bestStart,bestEnd)
def find_hamming_repeat_element(period,seq,start,end,allowPartials=False):
# count the number of occurences of each k-mer; note that we can't
# reject kmers containing smaller repeats yet, since for a sequence like
# ACACACACACAAACACACACACACACACAC we must first discover ACACAC as the best
# 6-mer, and THEN reject it; if we reject ACACAC while counting, we'd end
# up reporting something like ACACAA as the best motif
if ("element" in debug):
print >>stderr, "find_repeat_element(%d,%d,%d)" % (period,start,end)
kmerToCount = {}
kmerToFirst = {}
for ix in xrange(start,end-(period-1)):
kmer = seq[ix:ix+period]
if ("N" in kmer): continue
if (kmer not in kmerToCount):
kmerToCount[kmer] = 1
kmerToFirst[kmer] = ix
else:
kmerToCount[kmer] += 1
#if ("element" in debug):
# print >>stderr, " %d: %s" % (ix,kmer)
# choose the best k-mer; this is simply the most frequently occurring one,
# with ties broken by whichever one came first